answer
stringlengths
17
10.2M
package net.vicky; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import net.fusejna.ErrorCodes; /* * struct VPoint { char* name; int isDirectory; char* contents; int current_content_capacity; struct Queue *subQueue; struct * VPoint *parent; struct OpenVPoint *openContainerForThis; */ public class VickyFS { static Byte[] getLarge(final byte[] arr) { final Byte[] retArr = new Byte[arr.length]; for (int index = 0; index < retArr.length; index++) { retArr[index] = arr[index]; } return retArr; } static byte[] getSmall(final Byte[] arr) { final byte[] retArr = new byte[arr.length]; for (int index = 0; index < retArr.length; index++) { retArr[index] = arr[index]; } return retArr; } public static void main(final String[] args) { final VickyFS firstVFS = new VickyFS(50); firstVFS.create_point("dirA", VPoint.IS_DIRECTORY); firstVFS.create_point("dirA/dirA1", VPoint.IS_DIRECTORY); firstVFS.create_point("dirA/dirA1/dirA11", VPoint.IS_DIRECTORY); // System.out.println(firstVFS); firstVFS.create_point("dirA/dirA1/dirA11/fileA11a", VPoint.IS_FILE); firstVFS.create_point("dirA/dirA1/dirA11/fileA11b", VPoint.IS_FILE); final int A11aFD = firstVFS.open_file("dirA/dirA1/dirA11/fileA11a"); final byte[] bArr = new byte[] { 8, 80, 16, 89, 19, 42, 11, 56, 74, 19, 61, 34, 84, 100, 21, 71, 63, 9, 85, 61, 34, 82, 38, 86, 21, 82, 27, 86, 71, 9, 28, 43, 23, 55, 20, 36, 11, 57, 4, 43, 85, 68, 83, 32, 7, 80, 68, 44, 13, 46, 84, 90, 17, 83, 19, 10, 52, 5, 79, 23, 19, 41, 65, 59 }; firstVFS.vwrite(A11aFD, bArr.length, 0, ByteBuffer.wrap(bArr)); // reading final ByteBuffer readBuf = ByteBuffer.wrap(new byte[100]); firstVFS.vread(A11aFD, readBuf.remaining() - 1, 0, readBuf); final byte[] readArr = readBuf.array(); System.out.println("fileA11a contains: " + Arrays.toString(readArr)); firstVFS.change_dir("dirA"); firstVFS.change_dir("dirA1/dirA11"); System.out.println(firstVFS.currentDir); firstVFS.remove_point("fileA11a"); System.out.println(firstVFS.currentDir); firstVFS.change_dir("../.."); System.out.println(firstVFS.currentDir); firstVFS.remove_point("dirA1/dirA11"); System.out.println(firstVFS.currentDir); firstVFS.change_dir("dirA1/dirA11"); System.out.println(firstVFS.currentDir); } VPoint rootDir; VPoint currentDir; HashMap<Integer, VPoint> openFileMap; int lastAllocatedFD; // String current_path_str; int size, remaining_space; VickyFS(final int size) { lastAllocatedFD = -1; rootDir = new VPoint("/", VPoint.IS_DIRECTORY, null); currentDir = rootDir; openFileMap = new HashMap<Integer, VPoint>(); // current_path_str = "/"; this.size = size; remaining_space = size; } boolean addSpaceOf(final int newDataSize) { final int newSpaceNeeded = newDataSize * 2; // char is 2 bytes if (newSpaceNeeded < remaining_space) { remaining_space -= newSpaceNeeded; System.out.println("New space added: " + newSpaceNeeded + " Remaining: " + remaining_space + " Total: " + size); return true; } else { System.err.println( "Tried to add New space: " + newSpaceNeeded + " Remaining: " + remaining_space + " Total: " + size); return false; } } boolean change_dir(final String path) { if (path.equals("/") || path.equals("")) { currentDir = rootDir; return true; } final String remainingPath = resolvePath(path); if (traverseToNewDirInCurrentDir(remainingPath) == true) { return true; } else { System.out.println(this); return false; } } boolean close_file_point(final int fd) { if (openFileMap.containsKey(fd)) { openFileMap.remove(fd); return true; } else { System.err.println("No Such FD Mapped to an Open File"); return false; } } boolean create_point(final String path, final boolean type) { // save currentDir final VPoint oldCurrent = currentDir; final String newPointName = resolvePath(path); final boolean success = currentDir.addChildToDir(new VPoint(newPointName, type, currentDir)); // load back curretnDir currentDir = oldCurrent; return success; } boolean createNewPointUnderCurrentDir(final String newPointName, final boolean type) { if (newPointName == null || newPointName.equals("") || newPointName.length() == 0) { System.err.println("A point cannot be created with <blank> name"); return false; } else if (currentDir.searchForChildPoint(newPointName) == true) { System.err.println(currentDir.name + " already contains " + newPointName + " ."); return false; } else { final VPoint newVPoint = new VPoint(newPointName, type, currentDir); if (generateSpaceFor(newVPoint) == true) { System.out.println(newVPoint.name + " added under " + currentDir.name); currentDir.addChildToDir(newVPoint); return true; } else { System.err.println("Not enough space!!"); return false; } } } boolean createPoint(final String path, final boolean type) { // save currentDir final VPoint oldCurrent = currentDir; final String newPointName = resolvePath(path); final boolean success = currentDir.addChildToDir(new VPoint(newPointName, type, currentDir)); // load back curretnDir currentDir = oldCurrent; return success; } boolean generateSpaceFor(final VPoint newPoint) { int newSpaceNeeded = newPoint.name.length() * 2; // char is 2 bytes if (newPoint.isFile()) { newSpaceNeeded += newPoint.contents.size(); } if (newSpaceNeeded < remaining_space) { remaining_space -= newSpaceNeeded; System.out.println("New space added: " + newSpaceNeeded + " Remaining: " + remaining_space + " Total: " + size); return true; } else { System.out.println("New space added: " + newSpaceNeeded + " Remaining: " + remaining_space + " Total: " + size); return false; } } Integer getFDForOpenFileIfExits(final String filePointName) { if (openFileMap.containsValue(new VPoint(filePointName))) { for (final Map.Entry<Integer, VPoint> entry : openFileMap.entrySet()) { final VPoint existingPoint = entry.getValue(); if (existingPoint.name.equals(filePointName) && existingPoint.parentPoint == currentDir) { return entry.getKey(); } } } return null; } int open_file(final String path) { // save currentDir final VPoint oldCurrent = currentDir; final String newPointName = resolvePath(path); final int retVal = openFileInCurrentDir(newPointName); // load back curretnDir currentDir = oldCurrent; return retVal; } int openFileInCurrentDir(final String filePointName) { final Integer existingFD = getFDForOpenFileIfExits(filePointName); if (existingFD != null) { System.err.println(filePointName + " was already open."); return existingFD; } else if (filePointName == null || filePointName.equals("") || filePointName.length() == 0) { System.err.println("A point cannot be created with <blank> name"); return -1; } else if (currentDir.searchForChildPoint(filePointName) == true) { final VPoint toBeOpened = currentDir.returnSubPoint(filePointName); if (toBeOpened.isDirectory()) { System.err.println(toBeOpened.name + " is not a file. Cannot open..."); return -1; } else { openFileMap.put(++lastAllocatedFD, toBeOpened); return lastAllocatedFD; } } System.err.println("Should not be here. openFileInCurrentDir."); return -1; } void recoverSpaceFor(final VPoint removalPoint) { int spaceRecovered = removalPoint.name.length() * 2; // char is 2 bytes if (removalPoint.isFile()) { spaceRecovered += removalPoint.contents.size(); } remaining_space += spaceRecovered; System.out.println("New space added: " + spaceRecovered + " Remaining: " + remaining_space + " Total: " + size); } boolean remove_point(final String path) { boolean success; // save currentDir final VPoint oldCurrent = currentDir; final String newPointName = resolvePath(path); final VPoint toBeRemoved = currentDir.returnSubPoint(newPointName); if (toBeRemoved == null) { System.err.println("Could not find " + newPointName + " inside " + currentDir); success = false; } else { success = currentDir.removeChildFromDir(toBeRemoved); if (toBeRemoved.isFile()) { final Integer openFD = getFDForOpenFileIfExits(toBeRemoved.name); final VPoint openPoint = openFileMap.get(openFD); if (openPoint != null && openPoint.parentPoint == currentDir) { close_file_point(openFD); } } } // load back curretnDir currentDir = oldCurrent; return success; } /* * boolean removeOnePathLevel() { final int last_index_of_seperator = current_path_str.lastIndexOf('/'); if * (last_index_of_seperator != -1) { current_path_str = current_path_str.substring(0, last_index_of_seperator); return true; * } else { return false; } } */ boolean removePointUnderCurrentDir(final String exisingPointName) { if (exisingPointName == null || exisingPointName.equals("") || exisingPointName.length() == 0) { System.err.println("A point cannot exist with <blank> name"); return false; } else if (currentDir.searchForChildPoint(exisingPointName) == false) { System.err.println(currentDir.name + " does not contains " + exisingPointName + " ."); return false; } else { final VPoint toBeRemoved = currentDir.returnSubPoint(exisingPointName); recoverSpaceFor(toBeRemoved); System.out.println(toBeRemoved.name + " removed from under " + currentDir.name); currentDir.removeChildFromDir(toBeRemoved); return true; } } String resolvePath(final String originalPath) { try { final String[] pathArr = originalPath.split("/"); if (pathArr.length == 1) { // System.out.println("Nothing to resolve"); return originalPath; } else if (originalPath.lastIndexOf('/') == 0) { final String ret = originalPath.substring(1, originalPath.length()); System.out.println("removed / from start of " + originalPath + " --> " + ret); return ret; } else { for (int i = 0; i < pathArr.length - 1; i++) { if (traverseToNewDirInCurrentDir(pathArr[i]) == false) { return null; } } return pathArr[pathArr.length - 1]; } } catch (final Exception e) { System.out.println("Exception : resolve Path called for " + originalPath); return null; } } VPoint return_point(final String path) { // save currentDir if (currentDir == rootDir && path.equals("/")) { return rootDir; } final VPoint oldCurrent = currentDir; final String newPointName = resolvePath(path); final VPoint return_point; if (newPointName.equals(currentDir.name)) { return_point = currentDir; } else { return_point = returnPointInCurrentDir(newPointName); } // load back curretnDir currentDir = oldCurrent; return return_point; } VPoint return_point_fully_qualified(final String path) { // save currentDir if (currentDir == rootDir && path.equals("/")) { return rootDir; } final VPoint oldCurrent = currentDir; currentDir = rootDir; final String newPointName = resolvePath(path); final VPoint return_point; if (newPointName.equals(currentDir.name)) { return_point = currentDir; } else { return_point = returnPointInCurrentDir(newPointName); } // load back curretnDir currentDir = oldCurrent; return return_point; } String returnAbsolutePointName(final String path) { final String[] splitted = path.split("/"); return splitted[splitted.length - 1]; } VPoint returnPointInCurrentDir(final String exisingPointName) { if (exisingPointName == null || exisingPointName.equals("") || exisingPointName.length() == 0) { System.err.println("A point cannot exist with <blank> name"); return null; } else if (currentDir.searchForChildPoint(exisingPointName) == false) { System.err.println(currentDir.name + " does not contain " + exisingPointName); return null; } else { final VPoint toBeReturned = currentDir.returnSubPoint(exisingPointName); return toBeReturned; } } @Override public String toString() { return "Root>" + rootDir.toString() + "\n CurrentDir: " + currentDir.toString() + "-- Open: " + openFileMap.toString(); } /* * VPoint traverseDownPath(final String originalPath) { final String[] pathArr = originalPath.split("/"); if (pathArr.length * == 1) { System.out.println("Nothing to resolve"); return currentDir; } else { VPoint parentAtPath = currentDir; for (int * i = 0; i < pathArr.length - 1; i++) { final VPoint child = parentAtPath.returnSubPoint(pathArr[i]); if (child == null || * child.isFile()) { System.out.println("Could not resolve " + pathArr[i] + " in " + parentAtPath.name); return null; } else * { parentAtPath = child; } } System.out.println("Resolved. Returning " + parentAtPath.name); return parentAtPath; } } */ boolean traverseToNewDirInCurrentDir(final String exisingPointName) { if (exisingPointName == null || exisingPointName.equals("") || exisingPointName.length() == 0) { System.err.println("A directory cannot exist with <blank> name"); return false; } else if (exisingPointName.equals("..")) { return traverseUpOneLevel(); } else if (currentDir.searchForChildPoint(exisingPointName) == false) { System.err.println(currentDir.name + " does not contains " + exisingPointName); return false; } else { final VPoint toBeReturned = currentDir.returnSubPoint(exisingPointName); if (toBeReturned.isFile()) { System.err.println(toBeReturned.name + " is not a directory..."); return false; } else { currentDir = toBeReturned; // System.out.println("Entered " + toBeReturned.name); return true; } } } boolean traverseUpOneLevel() { if (currentDir.parentPoint != null) { currentDir = currentDir.parentPoint; return true; } else { System.err.println("Reached root or parentless point"); return false; } } int vread(final int fd, final int size, final int offset, final ByteBuffer buf) { if (openFileMap.containsKey(fd)) { final VPoint file = openFileMap.get(fd); final int lengthRead = Math.min(offset + size, file.contents.size()); final Byte[] bigByteArr = file.contents.subList(offset, lengthRead).toArray(new Byte[] {}); System.out.println(Arrays.toString(bigByteArr) + " read from " + file.name); buf.put(getSmall(bigByteArr)); return 0; } else { System.err.println("No Such FD Mapped to an Open File"); return -ErrorCodes.EBADF(); } } int vwrite(final int fd, final int size, final int offset, final ByteBuffer buf) { if (openFileMap.containsKey(fd)) { if (addSpaceOf(offset + size) == false) { System.err.println("Ran out of space."); return -ErrorCodes.ENOMEM(); } final byte[] byteArr = new byte[size]; buf.get(byteArr); final VPoint file = openFileMap.get(fd); file.contents.addAll(offset, Arrays.asList(getLarge(byteArr))); System.out.println(file.name + " now contains :" + file.contents); return 0; } else { System.err.println("No Such FD Mapped to an Open File"); return -ErrorCodes.EBADF(); } } } class VPoint { static final boolean IS_FILE = false; static final boolean IS_DIRECTORY = true; static final int INIT_CONTENT_SIZE = 4096; String name; boolean pointType; HashSet<VPoint> childpoints; ArrayList<Byte> contents; VPoint parentPoint; VPoint(final String name) { this.name = name; } VPoint(final String name, final boolean pointType, final VPoint parentPoint) { this.name = name; this.pointType = pointType; this.parentPoint = parentPoint; if (isDirectory()) { childpoints = new HashSet<VPoint>(); } else { contents = new ArrayList<Byte>(VPoint.INIT_CONTENT_SIZE); } } boolean addChildToDir(final VPoint childPoint) { if (pointType == VPoint.IS_FILE) { System.err.println(name + " is a File. Cannot add " + childPoint.name + " to it."); return false; } else { if (childpoints.contains(childPoint)) { System.err.println(name + " already contains " + childPoint.name + " in it."); return false; } if (childPoint.parentPoint.name != name) { System.err.println("Parents don't match.. Not adding.."); return false; } childpoints.add(childPoint); return true; } } @Override public boolean equals(final Object o) { if (o instanceof VPoint == false) { return false; } return name.contentEquals(((VPoint) o).name); } @Override public int hashCode() { return name.hashCode(); } boolean isDirectory() { return pointType == VPoint.IS_DIRECTORY; } boolean isFile() { return pointType == VPoint.IS_FILE; } boolean removeChildFromDir(final VPoint childPoint) { System.out.println(this); if (childpoints.contains(childPoint)) { childpoints.remove(childPoint); return true; } return false; } ArrayList<String> returnChildPoints() { final ArrayList<String> retList = new ArrayList<String>(childpoints.size()); final Iterator<VPoint> iter = childpoints.iterator(); for (final VPoint childPoint : childpoints) { retList.add(childPoint.name); } return retList; } VPoint returnSubPoint(final String childName) { if (isFile()) { System.err.println(name + " is a File. It cannot contain " + childName + " in it."); return null; } else { final VPoint proxyPoint = new VPoint(childName); if (childpoints.contains(proxyPoint) == false) { return null; } else { final ArrayList<VPoint> list = new ArrayList<VPoint>(childpoints); return list.get(list.indexOf(proxyPoint)); } } } boolean searchForChildPoint(final String childName) { if (isFile()) { System.err.println(name + " is a File. It cannot contain " + childName + " in it."); return false; } else { return childpoints.contains(new VPoint(childName)); } } @Override public String toString() { String ret = "Point > " + name + " > " + ((pointType == VPoint.IS_DIRECTORY) ? "Directory" : "File"); if (isDirectory()) { ret = ret + " - Children: " + childpoints.toString(); } else { ret = ret + " - Contents: " + contents; } return ret; } }
package tars.ui; import java.util.ArrayList; import java.util.List; import tars.model.tag.ReadOnlyTag; import tars.model.task.DateTime; import tars.model.task.rsv.RsvTask; public class Formatter { /** Format of indexed list item */ private static final String MESSAGE_INDEXED_LIST_ITEM = "%1$d. %2$s"; /** A decorative prefix added to the beginning of lines printed by TARS */ private static final String LINE_PREFIX = " "; /** A platform independent line separator. */ private static final String LS = System.lineSeparator(); /** Offset required to convert between 1-indexing and 0-indexing. */ private static final int DISPLAYED_INDEX_OFFSET = 1; public String formatTags(List<? extends ReadOnlyTag> tags) { final List<String> formattedTags = new ArrayList<>(); for (ReadOnlyTag tag : tags) { formattedTags.add(tag.getAsText()); } return format(asIndexedList(formattedTags)); } /** Formats the given strings for displaying to the user. */ public String format(String... messages) { StringBuilder sb = new StringBuilder(); for (String m : messages) { sb.append(LINE_PREFIX + m.replace("\n", LS + LINE_PREFIX) + LS); } return sb.toString(); } /** Formats a list of strings as an indexed list. */ private static String asIndexedList(List<String> listItems) { final StringBuilder formatted = new StringBuilder(); int displayIndex = 0 + DISPLAYED_INDEX_OFFSET; for (String listItem : listItems) { formatted.append(getIndexedListItem(displayIndex, listItem)).append("\n"); displayIndex++; } return formatted.toString(); } /** * Formats a string as an indexed list item. * * @param visibleIndex index for this listing */ private static String getIndexedListItem(int visibleIndex, String listItem) { return String.format(MESSAGE_INDEXED_LIST_ITEM, visibleIndex, listItem); } public static String formatDateTimeList(RsvTask rsvTask) { String formatted = ""; ArrayList<DateTime> dateTimeArrayList = rsvTask.getDateTimeList(); int count = 1; for (DateTime dt : dateTimeArrayList) { formatted += "[" + count + "] " + dt.toString() + "\n\n"; count++; } return formatted; } }
package ui.client; import common.client.Func; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import react.client.*; import javax.inject.Inject; import javax.inject.Singleton; @Singleton public class Popover extends ExternalComponent<Popover.Props> { @Inject public Popover() { } @Override protected native ReactClass getReactClass() /*-{ return $wnd.MaterialUi.Popover; }-*/; @JsType(isNative = true) public interface Props extends BaseProps { // ReactElement anchorEl; // unlike most objects this shouldn't be a String, thiss is for the anchor element the popover belongs to // Origin anchorOrigin; // ? type = PropTypes.origin, default { vertical: 'top', horizontal: 'left', } // Origin targetOrigin; // ? type = PropTypes.origin, default { vertical: 'top', horizontal: 'left', } // boolean animated = true; // boolean autoCloseWhenOffScreen = true; // boolean canAutoPosition = true; // String className; // boolean open; // StyleProps style; // ? default { overflowY: 'auto',} // boolean userLayerForClickAway; // double zDepth; // ? type = PropTypes.zDepth, default 1 // Func.Run animation; // func // Func.Run onRequestClose; // func // MouseEventHandler onClick; @JsProperty ReactElement getAnchorEl(); @JsProperty void setAnchorEl(ReactElement anchorEl); @JsProperty Origin getAnchorOrigin(); @JsProperty void setAnchorOrigin(Origin anchorOrigin); @JsProperty Origin getTargetOrigin(); @JsProperty void setTargetOrigin(Origin targetOrigin); @JsProperty boolean isAnimated(); @JsProperty void setAnimated(boolean animated); @JsProperty boolean isAutoCloseWhenOffScreen(); @JsProperty void setAutoCloseWhenOffScreen(boolean autoCloseWhenOffScreen); @JsProperty boolean isCanAutoPosition(); @JsProperty void setCanAutoPosition(boolean canAutoPosition); @JsProperty String getClassName(); @JsProperty void setClassName(String className); @JsProperty boolean isOpen(); @JsProperty void setOpen(boolean open); @JsProperty StyleProps getStyle(); @JsProperty void setStyle(StyleProps style); @JsProperty boolean isUserLayerForClickAway(); @JsProperty void setUserLayerForClickAway(boolean userLayerForClickAway); @JsProperty double getZDepth(); @JsProperty void setZDepth(double zDepth); @JsProperty Func.Run getAnimation(); @JsProperty void setAnimation(Func.Run animation); @JsProperty Func.Run getOnRequestClose(); @JsProperty void setOnRequestClose(Func.Run onRequestClose); @JsProperty MouseEventHandler getOnClick(); @JsProperty void setOnClick(MouseEventHandler onClick); // fluent setters @JsOverlay default Props anchorEl(final ReactElement anchorEl) { setAnchorEl(anchorEl); return this; } @JsOverlay default Props anchorOrigin(final Origin anchorOrigin) { setAnchorOrigin(anchorOrigin); return this; } @JsOverlay default Props targetOrigin(final Origin targetOrigin) { setTargetOrigin(targetOrigin); return this; } @JsOverlay default Props animated(final boolean animated) { setAnimated(animated); return this; } @JsOverlay default Props autoCloseWhenOffScreen(final boolean autoCloseWhenOffScreen) { setAutoCloseWhenOffScreen(autoCloseWhenOffScreen); return this; } @JsOverlay default Props canAutoPosition(final boolean canAutoPosition) { setCanAutoPosition(canAutoPosition); return this; } @JsOverlay default Props className(final String className) { setClassName(className); return this; } @JsOverlay default Props open(final boolean open) { setOpen(open); return this; } @JsOverlay default Props style(final StyleProps style) { setStyle(style); return this; } @JsOverlay default Props userLayerForClickAway(final boolean userLayerForClickAway) { setUserLayerForClickAway(userLayerForClickAway); return this; } @JsOverlay default Props zDepth(final double zDepth) { setZDepth(zDepth); return this; } @JsOverlay default Props animation(final Func.Run animation) { setAnimation(animation); return this; } @JsOverlay default Props onRequestClose(final Func.Run onRequestClose) { setOnRequestClose(onRequestClose); return this; } @JsOverlay default Props onClick(final MouseEventHandler onClick) { setOnClick(onClick); return this; } @JsOverlay default Props key(final String key) { setKey(key); return this; } } @JsType(isNative = true) public interface Origin { @JsProperty String getVertical(); @JsProperty void setVertical(String vertical); @JsProperty String getHorizontal(); @JsProperty void setHorizontal(String horizontal); } }
package water.api; import hex.DGLM.GLMModel; import hex.pca.PCA; import hex.pca.PCAModelView; import hex.*; import hex.KMeans2.KMeans2Model; import hex.KMeans2.KMeans2ModelView; import hex.NeuralNet.NeuralNetModel; import hex.gbm.GBM.GBMModel; import hex.glm.*; import hex.rf.RFModel; import java.util.HashMap; import water.*; import water.ValueArray.Column; import water.api.GLMProgressPage.GLMBuilder; import water.fvec.Frame; import water.fvec.Vec; import water.parser.CustomParser.PSetupGuess; import water.parser.ParseDataset; import water.util.Utils; import com.google.gson.*; public class Inspect extends Request { private static final HashMap<String, String> _displayNames = new HashMap<String, String>(); private static final long INFO_PAGE = -1; private final H2OExistingKey _key = new H2OExistingKey(KEY); private final LongInt _offset = new LongInt(OFFSET, INFO_PAGE, Long.MAX_VALUE); private final Int _view = new Int(VIEW, 100, 0, 10000); private final Str _producer = new Str(JOB, null); private final Int _max_column = new Int(COLUMNS_DISPLAY, MAX_COLUMNS_TO_DISPLAY); static final int MAX_COLUMNS_TO_DISPLAY = 1000; static { _displayNames.put(ENUM_DOMAIN_SIZE, "Enum Domain"); _displayNames.put(MEAN, "avg"); _displayNames.put(NUM_MISSING_VALUES, "Missing"); _displayNames.put(VARIANCE, "sd"); } // Constructor called from 'Exec' query instead of the direct view links Inspect(Key k) { _key.reset(); _key.check(this, k.toString()); _offset.reset(); _offset.check(this, ""); _max_column.reset(); _max_column.check(this, ""); _view.reset(); _view.check(this, ""); } // Default no-args constructor Inspect() { } public static Response redirect(JsonObject resp, Job keyProducer, Key dest) { JsonObject redir = new JsonObject(); if (keyProducer!=null) redir.addProperty(JOB, keyProducer.job_key.toString()); redir.addProperty(KEY, dest.toString()); return Response.redirect(resp, Inspect.class, redir); } public static Response redirect(JsonObject resp, Key dest) { return redirect(resp, null, dest); } public static Response redirect(Request req, Key dest) { return new Response(Response.Status.redirect, req, -1, -1, "Inspect", KEY, dest ); } public static String link(String txt, Key key) { return "<a href='Inspect.html?key=" + key + "'>" + txt + "</a>"; } @Override protected boolean log() { return false; } @Override protected Response serve() { // Key might not be the same as Value._key, e.g. a user key Key key = Key.make(_key.record()._originalValue); Value val = _key.value(); if(val == null) { // Some requests redirect before creating dest return RequestServer._http404.serve(); } if( val.type() == TypeMap.PRIM_B ) return serveUnparsedValue(key, val); Freezable f = val.getFreezable(); if( f instanceof ValueArray ) { ValueArray ary = (ValueArray)f; if( ary._cols.length==1 && ary._cols[0]._name==null ) return serveUnparsedValue(key, val); int columns_to_display = 0; if (_max_column.value() > 0) columns_to_display = _max_column.value(); return serveValueArray(ary, columns_to_display); } if( f instanceof Vec ) { return serveUnparsedValue(key, ((Vec) f).chunkIdx(0)); } if( f instanceof Frame ) { return serveFrame(key, (Frame) f); } if( f instanceof GLMModel ) { GLMModel m = (GLMModel)f; JsonObject res = new JsonObject(); res.add(GLMModel.NAME, m.toJson()); Response r = Response.done(res); r.setBuilder(ROOT_OBJECT, new GLMBuilder(m, null)); return r; } if( f instanceof hex.GLMGrid.GLMModels ) { JsonObject resp = new JsonObject(); resp.addProperty(Constants.DEST_KEY, val._key.toString()); return GLMGridProgress.redirect(resp,null,val._key); } if( f instanceof KMeansModel ) { KMeansModel m = (KMeansModel)f; JsonObject res = new JsonObject(); res.add(KMeansModel.NAME, m.toJson()); Response r = Response.done(res); r.setBuilder(KMeansModel.NAME, new KMeans.Builder(m)); return r; } if( f instanceof RFModel ) { RFModel rfModel = (RFModel)f; JsonObject response = new JsonObject(); return RFView.redirect(response, rfModel._selfKey, rfModel._dataKey, true); } /*if( f instanceof PCAModel ) { PCAModel m = (PCAModel)f; JsonObject res = new JsonObject(); res.add(PCAModel.NAME, m.toJson()); Response r = Response.done(res); r.setBuilder(PCAModel.NAME, new PCA.Builder(m)); return r; }*/ if( f instanceof Job.Fail ) { UKV.remove(val._key); // Not sure if this is a good place to do this return Response.error(((Job.Fail)f)._message); } if(f instanceof hex.glm.GLMModel) return GLMModelView.redirect2(this, key); if(f instanceof GBMModel) return GBMModelView.redirect(this, key); if( f instanceof GLMValidation) return GLMValidationView.redirect(this, key); if(f instanceof NeuralNetModel) return ((NeuralNet) f).redirect(this, key); if(f instanceof KMeans2Model) return KMeans2ModelView.redirect(this, key); if(f instanceof GridSearch) return ((GridSearch) f).redirect(); if(f instanceof hex.pca.PCAModel) return PCAModelView.redirect(this, key); return Response.error("No idea how to display a "+f.getClass()); } // Build a response JSON private final Response serveUnparsedValue(Key key, Value v) { JsonObject result = new JsonObject(); result.addProperty(VALUE_TYPE, "unparsed"); byte [] bits = v.getFirstBytes(); bits = Utils.unzipBytes(bits, Utils.guessCompressionMethod(bits)); PSetupGuess sguess = ParseDataset.guessSetup(bits); if(sguess != null && sguess._data != null && sguess._data[1].length > 0 ) { // Able to parse sanely? int zipped_len = v.getFirstBytes().length; double bytes_per_row = (double) zipped_len / sguess._data.length; long rows = (long) (v.length() / bytes_per_row); result.addProperty(NUM_ROWS, "~" + rows); // approx rows result.addProperty(NUM_COLS, sguess._data[1].length); result.add(ROWS, new Gson().toJsonTree(sguess._data)); } else { result.addProperty(NUM_ROWS, "unknown"); result.addProperty(NUM_COLS, "unknown"); } result.addProperty(VALUE_SIZE, v.length()); // The builder Response Response r = Response.done(result); // Some nice links in the response r.addHeader("<div class='alert'>" + Parse.link(key, "Parse into hex format") + "</div>"); // Set the builder for showing the rows r.setBuilder(ROWS, new ArrayBuilder() { public String caption(JsonArray array, String name) { return "<h4>First few sample rows</h4>"; } }); return r; } public Response serveValueArray(final ValueArray va) { return serveValueArray(va, va._cols.length); } /** * serve the value array with a capped # of columns [0,max_columns) */ public Response serveValueArray(final ValueArray va, int max_column) { if( _offset.value() > va._numrows ) return Response.error("Value only has " + va._numrows + " rows"); JsonObject result = new JsonObject(); result.addProperty(VALUE_TYPE, "parsed"); result.addProperty(KEY, va._key.toString()); result.addProperty(NUM_ROWS, va._numrows); result.addProperty(NUM_COLS, va._cols.length); result.addProperty(ROW_SIZE, va._rowsize); result.addProperty(VALUE_SIZE, va.length()); JsonArray cols = new JsonArray(); JsonArray rows = new JsonArray(); final int col_limit = Math.min(max_column, va._cols.length); for( int i = 0; i < col_limit; i++ ) { Column c = va._cols[i]; JsonObject json = new JsonObject(); json.addProperty(NAME, c._name); json.addProperty(OFFSET, c._off); json.addProperty(SIZE, Math.abs(c._size)); json.addProperty(BASE, c._base); json.addProperty(SCALE, (int) c._scale); json.addProperty(MIN, c._min); json.addProperty(MAX, c._max); json.addProperty(MEAN, c._mean); json.addProperty(VARIANCE, c._sigma); json.addProperty(NUM_MISSING_VALUES, va._numrows - c._n); json.addProperty(TYPE, c._domain != null ? "enum" : (c.isFloat() ? "float" : "int")); json.addProperty(ENUM_DOMAIN_SIZE, c._domain != null ? c._domain.length : 0); cols.add(json); } if( _offset.value() != INFO_PAGE ) { long endRow = Math.min(_offset.value() + _view.value(), va._numrows); long startRow = Math.min(_offset.value(), va._numrows - _view.value()); for( long row = Math.max(0, startRow); row < endRow; ++row ) { JsonObject obj = new JsonObject(); obj.addProperty(ROW, row); for( int i = 0; i < col_limit; ++i ) format(obj, va, row, i); rows.add(obj); } } result.add(COLS, cols); result.add(ROWS, rows); Response r = Response.done(result); r.setBuilder(ROOT_OBJECT, new ObjectBuilder() { @Override public String build(Response response, JsonObject object, String contextName) { String s = html(va._key, va._numrows, va._cols.length, va._rowsize, va.length()); Table t = new Table(argumentsToJson(), _offset.value(), _view.value(), va, col_limit); s += t.build(response, object.get(ROWS), ROWS); return s; } }); r.setBuilder(ROWS + "." + ROW, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { String json = elm.getAsString(); String html = _displayNames.get(json); return html != null ? html : RequestStatics.JSON2HTML(json); } }); return r; } private static void format(JsonObject obj, ValueArray va, long rowIdx, int colIdx) { if( rowIdx < 0 || rowIdx >= va._numrows ) return; if( colIdx >= va._cols.length ) return; ValueArray.Column c = va._cols[colIdx]; String name = c._name != null ? c._name : "" + colIdx; if( va.isNA(rowIdx, colIdx) ) { obj.addProperty(name, "NA"); } else if( c._domain != null ) { obj.addProperty(name, c._domain[(int) va.data(rowIdx, colIdx)]); } else if( (c._size > 0) && (c._scale == 1) ) { obj.addProperty(name, va.data(rowIdx, colIdx)); } else { obj.addProperty(name, va.datad(rowIdx, colIdx)); } } private static void format(JsonObject obj, Frame f, long rowIdx, int colIdx) { Vec v = f.vecs()[colIdx]; if( rowIdx < 0 || rowIdx >= v.length() ) return; String name = f._names[colIdx] != null ? f._names[colIdx] : "" + colIdx; if( v.isNA(rowIdx) ) obj.addProperty(name, "NA"); else if( v.isEnum() ) obj.addProperty(name, v.domain((int)v.at8(rowIdx))); else if( v.isInt() ) obj.addProperty(name, v.at8(rowIdx)); else obj.addProperty(name, v.at(rowIdx)); } private final String html(Key key, long rows, int cols, int bytesPerRow, long bytes) { String keyParam = KEY + "=" + key.toString(); StringBuilder sb = new StringBuilder(); // @formatter:off sb.append("" + "<h3>" + "<a href='RemoveAck.html?" + keyParam + "'>" + "<button class='btn btn-danger btn-mini'>X</button></a>" + "&nbsp;&nbsp;" + key.toString() + "</h3>"); if (_producer.valid() && _producer.value()!=null) { Job job = Job.findJob(Key.make(_producer.value())); if (job!= null) sb.append("<div class='alert alert-success'>" + "<b>Produced in ").append(PrettyPrint.msecs(job.runTimeMs(),true)).append(".</b></div>"); } sb.append("<div class='alert'>Set " + SetColumnNames.link(key,"Column Names") +"<br/>View " + SummaryPage.link(key, "Summary") + "<br/>Build models using " + PCA.link(key, "PCA") + ", " + RF.link(key, "Random Forest") + ", " + GLM.link(key, "GLM") + ", " + GLMGrid.link(key, "GLM Grid Search") + ", " + KMeans.link(key, "KMeans") + ", or " + NeuralNet.link(key, NeuralNet.DOC_GET) + "<br />" + "Score data using " + RFScore.link(key, "Random Forest") + ", " + GLMScore.link(KEY, key, 0.0, "GLM") + "</br><b>Download as</b> " + DownloadDataset.link(key, "CSV") + "</div>" + "<p><b><font size=+1>" + cols + " columns" + (bytesPerRow != 0 ? (", " + bytesPerRow + " bytes-per-row * " + rows + " rows = " + PrettyPrint.bytes(bytes)) : "") + "</font></b></p>"); // sb.append( // " <script>$('#inspect').submit( function() {" + // " $('html', 'table').animate({ scrollTop: $('#row_30').offset().top" + // "}, 2000);" + // "return false;" + // "});</script>"); String _scrollto = String.valueOf(_offset.value() - 1); sb.append( " <script>$(document).ready(function(){ " + " $('html, body').animate({ scrollTop: $('#row_"+_scrollto+"').offset().top" + "}, 2000);" + "return false;" + "});</script>"); sb.append( "<form class='well form-inline' action='Inspect.html' id='inspect'>" + " <input type='hidden' name='key' value="+key.toString()+">" + " <input type='text' class='input-small span5' placeholder='filter' " + " name='offset' id='offset' value='"+_offset.value()+"' maxlength='512'>" + " <button type='submit' class='btn btn-primary'>Jump to row!</button>" + "</form>"); // @formatter:on return sb.toString(); } // Frame public Response serveFrame(final Key key, final Frame f) { if( _offset.value() > f.numRows() ) return Response.error("Value only has " + f.numRows() + " rows"); JsonObject result = new JsonObject(); result.addProperty(VALUE_TYPE, "parsed"); result.addProperty(KEY, key.toString()); result.addProperty(NUM_ROWS, f.numRows()); result.addProperty(NUM_COLS, f.numCols()); JsonArray cols = new JsonArray(); JsonArray rows = new JsonArray(); for( int i = 0; i < f.numCols(); i++ ) { Vec v = f.vecs()[i]; JsonObject json = new JsonObject(); json.addProperty(NAME, f._names[i]); json.addProperty(MIN, v.min()); json.addProperty(MAX, v.max()); cols.add(json); } if( _offset.value() != INFO_PAGE ) { long endRow = Math.min(_offset.value() + _view.value(), f.numRows()); long startRow = Math.min(_offset.value(), f.numRows() - _view.value()); for( long row = Math.max(0, startRow); row < endRow; ++row ) { JsonObject obj = new JsonObject(); obj.addProperty(ROW, row); for( int i = 0; i < f.numCols(); ++i ) format(obj, f, row, i); rows.add(obj); } } result.add(COLS, cols); result.add(ROWS, rows); Response r = Response.done(result); r.setBuilder(ROOT_OBJECT, new ObjectBuilder() { @Override public String build(Response response, JsonObject object, String contextName) { String s = html(key, f.numRows(), f.numCols(), 0, 0); Table2 t = new Table2(argumentsToJson(), _offset.value(), _view.value(), f); s += t.build(response, object.get(ROWS), ROWS); return s; } }); r.setBuilder(ROWS + "." + ROW, new ArrayRowElementBuilder() { @Override public String elementToString(JsonElement elm, String contextName) { String json = elm.getAsString(); String html = _displayNames.get(json); return html != null ? html : RequestStatics.JSON2HTML(json); } }); return r; } private static final class Table extends PaginatedTable { private final ValueArray _va; private final int _max_columns; public Table(JsonObject query, long offset, int view, ValueArray va, int max_columns_to_display) { super(query, offset, view, va._numrows, true); _va = va; _max_columns = Math.min(max_columns_to_display, va._cols.length); } public Table(JsonObject query, long offset, int view, ValueArray va) { super(query, offset, view, va._numrows, true); _va = va; _max_columns = va._cols.length; } @Override public String build(Response response, JsonArray array, String contextName) { StringBuilder sb = new StringBuilder(); if (_va._cols.length > _max_columns) sb.append("<p style='text-align:center;'><center><h5 style='font-weight:800; color:red;'>Columns trimmed to " + _max_columns + "</h5></center></p>"); if( array.size() == 0 ) { // Fake row, needed by builder array = new JsonArray(); JsonObject fake = new JsonObject(); fake.addProperty(ROW, 0); for( int i = 0; i < _max_columns; ++i ) format(fake, _va, 0, i); array.add(fake); } sb.append(header(array)); JsonObject row = new JsonObject(); row.addProperty(ROW, MIN); for( int i = 0; i < _max_columns; i++ ) row.addProperty(_va._cols[i]._name, _va._cols[i]._min); sb.append(ARRAY_HEADER_ROW_BUILDER.build(response, row, contextName)); row.addProperty(ROW, MAX); for( int i = 0; i < _max_columns; i++ ) row.addProperty(_va._cols[i]._name, _va._cols[i]._max); sb.append(ARRAY_HEADER_ROW_BUILDER.build(response, row, contextName)); row.addProperty(ROW, MEAN); for( int i = 0; i < _max_columns; i++ ) row.addProperty(_va._cols[i]._name, _va._cols[i]._mean); sb.append(ARRAY_HEADER_ROW_BUILDER.build(response, row, contextName)); row.addProperty(ROW, VARIANCE); for( int i = 0; i < _max_columns; i++ ) row.addProperty(_va._cols[i]._name, _va._cols[i]._sigma); sb.append(ARRAY_HEADER_ROW_BUILDER.build(response, row, contextName)); row.addProperty(ROW, NUM_MISSING_VALUES); for( int i = 0; i < _max_columns; i++ ) row.addProperty(_va._cols[i]._name, _va._numrows - _va._cols[i]._n); sb.append(ARRAY_HEADER_ROW_BUILDER.build(response, row, contextName)); if( _offset == INFO_PAGE ) { row.addProperty(ROW, OFFSET); for( int i = 0; i < Math.min(MAX_COLUMNS_TO_DISPLAY,_va._cols.length); i++ ) row.addProperty(_va._cols[i]._name, _va._cols[i]._off); sb.append(defaultBuilder(row).build(response, row, contextName)); row.addProperty(ROW, SIZE); for( int i = 0; i < _max_columns; i++ ) row.addProperty(_va._cols[i]._name, Math.abs(_va._cols[i]._size)); sb.append(defaultBuilder(row).build(response, row, contextName)); row.addProperty(ROW, BASE); for( int i = 0; i < _max_columns; i++ ) row.addProperty(_va._cols[i]._name, _va._cols[i]._base); sb.append(defaultBuilder(row).build(response, row, contextName)); row.addProperty(ROW, SCALE); for( int i = 0; i < _max_columns; i++ ) row.addProperty(_va._cols[i]._name, (int) _va._cols[i]._scale); sb.append(defaultBuilder(row).build(response, row, contextName)); row.addProperty(ROW, ENUM_DOMAIN_SIZE); for( int i = 0; i < _max_columns; i++ ) row.addProperty(_va._cols[i]._name, _va._cols[i]._domain != null ? _va._cols[i]._domain.length : 0); sb.append(defaultBuilder(row).build(response, row, contextName)); } else { for( JsonElement e : array ) { Builder builder = response.getBuilderFor(contextName + "_ROW"); if( builder == null ) builder = defaultBuilder(e); sb.append(builder.build(response, e, contextName)); } } sb.append(footer(array)); if (_va._cols.length > _max_columns) sb.append("<p style='text-align:center;'><center><h5 style='font-weight:800; color:red;'>Columns trimmed to " + _max_columns + "</h5></center></p>"); return sb.toString(); } } private static final class Table2 extends PaginatedTable { private final Frame _f; public Table2(JsonObject query, long offset, int view, Frame f) { super(query, offset, view, f.numRows(), true); _f = f; } @Override public String build(Response response, JsonArray array, String contextName) { StringBuilder sb = new StringBuilder(); if( array.size() == 0 ) { // Fake row, needed by builder array = new JsonArray(); JsonObject fake = new JsonObject(); fake.addProperty(ROW, 0); for( int i = 0; i < _f.numCols(); ++i ) format(fake, _f, 0, i); array.add(fake); } sb.append(header(array)); JsonObject row = new JsonObject(); row.addProperty(ROW, MIN); for( int i = 0; i < _f.numCols(); i++ ) row.addProperty(_f._names[i], _f.vecs()[i].min()); sb.append(ARRAY_HEADER_ROW_BUILDER.build(response, row, contextName)); row.addProperty(ROW, MAX); for( int i = 0; i < _f.numCols(); i++ ) row.addProperty(_f._names[i], _f.vecs()[i].max()); sb.append(ARRAY_HEADER_ROW_BUILDER.build(response, row, contextName)); row.addProperty(ROW, FIRST_CHUNK); for( int i = 0; i < _f.numCols(); i++ ) row.addProperty(_f._names[i], _f.vecs()[i].chunk(0).getClass().getSimpleName()); sb.append(ARRAY_HEADER_ROW_BUILDER.build(response, row, contextName)); if( _offset == INFO_PAGE ) { for( int ci = 0; ci < _f.vecs()[0].nChunks(); ci++ ) { // Chunk chunk = _f.vecs()[ci].elem2BV(ci); String prefix = CHUNK + " " + ci + " "; row.addProperty(ROW, prefix + TYPE); for( int i = 0; i < _f.numCols(); i++ ) row.addProperty(_f._names[i], _f.vecs()[i].elem2BV(ci).getClass().getSimpleName()); sb.append(defaultBuilder(row).build(response, row, contextName)); row.addProperty(ROW, prefix + SIZE); for( int i = 0; i < _f.numCols(); i++ ) row.addProperty(_f._names[i], _f.vecs()[i].elem2BV(ci).byteSize()); sb.append(defaultBuilder(row).build(response, row, contextName)); } } else { for( JsonElement e : array ) { Builder builder = response.getBuilderFor(contextName + "_ROW"); if( builder == null ) builder = defaultBuilder(e); sb.append(builder.build(response, e, contextName)); } } sb.append(footer(array)); return sb.toString(); } } }
package org.commcare.activities; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.ScrollView; import android.widget.Switch; import android.widget.TextView; import android.widget.ToggleButton; import org.commcare.CommCareApplication; import org.commcare.core.interfaces.HttpResponseProcessor; import org.commcare.dalvik.R; import org.commcare.logging.AndroidLogger; import org.commcare.models.database.SqlStorage; import org.commcare.modern.util.Pair; import org.commcare.android.database.global.models.AppAvailableToInstall; import org.commcare.tasks.SimpleHttpTask; import org.commcare.tasks.templates.CommCareTaskConnector; import org.commcare.utils.ConnectivityStatus; import org.commcare.xml.AvailableAppsParser; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.xml.ElementParser; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.kxml2.io.KXmlParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class InstallFromListActivity<T> extends CommCareActivity<T> implements HttpResponseProcessor { private static final String TAG = InstallFromListActivity.class.getSimpleName(); public static final String PROFILE_REF = "profile-ref-selected"; private static final String REQUESTED_FROM_PROD_KEY = "have-requested-from-prod"; private static final String REQUESTED_FROM_INDIA_KEY = "have-requested-from-india"; private static final String ERROR_MESSAGE_KEY = "error-message-key"; private static final String AUTH_MODE_KEY = "auth-mode-key"; private static final String PROD_URL = "https: private static final String INDIA_URL = "https://india.commcarehq.org/phone/list_apps"; private static final int RETRIEVE_APPS_FOR_DIFF_USER = Menu.FIRST; private boolean inMobileUserAuthMode; private boolean requestedFromProd; private boolean requestedFromIndia; private String urlCurrentlyRequestingFrom; private String errorMessage; private View authenticateView; private TextView errorMessageBox; private View appsListContainer; private ListView appsListView; private List<AppAvailableToInstall> availableApps = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setInitialValues(savedInstanceState); setupUI(); if (errorMessage != null) { enterErrorState(errorMessage); } loadPreviouslyRetrievedAvailableApps(); } private void setupUI() { setContentView(R.layout.user_get_available_apps); errorMessageBox = (TextView)findViewById(R.id.error_message); authenticateView = findViewById(R.id.authenticate_view); setUpGetAppsButton(); setUpAppsList(); setUpToggle(); setProperAuthView(); } private void setUpGetAppsButton() { Button getAppsButton = (Button)findViewById(R.id.get_apps_button); getAppsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { errorMessageBox.setVisibility(View.INVISIBLE); if (inputIsValid()) { if (ConnectivityStatus.isNetworkAvailable(InstallFromListActivity.this)) { authenticateView.setVisibility(View.GONE); requestedFromIndia = false; requestedFromProd = false; requestAppList(); } else { enterErrorState(Localization.get("updates.check.network_unavailable")); } } } }); } private void setUpAppsList() { appsListContainer = findViewById(R.id.apps_list_container); appsListView = (ListView)findViewById(R.id.apps_list_view); appsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position < availableApps.size()) { AppAvailableToInstall app = availableApps.get(position); Intent i = new Intent(getIntent()); i.putExtra(PROFILE_REF, app.getMediaProfileRef()); setResult(RESULT_OK, i); finish(); } } }); } private void setUpToggle() { FrameLayout toggleContainer = (FrameLayout)findViewById(R.id.toggle_button_container); CompoundButton userTypeToggler; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { Switch switchButton = new Switch(this); switchButton.setTextOff(Localization.get("toggle.web.user.mode")); switchButton.setTextOn(Localization.get("toggle.mobile.user.mode")); userTypeToggler = switchButton; } else { ToggleButton toggleButton = new ToggleButton(this); toggleButton.setTextOff(Localization.get("toggle.web.user.mode")); toggleButton.setTextOn(Localization.get("toggle.mobile.user.mode")); userTypeToggler = toggleButton; } // Important for this call to come first; we don't want the listener to be invoked on the // first auto-setting, just on user-triggered ones userTypeToggler.setChecked(inMobileUserAuthMode); userTypeToggler.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { inMobileUserAuthMode = isChecked; setProperAuthView(); errorMessage = null; errorMessageBox.setVisibility(View.INVISIBLE); ((EditText)findViewById(R.id.edit_password)).setText(""); } }); toggleContainer.addView(userTypeToggler); } private void setProperAuthView() { final View mobileUserView = findViewById(R.id.mobile_user_view); final View webUserView = findViewById(R.id.web_user_view); if (inMobileUserAuthMode) { mobileUserView.setVisibility(View.VISIBLE); webUserView.setVisibility(View.GONE); } else { mobileUserView.setVisibility(View.GONE); webUserView.setVisibility(View.VISIBLE); } } private boolean inputIsValid() { String enteredPassword = ((EditText)findViewById(R.id.edit_password)).getText().toString(); if ("".equals(enteredPassword)) { enterErrorState(Localization.get("missing.fields")); return false; } if (inMobileUserAuthMode) { String enteredMobileUser = ((EditText)findViewById(R.id.edit_username)).getText().toString(); String enteredDomain = ((EditText)findViewById(R.id.edit_domain)).getText().toString(); if ("".equals(enteredMobileUser) || "".equals(enteredDomain)) { enterErrorState(Localization.get("missing.fields")); return false; } } else { String enteredEmail = ((EditText)findViewById(R.id.edit_email)).getText().toString(); if ("".equals(enteredEmail)) { enterErrorState(Localization.get("missing.fields")); return false; } if (!enteredEmail.contains("@")) { enterErrorState(Localization.get("email.address.invalid")); return false; } } return true; } private void setInitialValues(Bundle savedInstanceState) { if (savedInstanceState != null) { requestedFromIndia = savedInstanceState.getBoolean(REQUESTED_FROM_INDIA_KEY); requestedFromProd = savedInstanceState.getBoolean(REQUESTED_FROM_PROD_KEY); errorMessage = savedInstanceState.getString(ERROR_MESSAGE_KEY); inMobileUserAuthMode = savedInstanceState.getBoolean(AUTH_MODE_KEY); } else { inMobileUserAuthMode = true; } } @Override protected void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putBoolean(REQUESTED_FROM_INDIA_KEY, requestedFromIndia); savedInstanceState.putBoolean(REQUESTED_FROM_PROD_KEY, requestedFromProd); savedInstanceState.putString(ERROR_MESSAGE_KEY, errorMessage); savedInstanceState.putBoolean(AUTH_MODE_KEY, inMobileUserAuthMode); } /** * * @return whether a request was initiated */ private boolean requestAppList() { URL urlToTry = getURLToTry(); if (urlToTry != null) { final View processingRequestView = findViewById(R.id.processing_request_view); SimpleHttpTask task = new SimpleHttpTask(this, urlToTry, new HashMap<String, String>(), false, new Pair<>(getUsernameForAuth(), ((EditText)findViewById(R.id.edit_password)).getText().toString())) { @Override protected void onPreExecute() { super.onPreExecute(); processingRequestView.setVisibility(View.VISIBLE); } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); processingRequestView.setVisibility(View.GONE); } }; task.connect((CommCareTaskConnector)this); task.setResponseProcessor(this); setAttemptedRequestFlag(); task.executeParallel(); return true; } return false; } private String getUsernameForAuth() { if (inMobileUserAuthMode) { String username = ((EditText)findViewById(R.id.edit_username)).getText().toString(); String domain = ((EditText)findViewById(R.id.edit_domain)).getText().toString(); return username + "@" + domain + ".commcarehq.org"; } else { return ((EditText)findViewById(R.id.edit_email)).getText().toString(); } } private void setAttemptedRequestFlag() { if (PROD_URL.equals(urlCurrentlyRequestingFrom)) { requestedFromProd = true; } else { requestedFromIndia = true; } } private URL getURLToTry() { if (!requestedFromProd) { urlCurrentlyRequestingFrom = PROD_URL; } else if (!requestedFromIndia) { urlCurrentlyRequestingFrom = INDIA_URL; } else { return null; } try { return new URL(urlCurrentlyRequestingFrom); } catch (MalformedURLException e) { // This shouldn't ever happen because the URL is static Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW, "Encountered exception while creating " + "URL for apps list request"); return null; } } private void enterErrorState(String message) { errorMessage = message; authenticateView.setVisibility(View.VISIBLE); errorMessageBox.setVisibility(View.VISIBLE); errorMessageBox.setText(errorMessage); findViewById(R.id.auth_scroll_view).scrollTo(0, errorMessageBox.getBottom()); } @Override public void processSuccess(int responseCode, InputStream responseData) { processResponseIntoAppsList(responseData); repeatRequestOrShowResults(false); } private void processResponseIntoAppsList(InputStream responseData) { try { KXmlParser baseParser = ElementParser.instantiateParser(responseData); List<AppAvailableToInstall> apps = (new AvailableAppsParser(baseParser)).parse(); availableApps.addAll(apps); } catch (IOException | InvalidStructureException | XmlPullParserException | UnfullfilledRequirementsException e) { Logger.log(AndroidLogger.TYPE_RESOURCES, "Error encountered while parsing apps available for install"); } } @Override public void processRedirection(int responseCode) { handleRequestError(responseCode); } @Override public void processClientError(int responseCode) { handleRequestError(responseCode); } @Override public void processServerError(int responseCode) { handleRequestError(responseCode); } @Override public void processOther(int responseCode) { handleRequestError(responseCode); } @Override public void handleIOException(IOException exception) { repeatRequestOrShowResults(true); } private void handleRequestError(int responseCode) { Log.e(TAG, "Request to " + urlCurrentlyRequestingFrom + " in get available apps request " + "had error code response: " + responseCode); repeatRequestOrShowResults(true); } private void repeatRequestOrShowResults(final boolean responseWasError) { if (!requestAppList()) { // Means we've tried requesting to both endpoints this.runOnUiThread(new Runnable() { @Override public void run() { if (availableApps.size() == 0) { if (responseWasError) { enterErrorState(Localization.get("invalid.fields.entered." + (inMobileUserAuthMode ? "mobile" : "web"))); } else { enterErrorState(Localization.get("no.apps.available")); } } else { showResults(); } } }); } } private void showResults() { appsListContainer.setVisibility(View.VISIBLE); authenticateView.setVisibility(View.GONE); appsListView.setAdapter(new ArrayAdapter<AppAvailableToInstall>(this, android.R.layout.simple_list_item_1, availableApps) { @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; Context context = InstallFromListActivity.this; if (v == null) { v = View.inflate(context, R.layout.single_available_app_view, null); } AppAvailableToInstall app = this.getItem(position); TextView appName = (TextView)v.findViewById(R.id.app_name); appName.setText(app.getAppName()); TextView domain = (TextView)v.findViewById(R.id.domain); domain.setText(app.getDomainName()); return v; } }); rebuildOptionsMenu(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, RETRIEVE_APPS_FOR_DIFF_USER, 0, Localization.get("menu.app.list.install.other.user")); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); menu.findItem(RETRIEVE_APPS_FOR_DIFF_USER) .setVisible(appsListContainer.getVisibility() == View.VISIBLE); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == RETRIEVE_APPS_FOR_DIFF_USER) { clearPreviouslyRetrievedApps(); availableApps.clear(); appsListContainer.setVisibility(View.GONE); authenticateView.setVisibility(View.VISIBLE); clearAllFields(); rebuildOptionsMenu(); return true; } return super.onOptionsItemSelected(item); } private void clearAllFields() { ((TextView)findViewById(R.id.edit_username)).setText(""); ((TextView)findViewById(R.id.edit_password)).setText(""); ((TextView)findViewById(R.id.edit_domain)).setText(""); ((TextView)findViewById(R.id.edit_email)).setText(""); } private void loadPreviouslyRetrievedAvailableApps() { for (AppAvailableToInstall availableApp : storage()) { this.availableApps.add(availableApp); } if (this.availableApps.size() > 0) { showResults(); } } private void clearPreviouslyRetrievedApps() { storage().removeAll(); } private SqlStorage<AppAvailableToInstall> storage() { return CommCareApplication.instance() .getGlobalStorage(AppAvailableToInstall.STORAGE_KEY, AppAvailableToInstall.class); } }
package org.commcare.dalvik.application; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import org.commcare.dalvik.R; import org.commcare.dalvik.activities.AppManagerActivity; public class ManagerShortcut extends Activity { @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); Intent shortcutIntent = new Intent(getApplicationContext(), AppManagerActivity.class); shortcutIntent.addCategory(Intent.CATEGORY_HOME); Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.manager_activity_name)); Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); setResult(RESULT_OK, intent); finish(); } }
package net.squanchy.contest; import android.app.Activity; import android.view.ViewGroup; @SuppressWarnings("unused") // This is a no-op version for a debug facility class ContestTester { ContestTester(Activity activity) { // No-op (only does stuff in debug) } boolean testingEnabled() { return false; } void appendDebugControls(ViewGroup container, ContestService contestService) { // No-op (only does stuff in debug) } }
package BeanBagger; import com.sun.tools.attach.AttachNotSupportedException; import com.sun.tools.attach.VirtualMachine; import com.sun.tools.attach.VirtualMachineDescriptor; import java.io.BufferedWriter; import java.util.Set; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.management.*; import javax.management.ObjectInstance; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; /** * * @author s.ostenberg */ public class BeanBagger { private static final String CONNECTOR_ADDRESS_PROPERTY = "com.sun.management.jmxremote.localConnectorAddress"; public static VirtualMachineDescriptor TARGETDESCRIPTOR ; static JMXConnector myJMXconnector = null; //replace these with MBean // public static String TargetJVM = ""; //public static String TARGETBEAN = ""; // public static boolean ExactMatchRequired = false; // ALlows matching TargetVM process based on substring // public static String OUTFILE = "//tmp//output.yml"; // public static boolean suppresscomplex=true; // public static boolean ignoreunreadable=false; // public static boolean supressSun=false; // public static String JSONFile = "";//The file we will output to. // public static boolean outJSON=false;//Turn on JSON output // public static boolean prettyprint=false; /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { //Get the MBean server MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); //register the MBean BBConfig mBean = new BBConfig(); ObjectName name = new ObjectName("com.stiv.jmx:type=SystemConfig"); mbs.registerMBean(mBean, name); for(int x =0;x<args.length;x++) { String disarg = args[x]; switch(disarg) { case "-p": if(x==args.length && !args[x+1].startsWith("-"))Usage(); mBean.setTargetJVM(args[x+1]); x++; break; case "-ppj" : mBean.setoutJSON(true); mBean.setprettyprint(true); break; case "-j": mBean.setoutJSON(true); if(args.length-1>x && !args[x+1].startsWith("-"))//If next item on line exists and is not an option { mBean.setJSONFile(args[x+1]); x++; } break; case "-b": if(args.length-1>x && !args[x+1].startsWith("-")) { mBean.setTARGETBEAN(args[x+1]); x++; } break; case "-r": mBean.setignoreunreadable(true); break; case "-q": mBean.setsuppresscomplex(false); break; case "-m": mBean.setsupressSun(true); break; case "-x": mBean.setExactMatchRequired(true); break; case "-log": if(args.length-1>x && !args[x+1].startsWith("-"))//If next item on line exists and is not an option { mBean.setLogDir(args[x+1]); try { File theDir = new File(mBean.getLogDir()); // if the directory does not exist, create it if (!theDir.exists()) { System.out.println("creating directory: " + mBean.getLogDir()); theDir.mkdir(); } } catch(Exception ex) { System.out.println("Error creating directory: " + mBean.getLogDir()); System.exit(1); } // Write a readme file to the directory as a test try{ String rmf = mBean.getLogDir() + "/BeanBaggerreadme.txt"; try (PrintWriter out = new PrintWriter(rmf)) { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); out.println("Beanbagger started " + dateFormat.format(date) ); //consider adding options outlining the arguments started with. out.close(); } } catch(Exception ex){ System.out.println("Error creating files in: " + mBean.getLogDir()); } x++; } break; case "-l": mBean.setLoop(true); if(args.length-1>x && !args[x+1].startsWith("-")) { try{ mBean.setLoopDelaySeconds(Integer.parseInt(args[x+1]));} catch(Exception ex){ System.out.println("You call " + args[x+1] + " an integer" +mBean.getInsult()+"?"); Usage(); } x++; } else{mBean.setLoopDelaySeconds(30); } break; case "-c": mBean.setLoop(true); if(args.length-1>x && !args[x+1].startsWith("-")) { try{ mBean.setIterations(Integer.parseInt(args[x+1]));} catch(Exception ex){ System.out.println("You call " + args[x+1] + " an integer" +mBean.getInsult()+"?"); Usage(); } x++; } else{mBean.setIterations(5);} break; default: Usage(); }//End switch } //Variables have been set. We are done with intitial config Boolean loopagain=false; do { //Here we go, into da loop try { Map<String, VirtualMachine> result = new HashMap<>(); List<VirtualMachineDescriptor> list = VirtualMachine.list(); List<VirtualMachineDescriptor> MATCHINGLIST = new ArrayList<VirtualMachineDescriptor>(); Boolean gotit = false; String listofjvs = ""; System.out.println("Searching for matching VM instances"); for (VirtualMachineDescriptor vmd : list) { String desc = vmd.toString(); try { result.put(desc, VirtualMachine.attach(vmd)); String DN = vmd.displayName(); if (DN.contains(mBean.getTargetJVM()) || mBean.getTargetJVM().equalsIgnoreCase("*")) { if (DN.equals("")) { System.out.println(" Skipping unnamed JVM"); } //else if(!TargetJVM.startsWith("BeanBagger") && DN.contains("BeanBagger")){ System.out.println(" Skipping BeanBagger JVM"); } else { System.out.println(" Matching JVM instance found: " + DN); TARGETDESCRIPTOR = vmd; gotit = true; MATCHINGLIST.add(vmd); } } else { listofjvs += DN + " \n"; } } catch (IOException | AttachNotSupportedException e) { } } if (!gotit)//If we dont find the instance. { System.out.println("No JVM Processes matching " + mBean.getTargetJVM() + " were found."); System.out.println("Found instances: " + listofjvs); System.exit(1); } System.out.println(""); org.json.JSONObject Jinfrascan = new org.json.JSONObject();//Contains Hosts org.json.JSONArray Hosts = new org.json.JSONArray(); org.json.JSONObject Host = new org.json.JSONObject(); org.json.JSONArray JVMs = new org.json.JSONArray();//JVMs on host for (VirtualMachineDescriptor avmd : MATCHINGLIST) { myJMXconnector = getLocalConnection(VirtualMachine.attach(avmd));// Connects to the process containing our beans MBeanServerConnection myJMXConnection = myJMXconnector.getMBeanServerConnection(); //Connects to the MBean server for that process. System.out.println("Number of beans found in " + avmd.displayName() + ":" + myJMXConnection.getMBeanCount()); String getDefaultDomain = myJMXConnection.getDefaultDomain(); String[] getDomains = myJMXConnection.getDomains(); Set<ObjectInstance> beans = myJMXConnection.queryMBeans(null, null); org.json.JSONObject JVM = new org.json.JSONObject(); org.json.JSONArray JBeans = new org.json.JSONArray(); for (ObjectInstance instance : beans) { String daclassname = instance.getClassName(); if (mBean.getsupressSun() & (daclassname.startsWith("sun.") | daclassname.startsWith("com.sun."))) { continue; } if (daclassname.contains(mBean.getTARGETBEAN()) || mBean.getTARGETBEAN().contentEquals("*")) { MBeanAttributeInfo[] myAttributeArray = null; org.json.JSONObject Beanboy = new org.json.JSONObject(); org.json.JSONArray BeanieButes = new org.json.JSONArray(); try { MBeanInfo info = myJMXConnection.getMBeanInfo(instance.getObjectName()); myAttributeArray = info.getAttributes(); System.out.println(" Processing me a bean: " + daclassname); } catch (UnsupportedOperationException | RuntimeMBeanException | IllegalStateException ex) { System.out.println(" Error processing bean: " + daclassname); } for (MBeanAttributeInfo thisAttributeInfo : myAttributeArray) { String attvalue = ""; String myname = ""; String mytype = ""; String mydesc = ""; boolean myread = false; boolean mywrite = false; try { myname = thisAttributeInfo.getName(); mydesc = thisAttributeInfo.getDescription(); mytype = thisAttributeInfo.getType(); myread = thisAttributeInfo.isReadable(); mywrite = thisAttributeInfo.isWritable(); if (myread) { switch (mytype) { case "String": attvalue = (String) myJMXConnection.getAttribute(instance.getObjectName(), myname); break; case "java.lang.String": attvalue = (String) myJMXConnection.getAttribute(instance.getObjectName(), myname); break; case "boolean": attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString(); break; case "int": attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString(); break; case "long": attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString(); break; case "double": attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString(); break; default: attvalue = "*-Unsupported: complex type-*"; break; }//end switch }//end if else { attvalue = ""; } } catch (Exception ex) { attvalue = "*-Exception accessing value-*"; } //THis section is where we determine if we are going to record the value or not. boolean dooutput = false; if (mBean.getsuppresscomplex()) { dooutput = true; } else { try { if (!attvalue.startsWith("*-")) { dooutput = true; } } catch (Exception ex)//For attributes with no values. { attvalue = "*-No value-*"; dooutput = true; } } if (mBean.getignoreunreadable() && !myread) { dooutput = false; } if (dooutput) { org.json.JSONObject AtDatas = new org.json.JSONObject();// Create the list of attributes and values into an object. AtDatas.put("Name", myname); AtDatas.put("Type", mytype); if (myread) { AtDatas.put("Value", attvalue); System.out.println(" Name:" + myname + " Type:" + mytype + " Value:" + attvalue + " Writeable:" + mywrite); } else { System.out.println(" Name:" + myname + " Type:" + mytype + " Readable:" + myread + " Writeable:" + mywrite); AtDatas.put("Readable", myread); } AtDatas.put("Desc", mydesc); if (mywrite) { AtDatas.put("Writable", mywrite); } BeanieButes.put(AtDatas); } }//End processing Bean Attributes, add attributes to bean array. Beanboy.put(daclassname, BeanieButes);//add attributes to the bean JBeans.put(Beanboy);//add bean to VM }//End if this bean was skipped. }//End of process JVM instance beans JVM.put(avmd.displayName(), JBeans); JVMs.put(JVM); }//End JVM iteration java.net.InetAddress addr = java.net.InetAddress.getLocalHost(); String mename = addr.getHostName(); Host.put(mename, JVMs); //add vms to host Hosts.put(Host); //add server(s) to infra String time = String.valueOf(System.currentTimeMillis()); Jinfrascan.put(time, Hosts); // OK. How do I dump the JSON? if (mBean.getoutJSON()) { if (!mBean.getJSONFile().equals("")) { try { PrintWriter writer = new PrintWriter(mBean.getJSONFile(), "UTF-8"); if (mBean.getprettyprint()) { writer.println(Jinfrascan.toString(4)); } else { writer.println(Jinfrascan); } writer.close(); } catch (Exception ex) { System.out.print("Error processing file!"); System.out.print(ex); } } else { System.out.println("JSON Output:"); if (mBean.getprettyprint()) { System.out.print(Jinfrascan.toString(4)); } else { System.out.print(Jinfrascan); } } } if(mBean.getDoLogging()) { String rmf = mBean.getLogDir() + "/BeanBagger" + time + ".txt"; PrintWriter writer = new PrintWriter(rmf, "UTF-8"); if (mBean.getprettyprint()) { writer.println(Jinfrascan.toString(4)); } else { writer.println(Jinfrascan); } writer.close(); } } catch (Exception exception) { //Error handling to come. } loopagain=false; if(mBean.getLoop())loopagain=true; if( mBean.getIterations()>0 && mBean.getIterationsCount() < mBean.getIterations()){//If we are counting and havent reached limit loopagain=true; } if( mBean.getIterations()>0 && mBean.getIterationsCount() >= mBean.getIterations()){//If we are counting and havent reached limit loopagain=false; } if(!mBean.getLoop())loopagain=false; //If mBean says stop looping, stop it! if(loopagain){ System.out.println("Sleeping " + mBean.getLoopDelaySeconds() + " seconds. This was run " + mBean.getIterationsCount()); mBean.setIterationsCount(mBean.getIterationsCount() + 1); TimeUnit.SECONDS.sleep(mBean.getLoopDelaySeconds()); } } while (loopagain); System.out.println(""); System.out.println("Stiv's Beanbagger Finished"); } public static void Usage() { System.out.println("java -jar Beanbagger [-p {process}] [-b {bean}] -q -m [-j {filename}] -ppj"); System.out.println(" -p {process}: VM Process Name or substring of process to try to connect to. Defaults to all"); System.out.println(" -b {bean}: Restrict data to just one bean. Default is all beans "); System.out.println(" -j {optionalfilename}: Output results to single file in JSON format, or to console if no file specified."); System.out.println(" File will be overwritten each pass."); System.out.println(" -x :Requires exact match of VM Process Name"); System.out.println(" -q :Filter. Suppresses output of unsupported types or operations."); System.out.println(" -m :Filter. Suppresses iteration of Sun beans (sun.* and com.sun.*"); System.out.println(" -r :Filter. Suppresses logging of unreadable attributes"); System.out.println(" -l {seconds} :Loop continously. After completion, the dump will rerun in x seconds, default is 30"); System.out.println(" -c {iterations} :Count number of times to run. -c with no options sets to 5. Automatically sets -l"); System.out.println(" -ppj : Prettyprint JSON output, sets -j but not j- filename." ); System.out.println(" -log {logdir} : Write each pass to a new file in logdir with epoch time in the filename." ); System.out.println("\nProcesses found:"); List<VirtualMachineDescriptor> list = VirtualMachine.list(); for (VirtualMachineDescriptor vmd: list) { if(vmd.displayName().equals("")) { System.out.println(" {Unamed Instance}"); } else { System.out.println(" "+ vmd.displayName()); } } System.out.println(""); System.exit(1); } static JMXConnector getLocalConnection(VirtualMachine vm) throws Exception { Properties props = vm.getAgentProperties(); String connectorAddress = props.getProperty(CONNECTOR_ADDRESS_PROPERTY); if (connectorAddress == null) { props = vm.getSystemProperties(); String home = props.getProperty("java.home"); String agent = home + File.separator + "lib" + File.separator + "management-agent.jar"; vm.loadAgent(agent); props = vm.getAgentProperties(); connectorAddress = props.getProperty(CONNECTOR_ADDRESS_PROPERTY); } JMXServiceURL url = new JMXServiceURL(connectorAddress); return JMXConnectorFactory.connect(url); } }
package subobjectjava.translate; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import jnome.core.expression.invocation.ConstructorInvocation; import jnome.core.expression.invocation.JavaMethodInvocation; import jnome.core.expression.invocation.NonLocalJavaTypeReference; import jnome.core.expression.invocation.SuperConstructorDelegation; import jnome.core.language.Java; import jnome.core.modifier.Implements; import jnome.core.type.BasicJavaTypeReference; import jnome.core.type.JavaTypeReference; import org.rejuse.association.Association; import org.rejuse.association.SingleAssociation; import org.rejuse.logic.ternary.Ternary; import org.rejuse.predicate.SafePredicate; import org.rejuse.predicate.UnsafePredicate; import org.rejuse.property.Property; import subobjectjava.model.component.AbstractClause; import subobjectjava.model.component.ActualComponentArgument; import subobjectjava.model.component.ComponentNameActualArgument; import subobjectjava.model.component.ComponentParameter; import subobjectjava.model.component.ComponentParameterTypeReference; import subobjectjava.model.component.ComponentRelation; import subobjectjava.model.component.ComponentRelationSet; import subobjectjava.model.component.ComponentType; import subobjectjava.model.component.ConfigurationBlock; import subobjectjava.model.component.ConfigurationClause; import subobjectjava.model.component.FormalComponentParameter; import subobjectjava.model.component.InstantiatedComponentParameter; import subobjectjava.model.component.MultiActualComponentArgument; import subobjectjava.model.component.MultiFormalComponentParameter; import subobjectjava.model.component.ParameterReferenceActualArgument; import subobjectjava.model.component.RenamingClause; import subobjectjava.model.expression.AbstractTarget; import subobjectjava.model.expression.ComponentParameterCall; import subobjectjava.model.expression.SubobjectConstructorCall; import subobjectjava.model.language.JLo; import subobjectjava.model.type.RegularJLoType; import chameleon.core.compilationunit.CompilationUnit; import chameleon.core.declaration.Declaration; import chameleon.core.declaration.QualifiedName; import chameleon.core.declaration.Signature; import chameleon.core.declaration.SimpleNameDeclarationWithParametersHeader; import chameleon.core.declaration.SimpleNameDeclarationWithParametersSignature; import chameleon.core.declaration.SimpleNameSignature; import chameleon.core.declaration.TargetDeclaration; import chameleon.core.element.Element; import chameleon.core.expression.Expression; import chameleon.core.expression.InvocationTarget; import chameleon.core.expression.MethodInvocation; import chameleon.core.expression.NamedTarget; import chameleon.core.expression.NamedTargetExpression; import chameleon.core.lookup.DeclarationSelector; import chameleon.core.lookup.LookupException; import chameleon.core.lookup.SelectorWithoutOrder; import chameleon.core.member.Member; import chameleon.core.method.Implementation; import chameleon.core.method.Method; import chameleon.core.method.RegularImplementation; import chameleon.core.method.RegularMethod; import chameleon.core.method.exception.ExceptionClause; import chameleon.core.modifier.ElementWithModifiers; import chameleon.core.modifier.Modifier; import chameleon.core.namespace.NamespaceElement; import chameleon.core.namespacepart.Import; import chameleon.core.namespacepart.NamespacePart; import chameleon.core.namespacepart.TypeImport; import chameleon.core.property.ChameleonProperty; import chameleon.core.reference.CrossReference; import chameleon.core.reference.CrossReferenceWithArguments; import chameleon.core.reference.CrossReferenceWithName; import chameleon.core.reference.CrossReferenceWithTarget; import chameleon.core.reference.SimpleReference; import chameleon.core.reference.SpecificReference; import chameleon.core.statement.Block; import chameleon.core.variable.FormalParameter; import chameleon.core.variable.VariableDeclaration; import chameleon.core.variable.VariableDeclarator; import chameleon.exception.ChameleonProgrammerException; import chameleon.exception.ModelException; import chameleon.oo.language.ObjectOrientedLanguage; import chameleon.oo.type.BasicTypeReference; import chameleon.oo.type.DeclarationWithType; import chameleon.oo.type.ParameterBlock; import chameleon.oo.type.RegularType; import chameleon.oo.type.Type; import chameleon.oo.type.TypeElement; import chameleon.oo.type.TypeReference; import chameleon.oo.type.TypeWithBody; import chameleon.oo.type.generics.ActualType; import chameleon.oo.type.generics.BasicTypeArgument; import chameleon.oo.type.generics.InstantiatedTypeParameter; import chameleon.oo.type.generics.TypeParameter; import chameleon.oo.type.generics.TypeParameterBlock; import chameleon.oo.type.inheritance.AbstractInheritanceRelation; import chameleon.oo.type.inheritance.SubtypeRelation; import chameleon.support.expression.AssignmentExpression; import chameleon.support.expression.SuperTarget; import chameleon.support.expression.ThisLiteral; import chameleon.support.member.simplename.SimpleNameMethodInvocation; import chameleon.support.member.simplename.method.NormalMethod; import chameleon.support.member.simplename.method.RegularMethodInvocation; import chameleon.support.member.simplename.variable.MemberVariableDeclarator; import chameleon.support.modifier.Final; import chameleon.support.modifier.Interface; import chameleon.support.modifier.Public; import chameleon.support.statement.ReturnStatement; import chameleon.support.statement.StatementExpression; import chameleon.support.statement.ThrowStatement; import chameleon.support.variable.LocalVariableDeclarator; import chameleon.util.Util; public class JavaTranslator { public List<CompilationUnit> translate(CompilationUnit source, CompilationUnit implementationCompilationUnit) throws LookupException, ModelException { List<CompilationUnit> result = new ArrayList<CompilationUnit>(); // Remove a possible old translation of the given compilation unit // from the target model. NamespacePart originalNamespacePart = source.namespaceParts().get(0); NamespacePart newNamespacePart = implementationCompilationUnit.namespaceParts().get(0); Iterator<Type> originalTypes = originalNamespacePart.children(Type.class).iterator(); Iterator<Type> newTypes = newNamespacePart.children(Type.class).iterator(); while(originalTypes.hasNext()) { SingleAssociation<Type, Element> newParentLink = newTypes.next().parentLink(); Type translated = translatedImplementation(originalTypes.next()); newParentLink.getOtherRelation().replace(newParentLink, translated.parentLink()); } // newNamespacePart.clearImports(); for(Import imp: originalNamespacePart.imports()) { newNamespacePart.addImport(imp.clone()); } implementationCompilationUnit.flushCache(); result.add(implementationCompilationUnit); implementationCompilationUnit.namespacePart(1).getNamespaceLink().lock(); CompilationUnit interfaceCompilationUnit = interfaceCompilationUnit(source, implementationCompilationUnit); for(NamespacePart part: implementationCompilationUnit.descendants(NamespacePart.class)) { part.removeDuplicateImports(); } for(NamespacePart part: interfaceCompilationUnit.descendants(NamespacePart.class)) { part.removeDuplicateImports(); } result.add(interfaceCompilationUnit); return result; } private boolean isJLo(NamespaceElement element) { String fullyQualifiedName = element.getNamespace().getFullyQualifiedName(); return (! fullyQualifiedName.startsWith("java.")) && (! fullyQualifiedName.startsWith("javax.")) && (! fullyQualifiedName.equals("org.ietf.jgss")) && (! fullyQualifiedName.equals("org.omg.CORBA")) && (! fullyQualifiedName.equals("org.omg.CORBA_2_3")) && (! fullyQualifiedName.equals("org.omg.CORBA_2_3.portable")) && (! fullyQualifiedName.equals("org.omg.CORBA.DynAnyPackage")) && (! fullyQualifiedName.equals("org.omg.CORBA.ORBPackage")) && (! fullyQualifiedName.equals("org.omg.CORBA.Portable")) && (! fullyQualifiedName.equals("org.omg.CORBA.TypeCodePackage")) && (! fullyQualifiedName.equals("org.omg.CosNaming")) && (! fullyQualifiedName.equals("org.omg.CosNaming.NamingContextExtPackage")) && (! fullyQualifiedName.equals("org.omg.CosNaming.NamingContextPackage")) && (! fullyQualifiedName.equals("org.omg.Dynamic")) && (! fullyQualifiedName.equals("org.omg.DynamicAny")) && (! fullyQualifiedName.equals("org.omg.DynamicAny.DynAnyFactoryPackage")) && (! fullyQualifiedName.equals("org.omg.DynamicAny.DynAnyPackage")) && (! fullyQualifiedName.equals("org.omg.IOP")) && (! fullyQualifiedName.equals("org.omg.IOP.CodecFactoryPackage")) && (! fullyQualifiedName.equals("org.omg.IOP.CodecPackage")) && (! fullyQualifiedName.equals("org.omg.Messaging")) && (! fullyQualifiedName.equals("org.omg.PortableInterceptor")) && (! fullyQualifiedName.equals("org.omg.PortableInterceptor.ORBInitInfoPackage")) && (! fullyQualifiedName.equals("org.omg.PortableServer")) && (! fullyQualifiedName.equals("org.omg.PortableServer.CurrentPackage")) && (! fullyQualifiedName.equals("org.omg.PortableServer.PAOManagerPackage")) && (! fullyQualifiedName.equals("org.omg.PortableServer.PAOPackage")) && (! fullyQualifiedName.equals("org.omg.PortableServer.portable")) && (! fullyQualifiedName.equals("org.omg.PortableServer.ServantLocatorPackage")) && (! fullyQualifiedName.equals("org.omg.SendingContext")) && (! fullyQualifiedName.equals("org.omg.stub.java.rmi")) && (! fullyQualifiedName.equals("org.w3c.dom")) && (! fullyQualifiedName.equals("org.w3c.dom.bootstrap")) && (! fullyQualifiedName.equals("org.w3c.dom.events")) && (! fullyQualifiedName.equals("org.w3c.dom.ls")) && (! fullyQualifiedName.equals("org.xml.sax")) && (! fullyQualifiedName.equals("org.xml.sax.ext")) && (! fullyQualifiedName.equals("org.xml.sax.helpers")); } private CompilationUnit interfaceCompilationUnit(CompilationUnit original, CompilationUnit implementation) throws ModelException { original.flushCache(); implementation.flushCache(); CompilationUnit interfaceCompilationUnit = implementation.cloneTo(implementation.language()); NamespacePart interfaceNamespacePart = interfaceCompilationUnit.namespacePart(1); Type interfaceType = interfaceNamespacePart.declarations(Type.class).get(0); interfaceType.addModifier(new Interface()); transformToInterfaceDeep(interfaceType); for(BasicJavaTypeReference tref: interfaceType.descendants(BasicJavaTypeReference.class)) { String name = tref.signature().name(); if(name.endsWith(IMPL)) { tref.setSignature(new SimpleNameSignature(interfaceName(name))); } } interfaceCompilationUnit.flushCache(); return interfaceCompilationUnit; } private void rewriteConstructorCalls(Element<?> type) throws LookupException { Java language = type.language(Java.class); List<ConstructorInvocation> invocations = type.descendants(ConstructorInvocation.class); for(ConstructorInvocation invocation: invocations) { try { Type constructedType = invocation.getType(); if(isJLo(constructedType) && (! constructedType.isTrue(language.PRIVATE))) { transformToImplReference((CrossReferenceWithName) invocation.getTypeReference()); } } catch(LookupException exc) { transformToImplReference((CrossReferenceWithName) invocation.getTypeReference()); } } } private void rewriteThisLiterals(Element<?> type) throws LookupException { List<ThisLiteral> literals = type.descendants(ThisLiteral.class); for(ThisLiteral literal: literals) { TypeReference typeReference = literal.getTypeReference(); if(typeReference != null) { transformToImplReference((CrossReferenceWithName) typeReference); } } } private void rewriteComponentAccess(Element<?> type) throws LookupException { List<CrossReference> literals = type.descendants(CrossReference.class); for(CrossReference literal: literals) { if((literal instanceof CrossReferenceWithTarget)) { transformComponentAccessors((CrossReferenceWithTarget) literal); } } } private void transformComponentAccessors(CrossReferenceWithTarget cwt) { Element target = cwt.getTarget(); if(target instanceof CrossReferenceWithTarget) { transformComponentAccessors((CrossReferenceWithTarget) target); } boolean rewrite = false; String name = null; if((! (cwt instanceof MethodInvocation)) && (! (cwt instanceof TypeReference))) { name = ((CrossReferenceWithName)cwt).name(); try { Declaration decl = cwt.getElement(); if(decl instanceof ComponentRelation) { rewrite = true; } }catch(LookupException exc) { // rewrite = true; } } if(rewrite) { String getterName = getterName(name); MethodInvocation inv = new JavaMethodInvocation(getterName,(InvocationTarget) target); SingleAssociation parentLink = cwt.parentLink(); parentLink.getOtherRelation().replace(parentLink, inv.parentLink()); } } private void transformToInterfaceDeep(Type type) throws ModelException { List<Type> types = type.descendants(Type.class); types.add(type); for(Type t: types) { transformToInterface(t); } } private void transformToInterface(Type type) throws ModelException { String name = type.getName(); Java language = type.language(Java.class); if(name.endsWith(IMPL)) { copyTypeParametersIfNecessary(type); makePublic(type); List<SubtypeRelation> inheritanceRelations = type.nonMemberInheritanceRelations(SubtypeRelation.class); int last = inheritanceRelations.size() - 1; inheritanceRelations.get(last).disconnect(); for(TypeElement decl: type.directlyDeclaredElements()) { if(decl instanceof Method) { ((Method) decl).setImplementation(null); if(decl.is(language.CLASS) == Ternary.TRUE) { decl.disconnect(); } } if((decl.is(language.CONSTRUCTOR) == Ternary.TRUE) || (decl.is(language.PRIVATE) == Ternary.TRUE) || (decl instanceof VariableDeclarator && (! (decl.is(language.CLASS) == Ternary.TRUE)))) { decl.disconnect(); } // if(decl instanceof ElementWithModifiers) { makePublic(decl); removeFinal(decl); } type.signature().setName(interfaceName(name)); if(! (type.is(language.INTERFACE) == Ternary.TRUE)) { type.addModifier(new Interface()); } } } private void removeFinal(TypeElement<?> element) throws ModelException { Property property = element.language(ObjectOrientedLanguage.class).OVERRIDABLE.inverse(); for(Modifier modifier: element.modifiers(property)) { element.removeModifier(modifier); } } private void copyTypeParametersIfNecessary(Type type) { Type outmost = type.farthestAncestor(Type.class); if(outmost != null) { List<TypeParameter> typeParameters = outmost.parameters(TypeParameter.class); ParameterBlock tpars = type.parameterBlock(TypeParameter.class); if(tpars == null) { type.addParameterBlock(new TypeParameterBlock()); } for(TypeParameter<?> typeParameter:typeParameters) { type.addParameter(TypeParameter.class, typeParameter.clone()); } } } private void makePublic(ElementWithModifiers<?> element) throws ModelException { Java language = element.language(Java.class); Property access = element.property(language.SCOPE_MUTEX); if(access != language.PRIVATE) { for(Modifier mod: element.modifiers(language.SCOPE_MUTEX)) { mod.disconnect(); } element.addModifier(new Public()); } } private void transformToImplReference(CrossReferenceWithName ref) { if(ref instanceof CrossReferenceWithTarget) { CrossReferenceWithName target = (CrossReferenceWithName) ((CrossReferenceWithTarget)ref).getTarget(); if(target != null) { transformToImplReference(target); } } boolean change; try { Declaration referencedElement = ref.getElement(); if(referencedElement instanceof Type) { change = true; } else { change = false; } } catch(LookupException exc) { change = true; } if(change) { String name = ref.name(); if(! name.endsWith(IMPL)) { ref.setName(name+IMPL); } } } private void transformToInterfaceReference(SpecificReference ref) { SpecificReference target = (SpecificReference) ref.getTarget(); if(target != null) { transformToInterfaceReference(target); } String name = ref.signature().name(); if(name.endsWith(IMPL)) { ref.setSignature(new SimpleNameSignature(interfaceName(name))); } } private String interfaceName(String name) { if(! name.endsWith(IMPL)) { throw new IllegalArgumentException(); } return name.substring(0, name.length()-IMPL.length()); } /** * Return a type that represents the translation of the given JLow class to a Java class. * @throws ModelException */ private Type translatedImplementation(Type original) throws ChameleonProgrammerException, ModelException { Type result = original.clone(); result.setUniParent(original.parent()); List<ComponentRelation> relations = original.directlyDeclaredMembers(ComponentRelation.class); for(ComponentRelation relation : relations) { // Add a getter for subobject Method getterForComponent = getterForComponent(relation,result); if(getterForComponent != null) { result.add(getterForComponent); } // Add a setter for subobject Method setterForComponent = setterForComponent(relation,result); if(setterForComponent != null) { result.add(setterForComponent); } // Create the inner classes for the components inner(result, relation, result,original); result.flushCache(); addOutwardDelegations(relation, result); result.flushCache(); } replaceSuperCalls(result); for(ComponentRelation relation: result.directlyDeclaredMembers(ComponentRelation.class)) { replaceConstructorCalls(relation); MemberVariableDeclarator fieldForComponent = fieldForComponent(relation,result); if(fieldForComponent != null) { result.add(fieldForComponent); } relation.disconnect(); } List<Method> decls = selectorsFor(result); for(Method decl:decls) { result.add(decl); } List<ComponentParameterCall> calls = result.descendants(ComponentParameterCall.class); for(ComponentParameterCall call: calls) { FormalComponentParameter parameter = call.getElement(); MethodInvocation expr = new JavaMethodInvocation(selectorName(parameter),null); expr.addArgument((Expression) call.target()); SingleAssociation pl = call.parentLink(); pl.getOtherRelation().replace(pl, expr.parentLink()); } for(SubtypeRelation rel: result.nonMemberInheritanceRelations(SubtypeRelation.class)) { processSuperComponentParameters(rel); } rebindOverriddenMethods(result,original); addStaticHooksForMethodsOverriddenInSuperSubobject(result,original); addNonOverriddenStaticHooks(result,original); rewriteConstructorCalls(result); rewriteThisLiterals(result); rewriteComponentAccess(result); expandReferences(result); removeNonLocalReferences(result); // The result is still temporarily attached to the original model. transformToImplRecursive(result); result.setUniParent(null); return result; } private void addStaticHooksForMethodsOverriddenInSuperSubobject(Type result,Type original) throws ModelException { for(ComponentRelation relation: original.descendants(ComponentRelation.class)) { addStaticHooksForMethodsOverriddenInSuperSubobject(result,relation); } } @SuppressWarnings("unchecked") private void addStaticHooksForMethodsOverriddenInSuperSubobject(Type result,ComponentRelation relation) throws ModelException { Type container = containerOfDefinition(result, relation.farthestAncestor(Type.class), relation.componentType().signature()); List<Member> members = relation.componentType().members(); Java lang = relation.language(Java.class); ChameleonProperty ov = lang.OVERRIDABLE; ChameleonProperty def = lang.DEFINED; incorporateImports(relation,result.nearestAncestor(NamespacePart.class)); for(Member member: members) { if(member instanceof Method && member.nearestAncestor(ComponentRelation.class) == relation && member.isTrue(ov) && member.isTrue(def) && (!lang.isOperator((Method) member))) { Method newMethod = staticMethod(container, (Method) member); newMethod.setUniParent(member.parent()); incorporateImports(newMethod); substituteTypeParameters(newMethod); newMethod.setUniParent(null); RegularImplementation implementation = (RegularImplementation) newMethod.implementation(); if(implementation == null) { implementation = new RegularImplementation(new Block()); newMethod.setImplementation(implementation); } implementation.getBody().clear(); container.add(newMethod); } } } private void addNonOverriddenStaticHooks(Type result,Type original) throws LookupException { for(ComponentRelation relation: original.descendants(ComponentRelation.class)) { addNonOverriddenStaticHooks(result,relation); } } private void addNonOverriddenStaticHooks(Type result,ComponentRelation relation) throws LookupException { Type root = containerOfDefinition(result, relation.farthestAncestor(Type.class), relation.componentType().signature()); // System.out.println("Root for "+relation.componentType().getFullyQualifiedName()+" is "+root.getFullyQualifiedName()); List<Member> membersOfRelation = relation.componentType().members(); Set<ComponentRelation> overriddenRelations = (Set<ComponentRelation>) relation.overriddenMembers(); } private void rebindOverriddenMethods(Type result, Type original) throws ModelException { for(final Method method: original.descendants(Method.class)) { rebindOverriddenMethodsOf(result, original, method); } } private void rebindOverriddenMethodsOf(Type result, Type original, Method method) throws Error, ModelException { Set<? extends Member> overridden = method.overriddenMembers(); if(! overridden.isEmpty()) { final Method tmp = method.clone(); // Type containerOfNewDefinition = createOrGetInnerTypeForMethod(result, original, method); Type containerOfNewDefinition = containerOfDefinition(result,original, method); if(containerOfNewDefinition != null) { tmp.setUniParent(containerOfNewDefinition); // substituteTypeParameters(method); DeclarationSelector<Method> selector = new SelectorWithoutOrder<Method>(Method.class) { @Override public Signature signature() { return tmp.signature(); } }; Method newDefinitionInResult = null; try { newDefinitionInResult = containerOfNewDefinition.members(selector).get(0); } catch (IndexOutOfBoundsException e) { containerOfNewDefinition = containerOfDefinition(result, original, method); newDefinitionInResult = containerOfNewDefinition.members(selector).get(0); } Method<?,?,?,?> stat = newDefinitionInResult.clone(); String name = staticMethodName(method, containerOfNewDefinition); // String name = staticMethodName(method); stat.setName(name); containerOfNewDefinition.add(stat); if(!stat.descendants(ComponentParameterCall.class).isEmpty()) { throw new Error(); } } } for(Member toBeRebound: overridden) { rebind(result, original, method, (Method) toBeRebound); } } private void rebind(Type container, Type original, Method<?,?,?,?> newDefinition, Method toBeRebound) throws ModelException { Type containerOfNewDefinition = containerOfDefinition(container,original, newDefinition); Type rootOfNewDefinitionInOriginal = levelOfDefinition(newDefinition); List<Element> trailOfRootInOriginal = filterAncestors(rootOfNewDefinitionInOriginal); trailOfRootInOriginal.add(0, rootOfNewDefinitionInOriginal); trailOfRootInOriginal.remove(trailOfRootInOriginal.size()-1); Type containerToAdd = createOrGetInnerTypeAux(container, original, trailOfRootInOriginal,1); List<Element> trailtoBeReboundInOriginal = filterAncestors(toBeRebound); Type rootOfToBeRebound = levelOfDefinition(toBeRebound); while(! (trailtoBeReboundInOriginal.get(trailtoBeReboundInOriginal.size()-1) == rootOfToBeRebound)) { trailtoBeReboundInOriginal.remove(trailtoBeReboundInOriginal.size()-1); } trailtoBeReboundInOriginal.remove(trailtoBeReboundInOriginal.size()-1); Type containerOfToBebound = containerToAdd; if(! trailtoBeReboundInOriginal.isEmpty()) { containerOfToBebound = createOrGetInnerTypeAux(containerToAdd, original, trailtoBeReboundInOriginal,1); } if((containerOfToBebound != null) && ! containerOfToBebound.sameAs(containerOfNewDefinition)) { System.out.println(" System.out.println("Source: "+containerOfNewDefinition.getFullyQualifiedName()+"."+newDefinition.name()); System.out.println("Target: "+containerOfToBebound.getFullyQualifiedName()+"."+toBeRebound.name()); System.out.println(" String thisName = containerOfNewDefinition.getFullyQualifiedName(); Method reboundMethod = createOutward(toBeRebound, newDefinition.name(),thisName); //FIXME this is tricky. reboundMethod.setUniParent(toBeRebound); Implementation<Implementation> impl = reboundMethod.implementation(); reboundMethod.setImplementation(null); substituteTypeParameters(reboundMethod); reboundMethod.setImplementation(impl); reboundMethod.setUniParent(null); containerOfToBebound.add(reboundMethod); Method<?, ?, ?, ?> staticReboundMethod = staticMethod(containerOfToBebound, reboundMethod); String name = containerOfNewDefinition.getFullyQualifiedName().replace('.', '_'); for(SimpleNameMethodInvocation inv:staticReboundMethod.descendants(SimpleNameMethodInvocation.class)) { name = toImplName(name); inv.setName(staticMethodName(newDefinition, containerOfNewDefinition)); } containerOfToBebound.add(staticReboundMethod); containerOfToBebound.flushCache(); } } private Method<?, ?, ?, ?> staticMethod(Type containerOfToBebound, Method<?,?,?,?> reboundMethod) throws ModelException { Method<?,?,?,?> staticReboundMethod = reboundMethod.clone(); staticReboundMethod.setOrigin(reboundMethod); String newName = staticMethodName(reboundMethod,containerOfToBebound); // staticReboundMethod.addModifier(new Final()); ChameleonProperty nat = reboundMethod.language(Java.class).NATIVE; staticReboundMethod.setUniParent(reboundMethod.parent()); for(Modifier modifier: staticReboundMethod.modifiers(nat)) { modifier.disconnect(); } staticReboundMethod.setUniParent(null); staticReboundMethod.setName(newName); return staticReboundMethod; } private String staticMethodName(String methodName,Type containerOfToBebound) { return stripImpl(containerOfToBebound.getFullyQualifiedName().replace('.', '_')+"_"+methodName); } private String staticMethodName(Method clone,Type containerOfToBebound) { return staticMethodName(clone.name(), containerOfToBebound); } private String stripImpl(String string) { return string.replaceAll(IMPL, ""); } // private String staticMethodNameInOriginal(Method method, Type containerOfNewDefinition) { // return containerOfNewDefinition.getFullyQualifiedName().replace('.', '_')+"_"+method.name(); private Type containerOfDefinition(Type container, Type original, Element newDefinition) throws LookupException { Type containerOfNewDefinition = container; Type rootOfNewDefinitionInOriginal = levelOfDefinition(newDefinition); List<Element> trailOfRootInOriginal = filterAncestors(rootOfNewDefinitionInOriginal); trailOfRootInOriginal.add(0, rootOfNewDefinitionInOriginal); trailOfRootInOriginal.remove(trailOfRootInOriginal.size()-1); containerOfNewDefinition = createOrGetInnerTypeAux(container, original, trailOfRootInOriginal,1); List<Element> trailNewDefinitionInOriginal = filterAncestors(newDefinition); // Remove everything up to the container. while(! (trailNewDefinitionInOriginal.get(trailNewDefinitionInOriginal.size()-1) == rootOfNewDefinitionInOriginal)) { trailNewDefinitionInOriginal.remove(trailNewDefinitionInOriginal.size()-1); } // Remove the container. trailNewDefinitionInOriginal.remove(trailNewDefinitionInOriginal.size()-1); if(! trailNewDefinitionInOriginal.isEmpty()) { // trailOfRootInOriginal.add(0, rootOfNewDefinitionInOriginal); containerOfNewDefinition = createOrGetInnerTypeAux(containerOfNewDefinition, original, trailNewDefinitionInOriginal,1); } return containerOfNewDefinition; } private Type levelOfDefinition(Element<?> element) { Type result = element.nearestAncestor(Type.class, new SafePredicate<Type>(){ @Override public boolean eval(Type object) { return ! (object instanceof ComponentType); }}); return result; } private String toImplName(String name) { if(! name.endsWith(IMPL)) { name = name + IMPL; } return name; } private Type createOrGetInnerTypeForType(Type container, Type original, Type current, List<Element> elements, int baseOneIndex) throws LookupException { // Signature innerName = (new SimpleNameSignature(innerClassName(relationBeingTranslated, original))); Signature innerName = current.signature().clone(); SimpleReference<Type> tref = new SimpleReference<Type>(innerName, Type.class); tref.setUniParent(container); Type result; try { result= tref.getElement(); } catch(LookupException exc) { // We add the imports to the original. They are copied later on to 'container'. ComponentRelation relation = ((ComponentType)current).nearestAncestor(ComponentRelation.class); result = emptyInnerClassFor(relation, container); NamespacePart namespacePart = container.farthestAncestor(NamespacePart.class); incorporateImports(relation, namespacePart); // Since we are adding inner classes that were not written in the current namespacepart, their type // may not have been imported yet. Therefore, we add an import of the referenced component type. namespacePart.addImport(new TypeImport(container.language(Java.class).createTypeReference(relation.referencedComponentType().getFullyQualifiedName()))); container.add(result); container.flushCache(); } return createOrGetInnerTypeAux(result, original, elements, baseOneIndex + 1); } private Type createOrGetInnerTypeForComponent(Type container, Type original, ComponentRelation relationBeingTranslated, List<Element> elements, int baseOneIndex) throws LookupException { Signature innerName = null; innerName = (new SimpleNameSignature(innerClassName(relationBeingTranslated, container))); SimpleReference<Type> tref = new SimpleReference<Type>(innerName, Type.class); tref.setUniParent(container); Type result; try { result= tref.getElement(); } catch(LookupException exc) { // We add the imports to the original. They are copied later on to 'container'. result = emptyInnerClassFor(relationBeingTranslated, container); NamespacePart namespacePart = container.farthestAncestor(NamespacePart.class); incorporateImports(relationBeingTranslated, namespacePart); // Since we are adding inner classes that were not written in the current namespacepart, their type // may not have been imported yet. Therefore, we add an import of the referenced component type. namespacePart.addImport(new TypeImport(container.language(Java.class).createTypeReference(relationBeingTranslated.referencedComponentType().getFullyQualifiedName()))); container.add(result); container.flushCache(); } return createOrGetInnerTypeAux(result, original, elements, baseOneIndex + 1); } private List<Element> filterAncestors(Element<?> element) { SafePredicate<Element> predicate = componentRelationOrNonComponentTypePredicate(); return element.ancestors(Element.class, predicate); } private SafePredicate<Element> componentRelationOrNonComponentTypePredicate() { return new SafePredicate<Element>(){ @Override public boolean eval(Element object) { return (object instanceof ComponentRelation) || (object instanceof Type && !(object instanceof ComponentType)); }}; } // private SafePredicate<Type> nonComponentTypePredicate() { // return new SafePredicate<Type>(){ // @Override // public boolean eval(Type object) { // return !(object instanceof ComponentType); private Type createOrGetInnerTypeAux(Type container, Type original, List<Element> elements, int baseOneIndex) throws LookupException { int index = elements.size()-baseOneIndex; if(index >= 0) { Element element = elements.get(index); if(element instanceof ComponentRelation) { return createOrGetInnerTypeForComponent(container,original, (ComponentRelation) element, elements,baseOneIndex); } else { return createOrGetInnerTypeForType(container,original, (Type) element, elements,baseOneIndex); } } else { return container; } } private void transformToImplRecursive(Type type) throws ModelException { transformToImpl(type); for(Type nested: type.directlyDeclaredMembers(Type.class)) { transformToImplRecursive(nested); } } private void transformToImpl(Type type) throws ModelException { JLo lang = type.language(JLo.class); if(! type.isTrue(lang.PRIVATE)) { // Change the name of the outer type. // What a crappy code. I would probably be easier to not add IMPL // to the generated subobject class in the first place, but add // it afterwards. String oldName = type.getName(); String name = oldName; if(! name.endsWith(IMPL)) { name = name +IMPL; type.signature().setName(name); } for(SubtypeRelation relation: type.nonMemberInheritanceRelations(SubtypeRelation.class)) { BasicJavaTypeReference tref = (BasicJavaTypeReference) relation.superClassReference(); try { if((! relation.isTrue(lang.IMPLEMENTS_RELATION)) && isJLo(tref.getElement())) { tref.setSignature(new SimpleNameSignature(tref.signature().name()+IMPL)); } } catch(LookupException exc) { tref.getElement(); throw exc; } } implementOwnInterface(type); for(TypeElement decl: type.directlyDeclaredElements()) { if((decl instanceof Method) && (decl.is(lang.CONSTRUCTOR) == Ternary.TRUE)) { ((Method)decl).setName(name); } if(decl instanceof ElementWithModifiers) { makePublic(decl); } } } } private void implementOwnInterface(Type type) { JLo language = type.language(JLo.class); if(!type.isTrue(language.PRIVATE)) { String oldFQN = type.getFullyQualifiedName(); BasicJavaTypeReference createTypeReference = language.createTypeReference(oldFQN); transformToInterfaceReference(createTypeReference); copyTypeParametersIfNecessary(type, createTypeReference); SubtypeRelation relation = new SubtypeRelation(createTypeReference); relation.addModifier(new Implements()); type.addInheritanceRelation(relation); } } private void copyTypeParametersIfNecessary(Type type, BasicJavaTypeReference createTypeReference) { Java language = type.language(Java.class); if(! (type.is(language.CLASS) == Ternary.TRUE)) { copyTypeParametersFromFarthestAncestor(type, createTypeReference); } } private void copyTypeParametersFromFarthestAncestor(Element<?> type, BasicJavaTypeReference createTypeReference) { Type farthestAncestor = type.farthestAncestorOrSelf(Type.class); Java language = type.language(Java.class); List<TypeParameter> tpars = farthestAncestor.parameters(TypeParameter.class); for(TypeParameter parameter:tpars) { createTypeReference.addArgument(language.createBasicTypeArgument(language.createTypeReference(parameter.signature().name()))); } } private void processSuperComponentParameters(AbstractInheritanceRelation<?> relation) throws LookupException { TypeReference tref = relation.superClassReference(); Type type = relation.nearestAncestor(Type.class); if(tref instanceof ComponentParameterTypeReference) { ComponentParameterTypeReference ctref = (ComponentParameterTypeReference) tref; Type ctype = tref.getType(); type.addAll(selectorsForComponent(ctype)); relation.setSuperClassReference(ctref.componentTypeReference()); } } private void removeNonLocalReferences(Type type) throws LookupException { for(NonLocalJavaTypeReference tref: type.descendants(NonLocalJavaTypeReference.class)) { SingleAssociation<NonLocalJavaTypeReference, Element> parentLink = tref.parentLink(); parentLink.getOtherRelation().replace(parentLink, tref.actualReference().parentLink()); } } private void expandReferences(Element<?> type) throws LookupException { Java language = type.language(Java.class); for(BasicJavaTypeReference tref: type.descendants(BasicJavaTypeReference.class)) { if(tref.getTarget() == null) { try { // Filthy hack, should add meta information to such references, and use that instead. if(! tref.signature().name().contains(SHADOW)) { Type element = tref.getElement(); if(! element.isTrue(language.PRIVATE)) { String fullyQualifiedName = element.getFullyQualifiedName(); String predecessor = Util.getAllButLastPart(fullyQualifiedName); if(predecessor != null) { NamedTarget nt = new NamedTarget(predecessor); tref.setTarget(nt); } } } } catch(LookupException exc) { // This occurs because a generated element cannot be resolved in the original model. E.g. // an inner class of another class than the one that has been generated. } } } } private List<Method> selectorsFor(ComponentRelation rel) throws LookupException { Type t = rel.referencedComponentType(); return selectorsForComponent(t); } private List<Method> selectorsForComponent(Type t) throws LookupException { List<Method> result = new ArrayList<Method>(); for(ComponentParameter par: t.parameters(ComponentParameter.class)) { Method realSelector= realSelectorFor((InstantiatedComponentParameter) par); realSelector.setUniParent(t); substituteTypeParameters(realSelector); realSelector.setUniParent(null); result.add(realSelector); } return result; } private Method realSelectorFor(InstantiatedComponentParameter<?> par) throws LookupException { SimpleNameDeclarationWithParametersHeader header = new SimpleNameDeclarationWithParametersHeader(selectorName(par)); FormalComponentParameter formal = par.formalParameter(); Java language = par.language(Java.class); // Method result = new NormalMethod(header,formal.componentTypeReference().clone()); Type declarationType = formal.declarationType(); JavaTypeReference reference = language.reference(declarationType); reference.setUniParent(null); Method result = par.language(Java.class).createNormalMethod(header,reference); result.addModifier(new Public()); // result.addModifier(new Abstract()); header.addFormalParameter(new FormalParameter("argument", formal.containerTypeReference().clone())); Block body = new Block(); result.setImplementation(new RegularImplementation(body)); ActualComponentArgument arg = par.argument(); Expression expr; if(arg instanceof ComponentNameActualArgument) { ComponentNameActualArgument singarg = (ComponentNameActualArgument) arg; expr = new JavaMethodInvocation(getterName(singarg.declaration()),new NamedTargetExpression("argument", null)); body.addStatement(new ReturnStatement(expr)); } else if(arg instanceof ParameterReferenceActualArgument) { ParameterReferenceActualArgument ref = (ParameterReferenceActualArgument) arg; ComponentParameter p = ref.declaration(); expr = new JavaMethodInvocation(selectorName(p), null); ((JavaMethodInvocation)expr).addArgument(new NamedTargetExpression("argument",null)); body.addStatement(new ReturnStatement(expr)); } else { // result variable declaration VariableDeclaration declaration = new VariableDeclaration("result"); BasicJavaTypeReference arrayList = language.createTypeReference("java.util.ArrayList"); JavaTypeReference componentType = language.reference(formal.componentTypeReference().getElement()); componentType.setUniParent(null); BasicTypeArgument targ = language.createBasicTypeArgument(componentType); arrayList.addArgument(targ); // LocalVariableDeclarator varDecl = new LocalVariableDeclarator(reference.clone()); LocalVariableDeclarator varDecl = new LocalVariableDeclarator(arrayList.clone()); Expression init = new ConstructorInvocation(arrayList, null); declaration.setInitialization(init); varDecl.add(declaration); body.addStatement(varDecl); // add all components ComponentRelationSet componentRelations = ((MultiActualComponentArgument)arg).declaration(); for(DeclarationWithType rel: componentRelations.relations()) { Expression t = new NamedTargetExpression("result", null); SimpleNameMethodInvocation inv = new JavaMethodInvocation("add", t); Expression componentSelector; if(rel instanceof ComponentParameter) { if(rel instanceof MultiFormalComponentParameter) { inv.setName("addAll"); } componentSelector = new JavaMethodInvocation(selectorName((ComponentParameter)rel), null); ((JavaMethodInvocation)componentSelector).addArgument(new NamedTargetExpression("argument",null)); } else { componentSelector = new NamedTargetExpression(rel.signature().name(), new NamedTargetExpression("argument",null)); } inv.addArgument(componentSelector); body.addStatement(new StatementExpression(inv)); } // return statement expr = new NamedTargetExpression("result",null); body.addStatement(new ReturnStatement(expr)); } return result; } private List<Method> selectorsFor(Type type) throws LookupException { ParameterBlock<?,ComponentParameter> block = type.parameterBlock(ComponentParameter.class); List<Method> result = new ArrayList<Method>(); if(block != null) { for(ComponentParameter par: block.parameters()) { result.add(selectorFor((FormalComponentParameter<?>) par)); } } return result; } private String selectorName(ComponentParameter<?> par) { return "__select$"+ toUnderScore(par.nearestAncestor(Type.class).getFullyQualifiedName())+"$"+par.signature().name(); } private String toUnderScore(String string) { return string.replace('.', '_'); } private Method selectorFor(FormalComponentParameter<?> par) throws LookupException { SimpleNameDeclarationWithParametersHeader header = new SimpleNameDeclarationWithParametersHeader(selectorName(par)); Java language = par.language(Java.class); // Method result = new NormalMethod(header,par.componentTypeReference().clone()); JavaTypeReference reference = language.reference(par.declarationType()); reference.setUniParent(null); Method result = par.language(Java.class).createNormalMethod(header,reference); result.addModifier(new Public()); // result.addModifier(new Abstract()); header.addFormalParameter(new FormalParameter("argument", par.containerTypeReference().clone())); Block body = new Block(); result.setImplementation(new RegularImplementation(body)); ConstructorInvocation cons = new ConstructorInvocation((BasicJavaTypeReference) par.language(Java.class).createTypeReference("java.lang.Error"), null); body.addStatement(new ThrowStatement(cons)); return result; } private void replaceConstructorCalls(final ComponentRelation relation) throws LookupException { Type type = relation.nearestAncestor(Type.class); List<SubobjectConstructorCall> constructorCalls = type.descendants(SubobjectConstructorCall.class, new UnsafePredicate<SubobjectConstructorCall,LookupException>() { @Override public boolean eval(SubobjectConstructorCall constructorCall) throws LookupException { return constructorCall.getTarget().getElement().equals(relation); } } ); for(SubobjectConstructorCall call: constructorCalls) { MethodInvocation inv = new ConstructorInvocation((BasicJavaTypeReference) innerClassTypeReference(relation, type), null); // move actual arguments from subobject constructor call to new constructor call. inv.addAllArguments(call.getActualParameters()); MethodInvocation setterCall = new JavaMethodInvocation(setterName(relation), null); setterCall.addArgument(inv); SingleAssociation<SubobjectConstructorCall, Element> parentLink = call.parentLink(); parentLink.getOtherRelation().replace(parentLink, setterCall.parentLink()); } } private void inner(Type type, ComponentRelation relation, Type outer, Type outerTypeBeingTranslated) throws LookupException { Type innerClass = createInnerClassFor(relation,type,outerTypeBeingTranslated); type.add(innerClass); Type componentType = relation.componentType(); for(ComponentRelation nestedRelation: componentType.directlyDeclaredElements(ComponentRelation.class)) { // subst parameters ComponentRelation clonedNestedRelation = nestedRelation.clone(); clonedNestedRelation.setUniParent(nestedRelation.parent()); substituteTypeParameters(clonedNestedRelation); inner(innerClass, clonedNestedRelation, outer,outerTypeBeingTranslated); } } private void addOutwardDelegations(ComponentRelation relation, Type outer) throws LookupException { ConfigurationBlock block = relation.configurationBlock(); if(block != null) { TypeWithBody componentTypeDeclaration = relation.componentTypeDeclaration(); List<Method> elements = methodsOfComponentBody(componentTypeDeclaration); for(ConfigurationClause clause: block.clauses()) { if(clause instanceof AbstractClause) { AbstractClause ov = (AbstractClause)clause; final QualifiedName poppedName = ov.oldFqn().popped(); // Type targetInnerClass = searchInnerClass(outer, relation, poppedName); Declaration decl = ov.oldDeclaration(); if(decl instanceof Method) { final Method<?,?,?,?> method = (Method<?, ?, ?, ?>) decl; if(ov instanceof RenamingClause) { outer.add(createAlias(relation, method, ((SimpleNameDeclarationWithParametersSignature)ov.newSignature()).name())); } } } } } } private List<Method> methodsOfComponentBody(TypeWithBody componentTypeDeclaration) { List<Method> elements; if(componentTypeDeclaration != null) { elements = componentTypeDeclaration.body().children(Method.class); } else { elements = new ArrayList<Method>(); } return elements; } // private boolean containsMethodWithSameSignature(List<Method> elements, final Method<?, ?, ?, ?> method) throws LookupException { // boolean overriddenInSubobject = new UnsafePredicate<Method, LookupException>() { // public boolean eval(Method subobjectMethod) throws LookupException { // return subobjectMethod.signature().sameAs(method.signature()); // }.exists(elements); // return overriddenInSubobject; private Method createAlias(ComponentRelation relation, Method<?,?,?,?> method, String newName) throws LookupException { NormalMethod<?,?,?> result; result = innerMethod(method, newName); Block body = new Block(); result.setImplementation(new RegularImplementation(body)); MethodInvocation invocation = invocation(result, method.name()); // We now bind to the regular method name in case the method has not been overridden // and there is no 'original' method. // If it is overridden, then this adds 1 extra delegation, so we should optimize it later on. // Invocation invocation = invocation(result, original(method.name())); Expression target = new JavaMethodInvocation(getterName(relation), null); invocation.setTarget(target); substituteTypeParameters(method, result); addImplementation(method, body, invocation); return result; } /** * * @param relationBeingTranslated A component relation from either the original class, or one of its nested components. * @param outer The outer class being generated. */ private Type createInnerClassFor(ComponentRelation relationBeingTranslated, Type outer, Type outerTypeBeingTranslated) throws ChameleonProgrammerException, LookupException { Type result = emptyInnerClassFor(relationBeingTranslated, outer); processComponentRelationBody(relationBeingTranslated, outer, outerTypeBeingTranslated, result); return result; } private Type emptyInnerClassFor(ComponentRelation relationBeingTranslated, Type outer) throws LookupException { incorporateImports(relationBeingTranslated); String className = innerClassName(relationBeingTranslated, outer); Type result = new RegularJLoType(className); for(Modifier mod: relationBeingTranslated.modifiers()) { result.addModifier(mod.clone()); } TypeReference superReference = superClassReference(relationBeingTranslated); superReference.setUniParent(relationBeingTranslated); substituteTypeParameters(superReference); superReference.setUniParent(null); result.addInheritanceRelation(new SubtypeRelation(superReference)); List<Method> selectors = selectorsFor(relationBeingTranslated); for(Method selector:selectors) { result.add(selector); } processInnerClassMethod(relationBeingTranslated, relationBeingTranslated.referencedComponentType(), result); return result; } /** * Incorporate the imports of the namespace part of the declared type of the component relation to * the namespace part of the component relation. * @param relationBeingTranslated * @throws LookupException */ private void incorporateImports(ComponentRelation relationBeingTranslated) throws LookupException { incorporateImports(relationBeingTranslated, relationBeingTranslated.farthestAncestor(NamespacePart.class)); } private void incorporateImports(Method<?,?,?,?> method) throws LookupException { Java java = method.language(Java.class); NamespacePart namespacePart = method.nearestAncestor(NamespacePart.class); for(TypeReference tref: method.descendants(TypeReference.class)) { try { Type type = tref.getElement().baseType(); if(type instanceof RegularType) { TypeReference importRef = java.createTypeReference(type.getFullyQualifiedName()); namespacePart.addImport(new TypeImport(importRef)); } } catch(LookupException exc) { tref.getElement(); } } } /** * Incorporate the imports of the namespace part of the declared type of the component relation to * the given namespace part. * @param relationBeingTranslated * @throws LookupException */ private void incorporateImports(ComponentRelation relationBeingTranslated, NamespacePart target) throws LookupException { Type baseT = relationBeingTranslated.referencedComponentType().baseType(); NamespacePart originalNsp = baseT.farthestAncestor(NamespacePart.class); for(Import imp: originalNsp.imports()) { target.addImport(imp.clone()); } } private void processComponentRelationBody(ComponentRelation relation, Type outer, Type outerTypeBeingTranslated, Type result) throws LookupException { ComponentType ctype = relation.componentTypeDeclaration(); if(ctype != null) { if(ctype.ancestors().contains(outerTypeBeingTranslated)) { ComponentType clonedType = ctype.clone(); clonedType.setUniParent(relation); replaceOuterAndRootTargets(relation,clonedType); for(TypeElement typeElement:clonedType.body().elements()) { if(! (typeElement instanceof ComponentRelation)) { result.add(typeElement); } } } } } private void processInnerClassMethod(ComponentRelation relation, Type componentType, Type result) throws LookupException { List<Method> localMethods = componentType.directlyDeclaredMembers(Method.class); for(Method<?,?,?,?> method: localMethods) { if(method.is(method.language(ObjectOrientedLanguage.class).CONSTRUCTOR) == Ternary.TRUE) { NormalMethod<?,?,?> clone = (NormalMethod) method.clone(); clone.setUniParent(method.parent()); for(BasicTypeReference<?> tref: clone.descendants(BasicTypeReference.class)) { if(tref.getTarget() == null) { Type element = tref.getElement(); Type base = element.baseType(); if((! (element instanceof ActualType)) && base instanceof RegularType) { String fqn = base.getFullyQualifiedName(); String qn = Util.getAllButLastPart(fqn); if(qn != null && (! qn.isEmpty())) { tref.setTarget(new SimpleReference<TargetDeclaration>(qn, TargetDeclaration.class)); } } } } clone.setUniParent(null); String name = result.signature().name(); RegularImplementation impl = (RegularImplementation) clone.implementation(); Block block = new Block(); impl.setBody(block); // substitute parameters before replace the return type, method name, and the body. // the types are not known in the component type, and the super class of the component type // may not have a constructor with the same signature as the current constructor. substituteTypeParameters(method, clone); MethodInvocation inv = new SuperConstructorDelegation(); useParametersInInvocation(clone, inv); block.addStatement(new StatementExpression(inv)); clone.setReturnTypeReference(relation.language(Java.class).createTypeReference(name)); ((SimpleNameDeclarationWithParametersHeader)clone.header()).setName(name); result.add(clone); } } } private TypeReference superClassReference(ComponentRelation relation) throws LookupException { TypeReference superReference = relation.componentTypeReference().clone(); if(superReference instanceof ComponentParameterTypeReference) { superReference = ((ComponentParameterTypeReference) superReference).componentTypeReference(); } return superReference; } private void replaceOuterAndRootTargets(ComponentRelation rel, TypeElement<?> clone) { List<AbstractTarget> outers = clone.descendants(AbstractTarget.class); for(AbstractTarget o: outers) { String name = o.getTargetDeclaration().getName(); SingleAssociation parentLink = o.parentLink(); ThisLiteral e = new ThisLiteral(); e.setTypeReference(new BasicJavaTypeReference(name)); parentLink.getOtherRelation().replace(parentLink, e.parentLink()); } } public final static String SHADOW = "_subobject_"; public final static String IMPL = "_implementation"; private Method createOutward(Method<?,?,?,?> method, String newName, String className) throws LookupException { NormalMethod<?,?,?> result; if(//(method.is(method.language(ObjectOrientedLanguage.class).DEFINED) == Ternary.TRUE) && (method.is(method.language(ObjectOrientedLanguage.class).OVERRIDABLE) == Ternary.TRUE)) { result = innerMethod(method, method.name()); Block body = new Block(); result.setImplementation(new RegularImplementation(body)); MethodInvocation invocation = invocation(result, newName); TypeReference ref = method.language(Java.class).createTypeReference(className); ThisLiteral target = new ThisLiteral(ref); invocation.setTarget(target); substituteTypeParameters(method, result); addImplementation(method, body, invocation); } else { result = null; } return result; } // private Method createDispathToOriginal(Method<?,?,?,?> method, ComponentRelation relation) throws LookupException { // NormalMethod<?,?,?> result = null; // result = innerMethod(method, method.name()); // Block body = new Block(); // result.setImplementation(new RegularImplementation(body)); // MethodInvocation invocation = invocation(result, original(method.name())); // substituteTypeParameters(method, result); // addImplementation(method, body, invocation); // return result; // private TypeReference getRelativeClassReference(ComponentRelation relation) { // return relation.language(Java.class).createTypeReference(getRelativeClassName(relation)); // private String getRelativeClassName(ComponentRelation relation) { // return relation.nearestAncestor(Type.class).signature().name(); private void substituteTypeParameters(Method<?, ?, ?, ?> methodInTypeWhoseParametersMustBeSubstituted, NormalMethod<?, ?, ?> methodWhereActualTypeParametersMustBeFilledIn) throws LookupException { methodWhereActualTypeParametersMustBeFilledIn.setUniParent(methodInTypeWhoseParametersMustBeSubstituted); substituteTypeParameters(methodWhereActualTypeParametersMustBeFilledIn); methodWhereActualTypeParametersMustBeFilledIn.setUniParent(null); } private void addImplementation(Method<?, ?, ?, ?> method, Block body, MethodInvocation invocation) throws LookupException { if(method.returnType().equals(method.language(Java.class).voidType())) { body.addStatement(new StatementExpression(invocation)); } else { body.addStatement(new ReturnStatement(invocation)); } } private NormalMethod<?, ?, ?> innerMethod(Method<?, ?, ?, ?> method, String original) throws LookupException { NormalMethod<?, ?, ?> result; TypeReference tref = method.returnTypeReference().clone(); result = method.language(Java.class).createNormalMethod(method.header().clone(), tref); ((SimpleNameDeclarationWithParametersHeader)result.header()).setName(original); ExceptionClause exceptionClause = method.getExceptionClause(); ExceptionClause clone = (exceptionClause != null ? exceptionClause.clone(): null); result.setExceptionClause(clone); result.addModifier(new Public()); return result; } /** * Replace all references to type parameters * @param element * @throws LookupException */ private void substituteTypeParameters(Element<?> element) throws LookupException { List<TypeReference> crossReferences = element.descendants(TypeReference.class, new UnsafePredicate<TypeReference,LookupException>() { public boolean eval(TypeReference object) throws LookupException { try { return object.getDeclarator() instanceof InstantiatedTypeParameter; } catch (LookupException e) { e.printStackTrace(); throw e; } } }); for(TypeReference cref: crossReferences) { SingleAssociation parentLink = cref.parentLink(); Association childLink = parentLink.getOtherRelation(); InstantiatedTypeParameter declarator = (InstantiatedTypeParameter) cref.getDeclarator(); Type type = cref.getElement(); while(type instanceof ActualType) { type = ((ActualType)type).aliasedType(); } TypeReference namedTargetExpression = element.language(ObjectOrientedLanguage.class).createTypeReference(type.getFullyQualifiedName()); childLink.replace(parentLink, namedTargetExpression.parentLink()); } } // private void substituteTypeParameters(Element<?> element,NamespacePart nsp) throws LookupException { // List<TypeReference> crossReferences = // element.descendants(TypeReference.class, // new UnsafePredicate<TypeReference,LookupException>() { // public boolean eval(TypeReference object) throws LookupException { // try { // return object.getDeclarator() instanceof InstantiatedTypeParameter; // } catch (LookupException e) { // e.printStackTrace(); // throw e; // for(TypeReference cref: crossReferences) { // SingleAssociation parentLink = cref.parentLink(); // Association childLink = parentLink.getOtherRelation(); // InstantiatedTypeParameter declarator = (InstantiatedTypeParameter) cref.getDeclarator(); // Type type = cref.getElement(); // while(type instanceof ActualType) { // type = ((ActualType)type).aliasedType(); // TypeReference namedTargetExpression = element.language(ObjectOrientedLanguage.class).createTypeReference(type.getFullyQualifiedName()); // nsp.addImport(new TypeImport(namedTargetExpression.clone())); // childLink.replace(parentLink, namedTargetExpression.parentLink()); private String innerClassName(Type outer, QualifiedName qn) { StringBuffer result = new StringBuffer(); result.append(outer.signature().name()); result.append(SHADOW); List<Signature> sigs = qn.signatures(); int size = sigs.size(); for(int i = 0; i < size; i++) { result.append(((SimpleNameSignature)sigs.get(i)).name()); if(i < size - 1) { result.append(SHADOW); } } result.append(IMPL); return result.toString(); } private String innerClassName(ComponentRelation relation, Type outer) throws LookupException { return innerClassName(outer, relation.signature()); } private void replaceSuperCalls(Type type) throws LookupException { List<SuperTarget> superTargets = type.descendants(SuperTarget.class, new UnsafePredicate<SuperTarget,LookupException>() { @Override public boolean eval(SuperTarget superTarget) throws LookupException { return superTarget.getTargetDeclaration() instanceof ComponentRelation; } } ); for(SuperTarget superTarget: superTargets) { Element<?> cr = superTarget.parent(); if(cr instanceof CrossReferenceWithArguments) { Element<?> inv = cr.parent(); if(inv instanceof RegularMethodInvocation) { RegularMethodInvocation call = (RegularMethodInvocation) inv; ComponentRelation targetComponent = (ComponentRelation) superTarget.getTargetDeclaration(); MethodInvocation subObjectSelection = new JavaMethodInvocation(getterName(targetComponent), null); call.setTarget(subObjectSelection); String name = staticMethodName(call.name(), targetComponent.componentType()); call.setName(name); } } } } // private String original(String name) { // return "original__"+name; private MemberVariableDeclarator fieldForComponent(ComponentRelation relation, Type outer) throws LookupException { if(relation.overriddenMembers().isEmpty()) { MemberVariableDeclarator result = new MemberVariableDeclarator(componentTypeReference(relation, outer)); result.add(new VariableDeclaration(fieldName(relation))); return result; } else { return null; } } private BasicJavaTypeReference innerClassTypeReference(ComponentRelation relation, Type outer) throws LookupException { return relation.language(Java.class).createTypeReference(innerClassName(relation, outer)); } private String getterName(ComponentRelation relation) { return getterName(relation.signature().name()); } private String getterName(String componentName) { return componentName+COMPONENT; } public final static String COMPONENT = "__component__lkjkberfuncye__"; private Method getterForComponent(ComponentRelation relation, Type outer) throws LookupException { if(relation.overriddenMembers().isEmpty()) { JavaTypeReference returnTypeReference = componentTypeReference(relation, outer); RegularMethod result = relation.language(Java.class).createNormalMethod(new SimpleNameDeclarationWithParametersHeader(getterName(relation)), returnTypeReference); result.addModifier(new Public()); Block body = new Block(); result.setImplementation(new RegularImplementation(body)); body.addStatement(new ReturnStatement(new NamedTargetExpression(fieldName(relation), null))); return result; } else { return null; } } private String setterName(ComponentRelation relation) { return "set"+COMPONENT+"__"+relation.signature().name(); } private Method setterForComponent(ComponentRelation relation, Type outer) throws LookupException { if(relation.overriddenMembers().isEmpty()) { String name = relation.signature().name(); RegularMethod result = relation.language(Java.class).createNormalMethod(new SimpleNameDeclarationWithParametersHeader(setterName(relation)), relation.language(Java.class).createTypeReference("void")); BasicJavaTypeReference tref = componentTypeReference(relation, outer); result.header().addFormalParameter(new FormalParameter(name, tref)); result.addModifier(new Public()); Block body = new Block(); result.setImplementation(new RegularImplementation(body)); NamedTargetExpression componentFieldRef = new NamedTargetExpression(fieldName(relation), null); componentFieldRef.setTarget(new ThisLiteral()); body.addStatement(new StatementExpression(new AssignmentExpression(componentFieldRef, new NamedTargetExpression(name, null)))); return result; } else { return null; } } private BasicJavaTypeReference componentTypeReference(ComponentRelation relation, Type outer) throws LookupException { BasicJavaTypeReference tref = innerClassTypeReference(relation,outer); copyTypeParametersFromFarthestAncestor(outer,tref); transformToInterfaceReference(tref); return tref; } private MethodInvocation invocation(Method<?, ?, ?, ?> method, String origin) { MethodInvocation invocation = new JavaMethodInvocation(origin, null); // pass parameters. useParametersInInvocation(method, invocation); return invocation; } private void useParametersInInvocation(Method<?, ?, ?, ?> method, MethodInvocation invocation) { for(FormalParameter param: method.formalParameters()) { invocation.addArgument(new NamedTargetExpression(param.signature().name(), null)); } } private String fieldName(ComponentRelation relation) { return relation.signature().name(); } }
package com.mobica.cloud.aws.db; import com.amazonaws.services.dynamodbv2.datamodeling.*; import static com.mobica.cloud.aws.db.DbMessage.TABLE_NAME; @DynamoDBTable(tableName = TABLE_NAME) public class DbMessage { public static final String TABLE_NAME = "opendoors17-dev-test"; public static final String ID_NAME = "id"; @DynamoDBHashKey(attributeName = ID_NAME) private Long id; private String title; private String author; private String isbn; private String kind1; private String kind2; private String kind3; private String keyword1; private String keyword2; public DbMessage() { } public DbMessage(Long id) { this.id = id; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getKind1() { return kind1; } public void setKind1(String kind1) { this.kind1 = kind1; } public String getKind2() { return kind2; } public void setKind2(String kind2) { this.kind2 = kind2; } public String getKind3() { return kind3; } public void setKind3(String kind3) { this.kind3 = kind3; } public String getKeyword1() { return keyword1; } public void setKeyword1(String keyword1) { this.keyword1 = keyword1; } public String getKeyword2() { return keyword2; } public void setKeyword2(String keyword2) { this.keyword2 = keyword2; } @Override public String toString() { return "DbMessage{" + "id=" + id + ", title='" + title + '\'' + ", author='" + author + '\'' + ", isbn='" + isbn + '\'' + ", kind1='" + kind1 + '\'' + ", kind2='" + kind2 + '\'' + ", kind3='" + kind3 + '\'' + ", keyword1='" + keyword1 + '\'' + ", keyword2='" + keyword2 + '\'' + '}'; } }
package BSChecker; import java.util.ArrayList; /** * * @author tedpyne * Defines abstract class for types of grammatical errors */ public abstract class Error { /** * * @param text The block of text to find errors in * @return an ArrayList of int[2] pointers to the start and end of the error */ public abstract ArrayList<int[]> findErrors(String text); }
package runtime; import common.Tuple4; import common.Tuple6; import runtime.meta.MetaClass; import runtime.rtexception.VMExecutionException; import ycloader.YClassLoader; import ycloader.exception.ClassInitializingException; import ycloader.exception.ClassLinkingException; import ycloader.exception.ClassLoadingException; import yvm.auxil.Peel; import java.util.Map; public class YObject{ private MetaClass metaClassReference; private Object[] fields; private boolean fieldsInitialized; @SuppressWarnings("unused") public YObject(){ fields = new Object[1]; metaClassReference = null; } @SuppressWarnings("unused") public YObject(int dimension) { fields = new Object[dimension]; metaClassReference = null; } @SuppressWarnings("unused") public YObject(MetaClass metaClass) { metaClassReference = metaClass; fields = null; } @SuppressWarnings("unused") public static YObject derivedFrom(int x) { return new YObject().asInteger(x); } @SuppressWarnings("unused") public static YObject derivedFrom(long x) { return new YObject().asLong(x); } @SuppressWarnings("unused") public static YObject derivedFrom(double x) { return new YObject().asDouble(x); } @SuppressWarnings("unused") public static YObject derivedFrom(float x) { return new YObject().asFloat(x); } @SuppressWarnings("unused") public static YObject derivedFrom(String x) { return new YObject().asString(x); } @SuppressWarnings("unused") public static YObject derivedFrom(char x) { return new YObject().asChar(x); } @SuppressWarnings("unused") public static YObject derivedFrom(boolean x) { return new YObject().asBoolean(x); } @SuppressWarnings("unused") public MetaClass getMetaClassReference() { return metaClassReference; } @SuppressWarnings("unused") public void initiateFields(YClassLoader loader) { Map fieldDesc = metaClassReference.fields.getFields(); int fieldsNum = fieldDesc.size(); fields = new Object[fieldsNum]; class Counter { private int i = 0; public void inc() { i++; } public int get() { return i; } } final Counter counter = new Counter(); fieldDesc.forEach((_Unused, bundle) -> { counter.inc(); //if this field is not loaded into vm, load it right now if (!loader .getStartupThread() .runtimeVM() .methodScope() .existClass(Peel.peelFieldDescriptor(((Tuple4) bundle).get2Placeholder().toString()).get(0), loader.getClass())) { try { Tuple6 bundle1 = loader.loadClass(Peel.peelFieldDescriptor(((Tuple4) bundle).get2Placeholder().toString()).get(0)); MetaClass meta = loader.linkClass(bundle1); loader.getStartupThread().runtimeVM().methodScope().addMetaClass(meta); loader.loadInheritanceChain(meta.superClassName); loader.initializeClass(meta); } catch (ClassInitializingException | ClassLinkingException | ClassLoadingException e) { throw new VMExecutionException("can not load class" + Peel.peelFieldDescriptor(Peel.peelFieldDescriptor(((Tuple4) bundle).get2Placeholder().toString()).get(0)) + " while executing anewarray opcode"); } } //if is a primitive type, assign a default value, or create a new instance switch (Peel.peelFieldDescriptor(((Tuple4) bundle).get2Placeholder().toString()).get(0)) { case "java/lang/Byte": case "java/lang/Short": case "java/lang/Long": case "java/lang/Integer": fields[counter.get()] = YObject.derivedFrom(0); break; case "java/lang/Character": fields[counter.get()] = YObject.derivedFrom('\u0000'); break; case "java/lang/Double": fields[counter.get()] = YObject.derivedFrom(0.0); break; case "java/lang/Float": fields[counter.get()] = YObject.derivedFrom(0.0F); break; case "java/lang/Boolean": fields[counter.get()] = YObject.derivedFrom(false); break; default: fields[counter.get()] = new YObject( loader.getStartupThread() .runtimeVM() .methodScope() .getMetaClass( Peel.peelFieldDescriptor( ((Tuple4) bundle).get2Placeholder().toString()).get(0), loader.getClass())); break; } }); fieldsInitialized = true; } @SuppressWarnings("unused") public YObject getField(int index) { return (YObject) fields[index]; } @SuppressWarnings("unused") public void setField(int index, YObject value) { fields[index] = value; } @SuppressWarnings("unused") public boolean isInitialized() { return fieldsInitialized; } @SuppressWarnings("unused") YObject asInteger(int x){ fields[0] = x; return this; } @SuppressWarnings("unused") YObject asLong(long x){ fields[0] = x; return this; } @SuppressWarnings("unused") YObject asDouble(double x){ fields[0] = x; return this; } @SuppressWarnings("unused") YObject asFloat(float x){ fields[0] = x; return this; } @SuppressWarnings("unused") YObject asBoolean(boolean x) { fields[0] = x; return this; } @SuppressWarnings("unused") YObject asChar(char x) { fields[0] = x; return this; } @SuppressWarnings("unused") YObject asString(String x) { fields[0] = x; return this; } @SuppressWarnings("unused") public int toInteger(){ return (int) fields[0]; } @SuppressWarnings("unused") public long toLong(){ return (long) fields[0]; } @SuppressWarnings("unused") public double toDouble(){ return (double) fields[0]; } @SuppressWarnings("unused") public float toFloat(){ return (float) fields[0]; } @SuppressWarnings("unused") public String toString() { return (String) fields[0]; } @SuppressWarnings("unused") public boolean toBoolean() { return (boolean) fields[0]; } @SuppressWarnings("unused") public char toChar() { return (char) fields[0]; } @SuppressWarnings("unused") void setArrayComponent(int index, YObject value) { fields[index] = value; } @SuppressWarnings("unused") YObject getArrayComponent(int index) { return (YObject) fields[index]; } @SuppressWarnings("unused") public String getClassName() { return metaClassReference.qualifiedClassName; } }
package net.somethingdreadful.MAL.broadcasts; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.util.Log; import com.crashlytics.android.Crashlytics; import net.somethingdreadful.MAL.Home; import net.somethingdreadful.MAL.PrefManager; import net.somethingdreadful.MAL.R; import net.somethingdreadful.MAL.account.AccountService; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.tasks.APIAuthenticationErrorListener; import net.somethingdreadful.MAL.tasks.NetworkTask; import net.somethingdreadful.MAL.tasks.TaskJob; import java.util.ArrayList; public class AutoSync extends BroadcastReceiver implements APIAuthenticationErrorListener, NetworkTask.NetworkTaskListener { static NotificationManager nm; static boolean anime = false; static boolean manga = false; @Override public void onReceive(Context context, Intent intent) { if (context == null) { Crashlytics.log(Log.ERROR, "MALX", "AutoSync.onReceive(): context is null"); return; } PrefManager.create(context); if (MALApi.isNetworkAvailable(context)) { Intent notificationIntent = new Intent(context, Home.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); if (networkChange(intent) && !PrefManager.getAutosyncDone() || !networkChange(intent)) { ArrayList<String> args = new ArrayList<String>(); args.add(AccountService.getUsername()); args.add(""); new NetworkTask(TaskJob.FORCESYNC, MALApi.ListType.ANIME, context, this, this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, args.toArray(new String[args.size()])); new NetworkTask(TaskJob.FORCESYNC, MALApi.ListType.MANGA, context, this, this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, args.toArray(new String[args.size()])); nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification.Builder syncNotificationBuilder = new Notification.Builder(context).setOngoing(true) .setContentIntent(contentIntent) .setSmallIcon(R.drawable.notification_icon) .setContentTitle(context.getString(R.string.app_name)) .setContentText(context.getString(R.string.toast_info_SyncMessage)); Notification syncNotification; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) syncNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC); syncNotification = syncNotificationBuilder.build(); } else { syncNotification = syncNotificationBuilder.getNotification(); } nm.notify(R.id.notification_sync, syncNotification); } } else if (!networkChange(intent)) { PrefManager.setAutosyncDone(false); } } @Override public void onAPIAuthenticationError(MALApi.ListType type, TaskJob job) { notifyChange(type); } @Override public void onNetworkTaskFinished(Object result, TaskJob job, MALApi.ListType type, Bundle data, boolean cancelled) { notifyChange(type); } @Override public void onNetworkTaskError(TaskJob job, MALApi.ListType type, Bundle data, boolean cancelled) { notifyChange(type); } public boolean networkChange(Intent intent) { return intent != null && intent.getAction() != null && intent.getAction().equals(android.net.ConnectivityManager.CONNECTIVITY_ACTION); } public void notifyChange(MALApi.ListType anime) { if (anime.equals(MALApi.ListType.ANIME)) AutoSync.anime = true; else AutoSync.manga = true; if (AutoSync.anime && AutoSync.manga) { AutoSync.anime = false; AutoSync.manga = false; nm.cancel(R.id.notification_sync); PrefManager.setAutosyncDone(true); } } }
package net.somethingdreadful.MAL.broadcasts; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.util.Log; import com.crashlytics.android.Crashlytics; import net.somethingdreadful.MAL.Home; import net.somethingdreadful.MAL.PrefManager; import net.somethingdreadful.MAL.R; import net.somethingdreadful.MAL.account.AccountService; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.tasks.APIAuthenticationErrorListener; import net.somethingdreadful.MAL.tasks.NetworkTask; import net.somethingdreadful.MAL.tasks.TaskJob; import java.util.ArrayList; public class AutoSync extends BroadcastReceiver implements APIAuthenticationErrorListener, NetworkTask.NetworkTaskListener { static NotificationManager nm; @Override public void onReceive(Context context, Intent intent) { if (context == null) { Crashlytics.log(Log.ERROR, "MALX", "AutoSync.onReceive(): context is null"); return; } PrefManager.create(context); AccountService.create(context); if (MALApi.isNetworkAvailable(context) && AccountService.getAccount() != null) { Intent notificationIntent = new Intent(context, Home.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); if (networkChange(intent) && !PrefManager.getAutosyncDone() || !networkChange(intent)) { ArrayList<String> args = new ArrayList<String>(); args.add(AccountService.getUsername()); args.add(""); new NetworkTask(TaskJob.FORCESYNC, MALApi.ListType.ANIME, context, this, this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, args.toArray(new String[args.size()])); new NetworkTask(TaskJob.FORCESYNC, MALApi.ListType.MANGA, context, this, this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, args.toArray(new String[args.size()])); nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification.Builder syncNotificationBuilder = new Notification.Builder(context).setOngoing(true) .setContentIntent(contentIntent) .setSmallIcon(R.drawable.notification_icon) .setContentTitle(context.getString(R.string.app_name)) .setContentText(context.getString(R.string.toast_info_SyncMessage)); Notification syncNotification; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) syncNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC); syncNotification = syncNotificationBuilder.build(); } else { syncNotification = syncNotificationBuilder.getNotification(); } nm.notify(R.id.notification_sync, syncNotification); } } else if (!networkChange(intent)) { PrefManager.setAutosyncDone(false); } } @Override public void onAPIAuthenticationError(MALApi.ListType type, TaskJob job) { nm.cancel(R.id.notification_sync); PrefManager.setAutosyncDone(false); } @Override public void onNetworkTaskFinished(Object result, TaskJob job, MALApi.ListType type, Bundle data, boolean cancelled) { nm.cancel(R.id.notification_sync); PrefManager.setAutosyncDone(true); } @Override public void onNetworkTaskError(TaskJob job, MALApi.ListType type, Bundle data, boolean cancelled) { nm.cancel(R.id.notification_sync); PrefManager.setAutosyncDone(false); } public boolean networkChange(Intent intent) { return intent != null && intent.getAction() != null && intent.getAction().equals(android.net.ConnectivityManager.CONNECTIVITY_ACTION); } }
package net.somethingdreadful.MAL.sql; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.crashlytics.android.Crashlytics; import com.google.gson.Gson; import net.somethingdreadful.MAL.MALDateTools; import net.somethingdreadful.MAL.PrefManager; import net.somethingdreadful.MAL.account.AccountService; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.api.response.Activity; import net.somethingdreadful.MAL.api.response.Anime; import net.somethingdreadful.MAL.api.response.Manga; import net.somethingdreadful.MAL.api.response.Profile; import net.somethingdreadful.MAL.api.response.RecordStub; import net.somethingdreadful.MAL.api.response.Series; import net.somethingdreadful.MAL.api.response.User; import java.util.ArrayList; import java.util.HashMap; public class DatabaseManager { MALSqlHelper malSqlHelper; SQLiteDatabase dbRead; public DatabaseManager(Context context) { if (malSqlHelper == null) malSqlHelper = MALSqlHelper.getHelper(context); } public synchronized SQLiteDatabase getDBWrite() { return malSqlHelper.getWritableDatabase(); } public SQLiteDatabase getDBRead() { if (dbRead == null) dbRead = malSqlHelper.getReadableDatabase(); return dbRead; } public void saveAnimeList(ArrayList<Anime> list, String username) { Integer userId = getUserId(username); if (list != null && list.size() > 0 && userId != null) try { getDBWrite().beginTransaction(); for (Anime anime : list) saveAnime(anime, true, userId); getDBWrite().setTransactionSuccessful(); } catch (Exception e) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.saveAnimeList(): " + e.getMessage()); } finally { getDBWrite().endTransaction(); } } public void saveAnime(Anime anime, boolean IGF, String username) { saveAnime(anime, IGF, username.equals("") ? Integer.valueOf(0) : getUserId(username)); } public void saveAnime(Anime anime, boolean IGF, int userId) { saveAnime(anime, IGF, userId, false); } public void saveAnime(Anime anime, boolean IGF, int userId, boolean dontCreateBaseModel) { ContentValues cv = new ContentValues(); if (!AccountService.isMAL() && anime.getWatchedStatus() == null && !dontCreateBaseModel) anime.createBaseModel(); cv.put(MALSqlHelper.COLUMN_ID, anime.getId()); cv.put("recordName", anime.getTitle()); cv.put("recordType", anime.getType()); cv.put("imageUrl", anime.getImageUrl()); cv.put("recordStatus", anime.getStatus()); cv.put("episodesTotal", anime.getEpisodes()); if (!IGF) { cv.put("synopsis", anime.getSynopsis()); cv.put("memberScore", anime.getMembersScore()); cv.put("classification", anime.getClassification()); cv.put("membersCount", anime.getMembersCount()); cv.put("favoritedCount", anime.getFavoritedCount()); cv.put("popularityRank", anime.getPopularityRank()); cv.put("rank", anime.getRank()); cv.put("startDate", anime.getStartDate()); cv.put("endDate", anime.getEndDate()); cv.put("listedId", anime.getListedId()); } // don't use replace it replaces synopsis with null even when we don't put it in the ContentValues int updateResult = getDBWrite().update(MALSqlHelper.TABLE_ANIME, cv, MALSqlHelper.COLUMN_ID + " = ?", new String[]{Integer.toString(anime.getId())}); if (updateResult == 0) { Long insertResult = getDBWrite().insert(MALSqlHelper.TABLE_ANIME, null, cv); if (insertResult > 0) anime.setId(insertResult.intValue()); } if (anime.getId() > 0) { // save/update relations if saving was successful if (!IGF) { if (anime.getGenres() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_GENRES, "anime_id = ?", new String[]{String.valueOf(anime.getId())}); for (String genre : anime.getGenres()) { Integer genreId = getGenreId(genre); if (genreId != null) { ContentValues gcv = new ContentValues(); gcv.put("anime_id", anime.getId()); gcv.put("genre_id", genreId); getDBWrite().insert(MALSqlHelper.TABLE_ANIME_GENRES, null, gcv); } } } saveAnimeToAnimeRelation(anime.getAlternativeVersions(), anime.getId(), MALSqlHelper.RELATION_TYPE_ALTERNATIVE); saveAnimeToAnimeRelation(anime.getOther(), anime.getId(), MALSqlHelper.RELATION_TYPE_OTHER); saveAnimeToAnimeRelation(anime.getCharacterAnime(), anime.getId(), MALSqlHelper.RELATION_TYPE_CHARACTER); saveAnimeToAnimeRelation(anime.getPrequels(), anime.getId(), MALSqlHelper.RELATION_TYPE_PREQUEL); saveAnimeToAnimeRelation(anime.getSequels(), anime.getId(), MALSqlHelper.RELATION_TYPE_SEQUEL); saveAnimeToAnimeRelation(anime.getSideStories(), anime.getId(), MALSqlHelper.RELATION_TYPE_SIDE_STORY); saveAnimeToAnimeRelation(anime.getSpinOffs(), anime.getId(), MALSqlHelper.RELATION_TYPE_SPINOFF); saveAnimeToAnimeRelation(anime.getSummaries(), anime.getId(), MALSqlHelper.RELATION_TYPE_SUMMARY); saveTags(anime.getPersonalTags(), anime.getId(), MALSqlHelper.TABLE_ANIME_PERSONALTAGS); saveTags(anime.getTags(), anime.getId(), MALSqlHelper.TABLE_ANIME_TAGS); if (anime.getMangaAdaptions() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS, "anime_id = ? AND relationType = ?", new String[]{String.valueOf(anime.getId()), MALSqlHelper.RELATION_TYPE_ADAPTATION}); for (RecordStub mangaStub : anime.getMangaAdaptions()) saveAnimeToMangaRelation(anime.getId(), mangaStub, MALSqlHelper.RELATION_TYPE_ADAPTATION); } if (anime.getParentStory() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS, "anime_id = ? AND relationType = ?", new String[]{String.valueOf(anime.getId()), MALSqlHelper.RELATION_TYPE_PARENT_STORY}); saveAnimeToAnimeRelation(anime.getId(), anime.getParentStory(), MALSqlHelper.RELATION_TYPE_PARENT_STORY); } if (anime.getOtherTitles() != null) { saveOtherTitles(anime.getOtherTitlesEnglish(), anime.getId(), MALSqlHelper.TITLE_TYPE_ENGLISH, MALSqlHelper.TABLE_ANIME_OTHER_TITLES); saveOtherTitles(anime.getOtherTitlesJapanese(), anime.getId(), MALSqlHelper.TITLE_TYPE_JAPANESE, MALSqlHelper.TABLE_ANIME_OTHER_TITLES); saveOtherTitles(anime.getOtherTitlesSynonyms(), anime.getId(), MALSqlHelper.TITLE_TYPE_SYNONYM, MALSqlHelper.TABLE_ANIME_OTHER_TITLES); } if (anime.getProducers() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_PRODUCER, "anime_id = ?", new String[]{String.valueOf(anime.getId())}); for (String producer : anime.getProducers()) { Integer producerId = getProducerId(producer); if (producerId != null) { ContentValues gcv = new ContentValues(); gcv.put("anime_id", anime.getId()); gcv.put("producer_id", producerId); getDBWrite().replace(MALSqlHelper.TABLE_ANIME_PRODUCER, null, gcv); } } } } // update animelist if user id is provided if (userId > 0) { ContentValues alcv = new ContentValues(); alcv.put("profile_id", userId); alcv.put("anime_id", anime.getId()); alcv.put("status", anime.getWatchedStatus()); alcv.put("score", anime.getScore()); alcv.put("watched", anime.getWatchedEpisodes()); alcv.put("watchedStart", anime.getWatchingStart()); alcv.put("watchedEnd", anime.getWatchingEnd()); alcv.put("fansub", anime.getFansubGroup()); alcv.put("priority", anime.getPriority()); alcv.put("downloaded", anime.getEpsDownloaded()); alcv.put("rewatch", (anime.getRewatching() ? 1 : 0)); alcv.put("storage", anime.getStorage()); alcv.put("storageValue", anime.getStorageValue()); alcv.put("rewatchCount", anime.getRewatchCount()); alcv.put("rewatchValue", anime.getRewatchValue()); alcv.put("comments", anime.getPersonalComments()); alcv.put("dirty", anime.getDirty() != null ? new Gson().toJson(anime.getDirty()) : null); if (anime.getLastUpdate() != null) alcv.put("lastUpdate", anime.getLastUpdate().getTime()); getDBWrite().replace(MALSqlHelper.TABLE_ANIMELIST, null, alcv); } } } public Anime getAnime(Integer id, String username) { Anime result = null; Cursor cursor = getDBRead().rawQuery("SELECT a.*, al.score AS myScore, al.status AS myStatus, al.watched AS episodesWatched, al.dirty, al.lastUpdate, " + " al.watchedStart, al.WatchedEnd, al.fansub, al.priority, al.downloaded, al.storage, al.storageValue, al.rewatch, al.rewatchCount, al.rewatchValue, al.comments" + " FROM animelist al INNER JOIN anime a ON al.anime_id = a." + MALSqlHelper.COLUMN_ID + " WHERE al.profile_id = ? AND a." + MALSqlHelper.COLUMN_ID + " = ?", new String[]{getUserId(username).toString(), id.toString()}); if (cursor.moveToFirst()) { result = Anime.fromCursor(cursor); result.setGenres(getAnimeGenres(result.getId())); result.setTags(getAnimeTags(result.getId())); result.setAlternativeVersions(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_ALTERNATIVE)); result.setOther(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_OTHER)); result.setPersonalTags(getAnimePersonalTags(result.getId()), false); result.setCharacterAnime(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_CHARACTER)); result.setPrequels(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_PREQUEL)); result.setSequels(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_SEQUEL)); result.setSideStories(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_SIDE_STORY)); result.setSpinOffs(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_SPINOFF)); result.setSummaries(getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_SUMMARY)); result.setMangaAdaptions(getAnimeToMangaRelations(result.getId(), MALSqlHelper.RELATION_TYPE_ADAPTATION)); ArrayList<RecordStub> parentStory = getAnimeToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_PARENT_STORY); if (parentStory != null && parentStory.size() > 0) result.setParentStory(parentStory.get(0)); HashMap<String, ArrayList<String>> otherTitles = new HashMap<>(); otherTitles.put("english", getAnimeOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_ENGLISH)); otherTitles.put("japanese", getAnimeOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_JAPANESE)); otherTitles.put("synonyms", getAnimeOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_SYNONYM)); result.setOtherTitles(otherTitles); result.setProducers(getAnimeProducers(result.getId())); } cursor.close(); return result; } private boolean deleteAnime(Integer id) { return getDBWrite().delete(MALSqlHelper.TABLE_ANIME, MALSqlHelper.COLUMN_ID + " = ?", new String[]{id.toString()}) == 1; } public boolean deleteAnimeFromAnimelist(Integer id, String username) { boolean result = false; Integer userId = getUserId(username); if (userId != 0) { result = getDBWrite().delete(MALSqlHelper.TABLE_ANIMELIST, "profile_id = ? AND anime_id = ?", new String[]{userId.toString(), id.toString()}) == 1; if (result) { /* check if this record is used for other relations and delete if it's not to keep the database * still used relations can be: * - animelist of other user * - record is related to other anime or manga (e.g. as sequel or adaptation) */ // used in other animelist? boolean isUsed = recordExists(MALSqlHelper.TABLE_ANIMELIST, "anime_id", id.toString()); if (!isUsed) // no need to check more if its already used // used as related record of other anime? isUsed = recordExists(MALSqlHelper.TABLE_ANIME_ANIME_RELATIONS, "related_id", id.toString()); if (!isUsed) // no need to check more if its already used // used as related record of an manga? isUsed = recordExists(MALSqlHelper.TABLE_MANGA_ANIME_RELATIONS, "related_id", id.toString()); if (!isUsed) // its not used anymore, delete it deleteAnime(id); } } return result; } // delete all anime records without relations, because they're "dead" records public void cleanupAnimeTable() { getDBWrite().rawQuery("DELETE FROM anime WHERE " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT anime_id FROM " + MALSqlHelper.TABLE_ANIMELIST + ") AND " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT related_id FROM " + MALSqlHelper.TABLE_ANIME_ANIME_RELATIONS + ") AND " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT related_id FROM " + MALSqlHelper.TABLE_MANGA_ANIME_RELATIONS + ")", null); } public ArrayList<Anime> getAnimeList(String listType, String username) { return listType.equals("") ? getAnimeList(getUserId(username), "", false) : getAnimeList(getUserId(username), listType, false); } public ArrayList<Anime> getDirtyAnimeList(String username) { return getAnimeList(getUserId(username), "", true); } private ArrayList<Anime> getAnimeList(int userId, String listType, boolean dirtyOnly) { ArrayList<Anime> result = null; Cursor cursor; try { ArrayList<String> selArgs = new ArrayList<>(); selArgs.add(String.valueOf(userId)); if (!listType.equals("") && !listType.equals(Anime.STATUS_REWATCHING)) selArgs.add(listType); if (listType.equals(Anime.STATUS_REWATCHING)) cursor = getDBRead().rawQuery("SELECT a.*, al.score AS myScore, al.status AS myStatus, al.watched AS episodesWatched, al.dirty, al.lastUpdate," + " al.watchedStart, al.WatchedEnd, al.fansub, al.priority, al.downloaded, al.storage, al.storageValue, al.rewatch, al.rewatchCount, al.rewatchValue, al.comments" + " FROM animelist al INNER JOIN anime a ON al.anime_id = a." + MALSqlHelper.COLUMN_ID + " WHERE al.profile_id = ? AND al.rewatch = 1 " + (dirtyOnly ? " AND al.dirty IS NOT NULL " : "") + " ORDER BY a.recordName COLLATE NOCASE", selArgs.toArray(new String[selArgs.size()])); else cursor = getDBRead().rawQuery("SELECT a.*, al.score AS myScore, al.status AS myStatus, al.watched AS episodesWatched, al.dirty, al.lastUpdate," + " al.watchedStart, al.WatchedEnd, al.fansub, al.priority, al.downloaded, al.storage, al.storageValue, al.rewatch, al.rewatchCount, al.rewatchValue, al.comments" + " FROM animelist al INNER JOIN anime a ON al.anime_id = a." + MALSqlHelper.COLUMN_ID + " WHERE al.profile_id = ? " + (!listType.equals("") ? " AND al.status = ? " : "") + (dirtyOnly ? " AND al.dirty IS NOT NULL " : "") + " ORDER BY a.recordName COLLATE NOCASE", selArgs.toArray(new String[selArgs.size()])); if (cursor.moveToFirst()) { result = new ArrayList<>(); do result.add(Anime.fromCursor(cursor)); while (cursor.moveToNext()); } cursor.close(); } catch (SQLException e) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.getAnimeList(): " + e.getMessage()); } return result; } public void saveMangaList(ArrayList<Manga> list, String username) { Integer userId = getUserId(username); if (list != null && list.size() > 0 && userId != null) try { getDBWrite().beginTransaction(); for (Manga manga : list) saveManga(manga, true, userId); getDBWrite().setTransactionSuccessful(); } catch (Exception e) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.saveMangaList(): " + e.getMessage()); } finally { getDBWrite().endTransaction(); } } public void saveManga(Manga manga, boolean ignoreSynopsis, String username) { saveManga(manga, ignoreSynopsis, username.equals("") ? Integer.valueOf(0) : getUserId(username)); } public void saveManga(Manga manga, boolean ignoreSynopsis, int userId) { saveManga(manga, ignoreSynopsis, userId, false); } public void saveManga(Manga manga, boolean ignoreSynopsis, int userId, boolean dontCreateBaseModel) { ContentValues cv = new ContentValues(); if (!AccountService.isMAL() && manga.getReadStatus() == null && !dontCreateBaseModel) manga.createBaseModel(); cv.put(MALSqlHelper.COLUMN_ID, manga.getId()); cv.put("recordName", manga.getTitle()); cv.put("recordType", manga.getType()); cv.put("imageUrl", manga.getImageUrl()); cv.put("recordStatus", manga.getStatus()); cv.put("volumesTotal", manga.getVolumes()); cv.put("chaptersTotal", manga.getChapters()); if (!ignoreSynopsis) { cv.put("synopsis", manga.getSynopsis()); cv.put("membersCount", manga.getMembersCount()); cv.put("memberScore", manga.getMembersScore()); cv.put("favoritedCount", manga.getFavoritedCount()); cv.put("popularityRank", manga.getPopularityRank()); cv.put("rank", manga.getRank()); cv.put("listedId", manga.getListedId()); } // don't use replace it replaces synopsis with null even when we don't put it in the ContentValues int updateResult = getDBWrite().update(MALSqlHelper.TABLE_MANGA, cv, MALSqlHelper.COLUMN_ID + " = ?", new String[]{Integer.toString(manga.getId())}); if (updateResult == 0) { Long insertResult = getDBWrite().insert(MALSqlHelper.TABLE_MANGA, null, cv); if (insertResult > 0) { manga.setId(insertResult.intValue()); } } if (manga.getId() > 0) { // save/update relations if saving was successful if (!ignoreSynopsis) { // only on DetailView! if (manga.getGenres() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_GENRES, "manga_id = ?", new String[]{String.valueOf(manga.getId())}); for (String genre : manga.getGenres()) { Integer genreId = getGenreId(genre); if (genreId != null) { ContentValues gcv = new ContentValues(); gcv.put("manga_id", manga.getId()); gcv.put("genre_id", genreId); getDBWrite().replace(MALSqlHelper.TABLE_MANGA_GENRES, null, gcv); } } } saveTags(manga.getTags(), manga.getId(), MALSqlHelper.TABLE_MANGA_TAGS); saveTags(manga.getPersonalTags(), manga.getId(), MALSqlHelper.TABLE_MANGA_PERSONALTAGS); if (manga.getAlternativeVersions() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS, "manga_id = ? AND relationType = ?", new String[]{String.valueOf(manga.getId()), MALSqlHelper.RELATION_TYPE_ALTERNATIVE}); for (RecordStub mangaStub : manga.getAlternativeVersions()) saveMangaToMangaRelation(manga.getId(), mangaStub, MALSqlHelper.RELATION_TYPE_ALTERNATIVE); } if (manga.getRelatedManga() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS, "manga_id = ? AND relationType = ?", new String[]{String.valueOf(manga.getId()), MALSqlHelper.RELATION_TYPE_RELATED}); for (RecordStub mangaStub : manga.getRelatedManga()) saveMangaToMangaRelation(manga.getId(), mangaStub, MALSqlHelper.RELATION_TYPE_RELATED); } if (manga.getAnimeAdaptations() != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_MANGA_ANIME_RELATIONS, "manga_id = ? AND relationType = ?", new String[]{String.valueOf(manga.getId()), MALSqlHelper.RELATION_TYPE_ADAPTATION}); for (RecordStub animeStub : manga.getAnimeAdaptations()) saveMangaToAnimeRelation(manga.getId(), animeStub, MALSqlHelper.RELATION_TYPE_ADAPTATION); } if (manga.getOtherTitles() != null) { saveOtherTitles(manga.getOtherTitlesEnglish(), manga.getId(), MALSqlHelper.TITLE_TYPE_ENGLISH, MALSqlHelper.TABLE_MANGA_OTHER_TITLES); saveOtherTitles(manga.getOtherTitlesJapanese(), manga.getId(), MALSqlHelper.TITLE_TYPE_JAPANESE, MALSqlHelper.TABLE_MANGA_OTHER_TITLES); saveOtherTitles(manga.getOtherTitlesSynonyms(), manga.getId(), MALSqlHelper.TITLE_TYPE_SYNONYM, MALSqlHelper.TABLE_MANGA_OTHER_TITLES); } } // update mangalist if user id is provided if (userId > 0) { ContentValues mlcv = new ContentValues(); mlcv.put("profile_id", userId); mlcv.put("manga_id", manga.getId()); mlcv.put("status", manga.getReadStatus()); mlcv.put("score", manga.getScore()); mlcv.put("volumesRead", manga.getVolumesRead()); mlcv.put("chaptersRead", manga.getChaptersRead()); mlcv.put("readStart", manga.getReadingStart()); mlcv.put("readEnd", manga.getReadingEnd()); mlcv.put("priority", manga.getPriority()); mlcv.put("downloaded", manga.getChapDownloaded()); mlcv.put("rereading", manga.getRereadValue()); mlcv.put("rereadCount", manga.getRereadCount()); mlcv.put("comments", manga.getPersonalComments()); mlcv.put("dirty", manga.getDirty() != null ? new Gson().toJson(manga.getDirty()) : null); if (manga.getLastUpdate() != null) mlcv.put("lastUpdate", manga.getLastUpdate().getTime()); getDBWrite().replace(MALSqlHelper.TABLE_MANGALIST, null, mlcv); } } } public Manga getManga(Integer id, String username) { Manga result = null; Cursor cursor = getDBRead().rawQuery("SELECT m.*, ml.score AS myScore, ml.status AS myStatus, ml.chaptersRead, ml.volumesRead, ml.readStart, ml.readEnd," + " ml.priority, ml.downloaded, ml.rereading, ml.rereadCount, ml.comments, ml.dirty, ml.lastUpdate" + " FROM mangalist ml INNER JOIN manga m ON ml.manga_id = m." + MALSqlHelper.COLUMN_ID + " WHERE ml.profile_id = ? and m." + MALSqlHelper.COLUMN_ID + " = ?", new String[]{getUserId(username).toString(), id.toString()}); if (cursor.moveToFirst()) { result = Manga.fromCursor(cursor); result.setGenres(getMangaGenres(result.getId())); result.setTags(getMangaTags(result.getId())); result.setPersonalTags(getMangaPersonalTags(result.getId()), false); result.setAlternativeVersions(getMangaToMangaRelations(result.getId(), MALSqlHelper.RELATION_TYPE_ALTERNATIVE)); result.setRelatedManga(getMangaToMangaRelations(result.getId(), MALSqlHelper.RELATION_TYPE_RELATED)); result.setAnimeAdaptations(getMangaToAnimeRelations(result.getId(), MALSqlHelper.RELATION_TYPE_ADAPTATION)); HashMap<String, ArrayList<String>> otherTitles = new HashMap<>(); otherTitles.put("english", getMangaOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_ENGLISH)); otherTitles.put("japanese", getMangaOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_JAPANESE)); otherTitles.put("synonyms", getMangaOtherTitles(result.getId(), MALSqlHelper.TITLE_TYPE_SYNONYM)); result.setOtherTitles(otherTitles); } cursor.close(); return result; } private boolean deleteManga(Integer id) { return getDBWrite().delete(MALSqlHelper.TABLE_MANGA, MALSqlHelper.COLUMN_ID + " = ?", new String[]{id.toString()}) == 1; } public boolean deleteMangaFromMangalist(Integer id, String username) { boolean result = false; Integer userId = getUserId(username); if (userId != 0) { result = getDBWrite().delete(MALSqlHelper.TABLE_MANGALIST, "profile_id = ? AND manga_id = ?", new String[]{userId.toString(), id.toString()}) == 1; if (result) { /* check if this record is used for other relations and delete if it's not to keep the database * still used relations can be: * - mangalist of other user * - record is related to other anime or manga (e.g. as sequel or adaptation) */ // used in other mangalist? boolean isUsed = recordExists(MALSqlHelper.TABLE_MANGALIST, "manga_id", id.toString()); if (!isUsed) // no need to check more if its already used // used as related record of other manga? isUsed = recordExists(MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS, "related_id", id.toString()); if (!isUsed) // no need to check more if its already used // used as related record of an anime? isUsed = recordExists(MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS, "related_id", id.toString()); if (!isUsed) // its not used anymore, delete it deleteManga(id); } } return result; } // delete all manga records without relations, because they're "dead" records public void cleanupMangaTable() { getDBWrite().rawQuery("DELETE FROM manga WHERE " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT manga_id FROM " + MALSqlHelper.TABLE_MANGALIST + ") AND " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT related_id FROM " + MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS + ") AND " + MALSqlHelper.COLUMN_ID + " NOT IN (SELECT DISTINCT related_id FROM " + MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS + ")", null); } public ArrayList<Manga> getMangaList(String listType, String username) { if (listType.equals("")) return getMangaList(getUserId(username), "", false); else return getMangaList(getUserId(username), listType, false); } public ArrayList<Manga> getDirtyMangaList(String username) { return getMangaList(getUserId(username), "", true); } private ArrayList<Manga> getMangaList(int userId, String listType, boolean dirtyOnly) { ArrayList<Manga> result = null; Cursor cursor; try { ArrayList<String> selArgs = new ArrayList<>(); selArgs.add(String.valueOf(userId)); if (!listType.equals("")) selArgs.add(listType); cursor = getDBRead().rawQuery("SELECT m.*, ml.score AS myScore, ml.status AS myStatus, ml.chaptersRead, ml.volumesRead, ml.readStart, ml.readEnd," + " ml.priority, ml.downloaded, ml.rereading, ml.rereadCount, ml.comments, ml.dirty, ml.lastUpdate" + " FROM mangalist ml INNER JOIN manga m ON ml.manga_id = m." + MALSqlHelper.COLUMN_ID + " WHERE ml.profile_id = ? " + (!listType.equals("") ? " AND ml.status = ? " : "") + (dirtyOnly ? " AND ml.dirty <> \"\" " : "") + " ORDER BY m.recordName COLLATE NOCASE", selArgs.toArray(new String[selArgs.size()])); if (cursor.moveToFirst()) { result = new ArrayList<>(); do result.add(Manga.fromCursor(cursor)); while (cursor.moveToNext()); } cursor.close(); } catch (SQLException e) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.getMangaList(): " + e.getMessage()); } return result; } public void saveProfile(Profile profile) { ContentValues cv = new ContentValues(); cv.put("username", profile.getDisplayName()); cv.put("anime_time", profile.getAnimeTime()); cv.put("manga_chap", profile.getMangaChapters()); cv.put("about", profile.getAbout()); cv.put("list_order", profile.getListOrder()); cv.put("avatar_url", profile.getImageUrl()); cv.put("image_url_banner", profile.getImageUrlBanner()); cv.put("title_language", profile.getTitleLanguage()); cv.put("score_type", profile.getScoreType()); //cv.put("advanced_rating", profile.getAdvancedRating()); cv.put("notifications", profile.getNotifications()); // don't use replace it alters the autoincrement _id field! int updateResult = getDBWrite().update(MALSqlHelper.TABLE_PROFILE, cv, "username = ?", new String[]{profile.getDisplayName()}); if (updateResult > 0) {// updated row profile.setId(getUserId(profile.getDisplayName())); } else { Long insertResult = getDBWrite().insert(MALSqlHelper.TABLE_PROFILE, null, cv); profile.setId(insertResult.intValue()); } if (AccountService.getUsername().equals(profile.getDisplayName())) { PrefManager.setScoreType(profile.getScoreType() + 1); PrefManager.commitChanges(); } } public void saveUser(User profile) { ContentValues cv = new ContentValues(); cv.put("username", profile.getDisplayName()); cv.put("avatar_url", profile.getImageUrl()); // don't use replace it alters the autoincrement _id field! int updateResult = getDBWrite().update(MALSqlHelper.TABLE_PROFILE, cv, "username = ?", new String[]{profile.getDisplayName()}); if (updateResult > 0) {// updated row profile.setId(getUserId(profile.getDisplayName())); } else { Long insertResult = getDBWrite().insert(MALSqlHelper.TABLE_PROFILE, null, cv); profile.setId(insertResult.intValue()); } } public void saveUser(User user, Boolean profile) { ContentValues cv = new ContentValues(); cv.put("username", user.getName()); if (user.getProfile().getAvatarUrl().equals("http://cdn.myanimelist.net/images/questionmark_50.gif")) cv.put("avatar_url", "http://cdn.myanimelist.net/images/na.gif"); else cv.put("avatar_url", user.getProfile().getAvatarUrl()); if (user.getProfile().getDetails().getLastOnline() != null) cv.put("last_online", user.getProfile().getDetails().getLastOnline()); else cv.putNull("last_online"); if (profile) { if (user.getProfile().getDetails().getBirthday() != null) { String birthday = MALDateTools.parseMALDateToISO8601String(user.getProfile().getDetails().getBirthday()); cv.put("birthday", birthday.equals("") ? user.getProfile().getDetails().getBirthday() : birthday); } else cv.putNull("birthday"); cv.put("location", user.getProfile().getDetails().getLocation()); cv.put("website", user.getProfile().getDetails().getWebsite()); cv.put("comments", user.getProfile().getDetails().getComments()); cv.put("forum_posts", user.getProfile().getDetails().getForumPosts()); cv.put("gender", user.getProfile().getDetails().getGender()); if (user.getProfile().getDetails().getJoinDate() != null) { String joindate = MALDateTools.parseMALDateToISO8601String(user.getProfile().getDetails().getJoinDate()); cv.put("join_date", joindate.equals("") ? user.getProfile().getDetails().getJoinDate() : joindate); } else cv.putNull("join_date"); cv.put("access_rank", user.getProfile().getDetails().getAccessRank()); cv.put("anime_list_views", user.getProfile().getDetails().getAnimeListViews()); cv.put("manga_list_views", user.getProfile().getDetails().getMangaListViews()); cv.put("anime_time_days", user.getProfile().getAnimeStats().getTimeDays()); cv.put("anime_watching", user.getProfile().getAnimeStats().getWatching()); cv.put("anime_completed", user.getProfile().getAnimeStats().getCompleted()); cv.put("anime_on_hold", user.getProfile().getAnimeStats().getOnHold()); cv.put("anime_dropped", user.getProfile().getAnimeStats().getDropped()); cv.put("anime_plan_to_watch", user.getProfile().getAnimeStats().getPlanToWatch()); cv.put("anime_total_entries", user.getProfile().getAnimeStats().getTotalEntries()); cv.put("manga_time_days", user.getProfile().getMangaStats().getTimeDays()); cv.put("manga_reading", user.getProfile().getMangaStats().getReading()); cv.put("manga_completed", user.getProfile().getMangaStats().getCompleted()); cv.put("manga_on_hold", user.getProfile().getMangaStats().getOnHold()); cv.put("manga_dropped", user.getProfile().getMangaStats().getDropped()); cv.put("manga_plan_to_read", user.getProfile().getMangaStats().getPlanToRead()); cv.put("manga_total_entries", user.getProfile().getMangaStats().getTotalEntries()); } // don't use replace it alters the autoincrement _id field! int updateResult = getDBWrite().update(MALSqlHelper.TABLE_PROFILE, cv, "username = ?", new String[]{user.getName()}); if (updateResult > 0) {// updated row user.setId(getUserId(user.getName())); } else { Long insertResult = getDBWrite().insert(MALSqlHelper.TABLE_PROFILE, null, cv); user.setId(insertResult.intValue()); } } public void saveUserFriends(Integer userId, ArrayList<User> friends) { if (userId == null || friends == null) { return; } SQLiteDatabase db = getDBWrite(); db.beginTransaction(); try { db.delete(MALSqlHelper.TABLE_FRIENDLIST, "profile_id = ?", new String[]{userId.toString()}); for (User friend : friends) { ContentValues cv = new ContentValues(); cv.put("profile_id", userId); cv.put("friend_id", friend.getId()); db.insert(MALSqlHelper.TABLE_FRIENDLIST, null, cv); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } public User getProfile(String name) { User result = null; Cursor cursor; try { cursor = getDBRead().query(MALSqlHelper.TABLE_PROFILE, null, "username = ?", new String[]{name}, null, null, null); if (cursor.moveToFirst()) result = User.fromCursor(cursor); cursor.close(); } catch (SQLException e) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.getProfile(): " + e.getMessage()); } return result; } public ArrayList<User> getFriendList(String username) { ArrayList<User> friendlist = new ArrayList<>(); Cursor cursor = getDBRead().rawQuery("SELECT p1.* FROM " + MALSqlHelper.TABLE_PROFILE + " AS p1" + // for result rows " INNER JOIN " + MALSqlHelper.TABLE_PROFILE + " AS p2" + // for getting user id to given name " INNER JOIN " + MALSqlHelper.TABLE_FRIENDLIST + " AS fl ON fl.profile_id = p2." + MALSqlHelper.COLUMN_ID + // for user<>friend relation " WHERE p2.username = ? AND p1." + MALSqlHelper.COLUMN_ID + " = fl.friend_id ORDER BY p1.username COLLATE NOCASE", new String[]{username}); if (cursor.moveToFirst()) { do friendlist.add(User.fromCursor(cursor)); while (cursor.moveToNext()); } cursor.close(); return friendlist; } public void saveFriendList(ArrayList<User> friendlist, String username) { for (User friend : friendlist) if (AccountService.isMAL()) saveUser(friend, false); else saveUser(friend); Integer userId = getUserId(username); saveUserFriends(userId, friendlist); } private Integer getGenreId(String genre) { return getRecordId(MALSqlHelper.TABLE_GENRES, MALSqlHelper.COLUMN_ID, "recordName", genre); } private Integer getTagId(String tag) { return getRecordId(MALSqlHelper.TABLE_TAGS, MALSqlHelper.COLUMN_ID, "recordName", tag); } private Integer getProducerId(String producer) { return getRecordId(MALSqlHelper.TABLE_PRODUCER, MALSqlHelper.COLUMN_ID, "recordName", producer); } private Integer getUserId(String username) { if (username == null || username.equals("")) return 0; Integer id = getRecordId(MALSqlHelper.TABLE_PROFILE, MALSqlHelper.COLUMN_ID, "username", username); if (id == null) id = 0; return id; } private Integer getRecordId(String table, String idField, String searchField, String value) { Integer result = null; Cursor cursor = getDBRead().query(table, new String[]{idField}, searchField + " = ?", new String[]{value}, null, null, null); if (cursor.moveToFirst()) result = cursor.getInt(0); cursor.close(); if (result == null) { ContentValues cv = new ContentValues(); cv.put(searchField, value); Long addResult = getDBWrite().insert(table, null, cv); if (addResult > -1) result = addResult.intValue(); } return result; } public ArrayList<String> getAnimeGenres(Integer animeId) { return getArrayListString(getDBRead().rawQuery("SELECT g.recordName FROM " + MALSqlHelper.TABLE_GENRES + " g " + "INNER JOIN " + MALSqlHelper.TABLE_ANIME_GENRES + " ag ON ag.genre_id = g." + MALSqlHelper.COLUMN_ID + " WHERE ag.anime_id = ? ORDER BY g.recordName COLLATE NOCASE", new String[]{animeId.toString()})); } public ArrayList<String> getAnimeTags(Integer animeId) { return getArrayListString(getDBRead().rawQuery("SELECT t.recordName FROM " + MALSqlHelper.TABLE_TAGS + " t " + "INNER JOIN " + MALSqlHelper.TABLE_ANIME_TAGS + " at ON at.tag_id = t." + MALSqlHelper.COLUMN_ID + " WHERE at.anime_id = ? ORDER BY t.recordName COLLATE NOCASE", new String[]{animeId.toString()})); } public ArrayList<String> getAnimePersonalTags(Integer animeId) { return getArrayListString(getDBRead().rawQuery("SELECT t.recordName FROM " + MALSqlHelper.TABLE_TAGS + " t " + "INNER JOIN " + MALSqlHelper.TABLE_ANIME_PERSONALTAGS + " at ON at.tag_id = t." + MALSqlHelper.COLUMN_ID + " WHERE at.anime_id = ? ORDER BY t.recordName COLLATE NOCASE", new String[]{animeId.toString()})); } public ArrayList<String> getMangaPersonalTags(Integer mangaId) { return getArrayListString(getDBRead().rawQuery("SELECT t.recordName FROM " + MALSqlHelper.TABLE_TAGS + " t " + "INNER JOIN " + MALSqlHelper.TABLE_MANGA_PERSONALTAGS + " at ON at.tag_id = t." + MALSqlHelper.COLUMN_ID + " WHERE at.manga_id = ? ORDER BY t.recordName COLLATE NOCASE", new String[]{mangaId.toString()})); } public ArrayList<String> getMangaGenres(Integer mangaId) { return getArrayListString(getDBRead().rawQuery("SELECT g.recordName FROM " + MALSqlHelper.TABLE_GENRES + " g " + "INNER JOIN " + MALSqlHelper.TABLE_MANGA_GENRES + " mg ON mg.genre_id = g." + MALSqlHelper.COLUMN_ID + " WHERE mg.manga_id = ? ORDER BY g.recordName COLLATE NOCASE", new String[]{mangaId.toString()})); } public ArrayList<String> getMangaTags(Integer mangaId) { return getArrayListString(getDBRead().rawQuery("SELECT t.recordName FROM " + MALSqlHelper.TABLE_TAGS + " t " + "INNER JOIN " + MALSqlHelper.TABLE_MANGA_TAGS + " mt ON mt.tag_id = t." + MALSqlHelper.COLUMN_ID + " WHERE mt.manga_id = ? ORDER BY t.recordName COLLATE NOCASE", new String[]{mangaId.toString()})); } public ArrayList<String> getAnimeProducers(Integer animeId) { return getArrayListString(getDBRead().rawQuery("SELECT p.recordName FROM " + MALSqlHelper.TABLE_PRODUCER + " p " + "INNER JOIN " + MALSqlHelper.TABLE_ANIME_PRODUCER + " ap ON ap.producer_id = p." + MALSqlHelper.COLUMN_ID + " WHERE ap.anime_id = ? ORDER BY p.recordName COLLATE NOCASE", new String[]{animeId.toString()})); } private ArrayList<String> getAnimeOtherTitles(Integer animeId, String titleType) { return getArrayListString(getDBRead().query(MALSqlHelper.TABLE_ANIME_OTHER_TITLES, new String[]{"title"}, "anime_id = ? AND titleType = ?", new String[]{animeId.toString(), titleType}, null, null, "title COLLATE NOCASE")); } private ArrayList<String> getMangaOtherTitles(Integer mangaId, String titleType) { return getArrayListString(getDBRead().query(MALSqlHelper.TABLE_MANGA_OTHER_TITLES, new String[]{"title"}, "manga_id = ? AND titleType = ?", new String[]{mangaId.toString(), titleType}, null, null, "title COLLATE NOCASE")); } private ArrayList<String> getArrayListString(Cursor cursor) { ArrayList<String> result = null; if (cursor.moveToFirst()) { result = new ArrayList<>(); do result.add(cursor.getString(0)); while (cursor.moveToNext()); } cursor.close(); return result; } private boolean recordExists(String table, String searchField, String searchValue) { Cursor cursor = getDBRead().query(table, null, searchField + " = ?", new String[]{searchValue}, null, null, null); boolean result = cursor.moveToFirst(); cursor.close(); return result; } private void saveAnimeToAnimeRelation(int animeId, RecordStub relatedAnime, String relationType) { saveRelation(animeId, relatedAnime, relationType, MALSqlHelper.TABLE_ANIME_ANIME_RELATIONS, MALSqlHelper.TABLE_ANIME); } private void saveAnimeToMangaRelation(int animeId, RecordStub relatedManga, String relationType) { saveRelation(animeId, relatedManga, relationType, MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS, MALSqlHelper.TABLE_MANGA); } private void saveMangaToMangaRelation(int mangaId, RecordStub relatedManga, String relationType) { saveRelation(mangaId, relatedManga, relationType, MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS, MALSqlHelper.TABLE_MANGA); } private void saveMangaToAnimeRelation(int mangaId, RecordStub relatedAnime, String relationType) { saveRelation(mangaId, relatedAnime, relationType, MALSqlHelper.TABLE_MANGA_ANIME_RELATIONS, MALSqlHelper.TABLE_ANIME); } /* Storing relations is a little more complicated as we need to look if the related anime is * stored in the database, if not we need to create a new record before storing the information. * This record then only has the few informations that are available in the relation object * returned by the API (only id and title) */ private void saveRelation(int id, RecordStub related, String relationType, String relationTable, String table) { if (related.getId() == 0) { Crashlytics.log(Log.ERROR, "MALX", "DatabaseManager.saveRelation(): error saving relation: id must not be 0; title: " + related.getTitle()); return; } boolean relatedRecordExists; if (!recordExists(table, MALSqlHelper.COLUMN_ID, String.valueOf(related.getId()))) { ContentValues cv = new ContentValues(); cv.put(MALSqlHelper.COLUMN_ID, related.getId()); cv.put("recordName", related.getTitle()); relatedRecordExists = getDBWrite().insert(table, null, cv) > 0; } else { relatedRecordExists = true; } if (relatedRecordExists) { ContentValues cv = new ContentValues(); if (relationTable.contains("rel_anime")) cv.put("anime_id", id); else cv.put("manga_id", id); cv.put("related_id", related.getId()); cv.put("relationType", relationType); getDBWrite().replace(relationTable, null, cv); } } private ArrayList<RecordStub> getAnimeToAnimeRelations(Integer animeId, String relationType) { return getRecordStub("SELECT a." + MALSqlHelper.COLUMN_ID + ", a.recordName FROM " + MALSqlHelper.TABLE_ANIME + " a " + "INNER JOIN " + MALSqlHelper.TABLE_ANIME_ANIME_RELATIONS + " ar ON a." + MALSqlHelper.COLUMN_ID + " = ar.related_id " + "WHERE ar.anime_id = ? AND ar.relationType = ? ORDER BY a.recordName COLLATE NOCASE", animeId, relationType, MALApi.ListType.ANIME); } private ArrayList<RecordStub> getAnimeToMangaRelations(Integer animeId, String relationType) { return getRecordStub("SELECT m." + MALSqlHelper.COLUMN_ID + ", m.recordName FROM " + MALSqlHelper.TABLE_MANGA + " m " + "INNER JOIN " + MALSqlHelper.TABLE_ANIME_MANGA_RELATIONS + " ar ON m." + MALSqlHelper.COLUMN_ID + " = ar.related_id " + "WHERE ar.anime_id = ? AND ar.relationType = ? ORDER BY m.recordName COLLATE NOCASE", animeId, relationType, MALApi.ListType.MANGA); } private ArrayList<RecordStub> getMangaToMangaRelations(Integer mangaId, String relationType) { return getRecordStub("SELECT m." + MALSqlHelper.COLUMN_ID + ", m.recordName FROM " + MALSqlHelper.TABLE_MANGA + " m " + "INNER JOIN " + MALSqlHelper.TABLE_MANGA_MANGA_RELATIONS + " mr ON m." + MALSqlHelper.COLUMN_ID + " = mr.related_id " + "WHERE mr.manga_id = ? AND mr.relationType = ? ORDER BY m.recordName COLLATE NOCASE", mangaId, relationType, MALApi.ListType.MANGA); } private ArrayList<RecordStub> getMangaToAnimeRelations(Integer mangaId, String relationType) { return getRecordStub("SELECT a." + MALSqlHelper.COLUMN_ID + ", a.recordName FROM " + MALSqlHelper.TABLE_ANIME + " a " + "INNER JOIN " + MALSqlHelper.TABLE_MANGA_ANIME_RELATIONS + " mr ON a." + MALSqlHelper.COLUMN_ID + " = mr.related_id " + "WHERE mr.manga_id = ? AND mr.relationType = ? ORDER BY a.recordName COLLATE NOCASE", mangaId, relationType, MALApi.ListType.ANIME); } /** * Get recordStub lists from the Database * * @param Query The query to peform * @param id The anime/manga ID * @param relationType The relation type * @param listType The ListType (Anime or Manga) * @return ArrayList recordStub */ private ArrayList<RecordStub> getRecordStub(String Query, Integer id, String relationType, MALApi.ListType listType) { ArrayList<RecordStub> result = null; Cursor cursor = getDBRead().rawQuery(Query, new String[]{id.toString(), relationType}); if (cursor.moveToFirst()) { result = new ArrayList<>(); do { RecordStub recordStub = new RecordStub(); recordStub.setId(cursor.getInt(0), listType); recordStub.setTitle(cursor.getString(1)); result.add(recordStub); } while (cursor.moveToNext()); } cursor.close(); return result; } /** * Save the Tags into the database * * @param record The arraylist with the tags * @param id The anime id * @param tableName The table name */ private void saveTags(ArrayList<String> record, int id, String tableName) { String name = tableName.contains("anime") ? "anime_id" : "manga_id"; if (record != null) { // delete old relations getDBWrite().delete(tableName, name + " = ?", new String[]{String.valueOf(id)}); for (String tag : record) { Integer tagId = getTagId(tag); if (tagId != null) { ContentValues gcv = new ContentValues(); gcv.put(name, id); gcv.put("tag_id", tagId); getDBWrite().replace(tableName, null, gcv); } } } } /** * Save the alternative anime/manga titles to the database * * @param record The arraylist with the alternative names * @param id The anime/manga id * @param relationType The alternative title */ private void saveOtherTitles(ArrayList<String> record, int id, String relationType, String tableName) { String name = tableName.contains("anime") ? "anime_id" : "manga_id"; if (record != null) { // delete old relations getDBWrite().delete(tableName, name + " = ? and titleType = ?", new String[]{String.valueOf(id), relationType}); for (String title : record) { ContentValues cv = new ContentValues(); cv.put(name, id); cv.put("titleType", relationType); cv.put("title", title); getDBWrite().replace(tableName, null, cv); } } } /** * Save the Anime to Anime relations like sequel * * @param record Relations like sequel * @param id The anime id * @param relationType The relation type */ private void saveAnimeToAnimeRelation(ArrayList<RecordStub> record, int id, String relationType) { if (record != null) { // delete old relations getDBWrite().delete(MALSqlHelper.TABLE_ANIME_ANIME_RELATIONS, "anime_id = ? AND relationType = ?", new String[]{String.valueOf(id), relationType}); for (RecordStub stub : record) saveAnimeToAnimeRelation(id, stub, relationType); } } public void saveActivity(ArrayList<Activity> activities, String username) { Integer userId = getUserId(username); if (userId > 0) { for (Activity activity : activities) { ContentValues cv = new ContentValues(); cv.put(MALSqlHelper.COLUMN_ID, activity.getId()); cv.put("user", userId); cv.put("type", activity.getActivityType()); cv.put("created", activity.getCreatedAt()); cv.put("reply_count", activity.getReplyCount()); cv.put("status", activity.getStatus()); cv.put("value", activity.getValue()); if (activity.getSeries() != null) { if (activity.getSeries().getSeriesType().equals("anime")) { Anime anime = activity.getSeries().getAnime(); if (anime != null) { saveAnime(anime, true, 0, true); cv.put("series_anime", activity.getSeries().getId()); } } else if (activity.getSeries().getSeriesType().equals("manga")) { Manga manga = activity.getSeries().getManga(); if (manga != null) { saveManga(manga, true, 0, true); cv.put("series_manga", activity.getSeries().getId()); } } } getDBWrite().replace(MALSqlHelper.TABLE_ACTIVITIES, null, cv); if (activity.getUsers() != null) { for (Profile user : activity.getUsers()) { ContentValues ucv = new ContentValues(); ucv.put("profile_id", getUserId(user.getDisplayName())); ucv.put("activity_id", activity.getId()); getDBWrite().replace(MALSqlHelper.TABLE_ACTIVITIES_USERS, null, ucv); } } } } } public ArrayList<Activity> getActivity(String username) { ArrayList<Activity> result = null; Cursor cursor = getDBRead().query(MALSqlHelper.TABLE_ACTIVITIES, null, "user = ?", new String[]{getUserId(username).toString()}, null, null, MALSqlHelper.COLUMN_ID + " DESC"); if (cursor.moveToFirst()) { result = new ArrayList<>(); do { Activity activity = new Activity(); activity.setId(cursor.getInt(cursor.getColumnIndex(MALSqlHelper.COLUMN_ID))); activity.setUserId(cursor.getInt(cursor.getColumnIndex("user"))); activity.setActivityType(cursor.getString(cursor.getColumnIndex("type"))); activity.setCreatedAt(cursor.getString(cursor.getColumnIndex("created"))); activity.setReplyCount(cursor.getInt(cursor.getColumnIndex("reply_count"))); activity.setStatus(cursor.getString(cursor.getColumnIndex("status"))); activity.setValue(cursor.getString(cursor.getColumnIndex("value"))); if (!cursor.isNull(cursor.getColumnIndex("series_anime"))) { Anime anime = getAnime(cursor.getInt(cursor.getColumnIndex("series_anime")), username); if (anime != null) activity.setSeries(Series.fromAnime(anime)); } if (!cursor.isNull(cursor.getColumnIndex("series_manga"))) { Manga manga = getManga(cursor.getInt(cursor.getColumnIndex("series_manga")), username); if (manga != null) activity.setSeries(Series.fromManga(manga)); } Cursor userCursor = getDBWrite().rawQuery("SELECT p.* FROM " + MALSqlHelper.TABLE_PROFILE + " p INNER JOIN " + MALSqlHelper.TABLE_ACTIVITIES_USERS + " au ON p." + MALSqlHelper.COLUMN_ID + " = au.profile_id WHERE au.activity_id = ?", new String[]{String.valueOf(activity.getId())}); if (userCursor.moveToFirst()) { ArrayList<Profile> users = new ArrayList<>(); do { Profile profile = Profile.fromCursor(userCursor); users.add(profile); } while (userCursor.moveToNext()); activity.setUsers(users); } userCursor.close(); result.add(activity); } while (cursor.moveToNext()); } cursor.close(); return result; } }
package com.amverhagen.pulsedodge; import com.amverhagen.pulsedodge.playcomponents.CircleLine; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.input.GestureDetector; import com.badlogic.gdx.input.GestureDetector.GestureListener; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.viewport.Viewport; public class PulseDodge extends ApplicationAdapter implements InputProcessor, GestureListener { private InputMultiplexer inputMultiplexer; private final int GAME_WORLD_WIDTH = 900; private final int GAME_WORLD_HEIGHT = 1600; private GestureDetector gestureDetector; private SpriteBatch batch; private CircleLine circleLine; private Viewport viewport; private Camera camera; private Sprite background; @Override public void create() { inputMultiplexer = new InputMultiplexer(); gestureDetector = new GestureDetector(this); InputProcessor ip = this; inputMultiplexer.addProcessor(gestureDetector); inputMultiplexer.addProcessor(ip); camera = new OrthographicCamera(); camera.position.set(GAME_WORLD_WIDTH / 2, GAME_WORLD_HEIGHT / 2, 0); viewport = new FitViewport(GAME_WORLD_WIDTH, GAME_WORLD_HEIGHT, camera); viewport.apply(); batch = new SpriteBatch(); background = new Sprite(new Texture( Gdx.files.internal("background.png"))); background.setPosition(0, 0); background.setSize(GAME_WORLD_WIDTH, GAME_WORLD_HEIGHT); circleLine = new CircleLine(5, 0f, GAME_WORLD_HEIGHT / 3f, GAME_WORLD_WIDTH, GAME_WORLD_HEIGHT); Gdx.input.setInputProcessor(inputMultiplexer); } @Override public void resize(int width, int height) { viewport.update(width, height); camera.position.set(GAME_WORLD_WIDTH / 2, GAME_WORLD_HEIGHT / 2, 0); } @Override public void render() { Gdx.gl.glClearColor(0, 1, 0f, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); camera.update(); batch.setProjectionMatrix(camera.combined); batch.begin(); background.draw(batch); circleLine.getCircle().draw(batch); batch.end(); } @Override public boolean keyDown(int keycode) { if (keycode == Keys.D) { circleLine.moveRight(); } if (keycode == Keys.A) { circleLine.moveLeft(); } return false; } @Override public boolean keyUp(int keycode) { // TODO Auto-generated method stub return false; } @Override public boolean keyTyped(char character) { // TODO Auto-generated method stub return false; } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { // TODO Auto-generated method stub return false; } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { // TODO Auto-generated method stub return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { // TODO Auto-generated method stub return false; } @Override public boolean mouseMoved(int screenX, int screenY) { // TODO Auto-generated method stub return false; } @Override public boolean scrolled(int amount) { // TODO Auto-generated method stub return false; } @Override public boolean touchDown(float x, float y, int pointer, int button) { // TODO Auto-generated method stub return false; } @Override public boolean tap(float x, float y, int count, int button) { // TODO Auto-generated method stub return false; } @Override public boolean longPress(float x, float y) { // TODO Auto-generated method stub return false; } @Override public boolean fling(float velocityX, float velocityY, int button) { if (Math.abs(velocityX) > Math.abs(velocityY)) { if (velocityX > 0) { circleLine.moveRight(); ; } else { circleLine.moveLeft(); } } // TODO Auto-generated method stub return false; } @Override public boolean pan(float x, float y, float deltaX, float deltaY) { // TODO Auto-generated method stub return false; } @Override public boolean panStop(float x, float y, int pointer, int button) { // TODO Auto-generated method stub return false; } @Override public boolean zoom(float initialDistance, float distance) { // TODO Auto-generated method stub return false; } @Override public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1, Vector2 pointer2) { // TODO Auto-generated method stub return false; } }
package net.silentchaos512.gems.config; import java.io.File; import java.util.List; import com.google.common.collect.Lists; import net.minecraft.util.math.MathHelper; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.config.IConfigElement; import net.silentchaos512.gems.lib.EnumGem; import net.silentchaos512.gems.lib.module.ModuleCoffee; import net.silentchaos512.gems.lib.module.ModuleEntityRandomEquipment; import net.silentchaos512.gems.util.WeightedRandomItemSG; public class GemsConfig { /* * Debug */ public static boolean DEBUG_LOG_POTS_AND_LIGHTS = false; public static int DEBUG_LOT_POTS_AND_LIGHTS_DELAY = 1200; /* * Blocks */ public static int GLOW_ROSE_LIGHT_LEVEL = 10; public static int TELEPORTER_FREE_RANGE = 64; public static int TELEPORTER_COST_PER_BLOCK = 100; public static int TELEPORTER_COST_CROSS_DIMENSION = 100000; public static int TELEPORTER_MAX_CHARGE = 1000000; public static float TELEPORTER_REDSTONE_SEARCH_RADIUS = 2.0f; public static boolean TELEPORTER_ALLOW_DUMB = true; /* * Items */ public static int BURN_TIME_CHAOS_COAL = 6400; public static int FOOD_SUPPORT_DURATION = 600; public static float FOOD_SECRET_DONUT_CHANCE = 0.33f; public static float FOOD_SECRET_DONUT_TEXT_CHANCE = 0.6f; public static int RETURN_HOME_USE_TIME = 16; public static int RETURN_HOME_USE_COST = 10000; public static int RETURN_HOME_MAX_CHARGE = 100000; /* * Tools */ // TODO /* * GUI */ public static boolean SHOW_BONUS_ARMOR_BAR = true; /* * Recipes */ public static boolean RECIPE_TELEPORTER_DISABLE = false; public static boolean RECIPE_TELEPORTER_ANCHOR_DISABLE = false; public static boolean RECIPE_TELEPORTER_REDSTONE_DISABLE = false; public static boolean RECIPE_TOKEN_FROST_WALKER_DISABLE = false; public static boolean RECIPE_TOKEN_MENDING_DISABLE = false; /* * Misc */ public static boolean HIDE_FLAVOR_TEXT_ALWAYS = false; public static boolean HIDE_FLAVOR_TEXT_UNTIL_SHIFT = true; public static boolean RIGHT_CLICK_TO_PLACE_ENABLED = true; public static boolean RIGHT_CLICK_TO_PLACE_ON_SNEAK_ONLY = false; /* * World generation */ public static ConfigOptionOreGen WORLD_GEN_GEMS; public static ConfigOptionOreGen WORLD_GEN_GEMS_DARK; public static ConfigOptionOreGen WORLD_GEN_CHAOS; public static ConfigOptionOreGen WORLD_GEN_ENDER; public static List<WeightedRandomItemSG> GEM_WEIGHTS = Lists.newArrayList(); public static List<WeightedRandomItemSG> GEM_WEIGHTS_DARK = Lists.newArrayList(); public static int GLOW_ROSE_PER_CHUNK = 2; public static float CHAOS_NODES_PER_CHUNK = 0.006f; /* * Categories */ static final String split = Configuration.CATEGORY_SPLITTER; public static final String CAT_MAIN = "Main"; public static final String CAT_DEBUG = CAT_MAIN + split + "Debug"; public static final String CAT_BLOCK = CAT_MAIN + split + "Blocks"; public static final String CAT_CONTROLS = CAT_MAIN + split + "Controls"; public static final String CAT_ENCHANTMENT = CAT_MAIN + split + "Enchantment"; public static final String CAT_GUI = CAT_MAIN + split + "GUI"; public static final String CAT_ITEM = CAT_MAIN + split + "Items"; public static final String CAT_RECIPE = CAT_MAIN + split + "Recipes"; public static final String CAT_TOOLTIPS = CAT_MAIN + split + "Tooltips"; public static final String CAT_WORLD_GEN = CAT_MAIN + split + "World Generation"; public static final String CAT_WORLD_GEN_GEM_WEIGHT = CAT_WORLD_GEN + split + "Gem Weights"; private static File configFile; private static Configuration c; public static void init(File file) { configFile = file; c = new Configuration(file); load(); } public static void load() { try { //@formatter:off /* * Debug */ c.setCategoryComment(CAT_DEBUG, "Options for debugging. Generally, you should leave these " + "alone unless I tell you to change them. Enabling debug options will likely result in " + "log spam, but may help me track down issues."); DEBUG_LOG_POTS_AND_LIGHTS = c.getBoolean("Log Pots and Lights", CAT_DEBUG, DEBUG_LOG_POTS_AND_LIGHTS, "Logs the existence of Chaos Flower Pots and Phantom Lights. Their tile entities, to " + "be more precise. Also lists the position of each one."); DEBUG_LOT_POTS_AND_LIGHTS_DELAY = c.getInt("Log Pots and Lights - Delay", CAT_DEBUG, DEBUG_LOT_POTS_AND_LIGHTS_DELAY, 600, 72000, "Pot and Light logging will occur every this many ticks. 1200 ticks = 1 minute."); /* * Blocks */ final String catGlowRose = CAT_BLOCK + split + "Glow Rose"; GLOW_ROSE_LIGHT_LEVEL = c.getInt("Light Level", catGlowRose, GLOW_ROSE_LIGHT_LEVEL, 0, 15, "The light level glow roses emit."); final String catTeleporter = CAT_BLOCK + split + "Teleporter"; TELEPORTER_ALLOW_DUMB = c.getBoolean("Allow Dumb Teleporters", catTeleporter, TELEPORTER_ALLOW_DUMB, "Allows teleports to happen even if the destination teleporter has been removed."); TELEPORTER_COST_CROSS_DIMENSION = c.getInt("Chaos Cost Cross Dimension", catTeleporter, TELEPORTER_COST_CROSS_DIMENSION, 0, Integer.MAX_VALUE, "The amount of Chaos charged for traveling between dimensions."); TELEPORTER_COST_PER_BLOCK = c.getInt("Chaos Cost Per Block", catTeleporter, TELEPORTER_COST_PER_BLOCK, 0, Integer.MAX_VALUE, "The amount of Chaos charged per block traveled."); TELEPORTER_FREE_RANGE = c.getInt("Free Range", catTeleporter, TELEPORTER_FREE_RANGE, 0, Integer.MAX_VALUE, "The distance that can be teleported for free."); TELEPORTER_MAX_CHARGE = c.getInt("Max Chaos", catTeleporter, TELEPORTER_MAX_CHARGE, 0, Integer.MAX_VALUE, "The maximum amount of Chaos a teleporter can store."); /* * Items */ BURN_TIME_CHAOS_COAL = c.getInt("Chaos Coal Burn Time", CAT_ITEM, BURN_TIME_CHAOS_COAL, 0, Integer.MAX_VALUE, "The burn time of Chaos Coal. Regular coal is 1600 ticks."); // Food final String catFood = CAT_ITEM + split + "Food"; FOOD_SUPPORT_DURATION = c.getInt("Support Duration", catFood, FOOD_SUPPORT_DURATION, 0, 72000, "The base duration of potion effects from food. The actual duration will vary by effect."); FOOD_SECRET_DONUT_CHANCE = c.getFloat("Secret Donut Effect Chance", catFood, FOOD_SECRET_DONUT_CHANCE, 0.0f, 1.0f, "The chance of secret donuts giving potion effects."); FOOD_SECRET_DONUT_TEXT_CHANCE = c.getFloat("Secret Donut Text Chance", catFood, FOOD_SECRET_DONUT_TEXT_CHANCE, 0.0f, 1.0f, "The chance of secrets donuts putting weird text in your chat."); // Return Home Charm final String catReturnHome = CAT_ITEM + split + "Return Home Charm"; RETURN_HOME_USE_TIME = c.getInt("Use Time", catReturnHome, RETURN_HOME_USE_TIME, 0, Integer.MAX_VALUE, "The number of ticks the Return Home Charm must be 'charged' to use. Set to 0 for instant use."); RETURN_HOME_USE_COST = c.getInt("Use Cost", catReturnHome, RETURN_HOME_USE_COST, 0, Integer.MAX_VALUE, "The amount of Chaos required to teleport."); RETURN_HOME_MAX_CHARGE = c.getInt("Max Charge", catReturnHome, RETURN_HOME_MAX_CHARGE, 0, Integer.MAX_VALUE, "The maximum amount of Chaos a charm can hold."); /* * GUI */ SHOW_BONUS_ARMOR_BAR = c.getBoolean("Show Bonus Armor Bar", CAT_GUI, SHOW_BONUS_ARMOR_BAR, "Shows armor points beyond 20 on the bar as yellow armor pieces above the normal ones."); /* * Recipes */ RECIPE_TELEPORTER_DISABLE = c.getBoolean("Disable Regular Teleporter Recipes", CAT_RECIPE, RECIPE_TELEPORTER_DISABLE, "Disable recipes for regular gem teleporters."); RECIPE_TELEPORTER_ANCHOR_DISABLE = c.getBoolean("Disable Teleporter Anchor Recipes", CAT_RECIPE, RECIPE_TELEPORTER_ANCHOR_DISABLE, "Disable recipes for teleporter anchors."); RECIPE_TELEPORTER_REDSTONE_DISABLE = c.getBoolean("Disable Redstone Teleporter Recipes", CAT_RECIPE, RECIPE_TELEPORTER_REDSTONE_DISABLE, "Disable recipes for redstone gem teleporters."); RECIPE_TOKEN_FROST_WALKER_DISABLE = c.getBoolean("Disable Frost Walker Token Recipe", CAT_RECIPE, RECIPE_TOKEN_FROST_WALKER_DISABLE, "Disables recipes for Frost Walker enchantment tokens."); RECIPE_TOKEN_MENDING_DISABLE = c.getBoolean("Disable Mending Token Recipe", CAT_RECIPE, RECIPE_TOKEN_MENDING_DISABLE, "Disables recipes for Mending enchantment tokens."); /* * Misc */ HIDE_FLAVOR_TEXT_ALWAYS = c.getBoolean("Hide Flavor Text - Always", CAT_TOOLTIPS, HIDE_FLAVOR_TEXT_ALWAYS, "Always hide the potentially funny, but useless item descriptions."); HIDE_FLAVOR_TEXT_UNTIL_SHIFT = c.getBoolean("Hide Flavor Text - Until Shift", CAT_TOOLTIPS, HIDE_FLAVOR_TEXT_UNTIL_SHIFT, "Hide the flavor text until shift is pressed."); // Controls - right-click to place final String catRctp = CAT_CONTROLS + Configuration.CATEGORY_SPLITTER + "Right-click to place"; c.setCategoryComment(catRctp, "Mining tools have the ability to place blocks in the slot " + "after them (or in slot 9 if that doesn't work) by right-clicking."); RIGHT_CLICK_TO_PLACE_ENABLED = c.getBoolean("Enabled", catRctp, RIGHT_CLICK_TO_PLACE_ENABLED, "If set to false, the ability of mining tools to place blocks by right-clicking will be completely disabled."); RIGHT_CLICK_TO_PLACE_ON_SNEAK_ONLY = c.getBoolean("Only When Sneaking", catRctp, RIGHT_CLICK_TO_PLACE_ON_SNEAK_ONLY, "If set to true and right-click to place is enabled, this ability will only activate " + "while sneaking (holding shift, normally)."); /* * World Generation */ GLOW_ROSE_PER_CHUNK = c.getInt("Flowers per Chunk", CAT_WORLD_GEN, GLOW_ROSE_PER_CHUNK, 0, 100, "The number of glow roses to attempt to spawn per chunk."); CHAOS_NODES_PER_CHUNK = c.getFloat("Chaos Nodes per Chunk", CAT_WORLD_GEN, CHAOS_NODES_PER_CHUNK, 0.0f, 8.0f, "The number of chaos nodes to try to spawn per chunk. If less than 1 (recommended), you" + " can think of this as the chance to spawn in a chunk."); WORLD_GEN_GEMS = new ConfigOptionOreGen("Gems (Overworld)", 0, 10.0f, 8, 5, 45); WORLD_GEN_GEMS.loadValue(c, CAT_WORLD_GEN); WORLD_GEN_GEMS_DARK = new ConfigOptionOreGen("Dark Gems (Nether)", -1, 12.5f, 10, 30, 100); WORLD_GEN_GEMS_DARK.loadValue(c, CAT_WORLD_GEN); WORLD_GEN_CHAOS = new ConfigOptionOreGen("Chaos Ore", 0, 1.75f, 16, 5, 20); WORLD_GEN_CHAOS.loadValue(c, CAT_WORLD_GEN); WORLD_GEN_ENDER = new ConfigOptionOreGen("Ender Essence Ore", 1, 1.0f, 32, 10, 70); WORLD_GEN_ENDER.loadValue(c, CAT_WORLD_GEN); // Gem weights final int weightMax = 1000; c.setCategoryComment(CAT_WORLD_GEN_GEM_WEIGHT, "The spawn weights of the gems. If two gems have different weights, the gem with the\n" + "higher weight is more likely to be selected when placing gems in the world.\n" + "Just increasing weights will NOT increase the number of gems that spawn!\n" + "Values must be between 1 and " + weightMax + ", inclusive."); for (EnumGem gem : EnumGem.values()) { int k = c.get(CAT_WORLD_GEN_GEM_WEIGHT, gem.getGemName(), 10).getInt(); k = MathHelper.clamp_int(k, 1, weightMax); WeightedRandomItemSG item = new WeightedRandomItemSG(k, gem.ordinal() & 0xF); if (gem.ordinal() < EnumGem.CARNELIAN.ordinal()) { GEM_WEIGHTS.add(item); } else { GEM_WEIGHTS_DARK.add(item); } } //@formatter:on } catch (Exception e) { System.out.println("Oh noes!!! Couldn't load configuration file properly!"); } } public static void loadModuleConfigs() { ModuleCoffee.loadConfig(c); ModuleEntityRandomEquipment.loadConfig(c); } public static void save() { if (c.hasChanged()) { c.save(); } } public static ConfigCategory getCategory(String str) { return c.getCategory(str); } public static Configuration getConfiguration() { return c; } public static List<IConfigElement> getConfigElements() { return new ConfigElement(getCategory(CAT_MAIN)).getChildElements(); } }
package bisq.core.user; import bisq.core.app.AppOptionKeys; import bisq.core.app.BisqEnvironment; import bisq.core.btc.BaseCurrencyNetwork; import bisq.core.btc.BtcOptionKeys; import bisq.core.btc.nodes.BtcNodes; import bisq.core.btc.wallet.Restrictions; import bisq.core.dao.DaoOptionKeys; import bisq.core.locale.Country; import bisq.core.locale.CountryUtil; import bisq.core.locale.CryptoCurrency; import bisq.core.locale.CurrencyUtil; import bisq.core.locale.FiatCurrency; import bisq.core.locale.GlobalSettings; import bisq.core.locale.TradeCurrency; import bisq.core.payment.PaymentAccount; import bisq.network.p2p.network.BridgeAddressProvider; import bisq.common.proto.persistable.PersistedDataHost; import bisq.common.storage.Storage; import bisq.common.util.Utilities; import org.bitcoinj.core.Coin; import javax.inject.Inject; import javax.inject.Named; import javafx.beans.property.BooleanProperty; import javafx.beans.property.LongProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleLongProperty; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; import lombok.Getter; import lombok.Setter; import lombok.experimental.Delegate; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull; @Slf4j public final class Preferences implements PersistedDataHost, BridgeAddressProvider { private static final ArrayList<BlockChainExplorer> BTC_MAIN_NET_EXPLORERS = new ArrayList<>(Arrays.asList( new BlockChainExplorer("Blockstream.info", "https: new BlockChainExplorer("Blockstream.info Tor V3", "http: new BlockChainExplorer("OXT", "https: new BlockChainExplorer("Bitaps", "https: new BlockChainExplorer("Blockcypher", "https: new BlockChainExplorer("Tradeblock", "https: new BlockChainExplorer("Biteasy", "https: new BlockChainExplorer("Blockonomics", "https://www.blockonomics.co/api/tx?txid=", "https://www.blockonomics.co/#/search?q="), new BlockChainExplorer("Chainflyer", "http: new BlockChainExplorer("Smartbit", "https: new BlockChainExplorer("SoChain. Wow.", "https: new BlockChainExplorer("Blockchain.info", "https: new BlockChainExplorer("Insight", "https: ) ); private static final ArrayList<BlockChainExplorer> BTC_TEST_NET_EXPLORERS = new ArrayList<>(Arrays.asList( new BlockChainExplorer("Blockstream.info", "https: new BlockChainExplorer("Blockstream.info Tor V3", "http: new BlockChainExplorer("Blockcypher", "https: new BlockChainExplorer("Blocktrail", "https: new BlockChainExplorer("Biteasy", "https: new BlockChainExplorer("Smartbit", "https: new BlockChainExplorer("SoChain. Wow.", "https: )); public static final BlockChainExplorer BSQ_MAIN_NET_EXPLORER = new BlockChainExplorer("BSQ", "https://explorer.bisq.network/tx.html?tx=", "https://explorer.bisq.network/Address.html?addr="); public static final BlockChainExplorer BSQ_TEST_NET_EXPLORER = new BlockChainExplorer("BSQ", "https://explorer.bisq.network/testnet/tx.html?tx=", "https://explorer.bisq.network/testnet/Address.html?addr="); private static final ArrayList<BlockChainExplorer> LTC_MAIN_NET_EXPLORERS = new ArrayList<>(Arrays.asList( new BlockChainExplorer("Blockcypher", "https: new BlockChainExplorer("CryptoID", "https: new BlockChainExplorer("Abe Search", "http: new BlockChainExplorer("SoChain", "https: new BlockChainExplorer("Blockr.io", "http: )); private static final ArrayList<BlockChainExplorer> LTC_TEST_NET_EXPLORERS = new ArrayList<>(Arrays.asList( new BlockChainExplorer("SoChain", "https: )); private static final ArrayList<BlockChainExplorer> DASH_MAIN_NET_EXPLORERS = new ArrayList<>(Arrays.asList( new BlockChainExplorer("SoChain", "https: )); private static final ArrayList<BlockChainExplorer> DASH_TEST_NET_EXPLORERS = new ArrayList<>(Arrays.asList( new BlockChainExplorer("SoChain", "https: )); // payload is initialized so the default values are available for Property initialization. @Setter @Delegate(excludes = ExcludesDelegateMethods.class) private PreferencesPayload prefPayload = new PreferencesPayload(); private boolean initialReadDone = false; @Getter private final BooleanProperty useAnimationsProperty = new SimpleBooleanProperty(prefPayload.isUseAnimations()); @Getter private final BooleanProperty useCustomWithdrawalTxFeeProperty = new SimpleBooleanProperty(prefPayload.isUseCustomWithdrawalTxFee()); @Getter private final LongProperty withdrawalTxFeeInBytesProperty = new SimpleLongProperty(prefPayload.getWithdrawalTxFeeInBytes()); private final ObservableList<FiatCurrency> fiatCurrenciesAsObservable = FXCollections.observableArrayList(); private final ObservableList<CryptoCurrency> cryptoCurrenciesAsObservable = FXCollections.observableArrayList(); private final ObservableList<TradeCurrency> tradeCurrenciesAsObservable = FXCollections.observableArrayList(); private final Storage<PreferencesPayload> storage; private final BisqEnvironment bisqEnvironment; private final String btcNodesFromOptions, useTorFlagFromOptions, referralIdFromOptions, fullDaoNodeFromOptions, rpcUserFromOptions, rpcPasswordFromOptions; @Getter private final BooleanProperty useStandbyModeProperty = new SimpleBooleanProperty(prefPayload.isUseStandbyMode()); // Constructor @SuppressWarnings("WeakerAccess") @Inject public Preferences(Storage<PreferencesPayload> storage, BisqEnvironment bisqEnvironment, @Named(BtcOptionKeys.BTC_NODES) String btcNodesFromOptions, @Named(BtcOptionKeys.USE_TOR_FOR_BTC) String useTorFlagFromOptions, @Named(AppOptionKeys.REFERRAL_ID) String referralId, @Named(DaoOptionKeys.FULL_DAO_NODE) String fullDaoNode, @Named(DaoOptionKeys.RPC_USER) String rpcUser, @Named(DaoOptionKeys.RPC_PASSWORD) String rpcPassword) { this.storage = storage; this.bisqEnvironment = bisqEnvironment; this.btcNodesFromOptions = btcNodesFromOptions; this.useTorFlagFromOptions = useTorFlagFromOptions; this.referralIdFromOptions = referralId; this.fullDaoNodeFromOptions = fullDaoNode; this.rpcUserFromOptions = rpcUser; this.rpcPasswordFromOptions = rpcPassword; useAnimationsProperty.addListener((ov) -> { prefPayload.setUseAnimations(useAnimationsProperty.get()); GlobalSettings.setUseAnimations(prefPayload.isUseAnimations()); persist(); }); useStandbyModeProperty.addListener((ov) -> { prefPayload.setUseStandbyMode(useStandbyModeProperty.get()); persist(); }); fiatCurrenciesAsObservable.addListener((javafx.beans.Observable ov) -> { prefPayload.getFiatCurrencies().clear(); prefPayload.getFiatCurrencies().addAll(fiatCurrenciesAsObservable); prefPayload.getFiatCurrencies().sort(TradeCurrency::compareTo); persist(); }); cryptoCurrenciesAsObservable.addListener((javafx.beans.Observable ov) -> { prefPayload.getCryptoCurrencies().clear(); prefPayload.getCryptoCurrencies().addAll(cryptoCurrenciesAsObservable); prefPayload.getCryptoCurrencies().sort(TradeCurrency::compareTo); persist(); }); useCustomWithdrawalTxFeeProperty.addListener((ov) -> { prefPayload.setUseCustomWithdrawalTxFee(useCustomWithdrawalTxFeeProperty.get()); persist(); }); withdrawalTxFeeInBytesProperty.addListener((ov) -> { prefPayload.setWithdrawalTxFeeInBytes(withdrawalTxFeeInBytesProperty.get()); persist(); }); fiatCurrenciesAsObservable.addListener(this::updateTradeCurrencies); cryptoCurrenciesAsObservable.addListener(this::updateTradeCurrencies); } @Override public void readPersisted() { PreferencesPayload persisted = storage.initAndGetPersistedWithFileName("PreferencesPayload", 100); BaseCurrencyNetwork baseCurrencyNetwork = BisqEnvironment.getBaseCurrencyNetwork(); TradeCurrency preferredTradeCurrency; if (persisted != null) { prefPayload = persisted; GlobalSettings.setLocale(new Locale(prefPayload.getUserLanguage(), prefPayload.getUserCountry().code)); GlobalSettings.setUseAnimations(prefPayload.isUseAnimations()); preferredTradeCurrency = checkNotNull(prefPayload.getPreferredTradeCurrency(), "preferredTradeCurrency must not be null"); setPreferredTradeCurrency(preferredTradeCurrency); setFiatCurrencies(prefPayload.getFiatCurrencies()); setCryptoCurrencies(prefPayload.getCryptoCurrencies()); } else { prefPayload = new PreferencesPayload(); prefPayload.setUserLanguage(GlobalSettings.getLocale().getLanguage()); prefPayload.setUserCountry(CountryUtil.getDefaultCountry()); GlobalSettings.setLocale(new Locale(prefPayload.getUserLanguage(), prefPayload.getUserCountry().code)); preferredTradeCurrency = checkNotNull(CurrencyUtil.getCurrencyByCountryCode(prefPayload.getUserCountry().code), "preferredTradeCurrency must not be null"); prefPayload.setPreferredTradeCurrency(preferredTradeCurrency); setFiatCurrencies(CurrencyUtil.getMainFiatCurrencies()); setCryptoCurrencies(CurrencyUtil.getMainCryptoCurrencies()); switch (baseCurrencyNetwork.getCurrencyCode()) { case "BTC": setBlockChainExplorerMainNet(BTC_MAIN_NET_EXPLORERS.get(0)); setBlockChainExplorerTestNet(BTC_TEST_NET_EXPLORERS.get(0)); break; case "LTC": setBlockChainExplorerMainNet(LTC_MAIN_NET_EXPLORERS.get(0)); setBlockChainExplorerTestNet(LTC_TEST_NET_EXPLORERS.get(0)); break; case "DASH": setBlockChainExplorerMainNet(DASH_MAIN_NET_EXPLORERS.get(0)); setBlockChainExplorerTestNet(DASH_TEST_NET_EXPLORERS.get(0)); break; default: throw new RuntimeException("BaseCurrencyNetwork not defined. BaseCurrencyNetwork=" + baseCurrencyNetwork); } prefPayload.setDirectoryChooserPath(Utilities.getSystemHomeDirectory()); prefPayload.setOfferBookChartScreenCurrencyCode(preferredTradeCurrency.getCode()); prefPayload.setTradeChartsScreenCurrencyCode(preferredTradeCurrency.getCode()); prefPayload.setBuyScreenCurrencyCode(preferredTradeCurrency.getCode()); prefPayload.setSellScreenCurrencyCode(preferredTradeCurrency.getCode()); } prefPayload.setBsqBlockChainExplorer(baseCurrencyNetwork.isMainnet() ? BSQ_MAIN_NET_EXPLORER : BSQ_TEST_NET_EXPLORER); // We don't want to pass Preferences to all popups where the dont show again checkbox is used, so we use // that static lookup class to avoid static access to the Preferences directly. DontShowAgainLookup.setPreferences(this); GlobalSettings.setDefaultTradeCurrency(preferredTradeCurrency); // set all properties useAnimationsProperty.set(prefPayload.isUseAnimations()); useStandbyModeProperty.set(prefPayload.isUseStandbyMode()); useCustomWithdrawalTxFeeProperty.set(prefPayload.isUseCustomWithdrawalTxFee()); withdrawalTxFeeInBytesProperty.set(prefPayload.getWithdrawalTxFeeInBytes()); tradeCurrenciesAsObservable.addAll(prefPayload.getFiatCurrencies()); tradeCurrenciesAsObservable.addAll(prefPayload.getCryptoCurrencies()); // Override settings with options if set if (useTorFlagFromOptions != null && !useTorFlagFromOptions.isEmpty()) { if (useTorFlagFromOptions.equals("false")) setUseTorForBitcoinJ(false); else if (useTorFlagFromOptions.equals("true")) setUseTorForBitcoinJ(true); } if (btcNodesFromOptions != null && !btcNodesFromOptions.isEmpty()) { if (getBitcoinNodes() != null && !getBitcoinNodes().equals(btcNodesFromOptions)) { log.warn("The Bitcoin node(s) from the program argument and the one(s) persisted in the UI are different. " + "The Bitcoin node(s) {} from the program argument will be used.", btcNodesFromOptions); } setBitcoinNodes(btcNodesFromOptions); setBitcoinNodesOptionOrdinal(BtcNodes.BitcoinNodesOption.CUSTOM.ordinal()); } if (referralIdFromOptions != null && !referralIdFromOptions.isEmpty()) setReferralId(referralIdFromOptions); if (fullDaoNodeFromOptions != null && !fullDaoNodeFromOptions.isEmpty()) setDaoFullNode(fullDaoNodeFromOptions.toLowerCase().equals("true")); if (rpcUserFromOptions != null && !rpcUserFromOptions.isEmpty()) setRpcUser(rpcUserFromOptions); if (rpcPasswordFromOptions != null && !rpcPasswordFromOptions.isEmpty()) setRpcPw(rpcPasswordFromOptions); // For users from old versions the 4 flags a false but we want to have it true by default // PhoneKeyAndToken is also null so we can use that to enable the flags if (prefPayload.getPhoneKeyAndToken() == null) { setUseSoundForMobileNotifications(true); setUseTradeNotifications(true); setUseMarketNotifications(true); setUsePriceNotifications(true); } initialReadDone = true; persist(); } // API public void dontShowAgain(String key, boolean dontShowAgain) { prefPayload.getDontShowAgainMap().put(key, dontShowAgain); persist(); } public void resetDontShowAgain() { prefPayload.getDontShowAgainMap().clear(); persist(); } // Setter public void setUseAnimations(boolean useAnimations) { this.useAnimationsProperty.set(useAnimations); } public void addFiatCurrency(FiatCurrency tradeCurrency) { if (!fiatCurrenciesAsObservable.contains(tradeCurrency)) fiatCurrenciesAsObservable.add(tradeCurrency); } public void removeFiatCurrency(FiatCurrency tradeCurrency) { if (tradeCurrenciesAsObservable.size() > 1) { if (fiatCurrenciesAsObservable.contains(tradeCurrency)) fiatCurrenciesAsObservable.remove(tradeCurrency); if (prefPayload.getPreferredTradeCurrency() != null && prefPayload.getPreferredTradeCurrency().equals(tradeCurrency)) setPreferredTradeCurrency(tradeCurrenciesAsObservable.get(0)); } else { log.error("you cannot remove the last currency"); } } public void addCryptoCurrency(CryptoCurrency tradeCurrency) { if (!cryptoCurrenciesAsObservable.contains(tradeCurrency)) cryptoCurrenciesAsObservable.add(tradeCurrency); } public void removeCryptoCurrency(CryptoCurrency tradeCurrency) { if (tradeCurrenciesAsObservable.size() > 1) { if (cryptoCurrenciesAsObservable.contains(tradeCurrency)) cryptoCurrenciesAsObservable.remove(tradeCurrency); if (prefPayload.getPreferredTradeCurrency() != null && prefPayload.getPreferredTradeCurrency().equals(tradeCurrency)) setPreferredTradeCurrency(tradeCurrenciesAsObservable.get(0)); } else { log.error("you cannot remove the last currency"); } } public void setBlockChainExplorer(BlockChainExplorer blockChainExplorer) { if (BisqEnvironment.getBaseCurrencyNetwork().isMainnet()) setBlockChainExplorerMainNet(blockChainExplorer); else setBlockChainExplorerTestNet(blockChainExplorer); } public void setTacAccepted(boolean tacAccepted) { prefPayload.setTacAccepted(tacAccepted); persist(); } private void persist() { if (initialReadDone) storage.queueUpForSave(prefPayload); } public void setUserLanguage(@NotNull String userLanguageCode) { prefPayload.setUserLanguage(userLanguageCode); if (prefPayload.getUserCountry() != null && prefPayload.getUserLanguage() != null) GlobalSettings.setLocale(new Locale(prefPayload.getUserLanguage(), prefPayload.getUserCountry().code)); persist(); } public void setUserCountry(@NotNull Country userCountry) { prefPayload.setUserCountry(userCountry); if (prefPayload.getUserLanguage() != null) GlobalSettings.setLocale(new Locale(prefPayload.getUserLanguage(), userCountry.code)); persist(); } public void setPreferredTradeCurrency(TradeCurrency preferredTradeCurrency) { if (preferredTradeCurrency != null) { prefPayload.setPreferredTradeCurrency(preferredTradeCurrency); GlobalSettings.setDefaultTradeCurrency(preferredTradeCurrency); persist(); } } public void setUseTorForBitcoinJ(boolean useTorForBitcoinJ) { prefPayload.setUseTorForBitcoinJ(useTorForBitcoinJ); persist(); } public void setShowOwnOffersInOfferBook(boolean showOwnOffersInOfferBook) { prefPayload.setShowOwnOffersInOfferBook(showOwnOffersInOfferBook); persist(); } public void setMaxPriceDistanceInPercent(double maxPriceDistanceInPercent) { prefPayload.setMaxPriceDistanceInPercent(maxPriceDistanceInPercent); persist(); } public void setBackupDirectory(String backupDirectory) { prefPayload.setBackupDirectory(backupDirectory); persist(); } public void setAutoSelectArbitrators(boolean autoSelectArbitrators) { prefPayload.setAutoSelectArbitrators(autoSelectArbitrators); persist(); } public void setUsePercentageBasedPrice(boolean usePercentageBasedPrice) { prefPayload.setUsePercentageBasedPrice(usePercentageBasedPrice); persist(); } public void setTagForPeer(String hostName, String tag) { prefPayload.getPeerTagMap().put(hostName, tag); persist(); } public void setOfferBookChartScreenCurrencyCode(String offerBookChartScreenCurrencyCode) { prefPayload.setOfferBookChartScreenCurrencyCode(offerBookChartScreenCurrencyCode); persist(); } public void setBuyScreenCurrencyCode(String buyScreenCurrencyCode) { prefPayload.setBuyScreenCurrencyCode(buyScreenCurrencyCode); persist(); } public void setSellScreenCurrencyCode(String sellScreenCurrencyCode) { prefPayload.setSellScreenCurrencyCode(sellScreenCurrencyCode); persist(); } public void setIgnoreTradersList(List<String> ignoreTradersList) { prefPayload.setIgnoreTradersList(ignoreTradersList); persist(); } public void setDirectoryChooserPath(String directoryChooserPath) { prefPayload.setDirectoryChooserPath(directoryChooserPath); persist(); } public void setTradeChartsScreenCurrencyCode(String tradeChartsScreenCurrencyCode) { prefPayload.setTradeChartsScreenCurrencyCode(tradeChartsScreenCurrencyCode); persist(); } public void setTradeStatisticsTickUnitIndex(int tradeStatisticsTickUnitIndex) { prefPayload.setTradeStatisticsTickUnitIndex(tradeStatisticsTickUnitIndex); persist(); } public void setSortMarketCurrenciesNumerically(boolean sortMarketCurrenciesNumerically) { prefPayload.setSortMarketCurrenciesNumerically(sortMarketCurrenciesNumerically); persist(); } public void setBitcoinNodes(String bitcoinNodes) { prefPayload.setBitcoinNodes(bitcoinNodes); persist(); } public void setUseCustomWithdrawalTxFee(boolean useCustomWithdrawalTxFee) { useCustomWithdrawalTxFeeProperty.set(useCustomWithdrawalTxFee); } public void setWithdrawalTxFeeInBytes(long withdrawalTxFeeInBytes) { withdrawalTxFeeInBytesProperty.set(withdrawalTxFeeInBytes); } public void setBuyerSecurityDepositAsLong(long buyerSecurityDepositAsLong) { prefPayload.setBuyerSecurityDepositAsLong(Math.min(Restrictions.getMaxBuyerSecurityDeposit().value, Math.max(Restrictions.getMinBuyerSecurityDeposit().value, buyerSecurityDepositAsLong))); persist(); } public void setSelectedPaymentAccountForCreateOffer(@Nullable PaymentAccount paymentAccount) { prefPayload.setSelectedPaymentAccountForCreateOffer(paymentAccount); persist(); } public void setPayFeeInBtc(boolean payFeeInBtc) { prefPayload.setPayFeeInBtc(payFeeInBtc); persist(); } private void setFiatCurrencies(List<FiatCurrency> currencies) { fiatCurrenciesAsObservable.setAll(currencies.stream() .map(fiatCurrency -> new FiatCurrency(fiatCurrency.getCurrency())) .distinct().collect(Collectors.toList())); } private void setCryptoCurrencies(List<CryptoCurrency> currencies) { cryptoCurrenciesAsObservable.setAll(currencies.stream().distinct().collect(Collectors.toList())); } public void setBlockChainExplorerTestNet(BlockChainExplorer blockChainExplorerTestNet) { prefPayload.setBlockChainExplorerTestNet(blockChainExplorerTestNet); persist(); } public void setBlockChainExplorerMainNet(BlockChainExplorer blockChainExplorerMainNet) { prefPayload.setBlockChainExplorerMainNet(blockChainExplorerMainNet); persist(); } public void setResyncSpvRequested(boolean resyncSpvRequested) { prefPayload.setResyncSpvRequested(resyncSpvRequested); // We call that before shutdown so we dont want a delay here storage.queueUpForSave(prefPayload, 1); } public void setBridgeAddresses(List<String> bridgeAddresses) { prefPayload.setBridgeAddresses(bridgeAddresses); // We call that before shutdown so we dont want a delay here storage.queueUpForSave(prefPayload, 1); } // Only used from PB but keep it explicit as maybe it get used from the client and then we want to persist public void setPeerTagMap(Map<String, String> peerTagMap) { prefPayload.setPeerTagMap(peerTagMap); persist(); } public void setBridgeOptionOrdinal(int bridgeOptionOrdinal) { prefPayload.setBridgeOptionOrdinal(bridgeOptionOrdinal); persist(); } public void setTorTransportOrdinal(int torTransportOrdinal) { prefPayload.setTorTransportOrdinal(torTransportOrdinal); persist(); } public void setCustomBridges(String customBridges) { prefPayload.setCustomBridges(customBridges); persist(); } public void setBitcoinNodesOptionOrdinal(int bitcoinNodesOptionOrdinal) { prefPayload.setBitcoinNodesOptionOrdinal(bitcoinNodesOptionOrdinal); persist(); } public void setReferralId(String referralId) { prefPayload.setReferralId(referralId); persist(); } public void setPhoneKeyAndToken(String phoneKeyAndToken) { prefPayload.setPhoneKeyAndToken(phoneKeyAndToken); persist(); } public void setUseSoundForMobileNotifications(boolean value) { prefPayload.setUseSoundForMobileNotifications(value); persist(); } public void setUseTradeNotifications(boolean value) { prefPayload.setUseTradeNotifications(value); persist(); } public void setUseMarketNotifications(boolean value) { prefPayload.setUseMarketNotifications(value); persist(); } public void setUsePriceNotifications(boolean value) { prefPayload.setUsePriceNotifications(value); persist(); } public void setUseStandbyMode(boolean useStandbyMode) { this.useStandbyModeProperty.set(useStandbyMode); } public void setDaoFullNode(boolean value) { prefPayload.setDaoFullNode(value); persist(); } public void setRpcUser(String value) { prefPayload.setRpcUser(value); persist(); } public void setRpcPw(String value) { prefPayload.setRpcPw(value); persist(); } public void setTakeOfferSelectedPaymentAccountId(String value) { prefPayload.setTakeOfferSelectedPaymentAccountId(value); persist(); } // Getter public BooleanProperty useAnimationsProperty() { return useAnimationsProperty; } public ObservableList<FiatCurrency> getFiatCurrenciesAsObservable() { return fiatCurrenciesAsObservable; } public ObservableList<CryptoCurrency> getCryptoCurrenciesAsObservable() { return cryptoCurrenciesAsObservable; } public ObservableList<TradeCurrency> getTradeCurrenciesAsObservable() { return tradeCurrenciesAsObservable; } public BlockChainExplorer getBlockChainExplorer() { if (BisqEnvironment.getBaseCurrencyNetwork().isMainnet()) return prefPayload.getBlockChainExplorerMainNet(); else return prefPayload.getBlockChainExplorerTestNet(); } public ArrayList<BlockChainExplorer> getBlockChainExplorers() { final BaseCurrencyNetwork baseCurrencyNetwork = BisqEnvironment.getBaseCurrencyNetwork(); switch (baseCurrencyNetwork) { case BTC_MAINNET: return BTC_MAIN_NET_EXPLORERS; case BTC_TESTNET: case BTC_REGTEST: return BTC_TEST_NET_EXPLORERS; case LTC_MAINNET: return LTC_MAIN_NET_EXPLORERS; case LTC_TESTNET: case LTC_REGTEST: return LTC_TEST_NET_EXPLORERS; case DASH_MAINNET: return DASH_MAIN_NET_EXPLORERS; case DASH_REGTEST: case DASH_TESTNET: return DASH_TEST_NET_EXPLORERS; default: throw new RuntimeException("BaseCurrencyNetwork not defined. BaseCurrencyNetwork=" + baseCurrencyNetwork); } } public boolean showAgain(String key) { return !prefPayload.getDontShowAgainMap().containsKey(key) || !prefPayload.getDontShowAgainMap().get(key); } public boolean getUseTorForBitcoinJ() { // We override the useTorForBitcoinJ and set it to false if we detected a localhost node or if we are not on mainnet. // At testnet there are very few Bitcoin tor nodes and we don't provide tor nodes. if (!BisqEnvironment.getBaseCurrencyNetwork().isMainnet() || bisqEnvironment.isBitcoinLocalhostNodeRunning()) return false; else return prefPayload.isUseTorForBitcoinJ(); } public BooleanProperty useCustomWithdrawalTxFeeProperty() { return useCustomWithdrawalTxFeeProperty; } public LongProperty withdrawalTxFeeInBytesProperty() { return withdrawalTxFeeInBytesProperty; } public Coin getBuyerSecurityDepositAsCoin() { return Coin.valueOf(prefPayload.getBuyerSecurityDepositAsLong()); } //TODO remove and use isPayFeeInBtc instead public boolean getPayFeeInBtc() { return prefPayload.isPayFeeInBtc(); } @Override @Nullable public List<String> getBridgeAddresses() { return prefPayload.getBridgeAddresses(); } public long getWithdrawalTxFeeInBytes() { return Math.max(prefPayload.getWithdrawalTxFeeInBytes(), BisqEnvironment.getBaseCurrencyNetwork().getDefaultMinFeePerByte()); } // Private private void updateTradeCurrencies(ListChangeListener.Change<? extends TradeCurrency> change) { change.next(); if (change.wasAdded() && change.getAddedSize() == 1 && initialReadDone) tradeCurrenciesAsObservable.add(change.getAddedSubList().get(0)); else if (change.wasRemoved() && change.getRemovedSize() == 1 && initialReadDone) tradeCurrenciesAsObservable.remove(change.getRemoved().get(0)); } private interface ExcludesDelegateMethods { void setTacAccepted(boolean tacAccepted); void setUseAnimations(boolean useAnimations); void setUserLanguage(@NotNull String userLanguageCode); void setUserCountry(@NotNull Country userCountry); void setPreferredTradeCurrency(TradeCurrency preferredTradeCurrency); void setUseTorForBitcoinJ(boolean useTorForBitcoinJ); void setShowOwnOffersInOfferBook(boolean showOwnOffersInOfferBook); void setMaxPriceDistanceInPercent(double maxPriceDistanceInPercent); void setBackupDirectory(String backupDirectory); void setAutoSelectArbitrators(boolean autoSelectArbitrators); void setUsePercentageBasedPrice(boolean usePercentageBasedPrice); void setTagForPeer(String hostName, String tag); void setOfferBookChartScreenCurrencyCode(String offerBookChartScreenCurrencyCode); void setBuyScreenCurrencyCode(String buyScreenCurrencyCode); void setSellScreenCurrencyCode(String sellScreenCurrencyCode); void setIgnoreTradersList(List<String> ignoreTradersList); void setDirectoryChooserPath(String directoryChooserPath); void setTradeChartsScreenCurrencyCode(String tradeChartsScreenCurrencyCode); void setTradeStatisticsTickUnitIndex(int tradeStatisticsTickUnitIndex); void setSortMarketCurrenciesNumerically(boolean sortMarketCurrenciesNumerically); void setBitcoinNodes(String bitcoinNodes); void setUseCustomWithdrawalTxFee(boolean useCustomWithdrawalTxFee); void setWithdrawalTxFeeInBytes(long withdrawalTxFeeInBytes); void setBuyerSecurityDepositAsLong(long buyerSecurityDepositAsLong); void setSelectedPaymentAccountForCreateOffer(@Nullable PaymentAccount paymentAccount); void setBsqBlockChainExplorer(BlockChainExplorer bsqBlockChainExplorer); void setPayFeeInBtc(boolean payFeeInBtc); void setFiatCurrencies(List<FiatCurrency> currencies); void setCryptoCurrencies(List<CryptoCurrency> currencies); void setBlockChainExplorerTestNet(BlockChainExplorer blockChainExplorerTestNet); void setBlockChainExplorerMainNet(BlockChainExplorer blockChainExplorerMainNet); void setResyncSpvRequested(boolean resyncSpvRequested); void setDontShowAgainMap(Map<String, Boolean> dontShowAgainMap); void setPeerTagMap(Map<String, String> peerTagMap); void setBridgeAddresses(List<String> bridgeAddresses); void setBridgeOptionOrdinal(int bridgeOptionOrdinal); void setTorTransportOrdinal(int torTransportOrdinal); void setCustomBridges(String customBridges); void setBitcoinNodesOptionOrdinal(int bitcoinNodesOption); void setReferralId(String referralId); void setPhoneKeyAndToken(String phoneKeyAndToken); void setUseSoundForMobileNotifications(boolean value); void setUseTradeNotifications(boolean value); void setUseMarketNotifications(boolean value); void setUsePriceNotifications(boolean value); List<String> getBridgeAddresses(); long getWithdrawalTxFeeInBytes(); void setUseStandbyMode(boolean useStandbyMode); void setDaoFullNode(boolean value); void setRpcUser(String value); void setRpcPw(String value); void setTakeOfferSelectedPaymentAccountId(String value); } }
package com.brctl.test; import com.brctl.domain.Article; import com.brctl.service.IArticleService; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) // TODO WHY // @ContextConfiguration(locations = {"classpath:spring-config.xml", "classpath:spring-mvc-config.xml"}) @ContextConfiguration(locations = "classpath:spring-config.xml") public class ArticleTester { @Autowired private IArticleService articleService; public void setArticleService(IArticleService articleService) { this.articleService = articleService; } public IArticleService getArticleService() { return this.articleService; } @Test public void test() { List<Article> articles = articleService.findAll(); System.out.println(); for(Article article: articles) { System.out.println(article.getAuthor()); } } }
package dta.pizzeria.test; import javax.transaction.Transactional; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import dta.pizzeria.backend.PizzeriaBackendConfig; import dta.pizzeria.backend.entity.Client; import dta.pizzeria.backend.metier.ClientService; import dta.pizzeria.backend.metier.MailService; import org.springframework.http.ResponseEntity; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = PizzeriaBackendConfig.class) @WebAppConfiguration public class TestClient { @Autowired private ClientService clientService; @Autowired private MailService mailService; @Before @Transactional public void before() { clientService.deleteAll(); Client client1 = new Client("jean", "jacques", "xulakabo@mailzi.ru", "2 rue de JJ", "1234567890", "jj", "jj"); Client client2 = new Client("jeanne", "jacques", "pizzeria.dta@gmail.com", "2 rue de JJ22", "1234567890", "jj2", "jj2"); clientService.save(client1); clientService.save(client2); } // @Test // public void testClientService() { // List<Client> clients = clientService.findAll(); // Client client1 = new Client(); // for (Client client:clients){ // client1 = client; // client1.setNom("jean-"+client1.getNom()); // clientService.save(client1); @Test public void testMail() { ResponseEntity<?> resp = clientService.connexion("jj", "jj"); if (resp.getBody().getClass().equals(Client.class)){ System.out.println("<====}=0 Client trouvé "+resp.getBody().toString()); } if(resp.getBody().getClass().equals(String.class)){ System.out.println("<====}=0 Erreur: "+resp.getBody().toString()); } } }
package hudson.maven; import hudson.model.Describable; import hudson.model.BuildListener; import hudson.model.Action; import hudson.model.Project; import hudson.ExtensionPoint; import hudson.tasks.BuildStep; import java.io.IOException; import org.apache.maven.project.MavenProject; /** * Listens to the build execution of {@link MavenBuild}, * and normally records some information and exposes thoses * in {@link MavenBuild} later. * * <p> * TODO: talk about two nodes involved * Because builds may happen on a remote slave node, {@link MavenReporter} * implementation needs ... * * <p> * This is the {@link MavenBuild} equivalent of {@link BuildStep}. Instances * of {@link MavenReporter}s are persisted with {@link MavenModule}/{@link MavenModuleSet}, * possibly with configuration specific to that job. * * * <h2>Callback Firing Sequence</h2> * <p> * The callback methods are invoked in the following order: * * <pre> * SEQUENCE := preBuild MODULE* postBuild * MODULE := enterModule MOJO+ leaveModule * MOJO := preExecute postExecute * </pre> * * <p> * When an error happens, the call sequence could be terminated at any point * and no further callback methods might not be invoked. * * @author Kohsuke Kawaguchi * @see MavenReporters */ public abstract class MavenReporter implements Describable<MavenReporter>, ExtensionPoint { /** * Called before the actual maven2 execution begins. * * @param pom * Represents the POM to be executed. * @return * true if the build can continue, false if there was an error * and the build needs to be aborted. * @throws InterruptedException * If the build is interrupted by the user (in an attempt to abort the build.) * Normally the {@link MavenReporter} implementations may simply forward the exception * it got from its lower-level functions. * @throws IOException * If the implementation wants to abort the processing when an {@link IOException} * happens, it can simply propagate the exception to the caller. This will cause * the build to fail, with the default error message. * Implementations are encouraged to catch {@link IOException} on its own to * provide a better error message, if it can do so, so that users have better * understanding on why it failed. */ public boolean preBuild(MavenBuildProxy build, MavenProject pom, BuildListener listener) throws InterruptedException, IOException { return true; } /** * Called when the build enters a next {@link MavenProject}. * * <p> * When the current build is a multi-module reactor build, every time the build * moves on to the next module, this method will be invoked. * * <p> * Note that as of Maven 2.0.4, Maven does not perform any smart optimization * on the order of goal executions. Therefore, the same module might be entered more than * once during the build. * * @return * See {@link #preBuild} * @throws InterruptedException * See {@link #preBuild} * @throws IOException * See {@link #preBuild} */ public boolean enterModule(MavenBuildProxy build, MavenProject pom, BuildListener listener) throws InterruptedException, IOException { return true; } /** * Called when the build leaves the current {@link MavenProject}. * * @see #enterModule */ public boolean leaveModule(MavenBuildProxy build, MavenProject pom, BuildListener listener) throws InterruptedException, IOException { return true; } /** * Called before execution of a single mojo. * * @return * See {@link #preBuild} * @throws InterruptedException * See {@link #preBuild} * @throws IOException * See {@link #preBuild} */ public boolean preExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener) throws InterruptedException, IOException { return true; } /** * Called after execution of a single mojo. * <p> * See {@link #preExecute} for the contract. */ public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener) throws InterruptedException, IOException { return true; } /** * Called after the actual maven2 execution completed. * * @return * See {@link #preBuild} * @throws InterruptedException * See {@link #preBuild} * @throws IOException * See {@link #preBuild} */ public boolean postBuild(MavenBuildProxy build, MavenProject pom, BuildListener listener) throws InterruptedException, IOException { return true; } /** * Equivalent of {@link BuildStep#getProjectAction(Project)} * for {@link MavenReporter}. */ public Action getProjectAction(MavenModule project) { return null; } }
package hudson.scm; import hudson.model.AbstractBuild; import hudson.model.User; import hudson.scm.CVSChangeLogSet.CVSChangeLog; import hudson.util.IOException2; import hudson.util.Digester2; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import org.apache.commons.digester.Digester; import org.xml.sax.SAXException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Collection; import java.util.AbstractList; /** * {@link ChangeLogSet} for CVS. * @author Kohsuke Kawaguchi */ public final class CVSChangeLogSet extends ChangeLogSet<CVSChangeLog> { private List<CVSChangeLog> logs; public CVSChangeLogSet(AbstractBuild<?,?> build, List<CVSChangeLog> logs) { super(build); this.logs = Collections.unmodifiableList(logs); for (CVSChangeLog log : logs) log.setParent(this); } /** * Returns the read-only list of changes. */ public List<CVSChangeLog> getLogs() { return logs; } @Override public boolean isEmptySet() { return logs.isEmpty(); } public Iterator<CVSChangeLog> iterator() { return logs.iterator(); } public static CVSChangeLogSet parse( AbstractBuild build, java.io.File f ) throws IOException, SAXException { Digester digester = new Digester2(); ArrayList<CVSChangeLog> r = new ArrayList<CVSChangeLog>(); digester.push(r); digester.addObjectCreate("*/entry",CVSChangeLog.class); digester.addBeanPropertySetter("*/entry/date"); digester.addBeanPropertySetter("*/entry/time"); digester.addBeanPropertySetter("*/entry/author","user"); digester.addBeanPropertySetter("*/entry/msg"); digester.addSetNext("*/entry","add"); digester.addObjectCreate("*/entry/file",File.class); digester.addBeanPropertySetter("*/entry/file/name"); digester.addBeanPropertySetter("*/entry/file/fullName"); digester.addBeanPropertySetter("*/entry/file/revision"); digester.addBeanPropertySetter("*/entry/file/prevrevision"); digester.addCallMethod("*/entry/file/dead","setDead"); digester.addSetNext("*/entry/file","addFile"); try { digester.parse(f); } catch (IOException e) { throw new IOException2("Failed to parse "+f,e); } catch (SAXException e) { throw new IOException2("Failed to parse "+f,e); } // merge duplicate entries. Ant task somehow seems to report duplicate entries. for(int i=r.size()-1; i>=0; i CVSChangeLog log = r.get(i); boolean merged = false; if(!log.isComplete()) { r.remove(log); continue; } for(int j=0;j<i;j++) { CVSChangeLog c = r.get(j); if(c.canBeMergedWith(log)) { c.merge(log); merged = true; break; } } if(merged) r.remove(log); } return new CVSChangeLogSet(build,r); } /** * In-memory representation of CVS Changelog. */ public static class CVSChangeLog extends ChangeLogSet.Entry { private String date; private String time; private User author; private String msg; private final List<File> files = new ArrayList<File>(); /** * Returns true if all the fields that are supposed to be non-null is present. * This is used to make sure the XML file was correct. */ public boolean isComplete() { return date!=null && time!=null && msg!=null; } /** * Checks if two {@link CVSChangeLog} entries can be merged. * This is to work around the duplicate entry problems. */ public boolean canBeMergedWith(CVSChangeLog that) { if(!this.date.equals(that.date)) return false; if(!this.time.equals(that.time)) // TODO: perhaps check this loosely? return false; if(this.author==null || that.author==null || !this.author.equals(that.author)) return false; if(!this.msg.equals(that.msg)) return false; return true; } public void merge(CVSChangeLog that) { this.files.addAll(that.files); for (File f : that.files) f.parent = this; } @Exported public String getDate() { return date; } public void setDate(String date) { this.date = date; } @Exported public String getTime() { return time; } public void setTime(String time) { this.time = time; } @Exported public User getAuthor() { if(author==null) return User.getUnknown(); return author; } public Collection<String> getAffectedPaths() { return new AbstractList<String>() { public String get(int index) { return files.get(index).getName(); } public int size() { return files.size(); } }; } public void setUser(String author) { this.author = User.get(author); } @Exported public String getUser() {// digester wants read/write property, even though it never reads. Duh. return author.getDisplayName(); } @Exported public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public void addFile( File f ) { f.parent = this; files.add(f); } @Exported public List<File> getFiles() { return files; } } @ExportedBean(defaultVisibility=999) public static class File { private String name; private String fullName; private String revision; private String prevrevision; private boolean dead; private CVSChangeLog parent; /** * Gets the path name in the CVS repository, like * "foo/bar/zot.c" * * <p> * The path is relative to the workspace root. */ @Exported public String getName() { return name; } /** * Gets the full path name in the CVS repository, * like "/module/foo/bar/zot.c" * * <p> * Unlike {@link #getName()}, this method returns * a full name from the root of the CVS repository. */ @Exported public String getFullName() { if(fullName==null) { // Hudson < 1.91 doesn't record full path name for CVS, // so try to infer that from the current CVS setting. // This is an approximation since the config could have changed // since this build has done. SCM scm = parent.getParent().build.getProject().getScm(); if(scm instanceof CVSSCM) { CVSSCM cvsscm = (CVSSCM) scm; if(cvsscm.isFlatten()) { fullName = '/'+cvsscm.getAllModules()+'/'+name; } else { // multi-module set up. fullName = '/'+name; } } else { // no way to infer. fullName = '/'+name; } } return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } /** * Gets just the last component of the path, like "zot.c" */ public String getSimpleName() { int idx = name.lastIndexOf('/'); if(idx>0) return name.substring(idx+1); return name; } public void setName(String name) { this.name = name; } @Exported public String getRevision() { return revision; } public void setRevision(String revision) { this.revision = revision; } @Exported public String getPrevrevision() { return prevrevision; } public void setPrevrevision(String prevrevision) { this.prevrevision = prevrevision; } @Exported public boolean isDead() { return dead; } public void setDead() { this.dead = true; } @Exported public EditType getEditType() { // see issue #73. Can't do much better right now if(dead) return EditType.DELETE; if(revision.equals("1.1")) return EditType.ADD; return EditType.EDIT; } public CVSChangeLog getParent() { return parent; } } /** * Represents CVS revision number like "1.5.3.2". Immutable. */ public static class Revision { public final int[] numbers; public Revision(int[] numbers) { this.numbers = numbers; assert numbers.length%2==0; } public Revision(String s) { String[] tokens = s.split("\\."); numbers = new int[tokens.length]; for( int i=0; i<tokens.length; i++ ) numbers[i] = Integer.parseInt(tokens[i]); assert numbers.length%2==0; } /** * Returns a new {@link Revision} that represents the previous revision. * * For example, "1.5"->"1.4", "1.5.2.13"->"1.5.2.12", "1.5.2.1"->"1.5" * * @return * null if there's no previous version, meaning this is "1.1" */ public Revision getPrevious() { if(numbers[numbers.length-1]==1) { // x.y.z.1 => x.y int[] p = new int[numbers.length-2]; System.arraycopy(numbers,0,p,0,p.length); if(p.length==0) return null; return new Revision(p); } int[] p = numbers.clone(); p[p.length-1] return new Revision(p); } public String toString() { StringBuilder buf = new StringBuilder(); for (int n : numbers) { if(buf.length()>0) buf.append('.'); buf.append(n); } return buf.toString(); } } }
package org.maptalks.proj4; import org.testng.annotations.Test; import java.util.Arrays; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class Proj4Test { private static final String EPSG3857 = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs"; private static final String EPSG4326 = "+proj=longlat +datum=WGS84 +no_defs"; @Test public void testForward() throws Exception { Proj4 proj = new Proj4(EPSG4326, EPSG3857); double[] coord = proj.forward(new double[]{120.0, 30.0}); double tolerance = 1e-3; assertEquals(coord[0], 13358338.895192828, tolerance); assertEquals(coord[1], 3503549.843504374, tolerance); } @Test public void testInverse() throws Exception { Proj4 proj = new Proj4(EPSG4326, EPSG3857); double[] coord = proj.inverse(new double[]{13358338.89, 3503549.84}); double tolerance = 1e-7; assertEquals(coord[0], 120.0, tolerance); assertEquals(coord[1], 30.0, tolerance); } @Test public void testForwardWithDef() throws Exception { Proj4 proj = new Proj4("EPSG:4326", "EPSG:3857"); double[] coord = proj.forward(new double[]{120.0, 30.0}); double tolerance = 1e-3; assertEquals(coord[0], 13358338.895192828, tolerance); assertEquals(coord[1], 3503549.843504374, tolerance); } @Test public void testInverseWithDef() throws Exception { Proj4 proj = new Proj4("EPSG:4326", "EPSG:3857"); double[] coord = proj.inverse(new double[]{13358338.89, 3503549.84}); double tolerance = 1e-7; assertEquals(coord[0], 120.0, tolerance); assertEquals(coord[1], 30.0, tolerance); } @Test public void testForwardWithMixed() throws Exception { Proj4 proj = new Proj4(EPSG4326, "EPSG:3857"); double[] coord = proj.forward(new double[]{120.0, 30.0}); double tolerance = 1e-3; assertEquals(coord[0], 13358338.895192828, tolerance); assertEquals(coord[1], 3503549.843504374, tolerance); } @Test public void testInverseWithMixed() throws Exception { Proj4 proj = new Proj4("EPSG:4326", EPSG3857); double[] coord = proj.inverse(new double[]{13358338.89, 3503549.84}); double tolerance = 1e-7; assertEquals(coord[0], 120.0, tolerance); assertEquals(coord[1], 30.0, tolerance); } @Test public void testGcj02ToBaidu() throws Exception { double[][] expected = new double[][]{ {114.69490414027017,33.639096507711685}, {114.69488614273101,33.63804850387785}, {114.69500713986416,33.63794251496537}, {114.69578412001135,33.63793958798685}, {114.6959281162725,33.637965601694006}, {114.69751307493384,33.637957753486745} }; Proj4 proj = new Proj4("+proj=longlat +datum=GCJ02", "+proj=longlat +datum=BD09"); double[][] lonlats = new double[][]{ {114.68837663801743, 33.63312016454496}, {114.68835840204522, 33.632072446353945}, {114.68848002806972, 33.63196427051657}, {114.68926112541861, 33.63194729708501}, {114.68940588838505, 33.6319707051534}, {114.69099925796665, 33.63193416046613} }; for (int i = 0; i < lonlats.length; i++) { double[] coord = proj.forward(lonlats[i]); assertTrue(Arrays.equals(expected[i], coord)); } } }
package org.takes.rq; import com.google.common.base.Joiner; import com.jcabi.http.request.JdkRequest; import com.jcabi.http.response.RestResponse; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URI; import java.util.Arrays; import java.util.HashSet; import org.apache.commons.lang.StringUtils; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TemporaryFolder; import org.takes.Request; import org.takes.Response; import org.takes.Take; import org.takes.facets.hamcrest.HmRqHeader; import org.takes.http.FtRemote; import org.takes.misc.PerformanceTests; import org.takes.rs.RsText; @SuppressWarnings("PMD.TooManyMethods") public final class RqMultipartTest { /** * Carriage return constant. */ private static final String CRLF = "\r\n"; /** * Content disposition. */ private static final String DISPOSITION = "Content-Disposition"; /** * Content disposition plus form data. */ private static final String CONTENT = String.format( "%s: %s", RqMultipartTest.DISPOSITION, "form-data; name=\"%s\"" ); /** * Temp directory. */ @Rule public final transient TemporaryFolder temp = new TemporaryFolder(); /** * RqMultipart.Base can satisfy equals contract. * @throws IOException if some problem inside */ @Test public void satisfiesEqualsContract() throws IOException { final String body = "449 N Wolfe Rd, Sunnyvale, CA 94085"; final String part = "t-1"; final Request req = new RqMultipart.Fake( new RqFake(), new RqWithHeaders( new RqFake("", "", body), contentLengthHeader(body.getBytes().length), contentDispositionHeader( String.format("form-data; name=\"%s\"", part) ) ), new RqWithHeaders( new RqFake("", "", ""), contentLengthHeader(0), contentDispositionHeader( "form-data; name=\"data\"; filename=\"a.bin\"" ) ) ); final RqMultipart.Base one = new RqMultipart.Base(req); final RqMultipart.Base two = new RqMultipart.Base(req); try { MatcherAssert.assertThat(one, Matchers.equalTo(two)); } finally { req.body().close(); one.part(part).iterator().next().body().close(); two.part(part).iterator().next().body().close(); } } /** * RqMultipart.Base can throw exception on no closing boundary found. * @throws IOException if some problem inside */ @Test(expected = IOException.class) public void throwsExceptionOnNoClosingBoundaryFound() throws IOException { new RqMultipart.Base( new RqFake( Arrays.asList( "POST /h?a=4 HTTP/1.1", "Host: rtw.example.com", "Content-Type: multipart/form-data; boundary=AaB01x", "Content-Length: 100007" ), Joiner.on(RqMultipartTest.CRLF).join( "--AaB01x", "Content-Disposition: form-data; fake=\"t2\"", "", "447 N Wolfe Rd, Sunnyvale, CA 94085", "Content-Transfer-Encoding: uwf-8" ) ) ); } /** * RqMultipart.Fake can throw exception on no name * at Content-Disposition header. * @throws IOException if some problem inside */ @Test(expected = IOException.class) public void throwsExceptionOnNoNameAtContentDispositionHeader() throws IOException { new RqMultipart.Fake( new RqWithHeader( new RqFake("", "", "340 N Wolfe Rd, Sunnyvale, CA 94085"), RqMultipartTest.DISPOSITION, "form-data; fake=\"t-3\"" ) ); } /** * RqMultipart.Base can throw exception on no boundary * at Content-Type header. * @throws IOException if some problem inside */ @Test(expected = IOException.class) public void throwsExceptionOnNoBoundaryAtContentTypeHeader() throws IOException { new RqMultipart.Base( new RqFake( Arrays.asList( "POST /h?s=3 HTTP/1.1", "Host: wwo.example.com", "Content-Type: multipart/form-data; boundaryAaB03x", "Content-Length: 100005" ), "" ) ); } /** * RqMultipart.Base can throw exception on invalid Content-Type header. * @throws IOException if some problem inside */ @Test(expected = IOException.class) public void throwsExceptionOnInvalidContentTypeHeader() throws IOException { new RqMultipart.Base( new RqFake( Arrays.asList( "POST /h?r=3 HTTP/1.1", "Host: www.example.com", "Content-Type: multipart; boundary=AaB03x", "Content-Length: 100004" ), "" ) ); } /** * RqMultipart.Base can parse http body. * @throws IOException If some problem inside */ @Test public void parsesHttpBody() throws IOException { final String body = "40 N Wolfe Rd, Sunnyvale, CA 94085"; final String part = "t4"; final RqMultipart multi = new RqMultipart.Fake( new RqFake(), new RqWithHeaders( new RqFake("", "", body), contentLengthHeader(body.getBytes().length), contentDispositionHeader( String.format("form-data; name=\"%s\"", part) ) ), new RqWithHeaders( new RqFake("", "", ""), contentLengthHeader(0), contentDispositionHeader( "form-data; name=\"data\"; filename=\"a.bin\"" ) ) ); try { MatcherAssert.assertThat( new RqHeaders.Base( multi.part(part).iterator().next() ).header(RqMultipartTest.DISPOSITION), Matchers.hasItem("form-data; name=\"t4\"") ); MatcherAssert.assertThat( new RqPrint( new RqHeaders.Base( multi.part(part).iterator().next() ) ).printBody(), Matchers.allOf( Matchers.startsWith("40 N"), Matchers.endsWith("CA 94085") ) ); } finally { multi.part(part).iterator().next().body().close(); } } /** * RqMultipart.Fake can return empty iterator on invalid part request. * @throws IOException If some problem inside */ @Test public void returnsEmptyIteratorOnInvalidPartRequest() throws IOException { final String body = "443 N Wolfe Rd, Sunnyvale, CA 94085"; final RqMultipart multi = new RqMultipart.Fake( new RqFake(), new RqWithHeaders( new RqFake("", "", body), contentLengthHeader(body.getBytes().length), contentDispositionHeader( "form-data; name=\"t5\"" ) ), new RqWithHeaders( new RqFake("", "", ""), contentLengthHeader(0), contentDispositionHeader( "form-data; name=\"data\"; filename=\"a.zip\"" ) ) ); MatcherAssert.assertThat( multi.part("fake").iterator().hasNext(), Matchers.is(false) ); multi.body().close(); } /** * RqMultipart.Fake can return correct name set. * @throws IOException If some problem inside */ @Test public void returnsCorrectNamesSet() throws IOException { final String body = "441 N Wolfe Rd, Sunnyvale, CA 94085"; final RqMultipart multi = new RqMultipart.Fake( new RqFake(), new RqWithHeaders( new RqFake("", "", body), contentLengthHeader(body.getBytes().length), contentDispositionHeader( "form-data; name=\"address\"" ) ), new RqWithHeaders( new RqFake("", "", ""), contentLengthHeader(0), contentDispositionHeader( "form-data; name=\"data\"; filename=\"a.bin\"" ) ) ); try { MatcherAssert.assertThat( multi.names(), Matchers.<Iterable<String>>equalTo( new HashSet<String>(Arrays.asList("address", "data")) ) ); } finally { multi.body().close(); } } /** * RqMultipart.Base can return correct part length. * @throws IOException If some problem inside */ @Test public void returnsCorrectPartLength() throws IOException { final int length = 5000; final String part = "x-1"; final String body = Joiner.on(RqMultipartTest.CRLF).join( "--zzz", String.format(RqMultipartTest.CONTENT, part), "", StringUtils.repeat("X", length), "--zzz ); final Request req = new RqFake( Arrays.asList( "POST /post?u=3 HTTP/1.1", "Host: www.example.com", contentLengthHeader(body.getBytes().length), "Content-Type: multipart/form-data; boundary=zzz" ), body ); final RqMultipart.Smart regsmart = new RqMultipart.Smart( new RqMultipart.Base(req) ); try { MatcherAssert.assertThat( regsmart.single(part).body().available(), Matchers.equalTo(length) ); } finally { req.body().close(); regsmart.part(part).iterator().next().body().close(); } } /** * RqMultipart.Base can work in integration mode. * @throws IOException if some problem inside */ @Test public void consumesHttpRequest() throws IOException { final String part = "f-1"; final Take take = new Take() { @Override public Response act(final Request req) throws IOException { return new RsText( new RqPrint( new RqMultipart.Smart( new RqMultipart.Base(req) ).single(part) ).printBody() ); } }; final String body = Joiner.on(RqMultipartTest.CRLF).join( "--AaB0zz", String.format(RqMultipartTest.CONTENT, part), "", "my picture", "--AaB0zz ); new FtRemote(take).exec( // @checkstyle AnonInnerLengthCheck (50 lines) new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .method("POST") .header( "Content-Type", "multipart/form-data; boundary=AaB0zz" ) .header( "Content-Length", String.valueOf(body.getBytes().length) ) .body() .set(body) .back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .assertBody(Matchers.containsString("pic")); } } ); } /** * RqMultipart.Base can handle a big request in an acceptable time. * @throws IOException If some problem inside */ @Test @Category(PerformanceTests.class) public void handlesRequestInTime() throws IOException { final int length = 100000000; final String part = "test"; final File file = this.temp.newFile("handlesRequestInTime.tmp"); final BufferedWriter bwr = new BufferedWriter(new FileWriter(file)); bwr.write( Joiner.on(RqMultipartTest.CRLF).join( "--zzz", String.format(RqMultipartTest.CONTENT, part), "", "" ) ); for (int ind = 0; ind < length; ++ind) { bwr.write("X"); } bwr.write(RqMultipartTest.CRLF); bwr.write("--zzz bwr.write(RqMultipartTest.CRLF); bwr.close(); final long start = System.currentTimeMillis(); final Request req = new RqFake( Arrays.asList( "POST /post?u=3 HTTP/1.1", "Host: example.com", "Content-Type: multipart/form-data; boundary=zzz", String.format("Content-Length:%s", file.length()) ), new TempInputStream(new FileInputStream(file), file) ); final RqMultipart.Smart smart = new RqMultipart.Smart( new RqMultipart.Base(req) ); try { MatcherAssert.assertThat( smart.single(part).body().available(), Matchers.equalTo(length) ); MatcherAssert.assertThat( System.currentTimeMillis() - start, //@checkstyle MagicNumberCheck (1 line) Matchers.lessThan(3000L) ); } finally { req.body().close(); smart.part(part).iterator().next().body().close(); } } /** * RqMultipart.Base doesn't distort the content. * @throws IOException If some problem inside */ @Test public void notDistortContent() throws IOException { final int length = 1000000; final String part = "test1"; final File file = this.temp.newFile("notDistortContent.tmp"); final BufferedWriter bwr = new BufferedWriter(new FileWriter(file)); final String head = Joiner.on(RqMultipartTest.CRLF).join( "--zzz1", String.format(RqMultipartTest.CONTENT, part), "", "" ); bwr.write(head); final int byt = 0x7f; for (int idx = 0; idx < length; ++idx) { bwr.write(idx % byt); } final String foot = Joiner.on(RqMultipartTest.CRLF).join( "", "--zzz1 "" ); bwr.write(foot); bwr.close(); final Request req = new RqFake( Arrays.asList( "POST /post?u=3 HTTP/1.1", "Host: exampl.com", contentLengthHeader( head.getBytes().length + length + foot.getBytes().length ), "Content-Type: multipart/form-data; boundary=zzz1" ), new TempInputStream(new FileInputStream(file), file) ); final InputStream stream = new RqMultipart.Smart( new RqMultipart.Base(req) ).single(part).body(); try { MatcherAssert.assertThat( stream.available(), Matchers.equalTo(length) ); for (int idx = 0; idx < length; ++idx) { MatcherAssert.assertThat( String.format("byte %d not matched", idx), stream.read(), Matchers.equalTo(idx % byt) ); } } finally { req.body().close(); stream.close(); } } /** * RqMultipart.Base can produce parts with Content-Length. * @throws IOException If some problem inside */ @Test public void producesPartsWithContentLength() throws IOException { final String part = "t2"; final RqMultipart.Base multipart = new RqMultipart.Base( new RqFake( Arrays.asList( "POST /h?a=4 HTTP/1.1", "Host: rtw.example.com", "Content-Type: multipart/form-data; boundary=AaB01x", "Content-Length: 100007" ), Joiner.on("\r\n").join( "--AaB01x", String.format(RqMultipartTest.CONTENT, part), "", "447 N Wolfe Rd, Sunnyvale, CA 94085", "--AaB01x" ) ) ); try { MatcherAssert.assertThat( multipart.part(part) .iterator() .next(), new HmRqHeader( "content-length", "102" ) ); } finally { multipart.body().close(); multipart.part(part).iterator().next() .body().close(); } } /** * Format Content-Disposition header. * @param dsp Disposition * @return Content-Disposition header */ private static String contentDispositionHeader(final String dsp) { return String.format("Content-Disposition: %s", dsp); } /** * Format Content-Length header. * @param length Body length * @return Content-Length header */ private static String contentLengthHeader(final long length) { return String.format("Content-Length: %d", length); } }
package org.takes.rq; import com.google.common.base.Joiner; import com.jcabi.http.request.JdkRequest; import com.jcabi.http.response.RestResponse; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URI; import java.util.Arrays; import java.util.HashSet; import org.apache.commons.lang.StringUtils; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TemporaryFolder; import org.takes.Request; import org.takes.Response; import org.takes.Take; import org.takes.facets.hamcrest.HmRqHeader; import org.takes.http.FtRemote; import org.takes.misc.PerformanceTests; import org.takes.rs.RsText; @SuppressWarnings("PMD.TooManyMethods") public final class RqMultipartTest { /** * Carriage return constant. */ private static final String CRLF = "\r\n"; /** * Content disposition. */ private static final String DISPOSITION = "Content-Disposition"; /** * Content disposition plus form data. */ private static final String CONTENT = String.format( "%s: %s", RqMultipartTest.DISPOSITION, "form-data; name=\"%s\"" ); /** * Temp directory. */ @Rule public final transient TemporaryFolder temp = new TemporaryFolder(); /** * RqMultipart.Base can satisfy equals contract. * @throws IOException if some problem inside */ @Test public void satisfiesEqualsContract() throws IOException { final String body = "449 N Wolfe Rd, Sunnyvale, CA 94085"; final String part = "t-1"; final Request req = new RqMultipart.Fake( new RqFake(), new RqWithHeaders( new RqFake("", "", body), contentLengthHeader(body.getBytes().length), contentDispositionHeader( String.format("form-data; name=\"%s\"", part) ) ), new RqWithHeaders( new RqFake("", "", ""), contentLengthHeader(0), contentDispositionHeader( "form-data; name=\"data\"; filename=\"a.bin\"" ) ) ); final RqMultipart.Base one = new RqMultipart.Base(req); final RqMultipart.Base two = new RqMultipart.Base(req); try { MatcherAssert.assertThat(one, Matchers.equalTo(two)); } finally { req.body().close(); one.part(part).iterator().next().body().close(); two.part(part).iterator().next().body().close(); } } /** * RqMultipart.Base can throw exception on no closing boundary found. * @throws IOException if some problem inside */ @Test(expected = IOException.class) public void throwsExceptionOnNoClosingBoundaryFound() throws IOException { new RqMultipart.Base( new RqFake( Arrays.asList( "POST /h?a=4 HTTP/1.1", "Host: rtw.example.com", "Content-Type: multipart/form-data; boundary=AaB01x", "Content-Length: 100007" ), Joiner.on(RqMultipartTest.CRLF).join( "--AaB01x", "Content-Disposition: form-data; fake=\"t2\"", "", "447 N Wolfe Rd, Sunnyvale, CA 94085", "Content-Transfer-Encoding: uwf-8" ) ) ); } /** * RqMultipart.Fake can throw exception on no name * at Content-Disposition header. * @throws IOException if some problem inside */ @Test(expected = IOException.class) public void throwsExceptionOnNoNameAtContentDispositionHeader() throws IOException { new RqMultipart.Fake( new RqWithHeader( new RqFake("", "", "340 N Wolfe Rd, Sunnyvale, CA 94085"), RqMultipartTest.DISPOSITION, "form-data; fake=\"t-3\"" ) ); } /** * RqMultipart.Base can throw exception on no boundary * at Content-Type header. * @throws IOException if some problem inside */ @Test(expected = IOException.class) public void throwsExceptionOnNoBoundaryAtContentTypeHeader() throws IOException { new RqMultipart.Base( new RqFake( Arrays.asList( "POST /h?s=3 HTTP/1.1", "Host: wwo.example.com", "Content-Type: multipart/form-data; boundaryAaB03x", "Content-Length: 100005" ), "" ) ); } /** * RqMultipart.Base can throw exception on invalid Content-Type header. * @throws IOException if some problem inside */ @Test(expected = IOException.class) public void throwsExceptionOnInvalidContentTypeHeader() throws IOException { new RqMultipart.Base( new RqFake( Arrays.asList( "POST /h?r=3 HTTP/1.1", "Host: www.example.com", "Content-Type: multipart; boundary=AaB03x", "Content-Length: 100004" ), "" ) ); } /** * RqMultipart.Base can parse http body. * @throws IOException If some problem inside */ @Test public void parsesHttpBody() throws IOException { final String body = "40 N Wolfe Rd, Sunnyvale, CA 94085"; final String part = "t4"; final RqMultipart multi = new RqMultipart.Fake( new RqFake(), new RqWithHeaders( new RqFake("", "", body), contentLengthHeader(body.getBytes().length), contentDispositionHeader( String.format("form-data; name=\"%s\"", part) ) ), new RqWithHeaders( new RqFake("", "", ""), contentLengthHeader(0), contentDispositionHeader( "form-data; name=\"data\"; filename=\"a.bin\"" ) ) ); try { MatcherAssert.assertThat( new RqHeaders.Base( multi.part(part).iterator().next() ).header(RqMultipartTest.DISPOSITION), Matchers.hasItem("form-data; name=\"t4\"") ); MatcherAssert.assertThat( new RqPrint( new RqHeaders.Base( multi.part(part).iterator().next() ) ).printBody(), Matchers.allOf( Matchers.startsWith("40 N"), Matchers.endsWith("CA 94085") ) ); } finally { multi.part(part).iterator().next().body().close(); } } /** * RqMultipart.Fake can return empty iterator on invalid part request. * @throws IOException If some problem inside */ @Test public void returnsEmptyIteratorOnInvalidPartRequest() throws IOException { final String body = "443 N Wolfe Rd, Sunnyvale, CA 94085"; final RqMultipart multi = new RqMultipart.Fake( new RqFake(), new RqWithHeaders( new RqFake("", "", body), contentLengthHeader(body.getBytes().length), contentDispositionHeader( "form-data; name=\"t5\"" ) ), new RqWithHeaders( new RqFake("", "", ""), contentLengthHeader(0), contentDispositionHeader( "form-data; name=\"data\"; filename=\"a.zip\"" ) ) ); MatcherAssert.assertThat( multi.part("fake").iterator().hasNext(), Matchers.is(false) ); multi.body().close(); } /** * RqMultipart.Fake can return correct name set. * @throws IOException If some problem inside */ @Test public void returnsCorrectNamesSet() throws IOException { final String body = "441 N Wolfe Rd, Sunnyvale, CA 94085"; final RqMultipart multi = new RqMultipart.Fake( new RqFake(), new RqWithHeaders( new RqFake("", "", body), contentLengthHeader(body.getBytes().length), contentDispositionHeader( "form-data; name=\"address\"" ) ), new RqWithHeaders( new RqFake("", "", ""), contentLengthHeader(0), contentDispositionHeader( "form-data; name=\"data\"; filename=\"a.bin\"" ) ) ); try { MatcherAssert.assertThat( multi.names(), Matchers.<Iterable<String>>equalTo( new HashSet<String>(Arrays.asList("address", "data")) ) ); } finally { multi.body().close(); } } /** * RqMultipart.Base can return correct part length. * @throws IOException If some problem inside */ @Test public void returnsCorrectPartLength() throws IOException { final int length = 5000; final String part = "x-1"; final String body = Joiner.on(RqMultipartTest.CRLF).join( "--zzz", String.format(RqMultipartTest.CONTENT, part), "", StringUtils.repeat("X", length), "--zzz ); final Request req = new RqFake( Arrays.asList( "POST /post?u=3 HTTP/1.1", "Host: www.example.com", contentLengthHeader(body.getBytes().length), "Content-Type: multipart/form-data; boundary=zzz" ), body ); final RqMultipart.Smart regsmart = new RqMultipart.Smart( new RqMultipart.Base(req) ); try { MatcherAssert.assertThat( regsmart.single(part).body().available(), Matchers.equalTo(length) ); } finally { req.body().close(); regsmart.part(part).iterator().next().body().close(); } } /** * RqMultipart.Base can work in integration mode. * @throws IOException if some problem inside */ @Test public void consumesHttpRequest() throws IOException { final String part = "f-1"; final Take take = new Take() { @Override public Response act(final Request req) throws IOException { return new RsText( new RqPrint( new RqMultipart.Smart( new RqMultipart.Base(req) ).single(part) ).printBody() ); } }; final String body = Joiner.on(RqMultipartTest.CRLF).join( "--AaB0zz", String.format(RqMultipartTest.CONTENT, part), "", "my picture", "--AaB0zz ); new FtRemote(take).exec( // @checkstyle AnonInnerLengthCheck (50 lines) new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .method("POST") .header( "Content-Type", "multipart/form-data; boundary=AaB0zz" ) .header( "Content-Length", String.valueOf(body.getBytes().length) ) .body() .set(body) .back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .assertBody(Matchers.containsString("pic")); } } ); } /** * RqMultipart.Base can handle a big request in an acceptable time. * @throws IOException If some problem inside */ @Test @Category(PerformanceTests.class) public void handlesRequestInTime() throws IOException { final int length = 100000000; final String part = "test"; final File file = this.temp.newFile("handlesRequestInTime.tmp"); final BufferedWriter bwr = new BufferedWriter(new FileWriter(file)); bwr.write( Joiner.on(RqMultipartTest.CRLF).join( "--zzz", String.format(RqMultipartTest.CONTENT, part), "", "" ) ); for (int ind = 0; ind < length; ++ind) { bwr.write("X"); } bwr.write(RqMultipartTest.CRLF); bwr.write("--zzz bwr.write(RqMultipartTest.CRLF); bwr.close(); final long start = System.currentTimeMillis(); final Request req = new RqFake( Arrays.asList( "POST /post?u=3 HTTP/1.1", "Host: example.com", "Content-Type: multipart/form-data; boundary=zzz", String.format("Content-Length:%s", file.length()) ), new TempInputStream(new FileInputStream(file), file) ); final RqMultipart.Smart smart = new RqMultipart.Smart( new RqMultipart.Base(req) ); try { MatcherAssert.assertThat( smart.single(part).body().available(), Matchers.equalTo(length) ); MatcherAssert.assertThat( System.currentTimeMillis() - start, //@checkstyle MagicNumberCheck (1 line) Matchers.lessThan(3000L) ); } finally { req.body().close(); smart.part(part).iterator().next().body().close(); } } /** * RqMultipart.Base doesn't distort the content. * @throws IOException If some problem inside */ @Test public void notDistortContent() throws IOException { final int length = 1000000; final String part = "test1"; final File file = this.temp.newFile("notDistortContent.tmp"); final BufferedWriter bwr = new BufferedWriter(new FileWriter(file)); final String head = Joiner.on(RqMultipartTest.CRLF).join( "--zzz1", String.format(RqMultipartTest.CONTENT, part), "", "" ); bwr.write(head); final int byt = 0x7f; for (int idx = 0; idx < length; ++idx) { bwr.write(idx % byt); } final String foot = Joiner.on(RqMultipartTest.CRLF).join( "", "--zzz1 "" ); bwr.write(foot); bwr.close(); final Request req = new RqFake( Arrays.asList( "POST /post?u=3 HTTP/1.1", "Host: exampl.com", contentLengthHeader( head.getBytes().length + length + foot.getBytes().length ), "Content-Type: multipart/form-data; boundary=zzz1" ), new TempInputStream(new FileInputStream(file), file) ); final InputStream stream = new RqMultipart.Smart( new RqMultipart.Base(req) ).single(part).body(); try { MatcherAssert.assertThat( stream.available(), Matchers.equalTo(length) ); for (int idx = 0; idx < length; ++idx) { MatcherAssert.assertThat( String.format("byte %d not matched", idx), stream.read(), Matchers.equalTo(idx % byt) ); } } finally { req.body().close(); stream.close(); } } /** * RqMultipart.Base can produce parts with Content-Length. * @throws IOException If some problem inside */ @Test public void producesPartsWithContentLength() throws IOException { final String part = "t2"; final RqMultipart.Base multipart = new RqMultipart.Base( new RqFake( Arrays.asList( "POST /h?a=4 HTTP/1.1", "Host: rtw.example.com", "Content-Type: multipart/form-data; boundary=AaB01x", "Content-Length: 100007" ), Joiner.on("\r\n").join( "--AaB01x", String.format(RqMultipartTest.CONTENT, part), "", "447 N Wolfe Rd, Sunnyvale, CA 94085", "--AaB01x" ) ) ); try { MatcherAssert.assertThat( multipart.part(part) .iterator() .next(), new HmRqHeader( "content-length", "102" ) ); } finally { multipart.body().close(); multipart.part(part).iterator().next() .body().close(); } } /** * Format Content-Disposition header. * @param dsp Disposition * @return Content-Disposition header */ private static String contentDispositionHeader(final String dsp) { return String.format("Content-Disposition: %s", dsp); } /** * Format Content-Length header. * @param length Body length * @return Content-Length header */ private static String contentLengthHeader(final long length) { return String.format("Content-Length: %d", length); } }
package jlibs.core.graph.walkers; import jlibs.core.graph.sequences.*; import jlibs.core.graph.*; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import java.util.Stack; /** * @author Santhosh Kumar T */ public class PreorderWalker<E> extends AbstractSequence<E> implements Walker<E>{ private Sequence<? extends E> seq; private Navigator<E> navigator; public PreorderWalker(Sequence<? extends E> seq, Navigator<E> navigator){ this.seq = seq; this.navigator = navigator; _reset(); } public PreorderWalker(E elem, Navigator<E> navigator){ this(new DuplicateSequence<E>(elem), navigator); } @Override public void reset(){ super.reset(); _reset(); } private void _reset(){ path = null; stack.clear(); stack.push(new Children(seq.copy())); } @Override public PreorderWalker<E> copy(){ return new PreorderWalker<E>(seq.copy(), navigator); } private Stack<Children> stack = new Stack<Children>(); private Path path; private class Children{ boolean breakpoint; Sequence<? extends E> seq; public Children(Sequence<? extends E> seq){ this.seq = seq; } } @Override protected E findNext(){ // pop empty sequences while(!stack.isEmpty()){ Children elem = stack.peek(); if(elem.seq.next()==null){ if(elem.breakpoint) return null; else{ stack.pop(); if(path!=null) path = path.getParentPath(); } }else break; } if(stack.isEmpty()) return null; else{ E current = stack.peek().seq.current(); stack.push(new Children(navigator.children(current))); path = path==null ? new Path(current) : path.append(current); return current; } } public Path getCurrentPath(){ return path; } public void skip(){ if(stack.isEmpty()) throw new IllegalStateException("can't skip of descendants of null"); stack.peek().seq = EmptySequence.getInstance(); } public void addBreakpoint(){ if(stack.isEmpty()) throw new IllegalStateException("can't add breakpoint on empty sequence"); stack.peek().breakpoint = true; } public boolean isPaused(){ return !stack.isEmpty() && stack.peek().breakpoint; } @SuppressWarnings("unchecked") public void resume(){ if(isPaused()){ stack.peek().breakpoint = false; current.set(current.index()-1, (E)path.getElement()); } } public static void main(String[] args){ Class c1 = Number.class; Class c2 = Integer.class; System.out.println(c1.isAssignableFrom(c2)); System.out.println(c1.isAssignableFrom(c2)); JFrame frame = new JFrame(); JTree tree = new JTree(); frame.getContentPane().add(new JScrollPane(tree)); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); final PreorderWalker<DefaultMutableTreeNode> seq = new PreorderWalker<DefaultMutableTreeNode>((DefaultMutableTreeNode)tree.getModel().getRoot(), new Navigator<DefaultMutableTreeNode>(){ @Override public Sequence<DefaultMutableTreeNode> children(DefaultMutableTreeNode elem){ return new EnumeratedSequence<DefaultMutableTreeNode>(elem.children()); } }); WalkerUtil.walk(seq, new Processor<DefaultMutableTreeNode>(){ int indent = 0; @Override public boolean preProcess(DefaultMutableTreeNode elem, Path path){ for(int i=0; i<indent; i++) System.out.print(" "); System.out.println(elem+" "+seq.index()); indent++; return true; } @Override public void postProcess(DefaultMutableTreeNode elem, Path path){ indent // for(int i=0; i<indent; i++) // System.out.print(" "); // System.out.println("</"+elem+">"+path); } }); } }
package hudson.tasks.junit; import hudson.model.AbstractBuild; import hudson.util.IOException2; import hudson.*; import org.apache.tools.ant.DirectoryScanner; import org.dom4j.DocumentException; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * Root of all the test results for one build. * * @author Kohsuke Kawaguchi */ public final class TestResult extends MetaTabulatedResult { /** * List of all {@link SuiteResult}s in this test. * This is the core data structure to be persisted in the disk. */ private final List<SuiteResult> suites = new ArrayList<SuiteResult>(); /** * {@link #suites} keyed by their names for faster lookup. */ private transient Map<String,SuiteResult> suitesByName; /** * Results tabulated by package. */ private transient Map<String,PackageResult> byPackages; // set during the freeze phase private transient TestResultAction parent; /** * Number of all tests. */ private transient int totalTests; /** * Number of failed/error tests. */ private transient List<CaseResult> failedTests; /** * Creates an empty result. */ TestResult() { } /** * Collect reports from the given {@link DirectoryScanner}, while * filtering out all files that were created before the given tiem. */ public TestResult(long buildTime, DirectoryScanner results) throws IOException { String[] includedFiles = results.getIncludedFiles(); File baseDir = results.getBasedir(); boolean parsed=false; for (String value : includedFiles) { File reportFile = new File(baseDir, value); // only count files that were actually updated during this build if(buildTime <= reportFile.lastModified()) { parse(reportFile); parsed = true; } } if(!parsed) { long localTime = System.currentTimeMillis(); if(localTime < buildTime) // build time is in the the future. clock on this slave must be running behind throw new AbortException( "Clock on this slave is out of sync with the master, and therefore \n" + "I can't figure out what test results are new and what are old.\n" + "Please keep the slave clock in sync with the master."); File f = new File(baseDir,includedFiles[0]); throw new AbortException( String.format( "Test reports were found but none of them are new. Did tests run? \n"+ "For example, %s is %s old\n", f, Util.getTimeSpanString(buildTime-f.lastModified()))); } } /** * Parses an additional report file. */ public void parse(File reportFile) throws IOException { try { suites.add(new SuiteResult(reportFile)); } catch (RuntimeException e) { throw new IOException2("Failed to read "+reportFile,e); } catch (DocumentException e) { if(!reportFile.getPath().endsWith(".xml")) throw new IOException2("Failed to read "+reportFile+"\n"+ "Is this really a JUnit report file? Your configuration must be matching too many files",e); else throw new IOException2("Failed to read "+reportFile,e); } } public String getDisplayName() { return "Test Result"; } public AbstractBuild<?,?> getOwner() { return parent.owner; } @Override public TestResult getPreviousResult() { TestResultAction p = parent.getPreviousResult(); if(p!=null) return p.getResult(); else return null; } public String getTitle() { return "Test Result"; } public String getChildTitle() { return "Package"; } @Override public int getPassCount() { return totalTests-getFailCount(); } @Override public int getFailCount() { return failedTests.size(); } @Override public List<CaseResult> getFailedTests() { return failedTests; } @Override public Collection<PackageResult> getChildren() { return byPackages.values(); } public PackageResult getDynamic(String packageName, StaplerRequest req, StaplerResponse rsp) { return byPackage(packageName); } public PackageResult byPackage(String packageName) { return byPackages.get(packageName); } public SuiteResult getSuite(String name) { return suitesByName.get(name); } /** * Builds up the transient part of the data structure * from results {@link #parse(File) parsed} so far. * * <p> * After the data is frozen, more files can be parsed * and then freeze can be called again. */ public void freeze(TestResultAction parent) { this.parent = parent; if(suitesByName==null) { // freeze for the first time suitesByName = new HashMap<String,SuiteResult>(); totalTests = 0; failedTests = new ArrayList<CaseResult>(); byPackages = new TreeMap<String,PackageResult>(); } for (SuiteResult s : suites) { if(!s.freeze(this)) continue; suitesByName.put(s.getName(),s); totalTests += s.getCases().size(); for(CaseResult cr : s.getCases()) { if(!cr.isPassed()) failedTests.add(cr); String pkg = cr.getPackageName(); PackageResult pr = byPackage(pkg); if(pr==null) byPackages.put(pkg,pr=new PackageResult(this,pkg)); pr.add(cr); } } Collections.sort(failedTests,CaseResult.BY_AGE); for (PackageResult pr : byPackages.values()) pr.freeze(); } }
package org.mini2Dx.core.geom; import org.mini2Dx.core.exception.MdxException; import org.mini2Dx.core.graphics.Graphics; import org.mini2Dx.core.util.EdgeIterator; import com.badlogic.gdx.math.EarClippingTriangulator; import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.ShortArray; /** * Implements a rotatable polygon. Adds extra functionality to the default * polygon implementation in LibGDX */ public class Polygon extends Shape { private final EarClippingTriangulator triangulator; private final PolygonEdgeIterator edgeIterator = new PolygonEdgeIterator(); private final PolygonEdgeIterator internalEdgeIterator = new PolygonEdgeIterator(); private final Vector2 tmp1 = new Vector2(); private final Vector2 tmp2 = new Vector2(); final com.badlogic.gdx.math.Polygon polygon; private int totalSidesCache = -1; private float minX, minY, maxX, maxY; private ShortArray triangles; private float trackedRotation = 0f; private boolean isRectangle; private boolean minMaxDirty = true; private boolean trianglesDirty = true; /** * Constructor. Note that vertices must be in a clockwise order for * performance and accuracy. * * @param vertices * All points in x,y pairs. E.g. x1,y1,x2,y2,etc. */ public Polygon(float[] vertices) { polygon = new com.badlogic.gdx.math.Polygon(vertices); polygon.setOrigin(vertices[0], vertices[1]); triangulator = new EarClippingTriangulator(); getNumberOfSides(); } /** * Constructor with vectors. Note that vectors must be in a clockwise order * for performance and accuracy. * * @param points * All points in the polygon */ public Polygon(Vector2[] points) { this(toVertices(points)); } public Polygon lerp(Polygon target, float alpha) { final float inverseAlpha = 1.0f - alpha; float [] currentVertices = polygon.getTransformedVertices(); float [] targetVertices = target.polygon.getTransformedVertices(); if(currentVertices.length != targetVertices.length) { throw new MdxException("Cannot lerp polygons with different vertice amounts"); } if(currentVertices[0] != targetVertices[0] || currentVertices[1] != targetVertices[1]) { for(int i = 0; i < currentVertices.length; i += 2) { currentVertices[i] = (currentVertices[i] * inverseAlpha) + (targetVertices[i] * alpha); currentVertices[i + 1] = (currentVertices[i + 1] * inverseAlpha) + (targetVertices[i + 1] * alpha); } polygon.setOrigin(currentVertices[0], currentVertices[1]); polygon.setVertices(currentVertices); setDirty(); } if(getRotation() != target.getRotation()) { float rotation = (trackedRotation * inverseAlpha) + (target.getRotation() * alpha); polygon.setRotation(rotation - trackedRotation); trackedRotation = rotation; setDirty(); } return this; } @Override public Shape copy() { Polygon result = new Polygon(polygon.getTransformedVertices()); result.trackedRotation = trackedRotation; return result; } private void clearTotalSidesCache() { totalSidesCache = -1; } protected boolean triangleContains(float x, float y, float p1x, float p1y, float p2x, float p2y, float p3x, float p3y) { boolean b1, b2, b3; b1 = sign(x, y, p1x, p1y, p2x, p2y) < 0.0f; b2 = sign(x, y, p2x, p2y, p3x, p3y) < 0.0f; b3 = sign(x, y, p3x, p3y, p1x, p1y) < 0.0f; return ((b1 == b2) && (b2 == b3)); } protected float sign(float x, float y, float p1x, float p1y, float p2x, float p2y) { return (x - p2x) * (p1y - p2y) - (p1x - p2x) * (y - p2y); } @Override public boolean contains(float x, float y) { if (isRectangle) { return triangleContains(x, y, polygon.getTransformedVertices()[0], polygon.getTransformedVertices()[1], polygon.getTransformedVertices()[2], polygon.getTransformedVertices()[3], polygon.getTransformedVertices()[6], polygon.getTransformedVertices()[7]) || triangleContains(x, y, polygon.getTransformedVertices()[6], polygon.getTransformedVertices()[7], polygon.getTransformedVertices()[2], polygon.getTransformedVertices()[3], polygon.getTransformedVertices()[4], polygon.getTransformedVertices()[5]); } return polygon.contains(x, y); } @Override public boolean contains(Vector2 vector2) { return contains(vector2.x, vector2.y); } @Override public boolean contains(Shape shape) { if (shape.isCircle()) { Rectangle circleBox = ((Circle) shape).getBoundingBox(); return contains(circleBox.getPolygon()); } return contains(shape.getPolygon()); } public boolean contains(Polygon polygon) { return org.mini2Dx.core.geom.Intersector.containsPolygon(this, polygon); } @Override public boolean intersects(Shape shape) { if (shape.isCircle()) { return intersects((Circle) shape); } return intersects(shape.getPolygon()); } /** * Returns if this {@link Polygon} intersects another * * @param polygon * The other {@link Polygon} * @return True if the two {@link Polygon}s intersect */ public boolean intersects(Polygon polygon) { minMaxDirtyCheck(); polygon.minMaxDirtyCheck(); if (isRectangle && polygon.isRectangle) { boolean xAxisOverlaps = true; boolean yAxisOverlaps = true; if (maxX < polygon.minX) xAxisOverlaps = false; if (polygon.maxX < minX) xAxisOverlaps = false; if (maxY < polygon.minY) yAxisOverlaps = false; if (polygon.maxY < minY) yAxisOverlaps = false; return xAxisOverlaps && yAxisOverlaps; } if (polygon.minX > maxX) { return false; } if (polygon.maxX < minX) { return false; } if (polygon.minY > maxY) { return false; } if (polygon.maxY < minY) { return false; } boolean result = false; internalEdgeIterator.begin(); while (internalEdgeIterator.hasNext()) { internalEdgeIterator.next(); if (polygon.intersects(internalEdgeIterator.getEdgeLineSegment())) { result = true; break; } } internalEdgeIterator.end(); return result; } /** * Returns if this {@link Polygon} intersects a {@link Triangle} * * @param triangle * The {@link Triangle} to check * @return True if this {@link Polygon} and {@link Triangle} intersect */ public boolean intersects(Triangle triangle) { return intersects(triangle.polygon); } /** * Returns if the specified {@link Rectangle} intersects this * {@link Polygon} * * @param rectangle * The {@link Rectangle} to check * @return True if this {@link Polygon} and {@link Rectangle} intersect */ public boolean intersects(Rectangle rectangle) { return intersects(rectangle.polygon); } public boolean intersects(Circle circle) { if (isRectangle) { minMaxDirtyCheck(); float closestX = circle.getX(); float closestY = circle.getY(); if (circle.getX() < minX) { closestX = minX; } else if (circle.getX() > maxX) { closestX = maxX; } if (circle.getY() < minY) { closestY = minY; } else if (circle.getY() > maxY) { closestY = maxY; } closestX = closestX - circle.getX(); closestX *= closestX; closestY = closestY - circle.getY(); closestY *= closestY; return closestX + closestY < circle.getRadius() * circle.getRadius(); } boolean result = false; internalEdgeIterator.begin(); while (internalEdgeIterator.hasNext()) { internalEdgeIterator.next(); if (circle.intersectsLineSegment(internalEdgeIterator.getPointAX(), internalEdgeIterator.getPointAY(), internalEdgeIterator.getPointBX(), internalEdgeIterator.getPointBY())) { result = true; break; } } internalEdgeIterator.end(); return result; } @Override public boolean intersects(LineSegment lineSegment) { return intersectsLineSegment(lineSegment.getPointA(), lineSegment.getPointB()); } @Override public boolean intersectsLineSegment(Vector2 pointA, Vector2 pointB) { return Intersector.intersectSegmentPolygon(pointA, pointB, polygon); } @Override public boolean intersectsLineSegment(float x1, float y1, float x2, float y2) { tmp1.set(x1, y1); tmp2.set(x2, y2); return Intersector.intersectSegmentPolygon(tmp1, tmp2, polygon); } @Override public float getDistanceTo(float x, float y) { float[] vertices = polygon.getTransformedVertices(); float result = Intersector.distanceSegmentPoint(vertices[vertices.length - 2], vertices[vertices.length - 1], vertices[0], vertices[1], x, y); for (int i = 0; i < vertices.length - 2; i += 2) { float distance = Intersector.distanceSegmentPoint(vertices[i], vertices[i + 1], vertices[i + 2], vertices[i + 3], x, y); if (distance < result) { result = distance; } } return result; } /** * Adds an additional point to this {@link Polygon} * * @param x * The x coordinate * @param y * The y coordinate */ public void addPoint(float x, float y) { float[] existingVertices = polygon.getTransformedVertices(); float[] newVertices = new float[existingVertices.length + 2]; if (existingVertices.length > 0) { System.arraycopy(existingVertices, 0, newVertices, 0, existingVertices.length); } newVertices[existingVertices.length] = x; newVertices[existingVertices.length + 1] = y; polygon.translate(-polygon.getX(), -polygon.getY()); polygon.setVertices(newVertices); clearTotalSidesCache(); setDirty(); } /** * Adds an additional point to this {@link Polygon} * * @param point * The point to add as a {@link Vector2} */ public void addPoint(Vector2 point) { addPoint(point.x, point.y); } private void removePoint(int i) { float[] existingVertices = polygon.getTransformedVertices(); float[] newVertices = new float[existingVertices.length - 2]; if (i > 0) { System.arraycopy(existingVertices, 0, newVertices, 0, i); } if (i < existingVertices.length - 2) { System.arraycopy(existingVertices, i + 2, newVertices, i, existingVertices.length - i - 2); } polygon.translate(-polygon.getX(), -polygon.getY()); polygon.setVertices(newVertices); setDirty(); clearTotalSidesCache(); } /** * Removes a point from this {@link Polygon} * * @param x * The x coordinate * @param y * The y coordinate */ public void removePoint(float x, float y) { float[] existingVertices = polygon.getTransformedVertices(); for (int i = 0; i < existingVertices.length; i += 2) { if (existingVertices[i] != x) { continue; } if (existingVertices[i + 1] != y) { continue; } removePoint(i); return; } } /** * Removes a point from this {@link Polygon} * * @param point * The point to remove as a {@link Vector2} */ public void removePoint(Vector2 point) { removePoint(point.x, point.y); } @Override public int getNumberOfSides() { if (totalSidesCache < 0) { totalSidesCache = polygon.getTransformedVertices().length / 2; isRectangle = totalSidesCache == 4; } return totalSidesCache; } @Override public void draw(Graphics g) { g.drawPolygon(polygon.getTransformedVertices()); } @Override public void fill(Graphics g) { g.fillPolygon(polygon.getTransformedVertices(), getTriangles().items); } public float[] getVertices() { return polygon.getTransformedVertices(); } public void setVertices(float[] vertices) { polygon.setOrigin(vertices[0], vertices[1]); polygon.setRotation(0f); polygon.setVertices(vertices); trackedRotation = 0f; clearTotalSidesCache(); setDirty(); } public void setVertices(Vector2[] vertices) { setVertices(toVertices(vertices)); } @Override public float getRotation() { return trackedRotation; } @Override public void setRotation(float degrees) { setRotationAround(polygon.getTransformedVertices()[0], polygon.getTransformedVertices()[1], degrees); } @Override public void rotate(float degrees) { rotateAround(polygon.getTransformedVertices()[0], polygon.getTransformedVertices()[1], degrees); } @Override public void setRotationAround(float centerX, float centerY, float degrees) { if(trackedRotation == degrees && centerX == polygon.getOriginX() && centerY == polygon.getOriginY()) { return; } polygon.setVertices(polygon.getTransformedVertices()); polygon.setOrigin(centerX, centerY); polygon.setRotation(degrees - trackedRotation); trackedRotation = degrees; setDirty(); } @Override public void rotateAround(float centerX, float centerY, float degrees) { if(degrees == 0f) { return; } trackedRotation += degrees; float[] vertices = polygon.getTransformedVertices(); polygon.setRotation(0); polygon.setOrigin(centerX, centerY); polygon.setVertices(vertices); polygon.rotate(degrees); setDirty(); } /** * Returns the x coordinate * * @return The x coordinate of the first point in this {@link Polygon} */ @Override public float getX() { return getX(0); } /** * Returns the y coordinate * * @return The y coordinate of the first point in this {@link Polygon} */ @Override public float getY() { return getY(0); } /** * Returns the x coordinate of the corner at the specified index * * @param index * The point index * @return The x coordinate of the corner */ public float getX(int index) { return polygon.getTransformedVertices()[index * 2]; } /** * Returns the y coordinate of the corner at the specified index * * @param index * The point index * @return The y coordinate of the corner */ public float getY(int index) { return polygon.getTransformedVertices()[(index * 2) + 1]; } /** * Returns min X coordinate of this {@link Polygon} * * @return The left-most x coordinate */ public float getMinX() { minMaxDirtyCheck(); return minX; } /** * Returns min Y coordinate of this {@link Polygon} * * @return The up-most y coordinate */ public float getMinY() { minMaxDirtyCheck(); return minY; } /** * Returns max X coordinate of this {@link Polygon} * * @return The right-most x coordinate */ public float getMaxX() { minMaxDirtyCheck(); return maxX; } /** * Returns max Y coordinate of this {@link Polygon} * * @return The bottom-most y coordinate */ public float getMaxY() { minMaxDirtyCheck(); return maxY; } /** * Returns an array of vertex indices that the define the triangles which * make up this {@link Polygon} * * @return Array of triangle indices */ public ShortArray getTriangles() { trianglesDirtyCheck(); return triangles; } private static float[] toVertices(Vector2[] points) { if (points == null) { throw new MdxException(Point.class.getSimpleName() + " array cannot be null"); } if (points.length < 3) { throw new MdxException(Point.class.getSimpleName() + " must have at least 3 points"); } float[] result = new float[points.length * 2]; for (int i = 0; i < points.length; i++) { int index = i * 2; result[index] = points[i].x; result[index + 1] = points[i].y; } return result; } @Override public void setX(float x) { if(x == getX()) { return; } float[] vertices = polygon.getTransformedVertices(); float xDiff = x - getX(); for (int i = 0; i < vertices.length; i += 2) { vertices[i] += xDiff; } polygon.setOrigin(x, getY()); polygon.setVertices(vertices); setDirty(); } @Override public void setY(float y) { if(y == getY()) { return; } float[] vertices = polygon.getTransformedVertices(); float yDiff = y - getY(); for (int i = 1; i < vertices.length; i += 2) { vertices[i] += yDiff; } polygon.setOrigin(getX(), y); polygon.setVertices(vertices); setDirty(); } @Override public void set(float x, float y) { if(x == getX() && y == getY()) { return; } float[] vertices = polygon.getTransformedVertices(); float xDiff = x - getX(); float yDiff = y - getY(); for (int i = 0; i < vertices.length; i += 2) { vertices[i] += xDiff; vertices[i + 1] += yDiff; } polygon.setOrigin(x, y); polygon.setVertices(vertices); setDirty(); } public void set(Polygon polygon) { this.polygon.setOrigin(polygon.polygon.getOriginX(), polygon.polygon.getOriginY()); this.polygon.setVertices(polygon.polygon.getTransformedVertices()); this.polygon.setRotation(0f); this.trackedRotation = polygon.trackedRotation; clearTotalSidesCache(); setDirty(); } @Override public void translate(float translateX, float translateY) { float[] vertices = polygon.getTransformedVertices(); for (int i = 0; i < vertices.length; i += 2) { vertices[i] += translateX; vertices[i + 1] += translateY; } polygon.setOrigin(vertices[0], vertices[1]); polygon.setVertices(vertices); setDirty(); } @Override public EdgeIterator edgeIterator() { return edgeIterator; } @Override public boolean isCircle() { return false; } @Override public Polygon getPolygon() { return this; } public float getOriginX() { return polygon.getOriginX(); } public float getOriginY() { return polygon.getOriginY(); } boolean isDirty() { return minMaxDirty || trianglesDirty; } private void setDirty() { minMaxDirty = true; trianglesDirty = true; } private void minMaxDirtyCheck() { if(!minMaxDirty) { return; } calculateMinMaxXY(polygon.getTransformedVertices()); minMaxDirty = false; } private void trianglesDirtyCheck() { if(!trianglesDirty) { return; } computeTriangles(polygon.getTransformedVertices()); trianglesDirty = false; } private void computeTriangles(float[] vertices) { triangles = triangulator.computeTriangles(vertices); } private void calculateMinMaxXY(float[] vertices) { int minXIndex = 0; int minYIndex = 1; int maxXIndex = 0; int maxYIndex = 1; for (int i = 2; i < vertices.length; i += 2) { if (vertices[i] < vertices[minXIndex]) { minXIndex = i; } if (vertices[i + 1] < vertices[minYIndex]) { minYIndex = i + 1; } if (vertices[i] > vertices[maxXIndex]) { maxXIndex = i; } if (vertices[i + 1] > vertices[maxYIndex]) { maxYIndex = i + 1; } } this.minX = vertices[minXIndex]; this.minY = vertices[minYIndex]; this.maxX = vertices[maxXIndex]; this.maxY = vertices[maxYIndex]; } @Override public String toString() { StringBuilder result = new StringBuilder(); for (int i = 0; i < polygon.getTransformedVertices().length; i += 2) { result.append("["); result.append(polygon.getTransformedVertices()[i]); result.append(","); result.append(polygon.getTransformedVertices()[i + 1]); result.append("]"); } return result.toString(); } private class PolygonEdgeIterator extends EdgeIterator { private int edge = 0; private LineSegment edgeLineSegment = new LineSegment(0f, 0f, 1f, 1f); @Override protected void beginIteration() { edge = -1; } @Override protected void endIteration() { } @Override protected void nextEdge() { if (edge >= getNumberOfSides()) { throw new MdxException("No more edges remaining. Make sure to call end()"); } edge++; if (!hasNext()) { return; } edgeLineSegment.set(getPointAX(), getPointAY(), getPointBX(), getPointBY()); } @Override public boolean hasNext() { return edge < getNumberOfSides() - 1; } @Override public float getPointAX() { if (edge < 0) { throw new MdxException("Make sure to call next() after beginning iteration"); } return polygon.getTransformedVertices()[edge * 2]; } @Override public float getPointAY() { if (edge < 0) { throw new MdxException("Make sure to call next() after beginning iteration"); } return polygon.getTransformedVertices()[(edge * 2) + 1]; } @Override public float getPointBX() { if (edge < 0) { throw new MdxException("Make sure to call next() after beginning iteration"); } if (edge == getNumberOfSides() - 1) { return polygon.getTransformedVertices()[0]; } return polygon.getTransformedVertices()[(edge + 1) * 2]; } @Override public float getPointBY() { if (edge < 0) { throw new MdxException("Make sure to call next() after beginning iteration"); } if (edge == getNumberOfSides() - 1) { return polygon.getTransformedVertices()[1]; } return polygon.getTransformedVertices()[((edge + 1) * 2) + 1]; } @Override public LineSegment getEdgeLineSegment() { return edgeLineSegment; } } }
package tk.sunnylan.tacn.gui.taui1; import static tk.sunnylan.tacn.parse.Util.convertMarkToString; import java.io.IOException; import java.util.Iterator; import java.util.Map.Entry; import com.jfoenix.controls.JFXToggleButton; import com.jfoenix.controls.JFXTreeTableColumn; import com.jfoenix.controls.RecursiveTreeItem; import com.jfoenix.controls.cells.editors.TextFieldEditorBuilder; import com.jfoenix.controls.cells.editors.base.GenericEditableTreeTableCell; import com.jfoenix.controls.datamodels.treetable.RecursiveTreeObject; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeTableColumn; import javafx.scene.control.TreeTableColumn.CellDataFeatures; import javafx.scene.control.TreeTableColumn.CellEditEvent; import tk.sunnylan.tacn.data.Assignment; import tk.sunnylan.tacn.data.Mark; import tk.sunnylan.tacn.data.Subject; import tk.sunnylan.tacn.parse.Parse; public class SubjectView extends Scene { public final ObservableList<AssignmentWrapper> assignments; public final JFXToggleButton toggleSummary; private SummaryView sum; private Subject subject; public static SubjectView getNewSubjectView(Subject subject) throws IOException { FXMLLoader mahLoader = new FXMLLoader(TAUI1.class.getResource("SubjectView.fxml")); return new SubjectView(mahLoader.load(), mahLoader.getController(), subject); } public SubjectView(Parent root, SubjectViewController controller, Subject subject) { super(root); try { sum = SummaryView.getNewScene(subject); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } controller.summaryPane.getChildren().add(sum.getRoot()); assignments = FXCollections.observableArrayList(); initMarkTable(controller, subject); toggleSummary = new JFXToggleButton(); toggleSummary.setText("Show summary"); toggleSummary.setOnAction((e) -> { controller.summaryPane.getChildren().clear(); if (toggleSummary.isSelected()) { controller.summaryPane.getChildren().add(sum.getRoot()); } }); toggleSummary.setSelected(true); } private void initMarkTable(SubjectViewController controller, Subject subject) { this.subject = subject; JFXTreeTableColumn<AssignmentWrapper, String> assignmentColumn = new JFXTreeTableColumn<>("Assignment"); assignmentColumn.setCellValueFactory((CellDataFeatures<AssignmentWrapper, String> param) -> { if (assignmentColumn.validateValue(param)) return param.getValue().getValue().name; else return assignmentColumn.getComputedValue(param); }); assignmentColumn.setPrefWidth(200); controller.tableMarks.getColumns().add(assignmentColumn); for (String section : subject.sections) { JFXTreeTableColumn<AssignmentWrapper, String> sectionColumn = new JFXTreeTableColumn<>(section); sectionColumn.setCellValueFactory((CellDataFeatures<AssignmentWrapper, String> param) -> { if (sectionColumn.validateValue(param)) { Assignment a = param.getValue().getValue().a; if (a.containsMark(section)) { Mark m = a.getMark(section); return new SimpleStringProperty(convertMarkToString(m)); } } return sectionColumn.getComputedValue(param); }); sectionColumn.setCellFactory( ((TreeTableColumn<AssignmentWrapper, String> param) -> new GenericEditableTreeTableCell<AssignmentWrapper, String>( new TextFieldEditorBuilder()))); sectionColumn.setOnEditCommit((CellEditEvent<AssignmentWrapper, String> t) -> { AssignmentWrapper wr = ((AssignmentWrapper) t.getTreeTableView() .getTreeItem(t.getTreeTablePosition().getRow()).getValue()); if (t.getNewValue().isEmpty()) { wr.a.clearMark(section); } else if (!wr.a.containsMark(section)) try { wr.a.addMark(new Mark(0, 0, 0), section); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if (!Parse.parseMark(wr.a.getMark(section), t.getNewValue())) { if (!Parse.parseMark(wr.a.getMark(section), t.getOldValue())) { wr.a.clearMark(section); } } refresh(); }); sectionColumn.setPrefWidth(150); sectionColumn.getStyleClass().add("centercol"); controller.tableMarks.getColumns().add(sectionColumn); } refresh(); TreeItem<AssignmentWrapper> rootItem = new RecursiveTreeItem<AssignmentWrapper>(assignments, RecursiveTreeObject::getChildren); controller.tableMarks.setRoot(rootItem); } public void refresh() { assignments.removeAll(assignments); Iterator<Entry<String, Assignment>> f = subject.getAssignmentIterator(); Entry<String, Assignment> entry; while (f.hasNext()) { entry = f.next(); assignments.add(new AssignmentWrapper(entry.getValue(), entry.getKey())); } sum.refresh(); } static class AssignmentWrapper extends RecursiveTreeObject<AssignmentWrapper> { public final StringProperty name; public final Assignment a; public AssignmentWrapper(Assignment a, String name) { this.a = a; this.name = new SimpleStringProperty(name); } } }
import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * * @author gvalent8 */ public class guitest1 extends javax.swing.JFrame { /** * Creates new form guitest1 */ public guitest1() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jButton1 = new javax.swing.JButton(); jFormattedTextField1 = new javax.swing.JFormattedTextField(); jFormattedTextField2 = new javax.swing.JFormattedTextField(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jButton7 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jButton9 = new javax.swing.JButton(); jButton10 = new javax.swing.JButton(); jButton11 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jButton1.setText("="); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jFormattedTextField1.setText("Enter Number"); jFormattedTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jFormattedTextField1ActionPerformed(evt); } }); add listener = new add(); jButton2.addActionListener(listener); subtract listener2 = new subtract(); jButton3.addActionListener(listener); multi listener3 = new multi(); jButton4.addActionListener(listener); divide listener4 = new divide(); jButton5.addActionListener(listener); abs listener5 = new abs(); jButton6.addActionListener(listener); base2 listener6 = new base2(); jButton7.addActionListener(listener); base16 listener7 = new base16(); jButton8.addActionListener(listener); root listener8 = new root(); jButton9.addActionListener(listener); square listener9 = new square(); jButton10.addActionListener(listener); jFormattedTextField2.setEnabled(false); jButton2.setText("+"); jButton3.setText("-"); jButton4.setText("*"); jButton5.setText("/"); jButton6.setText("abs"); jButton7.setText("Base2"); jButton8.setText("Base16"); jButton9.setText("SquareRoot"); jButton10.setText("Square"); jButton10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton10ActionPerformed(evt); } }); jButton11.setText("Wolframalpha"); jButton11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton11ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(55, 55, 55) .addComponent(jFormattedTextField1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton6) .addGap(99, 99, 99)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jButton5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton8) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton10)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton4) .addComponent(jButton3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jButton7)) .addComponent(jButton9))))) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jButton11)) .addGroup(layout.createSequentialGroup() .addGap(23, 23, 23) .addComponent(jButton1) .addGap(18, 18, 18) .addComponent(jFormattedTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 383, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(131, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton6)) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(0, 55, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jButton10)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton3) .addComponent(jButton9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton4) .addComponent(jButton7)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton5) .addComponent(jButton8)) .addGap(68, 68, 68) .addComponent(jButton11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jFormattedTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); pack(); }// </editor-fold> private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) { } private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void jFormattedTextField1ActionPerformed(java.awt.event.ActionEvent evt) { String textFieldValue = jFormattedTextField1.getText(); } private static class add implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } private static class subtract implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } private static class multi implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } private static class divide implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } private static class base2 implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } private static class base16 implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } private static class root implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } private static class square implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } private static class abs implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(guitest1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(guitest1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(guitest1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(guitest1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new guitest1().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JButton jButton10; private javax.swing.JButton jButton11; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JButton jButton9; private javax.swing.JFormattedTextField jFormattedTextField1; private javax.swing.JFormattedTextField jFormattedTextField2; // End of variables declaration }
package tutorialspoint.datastructures; import java.util.Iterator; import java.util.Properties; import java.util.Set; public class PropDemo { @SuppressWarnings("rawtypes") public static void main(String args[]) { Properties capitals = new Properties(); Set states; String str; capitals.put("Illinois", "Springfield"); capitals.put("Missouri", "Jefferson City"); capitals.put("Washington", "Olympia"); capitals.put("California", "Sacramento"); capitals.put("Indiana", "Indianapolis"); // Show all states and capitals in hashtable. states = capitals.keySet(); // get set-view of keys Iterator itr = states.iterator(); while (itr.hasNext()) { str = (String) itr.next(); System.out.println("The capital of " + str + " is " + capitals.getProperty(str) + "."); } System.out.println(); // look for state not in list -- specify default str = capitals.getProperty("Florida", "Not Found"); System.out.println("The capital of Florida is " + str + "."); } }
package us.kbase.shock.client; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ByteArrayBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import us.kbase.auth.AuthService; import us.kbase.auth.AuthToken; import us.kbase.auth.AuthUser; import us.kbase.shock.client.exceptions.ExpiredTokenException; import us.kbase.shock.client.exceptions.InvalidShockUrlException; import us.kbase.shock.client.exceptions.ShockHttpException; public class BasicShockClient { private final URI baseurl; private final URI nodeurl; private final HttpClient client = new DefaultHttpClient(); private final ObjectMapper mapper = new ObjectMapper(); private AuthToken token; private static final String AUTH = "Authorization"; private static final String OAUTH = "OAuth "; private static final String DOWNLOAD = "/?download"; private static final String ATTRIBFILE = "attribs"; public BasicShockClient(URL url) throws IOException, InvalidShockUrlException, ExpiredTokenException { this(url, null); } @SuppressWarnings("unchecked") public BasicShockClient(URL url, AuthToken token) throws IOException, InvalidShockUrlException, ExpiredTokenException { updateToken(token); mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); String turl = url.getProtocol() + "://" + url.getAuthority() + url.getPath(); if (turl.charAt(turl.length() - 1) != '/') { turl = turl + "/"; } if (!(url.getProtocol().equals("http") || url.getProtocol().equals("https"))) { throw new InvalidShockUrlException(turl.toString()); } final HttpResponse response = client.execute(new HttpGet(turl)); final String resp = EntityUtils.toString(response.getEntity()); Map<String, Object> shockresp = null; try { shockresp = mapper.readValue(resp, Map.class); } catch (JsonParseException jpe) { throw new InvalidShockUrlException(turl.toString()); } if (!shockresp.get("id").equals("Shock")) { throw new InvalidShockUrlException(turl.toString()); } URL shockurl = new URL(shockresp.get("url").toString()); //https->http is caused by the router, not shock, per Jared if (url.getProtocol().equals("https")) { shockurl = new URL("https", shockurl.getAuthority(), shockurl.getPort(), shockurl.getFile()); } try { baseurl = shockurl.toURI(); } catch (URISyntaxException use) { throw new Error(use); //something went badly wrong } nodeurl = baseurl.resolve("node/"); } public void updateToken(AuthToken token) throws ExpiredTokenException { if (token == null) { this.token = null; return; } if (token.isExpired()) { throw new ExpiredTokenException(token.getTokenId()); } this.token = token; } public URL getShockUrl() { return uriToUrl(baseurl); } public ShockNode getNode(ShockNodeId id) throws IOException, ShockHttpException, ExpiredTokenException { final URI targeturl = nodeurl.resolve(id.getId()); final HttpGet htg = new HttpGet(targeturl); authorize(htg); final HttpResponse response = client.execute(htg); return getShockNode(response); } private ShockNode getShockNode(HttpResponse response) throws IOException, ShockHttpException { final String resp = EntityUtils.toString(response.getEntity()); try { return mapper.readValue(resp, ShockNodeResponse.class).getShockNode(); } catch (JsonParseException jpe) { throw new Error(jpe); //something's broken } } private void authorize(HttpRequestBase httpreq) throws ExpiredTokenException { if (token != null) { //TODO test when can get hands on expired token if (token.isExpired()) { throw new ExpiredTokenException(token.getTokenId()); } httpreq.setHeader(AUTH, OAUTH + token); } } public String getFileAsString(ShockNodeId id) throws IOException, ShockHttpException, ExpiredTokenException { final URI targeturl = nodeurl.resolve(id.getId() + DOWNLOAD); final HttpGet htg = new HttpGet(targeturl); authorize(htg); final HttpResponse response = client.execute(htg); final int code = response.getStatusLine().getStatusCode(); if (code > 299) { getShockNode(response); //trigger errors } return EntityUtils.toString(response.getEntity()); } public ShockNode addNode() throws IOException, ShockHttpException, JsonProcessingException, ExpiredTokenException { return _addNode(null, null, null); } public ShockNode addNode(Map<String, Object> attributes) throws IOException, ShockHttpException, JsonProcessingException, ExpiredTokenException { if (attributes == null) { throw new NullPointerException("attributes"); } return _addNode(attributes, null, null); } public ShockNode addNode(String file, String filename) throws IOException, ShockHttpException, JsonProcessingException, ExpiredTokenException { if (file == null) { throw new NullPointerException("file"); } if (filename == null) { throw new NullPointerException("filename"); } return _addNode(null, file, filename); } public ShockNode addNode(Map<String, Object> attributes, String file, String filename) throws IOException, ShockHttpException, JsonProcessingException, ExpiredTokenException { if (attributes == null) { throw new NullPointerException("attributes"); } if (file == null) { throw new NullPointerException("file"); } if (filename == null) { throw new NullPointerException("filename"); } return _addNode(attributes, file, filename); } private ShockNode _addNode(Map<String, Object> attributes, String file, String filename) throws IOException, ShockHttpException, JsonProcessingException, ExpiredTokenException { final HttpPost htp = new HttpPost(nodeurl); authorize(htp); if (attributes != null && file != null) { final MultipartEntity mpe = new MultipartEntity(); if (attributes != null) { final byte[] attribs = mapper.writeValueAsBytes(attributes); mpe.addPart("attributes", new ByteArrayBody(attribs, ATTRIBFILE)); } if (file != null) { mpe.addPart("upload", new ByteArrayBody(file.getBytes(), filename)); } htp.setEntity(mpe); } HttpResponse response = client.execute(htp); ShockNode sn = getShockNode(response); return sn; } public void deleteNode(ShockNodeId id) throws IOException, ShockHttpException, ExpiredTokenException { final URI targeturl = nodeurl.resolve(id.getId()); final HttpDelete htd = new HttpDelete(targeturl); authorize(htd); final HttpResponse response = client.execute(htd); getShockNode(response); //triggers throwing errors } public void setNodeReadable(ShockNodeId id, AuthUser user) { //TODO } public void setNodeWorldReadable(ShockNode id) { //TODO } //for known good uris ONLY private URL uriToUrl(URI uri) { try { return uri.toURL(); } catch (MalformedURLException mue) { throw new Error(mue); //something is seriously fuxxored } } public static void main(String[] args) throws Exception { AuthUser au = AuthService.login("x", "x"); BasicShockClient bsc = new BasicShockClient(new URL("http://localhost:7044"), au.getToken()); System.out.println("***Add node"); Map<String, Object> attribs = new HashMap<String, Object>(); attribs.put("foo", "newbar"); ShockNode node = bsc.addNode(attribs, "some serious crap right here", "seriouscrapfile"); System.out.println(node); System.out.println("***Get node"); System.out.println(bsc.getNode(node.getId())); System.out.println("***Get file"); System.out.println(bsc.getFileAsString(node.getId())); System.out.println("***Get node with no auth"); BasicShockClient bscNoAuth = new BasicShockClient(new URL("http://localhost:7044")); try { bscNoAuth.getNode(node.getId()); } catch (ShockHttpException she) { System.out.println(she); } System.out.println("***delete node"); bsc.deleteNode(node.getId()); System.out.println("***get deleted node"); try { System.out.println(bsc.getNode(node.getId())); } catch (ShockHttpException she) { System.out.println(she); } System.out.println("***Add empty node"); ShockNode node2 = bsc.addNode(); System.out.println("***Get non-existant file"); try { bsc.getFileAsString(node2.getId()); } catch (ShockHttpException she) { System.out.println(she); } ShockNode node2get = bsc.getNode(node2.getId()); System.out.println(bsc.getNode(node2get.getId())); //TODO that token wasn't expired. Pfft. // AuthToken expired = new AuthToken(""); // try { // @SuppressWarnings("unused") // } catch (ExpiredTokenException ete) { // System.out.println(ete); // try { // bsc.updateToken(expired); // } catch (ExpiredTokenException ete) { // System.out.println(ete); //TODO tests for tokens that expire while in the client BasicShockClient bsc2 = new BasicShockClient(new URL("http://kbase.us/services/shock-api")); ShockNodeId snid2 = new ShockNodeId("9ae2658e-057f-4f89-81a1-a41c09c7313a"); System.out.println("***Get node " + snid2 + " from " + bsc2.getShockUrl()); System.out.println(bsc2.getNode(snid2)); //TODO test readable nodes //TODO test errors } }
package org.openlca.core.matrix.io; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; import java.util.function.Consumer; import org.openlca.core.matrix.format.ByteMatrixReader; import org.openlca.core.matrix.format.MatrixReader; public final class Csv { private DecimalFormat numberFormat; private String delimiter = ","; private Charset charset = StandardCharsets.UTF_8; public static Csv defaultConfig() { return new Csv(); } public String quote(String s) { if (s == null) return "\"\""; return s.contains("\"") ? "\"" + s.replace("\"", "\"\"") + "\"" : "\"" + s + "\""; } public Csv withDelimiter(String delimiter) { if (delimiter != null) { this.delimiter = delimiter; } return this; } public Csv withEncoding(Charset charset) { if (charset != null) { this.charset = charset; } return this; } public Csv withDecimalSeparator(char separator) { if (separator == '.') { numberFormat = null; return this; } numberFormat = (DecimalFormat) NumberFormat.getInstance(Locale.US); numberFormat.setMaximumFractionDigits(1000); numberFormat.setGroupingUsed(false); var symbols = numberFormat.getDecimalFormatSymbols(); symbols.setDecimalSeparator(separator); numberFormat.setDecimalFormatSymbols(symbols); return this; } public void write(double[] vector, File file) { if (vector == null || file == null) return; writer(file, w -> { for (double v : vector) { writeln(w, format(v)); } }); } public void write(MatrixReader matrix, File file) { if (matrix == null || file == null) return; var buffer = new String[matrix.columns()]; writer(file, w -> { for (int row = 0; row < matrix.rows(); row++) { for (int col = 0; col < matrix.columns(); col++) { buffer[col] = format(matrix.get(row, col)); } writeln(w, line(buffer)); } }); } private String format(double v) { if (v == 0) return "0"; return numberFormat == null ? Double.toString(v) : numberFormat.format(v); } public void write(ByteMatrixReader matrix, File file) { if (matrix == null || file == null) return; var buffer = new String[matrix.columns()]; writer(file, w -> { for (int row = 0; row < matrix.rows(); row++) { for (int col = 0; col < matrix.columns(); col++) { buffer[col] = Integer.toString(matrix.get(row, col)); } writeln(w, line(buffer)); } }); } void writeln(BufferedWriter writer, String line) { try { writer.write(line); writer.newLine(); } catch (Exception e) { throw new RuntimeException(e); } } void writer(File file, Consumer<BufferedWriter> fn) { try (var stream = new FileOutputStream(file); var writer = new OutputStreamWriter(stream, charset); var buffer = new BufferedWriter(writer)) { fn.accept(buffer); buffer.flush(); } catch (IOException e) { throw new RuntimeException("Failed to write file: " + file.getName(), e); } } String line(String[] entries) { if (entries == null) return ""; var b = new StringBuilder(); for (int i = 0; i < entries.length; i++) { if (i != 0) { b.append(delimiter); } var e = entries[i]; if(e != null) { b.append(e); } } return b.toString(); } }
package org.sstctf.snake_game; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; /** * This class represents the pellet that can be picked up by the snake. * The class deals with spawning the pellet * and rendering it. * * It is an object of the game and thus extends GameObject. * * @author Andrew Quach * @author Stanislav Lyakhov * * @version 1.0.0 */ public class Pellet extends GameObject { private Handler handler; private boolean isPellet; /** * Creates a pellet given its X and Y coordinates. * Sets the ID of the object to Pellet. * * @param posX the position of the pellet on the X axis * @param posY the position of the pellet on the Y axis * @param handler handles all game objects */ public Pellet(int posX, int posY, Handler handler) { super(posX, posY, ID.Pellet); this.handler = handler; isPellet = true; } /** * Handles the random generation of a pellet object. * * @return the coordinates of the next spawn point of the pellet */ public int[] randomSpawn() { List<int[]> occupiedSpaces = null; for (int i = 0; i < handler.objects.size(); i++) { GameObject temp = handler.objects.get(i); if (temp.getID() == ID.Snake) { occupiedSpaces = (((Snake) temp).getSnakeParts()); } } Random random = new Random(); while (occupiedSpaces.size() != 1444) { int[] spawn = {random.nextInt(38)+1, random.nextInt(38)+1}; if (checkSpace(spawn, occupiedSpaces)) { return spawn; } } return new int[]{-1, -1}; } /** * Checks if a randomly generated spawn point is occupied. * Helper method for generating random spawn point for the pellet object. * * @param spawn array containing the X and Y coordinates of a planned spawn point * @param occupiedSpaces list of cood1inates of spaces occupied by the snake * * @return true if spawn point is occupied * @return false if spawn point is unoccupied * */ private boolean checkSpace(int[] spawn, List<int[]> occupiedSpaces){ for (int i = 0; i < occupiedSpaces.size(); i++) { if (Arrays.equals(occupiedSpaces.get(i), spawn)) { return false; } } return true; } /** * Sets the pellet to either existing/not existing * * @param isPellet */ public void setPellet(boolean isPellet) { this.isPellet = isPellet; } /** * Override of GameObject tick method. * Checks if pellet exists every tick, * if not spawns new pellet. */ @Override public void tick() { if (!isPellet) { setPosition(randomSpawn()); isPellet = true; } } /** * Override of GameObject render method. * Handles the rendering of the pellet. * Yellow rectangle. */ @Override public void render(Graphics g) { g.setColor(Color.YELLOW); g.fillRect(getPosition()[0]*Game.SCALE, getPosition()[1]*Game.SCALE, Game.SCALE, Game.SCALE); } /** * Override of GameObject getBounds method. * Handles the hitboxes of the pellet. * * @return the hitboxes of the pellet */ @Override public List<Rectangle> getBounds() { List<Rectangle> hitboxes = new ArrayList<Rectangle>(); hitboxes.add(new Rectangle(getPosition()[0]*Game.SCALE, getPosition()[1]*Game.SCALE, Game.SCALE, Game.SCALE)); return hitboxes; } }
package com.limpoxe.fairy.util; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @SuppressWarnings("unchecked") public class RefInvoker { private static final ClassLoader system = ClassLoader.getSystemClassLoader(); private static final ClassLoader bootloader = system.getParent(); private static final ClassLoader application = RefInvoker.class.getClassLoader(); private static HashMap<String, Class> clazzCache = new HashMap<String, Class>(); public static Class forName(String clazzName) throws ClassNotFoundException { Class clazz = clazzCache.get(clazzName); if (clazz == null) { clazz = Class.forName(clazzName); ClassLoader cl = clazz.getClassLoader(); if (cl == system || cl == application || cl == bootloader) { clazzCache.put(clazzName, clazz); } } return clazz; } public static Object newInstance(String className, Class[] paramTypes, Object[] paramValues) { try { Class clazz = forName(className); Constructor constructor = clazz.getConstructor(paramTypes); if (!constructor.isAccessible()) { constructor.setAccessible(true); } return constructor.newInstance(paramValues); } catch (ClassNotFoundException e) { e.printStackTrace(); LogUtil.printException("ClassNotFoundException", e); } catch (NoSuchMethodException e) { e.printStackTrace(); LogUtil.printException("NoSuchMethodException", e); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; } public static Object invokeMethod(Object target, String className, String methodName, Class[] paramTypes, Object[] paramValues) { try { Class clazz = forName(className); return invokeMethod(target, clazz, methodName, paramTypes, paramValues); }catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } public static Object invokeMethod(Object target, Class clazz, String methodName, Class[] paramTypes, Object[] paramValues) { try { Method method = clazz.getDeclaredMethod(methodName, paramTypes); if (!method.isAccessible()) { method.setAccessible(true); } return method.invoke(target, paramValues); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; } @SuppressWarnings("rawtypes") public static Object getField(Object target, String className, String fieldName) { try { Class clazz = forName(className); return getField(target, clazz, fieldName); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } @SuppressWarnings("rawtypes") public static Object getField(Object target, Class clazz, String fieldName) { try { Field field = clazz.getDeclaredField(fieldName); if (!field.isAccessible()) { field.setAccessible(true); } return field.get(target); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { // try supper for Miui, Miui has a class named MiuiPhoneWindow try { Field field = clazz.getSuperclass().getDeclaredField(fieldName); field.setAccessible(true); return field.get(target); } catch (Exception superE) { e.printStackTrace(); superE.printStackTrace(); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } @SuppressWarnings("rawtypes") public static void setField(Object target, String className, String fieldName, Object fieldValue) { try { Class clazz = forName(className); setField(target, clazz, fieldName, fieldValue); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static void setField(Object target, Class clazz, String fieldName, Object fieldValue) { try { Field field = clazz.getDeclaredField(fieldName); if (!field.isAccessible()) { field.setAccessible(true); } field.set(target, fieldValue); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { // try supper for Miui, Miui has a class named MiuiPhoneWindow try { Field field = clazz.getSuperclass().getDeclaredField(fieldName); if (!field.isAccessible()) { field.setAccessible(true); } field.set(target, fieldValue); } catch (Exception superE) { e.printStackTrace(); //superE.printStackTrace(); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } public static Method findMethod(Object object, String methodName, Class[] clazzes) { try { return object.getClass().getDeclaredMethod(methodName, clazzes); } catch (NoSuchMethodException e) { e.printStackTrace(); } return null; } public static Method findMethod(Object object, String methodName, Object[] args) { if (args == null) { try { return object.getClass().getDeclaredMethod(methodName, (Class[])null); } catch (NoSuchMethodException e) { e.printStackTrace(); } return null; } else { Method[] methods = object.getClass().getDeclaredMethods(); boolean isFound = false; Method method = null; for(Method m: methods) { if (m.getName().equals(methodName)) { Class<?>[] types = m.getParameterTypes(); if (types.length == args.length) { isFound = true; for(int i = 0; i < args.length; i++) { if (!(types[i] == args[i].getClass() || (types[i].isPrimitive() && primitiveToWrapper(types[i]) == args[i].getClass()))) { isFound = false; break; } } if (isFound) { method = m; break; } } } } return method; } } private static final Map<Class<?>, Class<?>> primitiveWrapperMap = new HashMap<Class<?>, Class<?>>(); static { primitiveWrapperMap.put(Boolean.TYPE, Boolean.class); primitiveWrapperMap.put(Byte.TYPE, Byte.class); primitiveWrapperMap.put(Character.TYPE, Character.class); primitiveWrapperMap.put(Short.TYPE, Short.class); primitiveWrapperMap.put(Integer.TYPE, Integer.class); primitiveWrapperMap.put(Long.TYPE, Long.class); primitiveWrapperMap.put(Double.TYPE, Double.class); primitiveWrapperMap.put(Float.TYPE, Float.class); primitiveWrapperMap.put(Void.TYPE, Void.TYPE); } static Class<?> primitiveToWrapper(final Class<?> cls) { Class<?> convertedClass = cls; if (cls != null && cls.isPrimitive()) { convertedClass = primitiveWrapperMap.get(cls); } return convertedClass; } public static ArrayList dumpAllInfo(String className) { try { Class clazz = Class.forName(className); return dumpAllInfo(clazz); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } public static ArrayList dumpAllInfo(Class clazz) { ArrayList arrayList = new ArrayList(); LogUtil.i("clazz=" + clazz.getName()); LogUtil.i("Superclass=" + clazz.getSuperclass()); Constructor[] ctors = clazz.getDeclaredConstructors(); if (ctors != null) { LogUtil.i("DeclaredConstructors for(Constructor c : ctors){ LogUtil.i(c); arrayList.add(c); } } Constructor[] publicCtors = clazz.getConstructors(); if (publicCtors != null) { LogUtil.i("Constructors for(Constructor c :publicCtors){ LogUtil.i(c); arrayList.add(c); } } Method[] mtds = clazz.getDeclaredMethods(); if (mtds != null) { LogUtil.i("DeclaredMethods for(Method m : mtds){ LogUtil.i(m); arrayList.add(m); } } Method[] mts = clazz.getMethods(); if (mts != null) { LogUtil.i("Methods for(Method m : mts){ LogUtil.i(m); arrayList.add(m); } } Class<?>[] inners = clazz.getDeclaredClasses(); if (inners != null) { LogUtil.i("DeclaredClasses for(Class c : inners){ LogUtil.i(c.getName()); arrayList.add(c.getName()); } } Class<?>[] classes = clazz.getClasses(); if (classes != null) { LogUtil.i("classes for(Class c : classes){ LogUtil.i(c.getName()); arrayList.add(c.getName()); } } Field[] dfields = clazz.getDeclaredFields(); if (dfields != null) { LogUtil.i("DeclaredFields for(Field f : dfields){ LogUtil.i(f); arrayList.add(f); } } Field[] fields = clazz.getFields(); if (fields != null) { LogUtil.i("Fields for(Field f : fields){ LogUtil.i(f); arrayList.add(f); } } Annotation[] anns = clazz.getAnnotations(); if (anns != null) { LogUtil.i("Annotations for(Annotation an : anns){ LogUtil.i(an); arrayList.add(an); } } return arrayList; } public static ArrayList dumpAllInfo(Object object) { Class clazz = object.getClass(); return dumpAllInfo(clazz); } }
package uk.ac.ebi.atlas.utils; import com.google.common.base.Preconditions; import java.awt.Color; public class ColourGradient { public static String getGradientColour(double value, double min, double max, String lowValueColourString, String highValueColourString) { Preconditions.checkArgument( value >= 0.0 && value >= min && value <= max || value < 0 && value <= min && value >= max); Color lowValueColour = getColour(lowValueColourString); Color highValueColour = getColour(highValueColourString); return colourToHexString(getGradientColour(value, min, max, lowValueColour, highValueColour)); } private static Color getColour(String colourString) { if (colourString.startsWith(" return Color.decode(colourString); } return getColourByName(colourString); } private static String colourToHexString(Color colour) { return "#" + Integer.toHexString(colour.getRGB()).substring(2).toUpperCase(); } private static Color getColourByName(String colourName) { try { return (Color)Color.class.getField(colourName).get(null); } catch (NoSuchFieldException | IllegalAccessException e) { throw new IllegalArgumentException(e); } } // Determines what colour a heat map cell should be based upon the cell values. private static Color getGradientColour(double value, double min, double max, Color lowValueColour, Color highValueColour) { double percentPosition = calculatePercentPosition(value, min, max); // Which colour group does that put us in. int colourPosition = getColourPosition(percentPosition, lowValueColour, highValueColour); return calculateColorForPosition(colourPosition, lowValueColour, highValueColour); } private static Color calculateColorForPosition(int colourPosition, Color lowValueColour, Color highValueColour) { int r = lowValueColour.getRed(); int g = lowValueColour.getGreen(); int b = lowValueColour.getBlue(); // Make n shifts of the colour, where n is the colourPosition. for (int i = 0 ; i < colourPosition ; i++) { int rDistance = r - highValueColour.getRed(); int gDistance = g - highValueColour.getGreen(); int bDistance = b - highValueColour.getBlue(); if ((Math.abs(rDistance) >= Math.abs(gDistance)) && (Math.abs(rDistance) >= Math.abs(bDistance))) { // Red must be the largest. r = updateColourValue(r, rDistance); } else if (Math.abs(gDistance) >= Math.abs(bDistance)) { // Green must be the largest. g = updateColourValue(g, gDistance); } else { // Blue must be the largest. b = updateColourValue(b, bDistance); } } return new Color(r, g, b); } private static double calculatePercentPosition(double data, double min, double max) { double range = max - min; double position = data - min; return position / range; } // Returns how many colour shifts are required from the lowValueColour to get to the correct colour position private static int getColourPosition(double percentPosition, Color lowValueColour, Color highValueColour) { int colourDistance = calculateColourDistance(lowValueColour, highValueColour); return (int) Math.round(colourDistance * percentPosition); } static int updateColourValue(int colourValue, int colourDistance) { if (colourDistance < 0) { return colourValue + 1; } else if (colourDistance > 0) { return colourValue - 1; } else { // This shouldn't actually happen here. return colourValue; } } /* * Calculate and update the field for the distance between the low colour * and high colour. The distance is the number of steps between one colour * and the other using an RGB coding with 0-255 values for each of red, * green and blue. So the maximum colour distance is 255 + 255 + 255. */ private static int calculateColourDistance(Color lowValueColour, Color highValueColour) { int r1 = lowValueColour.getRed(); int g1 = lowValueColour.getGreen(); int b1 = lowValueColour.getBlue(); int r2 = highValueColour.getRed(); int g2 = highValueColour.getGreen(); int b2 = highValueColour.getBlue(); return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2); } }
package org.basex.io.random; import java.io.*; import org.basex.io.*; import org.basex.util.*; public final class DataAccess implements AutoCloseable { /** Buffer manager. */ private final Buffers bm = new Buffers(); /** Reference to the data input stream. */ private final RandomAccessFile raf; /** File length. */ private long length; /** Changed flag. */ private boolean changed; /** Offset. */ private int off; /** * Constructor, initializing the file reader. * @param file the file to be read * @throws IOException I/O Exception */ public DataAccess(final IOFile file) throws IOException { RandomAccessFile f = null; try { f = new RandomAccessFile(file.file(), "rw"); length = f.length(); raf = f; cursor(0); } catch(final IOException ex) { if(f != null) f.close(); throw ex; } } /** * Flushes the buffered data. */ public synchronized void flush() { try { for(final Buffer b : bm.all()) if(b.dirty) writeBlock(b); if(changed) { raf.setLength(length); changed = false; } } catch(final IOException ex) { Util.stack(ex); } } @Override public synchronized void close() { flush(); try { raf.close(); } catch(final IOException ex) { Util.stack(ex); } } /** * Returns the current file position. * @return position in the file */ public long cursor() { return buffer(false).pos + off; } /** * Returns the file length. * @return file length */ public long length() { return length; } /** * Checks if more bytes can be read. * @return result of check */ public boolean more() { return cursor() < length; } /** * Reads a byte value from the specified position. * @param pos position * @return integer value */ public synchronized byte read1(final long pos) { cursor(pos); return read1(); } /** * Reads a byte value. * @return integer value */ public synchronized byte read1() { return (byte) read(); } /** * Reads an integer value from the specified position. * @param pos position * @return integer value */ public synchronized int read4(final long pos) { cursor(pos); return read4(); } /** * Reads an integer value. * @return integer value */ public synchronized int read4() { return (read() << 24) + (read() << 16) + (read() << 8) + read(); } /** * Reads a 5-byte value from the specified file offset. * @param pos position * @return long value */ public synchronized long read5(final long pos) { cursor(pos); return read5(); } /** * Reads a 5-byte value. * @return long value */ public synchronized long read5() { return ((long) read() << 32) + ((long) read() << 24) + (read() << 16) + (read() << 8) + read(); } /** * Reads a {@link Num} value from disk. * @param p text position * @return read num */ public synchronized int readNum(final long p) { cursor(p); return readNum(); } /** * Reads a token from disk. * @param p text position * @return text as byte array */ public synchronized byte[] readToken(final long p) { cursor(p); return readToken(); } /** * Reads the next token from disk. * @return text as byte array */ public synchronized byte[] readToken() { final int l = readNum(); return readBytes(l); } /** * Reads a number of bytes from the specified offset. * @param pos position * @param len length * @return byte array */ public synchronized byte[] readBytes(final long pos, final int len) { cursor(pos); return readBytes(len); } /** * Reads a number of bytes. * @param len length * @return byte array */ public synchronized byte[] readBytes(final int len) { int l = len; int ll = IO.BLOCKSIZE - off; final byte[] b = new byte[l]; System.arraycopy(buffer(false).data, off, b, 0, Math.min(l, ll)); if(l > ll) { l -= ll; while(l > IO.BLOCKSIZE) { System.arraycopy(buffer(true).data, 0, b, ll, IO.BLOCKSIZE); ll += IO.BLOCKSIZE; l -= IO.BLOCKSIZE; } System.arraycopy(buffer(true).data, 0, b, ll, l); } off += l; return b; } /** * Sets the disk cursor. * @param pos read position */ public void cursor(final long pos) { off = (int) (pos & IO.BLOCKSIZE - 1); final long b = pos - off; if(!bm.cursor(b)) return; final Buffer bf = bm.current(); try { if(bf.dirty) writeBlock(bf); bf.pos = b; raf.seek(bf.pos); if(bf.pos < raf.length()) raf.readFully(bf.data, 0, (int) Math.min(length - bf.pos, IO.BLOCKSIZE)); } catch(final IOException ex) { Util.stack(ex); } } /** * Reads the next compressed number and returns it as integer. * @return next integer */ public synchronized int readNum() { final int value = read(); switch(value & 0xC0) { case 0: return value; case 0x40: return (value - 0x40 << 8) + read(); case 0x80: return (value - 0x80 << 24) + (read() << 16) + (read() << 8) + read(); default: return (read() << 24) + (read() << 16) + (read() << 8) + read(); } } /** * Writes a 5-byte value to the specified position. * @param pos position in the file * @param value value to be written */ public void write5(final long pos, final long value) { cursor(pos); write((byte) (value >>> 32)); write((byte) (value >>> 24)); write((byte) (value >>> 16)); write((byte) (value >>> 8)); write((byte) value); } /** * Writes an integer value to the specified position. * @param pos write position * @param value byte array to be appended */ public void write4(final long pos, final int value) { cursor(pos); write4(value); } /** * Writes an integer value to the current position. * @param value value to be written */ public void write4(final int value) { write(value >>> 24); write(value >>> 16); write(value >>> 8); write(value); } /** * Write a value to the file. * @param pos write position * @param value value to be written */ public void writeNum(final long pos, final int value) { cursor(pos); writeNum(value); } /** * Writes integers to the file in compressed form. * @param p write position * @param values integer values */ public void writeNums(final long p, final int[] values) { cursor(p); writeNum(values.length); for(final int n : values) writeNum(n); } /** * Writes a byte array to the file. * @param buffer buffer containing the token * @param offset offset in the buffer where the token starts * @param len token length */ public void writeBytes(final byte[] buffer, final int offset, final int len) { final int last = offset + len; int o = offset; while(o < last) { final Buffer bf = buffer(); final int l = Math.min(last - o, IO.BLOCKSIZE - off); System.arraycopy(buffer, o, bf.data, off, l); bf.dirty = true; off += l; o += l; // adjust file size final long nl = bf.pos + off; if(nl > length) length(nl); } } /** * Appends a value to the file and return it's offset. * @param pos write position * @param values byte array to be appended */ public void writeToken(final long pos, final byte[] values) { cursor(pos); writeToken(values, 0, values.length); } /** * Returns the offset to a free slot for writing an entry with the * specified length. Fills the original space with 0xFF to facilitate * future write operations. * @param pos original offset * @param size size of new text entry * @return new offset to store text */ public long free(final long pos, final int size) { // old text size (available space) int os = readNum(pos) + (int) (cursor() - pos); // extend available space by subsequent zero-bytes cursor(pos + os); for(; pos + os < length && os < size && read() == 0xFF; os++); long o = pos; if(pos + os == length) { // entry is placed last: reset file length (discard last entry) length(pos); } else { int t = size; if(os < size) { // gap is too small for new entry... // reset cursor to overwrite entry cursor(pos); t = 0; // place new entry after last entry o = length; } else { // gap is large enough: set cursor to overwrite remaining bytes cursor(pos + size); } // fill gap with 0xFF for future updates while(t++ < os) write(0xFF); } return o; } /** * Sets the file length. * @param len file length */ private synchronized void length(final long len) { if(len != length) { changed = true; length = len; } } /** * Reads the next byte. * @return next byte */ private int read() { final Buffer bf = buffer(); return bf.data[off++] & 0xFF; } /** * Writes the next byte. * @param value byte to be written */ private void write(final int value) { final Buffer bf = buffer(); bf.dirty = true; bf.data[off++] = (byte) value; final long nl = bf.pos + off; if(nl > length) length(nl); } /** * Write a token to the file. * @param buffer buffer containing the token * @param offset offset in the buffer where the token starts * @param len token length */ private void writeToken(final byte[] buffer, final int offset, final int len) { writeNum(len); writeBytes(buffer, offset, len); } /** * Appends a value to the file and return it's offset. * @param value number to be appended */ private void writeNum(final int value) { if(value < 0 || value > 0x3FFFFFFF) { write(0xC0); write(value >>> 24); write(value >>> 16); write(value >>> 8); write(value); } else if(value > 0x3FFF) { write(value >>> 24 | 0x80); write(value >>> 16); write(value >>> 8); write(value); } else if(value > 0x3F) { write(value >>> 8 | 0x40); write(value); } else { write(value); } } /** * Writes the specified block to disk. * @param buffer buffer to write * @throws IOException I/O exception */ private void writeBlock(final Buffer buffer) throws IOException { final long pos = buffer.pos, len = Math.min(IO.BLOCKSIZE, length - pos); raf.seek(pos); raf.write(buffer.data, 0, (int) len); buffer.dirty = false; } /** * Returns a buffer which can be used for writing new bytes. * @return buffer */ private Buffer buffer() { return buffer(off == IO.BLOCKSIZE); } /** * Returns the current or next buffer. * @param next next block * @return buffer */ private Buffer buffer(final boolean next) { if(next) cursor(bm.current().pos + IO.BLOCKSIZE); return bm.current(); } }
package org.waterforpeople.mapping.helper; import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.waterforpeople.mapping.analytics.domain.AccessPointStatusSummary; import org.waterforpeople.mapping.dao.AccessPointDao; import org.waterforpeople.mapping.dao.SurveyAttributeMappingDao; import org.waterforpeople.mapping.dao.SurveyInstanceDAO; import org.waterforpeople.mapping.domain.AccessPoint; import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType; import org.waterforpeople.mapping.domain.AccessPointMappingHistory; import org.waterforpeople.mapping.domain.GeoCoordinates; import org.waterforpeople.mapping.domain.QuestionAnswerStore; import org.waterforpeople.mapping.domain.SurveyAttributeMapping; import com.beoui.geocell.GeocellManager; import com.beoui.geocell.model.Point; import com.gallatinsystems.common.util.StringUtil; import com.gallatinsystems.framework.analytics.summarization.DataSummarizationRequest; import com.gallatinsystems.framework.dao.BaseDAO; import com.gallatinsystems.framework.domain.DataChangeRecord; import com.gallatinsystems.survey.dao.QuestionDao; import com.gallatinsystems.survey.domain.Question; import com.google.appengine.api.labs.taskqueue.Queue; import com.google.appengine.api.labs.taskqueue.QueueFactory; public class AccessPointHelper { private static String photo_url_root; private static final String GEO_TYPE = "GEO"; private static final String PHOTO_TYPE = "IMAGE"; private SurveyAttributeMappingDao mappingDao; static { Properties props = System.getProperties(); photo_url_root = props.getProperty("photo_url_root"); } private static Logger logger = Logger.getLogger(AccessPointHelper.class .getName()); public AccessPointHelper() { mappingDao = new SurveyAttributeMappingDao(); } public AccessPoint getAccessPoint(Long id) { BaseDAO<AccessPoint> apDAO = new BaseDAO<AccessPoint>(AccessPoint.class); return apDAO.getByKey(id); } public void processSurveyInstance(String surveyInstanceId) { // Get the survey and QuestionAnswerStore // Get the surveyDefinition SurveyInstanceDAO sid = new SurveyInstanceDAO(); List<QuestionAnswerStore> questionAnswerList = sid .listQuestionAnswerStore(Long.parseLong(surveyInstanceId), null); Collection<AccessPoint> apList; if (questionAnswerList != null && questionAnswerList.size() > 0) { apList = parseAccessPoint(new Long(questionAnswerList.get(0) .getSurveyId()), questionAnswerList, AccessPoint.AccessPointType.WATER_POINT); if (apList != null) { for (AccessPoint ap : apList) { saveAccessPoint(ap); } } } } private Collection<AccessPoint> parseAccessPoint(Long surveyId, List<QuestionAnswerStore> questionAnswerList, AccessPoint.AccessPointType accessPointType) { Collection<AccessPoint> apList = null; List<SurveyAttributeMapping> mappings = mappingDao .listMappingsBySurvey(surveyId); if (mappings != null) { apList = parseAccessPoint(surveyId, questionAnswerList, mappings); } else { logger.log(Level.SEVERE, "NO mappings for survey " + surveyId); } return apList; } /** * uses the saved mappings for the survey definition to parse values in the * questionAnswerStore into attributes of an AccessPoint object * * TODO: figure out way around known limitation of only having 1 GEO * response per survey * * @param questionAnswerList * @param mappings * @return */ private Collection<AccessPoint> parseAccessPoint(Long surveyId, List<QuestionAnswerStore> questionAnswerList, List<SurveyAttributeMapping> mappings) { HashMap<String, AccessPoint> apMap = new HashMap<String, AccessPoint>(); List<AccessPointMappingHistory> apmhList = new ArrayList<AccessPointMappingHistory>(); List<Question> questionList = new QuestionDao() .listQuestionsBySurvey(surveyId); if (questionAnswerList != null) { for (QuestionAnswerStore qas : questionAnswerList) { SurveyAttributeMapping mapping = getMappingForQuestion( mappings, qas.getQuestionID()); if (mapping != null) { List<String> types = mapping.getApTypes(); if (types == null || types.size() == 0) { // default the list to be access point if nothing is // specified (for backward compatibility) types.add(AccessPointType.WATER_POINT.toString()); } else { if (types.contains(AccessPointType.PUBLIC_INSTITUTION .toString()) && (types.contains(AccessPointType.HEALTH_POSTS .toString()) || types .contains(AccessPointType.SCHOOL .toString()))) { types.remove(AccessPointType.PUBLIC_INSTITUTION .toString()); } } for (String type : types) { AccessPointMappingHistory apmh = new AccessPointMappingHistory(); apmh.setSource(this.getClass().getName()); apmh.setSurveyId(surveyId); apmh.setSurveyInstanceId(qas.getSurveyInstanceId()); apmh.setQuestionId(Long.parseLong(qas.getQuestionID())); apmh.addAccessPointType(type); try { AccessPoint ap = apMap.get(type); if (ap == null) { ap = new AccessPoint(); ap.setPointType(AccessPointType.valueOf(type)); // if(AccessPointType.PUBLIC_INSTITUTION.toString().equals(type)){ // //get the pointType value from the survey to // properly set it apMap.put(type, ap); } ap.setCollectionDate(qas.getCollectionDate()); setAccessPointField(ap, qas, mapping, apmh); } catch (NoSuchFieldException e) { logger.log( Level.SEVERE, "Could not map field to access point: " + mapping.getAttributeName() + ". Check the surveyAttribueMapping for surveyId " + surveyId); } catch (IllegalAccessException e) { logger.log(Level.SEVERE, "Could not set field to access point: " + mapping.getAttributeName() + ". Illegal access."); } for (Question q : questionList) { if (q.getKey().getId() == Long.parseLong(qas .getQuestionID())) { apmh.setQuestionText(q.getText()); break; } } apmhList.add(apmh); } } if (apmhList.size() > 0) { BaseDAO<AccessPointMappingHistory> apmhDao = new BaseDAO<AccessPointMappingHistory>( AccessPointMappingHistory.class); apmhDao.save(apmhList); } } } return apMap.values(); } public static void setAccessPointField(AccessPoint ap, QuestionAnswerStore qas, SurveyAttributeMapping mapping, AccessPointMappingHistory apmh) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { apmh.setResponseAnswerType(qas.getType()); if (GEO_TYPE.equalsIgnoreCase(qas.getType())) { GeoCoordinates geoC = new GeoCoordinates().extractGeoCoordinate(qas .getValue()); ap.setLatitude(geoC.getLatitude()); ap.setLongitude(geoC.getLongitude()); ap.setAltitude(geoC.getAltitude()); apmh.setSurveyResponse(geoC.getLatitude() + "|" + geoC.getLongitude() + "|" + geoC.getAltitude()); apmh.setQuestionAnswerType("GEO"); apmh.setAccessPointValue(ap.getLatitude() + "|" + ap.getLongitude() + "|" + ap.getAltitude()); apmh.setAccessPointField("Latitude,Longitude,Altitude"); } else { apmh.setSurveyResponse(qas.getValue()); // if it's a value or OTHER type Field f = ap.getClass() .getDeclaredField(mapping.getAttributeName()); if (!f.isAccessible()) { f.setAccessible(true); } apmh.setAccessPointField(f.getName()); // TODO: Hack. In the QAS the type is PHOTO, but we were looking for // image this is why we were getting /sdcard I think. if (PHOTO_TYPE.equalsIgnoreCase(qas.getType()) || qas.getType().equals("PHOTO")) { String newURL = null; String[] photoParts = qas.getValue().split("/"); if (qas.getValue().startsWith("/sdcard")) { newURL = photo_url_root + photoParts[2]; } else if (qas.getValue().startsWith("/mnt")) { newURL = photo_url_root + photoParts[3]; } f.set(ap, newURL); apmh.setQuestionAnswerType("PHOTO"); apmh.setAccessPointValue(ap.getPhotoURL()); } else if (mapping.getAttributeName().equals("pointType")) { if (qas.getValue().contains("Health")) { f.set(ap, AccessPointType.HEALTH_POSTS); } else { qas.setValue(qas.getValue().replace(" ", "_")); f.set(ap, AccessPointType.valueOf(qas.getValue() .toUpperCase())); } } else { String stringVal = qas.getValue(); if (stringVal != null && stringVal.trim().length() > 0) { if (f.getType() == String.class) { f.set(ap, qas.getValue()); apmh.setQuestionAnswerType("String"); apmh.setAccessPointValue(f.get(ap).toString()); } else if (f.getType() == AccessPoint.Status.class) { String val = qas.getValue(); f.set(ap, encodeStatus(val, ap.getPointType())); apmh.setQuestionAnswerType("STATUS"); apmh.setAccessPointValue(f.get(ap).toString()); } else if (f.getType() == Double.class) { try { Double val = Double.parseDouble(stringVal.trim()); f.set(ap, val); apmh.setQuestionAnswerType("DOUBLE"); apmh.setAccessPointValue(f.get(ap).toString()); } catch (Exception e) { logger.log(Level.SEVERE, "Could not parse " + stringVal + " as double", e); apmh.setMappingMessage("Could not parse " + stringVal + " as double"); } } else if (f.getType() == Long.class) { try { String temp = stringVal.trim(); if (temp.contains(".")) { temp = temp.substring(0, temp.indexOf(".")); } Long val = Long.parseLong(temp); f.set(ap, val); logger.info("Setting " + f.getName() + " to " + val + " for ap: " + (ap.getKey() != null ? ap.getKey() .getId() : "UNSET")); apmh.setQuestionAnswerType("LONG"); apmh.setAccessPointValue(f.get(ap).toString()); } catch (Exception e) { logger.log(Level.SEVERE, "Could not parse " + stringVal + " as long", e); apmh.setMappingMessage("Could not parse " + stringVal + " as long"); } } else if (f.getType() == Boolean.class) { try { Boolean val = null; if (stringVal.toLowerCase().contains("yes")) { val = true; } else if (stringVal.toLowerCase().contains("no")) { val = false; } else { val = Boolean.parseBoolean(stringVal.trim()); } f.set(ap, val); apmh.setQuestionAnswerType("BOOLEAN"); apmh.setAccessPointValue(f.get(ap).toString()); } catch (Exception e) { logger.log(Level.SEVERE, "Could not parse " + stringVal + " as boolean", e); apmh.setMappingMessage("Could not parse " + stringVal + " as boolean"); } } } } } } /** * reads value of field from AccessPoint via reflection * * @param ap * @param field * @return */ public static String getAccessPointFieldAsString(AccessPoint ap, String field) { try { Field f = ap.getClass().getDeclaredField(field); if (!f.isAccessible()) { f.setAccessible(true); } Object val = f.get(ap); if (val != null) { return val.toString(); } } catch (Exception e) { logger.log(Level.SEVERE, "Could not extract field value: " + field, e); } return null; } private SurveyAttributeMapping getMappingForQuestion( List<SurveyAttributeMapping> mappings, String questionId) { if (mappings != null) { for (SurveyAttributeMapping mapping : mappings) { if (mapping.getSurveyQuestionId().equals(questionId)) { return mapping; } } } return null; } /** * saves an access point and fires off a summarization message * * @param ap * @return */ public AccessPoint saveAccessPoint(AccessPoint ap) { AccessPointDao apDao = new AccessPointDao(); AccessPoint apCurrent = null; if (ap != null) { if (ap.getPointType() != null && ap.getLatitude() != null && ap.getLongitude() != null) { apCurrent = apDao.findAccessPoint(ap.getPointType(), ap.getLatitude(), ap.getLongitude(), ap.getCollectionDate()); if (apCurrent != null) { if (!apCurrent.getKey().equals(ap.getKey())) { ap.setKey(apCurrent.getKey()); } } } if (ap.getKey() != null) { String oldValues = null; if (ap != null && ap.getKey() != null && apCurrent == null) { apCurrent = apDao.getByKey(ap.getKey()); } if (apCurrent != null) { oldValues = formChangeRecordString(apCurrent); if (apCurrent != null) { ap.setKey(apCurrent.getKey()); apCurrent = ap; } // TODO: Hack since the fileUrl keeps getting set to // incorrect value ap = apDao.save(apCurrent); String newValues = formChangeRecordString(ap); if (oldValues != null) { DataChangeRecord change = new DataChangeRecord( AccessPointStatusSummary.class.getName(), "n/a", oldValues, newValues); Queue queue = QueueFactory.getQueue("dataUpdate"); queue.add(url("/app_worker/dataupdate") .param(DataSummarizationRequest.OBJECT_KEY, ap.getKey().getId() + "") .param(DataSummarizationRequest.OBJECT_TYPE, "AccessPointSummaryChange") .param(DataSummarizationRequest.VALUE_KEY, change.packString())); } } } else { if (ap.getGeocells() == null || ap.getGeocells().size() == 0) { if (ap.getLatitude() != null && ap.getLongitude() != null) { ap.setGeocells(GeocellManager .generateGeoCell(new Point(ap.getLatitude(), ap .getLongitude()))); } } ap = apDao.save(ap); Queue summQueue = QueueFactory.getQueue("dataSummarization"); summQueue.add(url("/app_worker/datasummarization").param( "objectKey", ap.getKey().getId() + "").param("type", "AccessPoint")); } } return ap; } private String formChangeRecordString(AccessPoint ap) { String changeString = null; if (ap != null) { changeString = (ap.getCountryCode() != null ? ap.getCountryCode() : "") + "|" + (ap.getCommunityCode() != null ? ap.getCommunityCode() : "") + "|" + (ap.getPointType() != null ? ap.getPointType().toString() : "") + "|" + (ap.getPointStatus() != null ? ap.getPointStatus() .toString() : "") + "|" + StringUtil.getYearString(ap.getCollectionDate()); } return changeString; } public List<AccessPoint> listAccessPoint(String cursorString) { AccessPointDao apDao = new AccessPointDao(); return apDao.list(cursorString); } public static AccessPoint.Status encodeStatus(String statusVal, AccessPoint.AccessPointType pointType) { AccessPoint.Status status = null; statusVal = statusVal.toLowerCase().trim(); if (pointType.equals(AccessPointType.WATER_POINT)) { if ("functioning but with problems".equals(statusVal) || "working but with problems".equals(statusVal)) { status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS; } else if ("broken down system".equals(statusVal) || "broken down".equals(statusVal) || statusVal.contains("broken")) { status = AccessPoint.Status.BROKEN_DOWN; } else if ("no improved system".equals(statusVal) || "not a protected waterpoint".equals(statusVal)) { status = AccessPoint.Status.NO_IMPROVED_SYSTEM; } else if ("functioning and meets government standards" .equals(statusVal) || "working and protected".equals(statusVal)) { status = AccessPoint.Status.FUNCTIONING_HIGH; } else if ("high".equalsIgnoreCase(statusVal) || "functioning".equals(statusVal)) { status = AccessPoint.Status.FUNCTIONING_HIGH; } else if ("ok".equalsIgnoreCase(statusVal)) { status = AccessPoint.Status.FUNCTIONING_OK; } else { status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS; } } else if (pointType.equals(AccessPointType.SANITATION_POINT)) { if ("latrine full".equals(statusVal)) status = AccessPoint.Status.LATRINE_FULL; else if ("Latrine used but technical problems evident" .toLowerCase().trim().equals(statusVal)) status = AccessPoint.Status.LATRINE_USED_TECH_PROBLEMS; else if ("Latrine not being used due to structural/technical problems" .toLowerCase().equals(statusVal)) status = AccessPoint.Status.LATRINE_NOT_USED_TECH_STRUCT_PROBLEMS; else if ("Do not Know".toLowerCase().equals(statusVal)) status = AccessPoint.Status.LATRINE_DO_NOT_KNOW; else if ("Functional".toLowerCase().equals(statusVal)) status = AccessPoint.Status.LATRINE_FUNCTIONAL; } else { if ("functioning but with problems".equals(statusVal)) { status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS; } else if ("broken down system".equals(statusVal)) { status = AccessPoint.Status.BROKEN_DOWN; } else if ("no improved system".equals(statusVal)) status = AccessPoint.Status.NO_IMPROVED_SYSTEM; else if ("functioning and meets government standards" .equals(statusVal)) status = AccessPoint.Status.FUNCTIONING_HIGH; else if ("high".equalsIgnoreCase(statusVal)) { status = AccessPoint.Status.FUNCTIONING_HIGH; } else if ("ok".equalsIgnoreCase(statusVal)) { status = AccessPoint.Status.FUNCTIONING_OK; } else { status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS; } } return status; } private void copyNonKeyValues(AccessPoint source, AccessPoint target) { if (source != null && target != null) { Field[] fields = AccessPoint.class.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { try { if (isCopyable(fields[i].getName())) { fields[i].setAccessible(true); fields[i].set(target, fields[i].get(source)); } } catch (Exception e) { logger.log(Level.SEVERE, "Can't set the field: " + fields[i].getName()); } } } } private boolean isCopyable(String name) { if ("key".equals(name)) { return false; } else if ("serialVersionUID".equals(name)) { return false; } else if ("jdoFieldFlags".equals(name)) { return false; } else if ("jdoPersistenceCapableSuperclass".equals(name)) { return false; } else if ("jdoFieldTypes".equals(name)) { return false; } else if ("jdoFieldNames".equals(name)) { return false; } else if ("jdoInheritedFieldCount".equals(name)) { return false; } return true; } }
package com.nucc.hackwinds; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.text.format.Time; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.Toast; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; public class forecastFragment extends ListFragment { Fetcher fetch; ArrayList<Forecast> forecastValues; ForecastArrayAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Fill the list adapter with a background task forecastValues = new ArrayList<Forecast>(); getDate(); fetch = new Fetcher(); fetch.execute(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View V = inflater.inflate(R.layout.forecast_fragment, container, false); return V; } @Override public void onListItemClick(ListView l, View v, int pos, long id) { super.onListItemClick(l, v, pos, id); Toast.makeText(getActivity(), "Item " + pos + " was clicked", Toast.LENGTH_SHORT).show(); } private void getDate() { // Get the date and set the labels correctly Time now = new Time(); now.setToNow(); String[] days = new String[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; // Set the header text to the date for (int i = 0; i<5; i++) { forecastValues.add(new Forecast(days[(now.weekDay + i) % days.length], "","")); } } private void getForecast() { // Exectute the background task fetch = new Fetcher(); fetch.execute(); } class Fetcher extends AsyncTask<Void, Void, Void> { Document doc; @Override protected Void doInBackground(Void... arg0) { try { doc = Jsoup.connect("http: Elements elements = doc.select("p"); int count = 0; for (int i=0; i<10; i++) { if ((i % 2)==0) { forecastValues.get(count).overview = elements.get(i+1).text(); } else { forecastValues.get(count).detail = elements.get(i+1).text(); count++; } } } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); adapter = new ForecastArrayAdapter(getActivity(), forecastValues); setListAdapter(adapter); } } }
package org.unitime.timetable.action; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessages; import org.hibernate.criterion.Order; import org.unitime.commons.Debug; import org.unitime.commons.User; import org.unitime.commons.web.Web; import org.unitime.commons.web.WebTable; import org.unitime.timetable.ApplicationProperties; import org.unitime.timetable.form.RoomGroupListForm; import org.unitime.timetable.model.Department; import org.unitime.timetable.model.Location; import org.unitime.timetable.model.Roles; import org.unitime.timetable.model.RoomDept; import org.unitime.timetable.model.RoomGroup; import org.unitime.timetable.model.Session; import org.unitime.timetable.model.TimetableManager; import org.unitime.timetable.model.dao.RoomGroupDAO; import org.unitime.timetable.model.dao.TimetableManagerDAO; import org.unitime.timetable.util.Constants; import org.unitime.timetable.util.LookupTables; import org.unitime.timetable.util.PdfEventHandler; import org.unitime.timetable.webutil.PdfWebTable; import com.lowagie.text.Document; import com.lowagie.text.FontFactory; import com.lowagie.text.Paragraph; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; public class RoomGroupListAction extends Action { /** * Method execute * @param mapping * @param form * @param request * @param response * @return ActionForward */ public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { RoomGroupListForm roomGroupListForm = (RoomGroupListForm) form; HttpSession webSession = request.getSession(); if (!Web.isLoggedIn(webSession)) { throw new Exception("Access Denied."); } User user = Web.getUser(webSession); ActionMessages errors = new ActionMessages(); //get deptCode from request - for user with only one department String deptCode = (String)request.getAttribute("deptCode"); if (deptCode != null) { roomGroupListForm.setDeptCodeX(deptCode); } if (webSession.getAttribute(Constants.DEPT_CODE_ATTR_ROOM_NAME) != null && (roomGroupListForm.getDeptCodeX() == null)) { roomGroupListForm.setDeptCodeX(webSession.getAttribute( Constants.DEPT_CODE_ATTR_ROOM_NAME).toString()); } // Set Session Variable if (!roomGroupListForm.getDeptCodeX().equalsIgnoreCase("")) { webSession.setAttribute(Constants.DEPT_CODE_ATTR_ROOM_NAME, roomGroupListForm.getDeptCodeX()); } // Validate input errors = roomGroupListForm.validate(mapping, request); // Validation fails if (errors.size() > 0) { saveErrors(request, errors); return mapping.findForward("showRoomGroupSearch"); } buildGroupTable(request, roomGroupListForm); //set request attribute for department Long sessionId = Session.getCurrentAcadSession(user).getSessionId(); LookupTables.setupDeptsForUser(request, user, sessionId, true); if (user.getRole().equals(Roles.ADMIN_ROLE)) roomGroupListForm.setCanAdd(true); else if (Constants.ALL_OPTION_LABEL.equals(roomGroupListForm.getDeptCodeX())) { roomGroupListForm.setCanAdd(false); String mgrId = (String)user.getAttribute(Constants.TMTBL_MGR_ID_ATTR_NAME); TimetableManager owner = (new TimetableManagerDAO()).get(new Long(mgrId)); for (Iterator i=owner.departmentsForSession(sessionId).iterator();i.hasNext();) { Department d = (Department)i.next(); if (d.isEditableBy(user)) { roomGroupListForm.setCanAdd(true); break; } } } else { roomGroupListForm.setCanAdd(false); String mgrId = (String)user.getAttribute(Constants.TMTBL_MGR_ID_ATTR_NAME); TimetableManager owner = (new TimetableManagerDAO()).get(new Long(mgrId)); for (Iterator i=owner.departmentsForSession(sessionId).iterator();i.hasNext();) { Department d = (Department)i.next(); if (d.getDeptCode().equals(roomGroupListForm.getDeptCodeX()) && d.isEditableBy(user)) { roomGroupListForm.setCanAdd(true); break; } } } if ("Export PDF".equals(request.getParameter("op"))) { buildPdfGroupTable(request, roomGroupListForm); } return mapping.findForward("showRoomGroupList"); } private void buildGroupTable( HttpServletRequest request, RoomGroupListForm roomGroupListForm) throws Exception{ HttpSession webSession = request.getSession(); ArrayList globalRoomGroups = new ArrayList(); Set departmentRoomGroups = new HashSet(); User user = Web.getUser(webSession); Long sessionId = org.unitime.timetable.model.Session.getCurrentAcadSession(user).getSessionId(); String mgrId = (String)user.getAttribute(Constants.TMTBL_MGR_ID_ATTR_NAME); TimetableManagerDAO tdao = new TimetableManagerDAO(); TimetableManager manager = tdao.get(new Long(mgrId)); boolean isAdmin = user.getRole().equals(Roles.ADMIN_ROLE); boolean showAll = false; Set depts = null; if (roomGroupListForm.getDeptCodeX().equalsIgnoreCase("All")) { if (isAdmin) { showAll = true; depts = Department.findAll(sessionId); } else { depts = Department.findAllOwned(sessionId, manager, false); } } else { depts = new HashSet(1); depts.add(Department.findByDeptCode(roomGroupListForm.getDeptCodeX(),sessionId)); } org.hibernate.Session hibSession = null; try { RoomGroupDAO d = new RoomGroupDAO(); hibSession = d.getSession(); List list = hibSession .createCriteria(RoomGroup.class) .addOrder(Order.asc("name")) .list(); for (Iterator iter = list.iterator();iter.hasNext();) { RoomGroup rg = (RoomGroup) iter.next(); if (rg.isGlobal()!=null && rg.isGlobal().booleanValue()) { globalRoomGroups.add(rg); } else { if (rg.getDepartment()==null) continue; if (!rg.getDepartment().getSessionId().equals(sessionId)) continue; if (roomGroupListForm.getDeptCodeX().equalsIgnoreCase("All")) { if (depts.contains(rg.getDepartment()) || isAdmin) { departmentRoomGroups.add(rg); } } else if (rg.getDepartment().getDeptCode().equalsIgnoreCase(roomGroupListForm.getDeptCodeX())) { departmentRoomGroups.add(rg); } } } } catch (Exception e) { Debug.error(e); } WebTable.setOrder(request.getSession(),"roomGroupList.gord",request.getParameter("gord"),1); WebTable.setOrder(request.getSession(),"roomGroupList.mord",request.getParameter("mord"),1); WebTable globalWebTable = new WebTable(5, "Global Room Groups", "roomGroupList.do?gord=%%", new String[] { "Name", "Abbreviation", "Default", "Rooms", "Description" }, new String[] { "left", "left", "middle", "left", "left" }, new boolean[] { true, true, true, true, true} ); WebTable departmentWebTable = new WebTable(5, "Department Room Groups", "roomGroupList.do?mord=%%", new String[] { "Name", "Abbreviation", "Department", "Rooms", "Description" }, new String[] { "left", "left", "left", "left", "left" }, new boolean[] { true, true, true, true, true} ); boolean haveGlobalRoomGroup = false; for (Iterator it = globalRoomGroups.iterator(); it.hasNext();) { RoomGroup rg = (RoomGroup) it.next(); Collection rs = new TreeSet(rg.getRooms()); StringBuffer assignedRoom = new StringBuffer(); boolean haveRooms = false; for (Iterator iter = rs.iterator();iter.hasNext();) { Location r = (Location) iter.next(); if (!sessionId.equals(r.getSession().getUniqueId())) continue; if (!showAll) { boolean skip = true; for (Iterator j=r.getRoomDepts().iterator();j.hasNext();) { RoomDept rd = (RoomDept)j.next(); if (depts.contains(rd.getDepartment())) { skip=false; break; } } if (skip) continue; } if (assignedRoom.length() > 0) assignedRoom.append(", "); assignedRoom.append(r.getLabel().replaceAll(" ","&nbsp;")); haveRooms = true; } if (!isAdmin && !haveRooms) continue; globalWebTable.addLine( (isAdmin?"onClick=\"document.location='roomGroupEdit.do?doit=editRoomGroup&id="+rg.getUniqueId()+ "';\"":null), new String[] { "<A name=\"A"+rg.getUniqueId()+"\"></A>"+ (isAdmin?"":"<font color=gray>")+rg.getName().replaceAll(" ","&nbsp;")+(isAdmin?"":"</font>"), (isAdmin?"":"<font color=gray>")+rg.getAbbv().replaceAll(" ","&nbsp;")+(isAdmin?"":"</font>"), (rg.isDefaultGroup().booleanValue()?"<IMG border='0' title='This group is default group.' alt='Default' align='absmiddle' src='images/tick.gif'>":""), (isAdmin?"":"<font color=gray>")+assignedRoom+(isAdmin?"":"</font>"), (isAdmin?"":"<font color=gray>")+(rg.getDescription() == null ? "" : rg.getDescription()).replaceAll(" ","&nbsp;").replaceAll("\\\n","<BR>")+(isAdmin?"":"</font>") }, new Comparable[] { rg.getName(), rg.getAbbv(), new Integer(rg.isDefaultGroup().booleanValue()?0:1), null, (rg.getDescription() == null ? "" : rg.getDescription()) }); haveGlobalRoomGroup = true; } for (Iterator it = departmentRoomGroups.iterator(); it.hasNext();) { RoomGroup rg = (RoomGroup) it.next(); Collection rs = new TreeSet(rg.getRooms()); Department rgOwningDept = rg.getDepartment(); //boolean isOwner = isAdmin || rgOwningDept.equals(manager); boolean isOwner = isAdmin || manager.getDepartments().contains(rgOwningDept); boolean isEditable = rgOwningDept.isEditableBy(user); String ownerName = "<i>Not defined</i>"; if (rgOwningDept != null) { ownerName = "<span title='"+rgOwningDept.getHtmlTitle()+"'>"+ rgOwningDept.getShortLabel()+ "</span>"; } StringBuffer assignedRoom = new StringBuffer(); StringBuffer availableRoom = new StringBuffer(); for (Iterator iter = rs.iterator();iter.hasNext();) { Location r = (Location) iter.next(); boolean skip = true; for (Iterator j=r.getRoomDepts().iterator();j.hasNext();) { RoomDept rd = (RoomDept)j.next(); if (rg.getDepartment().equals(rd.getDepartment())) { skip=false; break; } } if (skip) continue; if (assignedRoom.length() > 0) assignedRoom.append(", "); assignedRoom.append(r.getLabel().replaceAll(" ","&nbsp;")); } departmentWebTable.addLine( (isEditable?"onClick=\"document.location='roomGroupEdit.do?doit=editRoomGroup&id="+rg.getUniqueId()+ "';\"":null), new String[] { "<A name=\"A"+rg.getUniqueId()+"\"></A>"+ (isOwner?"":"<font color=gray>")+rg.getName().replaceAll(" ","&nbsp;")+(isOwner?"":"</font>"), (isOwner?"":"<font color=gray>")+rg.getAbbv().replaceAll(" ","&nbsp;")+(isOwner?"":"</font>"), (isOwner?"":"<font color=gray>")+ownerName+(isOwner?"":"</font>"), (isOwner?"":"<font color=gray>")+assignedRoom+(isOwner?"":"</font>"), (isOwner?"":"<font color=gray>")+(rg.getDescription() == null ? "" : rg.getDescription()).replaceAll(" ","&nbsp;").replaceAll("\\\n","<BR>")+(isOwner?"":"</font>") }, new Comparable[] { rg.getName(), rg.getAbbv(), ownerName, null, (rg.getDescription() == null ? "" : rg.getDescription()) }); } if (haveGlobalRoomGroup) request.setAttribute("roomGroupsGlobal", globalWebTable.printTable(WebTable.getOrder(request.getSession(),"roomGroupList.gord"))); else request.removeAttribute("roomGroupsGlobal"); if (!departmentRoomGroups.isEmpty()) request.setAttribute("roomGroupsDepartment", departmentWebTable.printTable(WebTable.getOrder(request.getSession(),"roomGroupList.mord"))); else request.removeAttribute("roomGroupsDepartment"); } public static void buildPdfGroupTable(HttpServletRequest request, RoomGroupListForm roomGroupListForm) throws Exception{ FileOutputStream out = null; try { File file = ApplicationProperties.getTempFile("room_groups", "pdf"); out = new FileOutputStream(file); HttpSession webSession = request.getSession(); ArrayList globalRoomGroups = new ArrayList(); Set departmentRoomGroups = new HashSet(); User user = Web.getUser(webSession); Long sessionId = org.unitime.timetable.model.Session.getCurrentAcadSession(user).getSessionId(); String mgrId = (String)user.getAttribute(Constants.TMTBL_MGR_ID_ATTR_NAME); TimetableManagerDAO tdao = new TimetableManagerDAO(); TimetableManager manager = tdao.get(new Long(mgrId)); boolean isAdmin = user.getRole().equals(Roles.ADMIN_ROLE); boolean showAll = false; Set depts = null; if (roomGroupListForm.getDeptCodeX().equalsIgnoreCase("All")) { if (isAdmin) { showAll = true; depts = Department.findAll(sessionId); } else { depts = Department.findAllOwned(sessionId, manager, false); } } else { depts = new HashSet(1); depts.add(Department.findByDeptCode(roomGroupListForm.getDeptCodeX(),sessionId)); } org.hibernate.Session hibSession = null; boolean splitRows = false; try { RoomGroupDAO d = new RoomGroupDAO(); hibSession = d.getSession(); List list = hibSession .createCriteria(RoomGroup.class) .addOrder(Order.asc("name")) .list(); for (Iterator iter = list.iterator();iter.hasNext();) { RoomGroup rg = (RoomGroup) iter.next(); if (rg.isGlobal()!=null && rg.isGlobal().booleanValue()) { globalRoomGroups.add(rg); } else { if (rg.getDepartment()==null) continue; if (!rg.getDepartment().getSessionId().equals(sessionId)) continue; if (roomGroupListForm.getDeptCodeX().equalsIgnoreCase("All")) { if (depts.contains(rg.getDepartment()) || isAdmin) { departmentRoomGroups.add(rg); } } else if (rg.getDepartment().getDeptCode().equalsIgnoreCase(roomGroupListForm.getDeptCodeX())) { departmentRoomGroups.add(rg); } } } } catch (Exception e) { Debug.error(e); } PdfWebTable globalWebTable = new PdfWebTable(5, "Global Room Groups", null, new String[] { "Name", "Abbreviation", "Default ", "Rooms", "Description" }, new String[] { "left", "left", "middle", "left", "left" }, new boolean[] { true, true, true, true, true} ); PdfWebTable departmentWebTable = new PdfWebTable(5, "Department Room Groups", null, new String[] { "Name", "Abbreviation", "Department ", "Rooms", "Description" }, new String[] { "left", "left", "left", "left", "left" }, new boolean[] { true, true, true, true, true} ); boolean haveGlobalRoomGroup = false; for (Iterator it = globalRoomGroups.iterator(); it.hasNext();) { RoomGroup rg = (RoomGroup) it.next(); Collection rs = new TreeSet(rg.getRooms()); StringBuffer assignedRoom = new StringBuffer(); boolean haveRooms = false; int nrRows = 0; for (Iterator iter = rs.iterator();iter.hasNext();) { Location r = (Location) iter.next(); if (!sessionId.equals(r.getSession().getUniqueId())) continue; if (!showAll) { boolean skip = true; for (Iterator j=r.getRoomDepts().iterator();j.hasNext();) { RoomDept rd = (RoomDept)j.next(); if (depts.contains(rd.getDepartment())) { skip=false; break; } } if (skip) continue; } if (assignedRoom.length() > 0) assignedRoom.append(", "); if (PdfWebTable.getWidthOfLastLine(assignedRoom.toString(),false,false)>500) { assignedRoom.append("\n"); nrRows++; } assignedRoom.append(r.getLabel()); haveRooms = true; } if (nrRows>40) splitRows = true; if (!isAdmin && !haveRooms) continue; globalWebTable.addLine( null, new String[] { rg.getName(), rg.getAbbv(), (rg.isDefaultGroup().booleanValue()?"Yes":"No"), assignedRoom.toString(), (rg.getDescription() == null ? "" : rg.getDescription())}, new Comparable[] { rg.getName(), rg.getAbbv(), new Integer(rg.isDefaultGroup().booleanValue()?0:1), null, (rg.getDescription() == null ? "" : rg.getDescription()) }); haveGlobalRoomGroup = true; } for (Iterator it = departmentRoomGroups.iterator(); it.hasNext();) { RoomGroup rg = (RoomGroup) it.next(); Collection rs = new TreeSet(rg.getRooms()); Department rgOwningDept = rg.getDepartment(); //boolean isOwner = isAdmin || rgOwningDept.equals(manager); boolean isOwner = isAdmin || manager.getDepartments().contains(rgOwningDept); boolean isEditable = rgOwningDept.isEditableBy(user); String ownerName = "@@ITALIC Not defined"; if (rgOwningDept != null) { ownerName = rgOwningDept.getShortLabel(); } StringBuffer assignedRoom = new StringBuffer(); StringBuffer availableRoom = new StringBuffer(); for (Iterator iter = rs.iterator();iter.hasNext();) { Location r = (Location) iter.next(); boolean skip = true; for (Iterator j=r.getRoomDepts().iterator();j.hasNext();) { RoomDept rd = (RoomDept)j.next(); if (rg.getDepartment().equals(rd.getDepartment())) { skip=false; break; } } if (skip) continue; if (assignedRoom.length() > 0) assignedRoom.append(", "); if (PdfWebTable.getWidthOfLastLine(assignedRoom.toString(),false,false)>500) assignedRoom.append("\n"); assignedRoom.append(r.getLabel()); } departmentWebTable.addLine( null, new String[] { rg.getName(), rg.getAbbv(), ownerName, assignedRoom.toString(), (rg.getDescription() == null ? "" : rg.getDescription())}, new Comparable[] { rg.getName(), rg.getAbbv(), ownerName, null, (rg.getDescription() == null ? "" : rg.getDescription()) }); } Document doc = null; if (haveGlobalRoomGroup) { PdfWebTable table = globalWebTable; PdfPTable pdfTable = table.printPdfTable(WebTable.getOrder(request.getSession(),"roomGroupList.gord")); pdfTable.setSplitRows(splitRows); if (doc==null) { doc = new Document(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()),30,30,30,30); PdfWriter iWriter = PdfWriter.getInstance(doc, out); iWriter.setPageEvent(new PdfEventHandler()); doc.open(); } else { doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); } doc.add(new Paragraph(table.getName(), FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16))); doc.add(pdfTable); } if (!departmentRoomGroups.isEmpty()) { PdfWebTable table = departmentWebTable; PdfPTable pdfTable = table.printPdfTable(WebTable.getOrder(request.getSession(),"roomGroupList.mord")); if (doc==null) { doc = new Document(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()),30,30,30,30); PdfWriter iWriter = PdfWriter.getInstance(doc, out); iWriter.setPageEvent(new PdfEventHandler()); doc.open(); } else { doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); } doc.add(new Paragraph(table.getName(), FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16))); doc.add(pdfTable); } if (doc==null) return; doc.close(); request.setAttribute(Constants.REQUEST_OPEN_URL, "temp/"+file.getName()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out!=null) out.close(); } catch (IOException e) {} } } }
package com.elmakers.mine.bukkit.block; import java.lang.ref.WeakReference; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.WeakHashMap; import java.util.logging.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.FallingBlock; import org.bukkit.entity.Hanging; import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import org.bukkit.potion.PotionEffectType; import com.elmakers.mine.bukkit.api.action.CastContext; import com.elmakers.mine.bukkit.api.batch.Batch; import com.elmakers.mine.bukkit.api.block.BlockData; import com.elmakers.mine.bukkit.api.block.ModifyType; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.api.magic.MaterialSet; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.batch.UndoBatch; import com.elmakers.mine.bukkit.entity.EntityData; import com.elmakers.mine.bukkit.entity.SpawnedEntity; import com.elmakers.mine.bukkit.materials.MaterialSets; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.DeprecatedUtils; import com.elmakers.mine.bukkit.utility.EntityMetadataUtils; import com.google.common.base.Preconditions; /** * Implements a Collection of Blocks, for quick getting/putting while iterating * over a set or area of blocks. * * <p>This stores BlockData objects, which are hashable via their Persisted * inheritance, and their LocationData id (which itself has a hash function * based on world name and BlockVector's hash function) */ public class UndoList extends BlockList implements com.elmakers.mine.bukkit.api.block.UndoList { public static @Nonnull MaterialSet attachables = MaterialSets.empty(); public static @Nonnull MaterialSet attachablesWall = MaterialSets.empty(); public static @Nonnull MaterialSet attachablesDouble = MaterialSets.empty(); protected static final UndoRegistry registry = new UndoRegistry(); protected static final Map<Entity, com.elmakers.mine.bukkit.api.block.UndoList> watchedEntities = new WeakHashMap<>(); protected static BlockComparator blockComparator = new BlockComparator(); protected Map<Long, BlockData> watching; private Set<String> worlds = new HashSet<>(); private boolean loading = false; protected Deque<Runnable> runnables; protected Map<UUID, SpawnedEntity> spawnedEntities; protected Map<UUID, EntityData> modifiedEntities; protected WeakReference<CastContext> context; protected WeakReference<Mage> owner; protected MageController controller; protected Plugin plugin; protected boolean undone = false; protected boolean finished = false; protected int timeToLive = 0; protected ModifyType modifyType = ModifyType.NO_PHYSICS; protected boolean lockChunks = false; protected boolean bypass = false; protected boolean hasBeenScheduled = false; protected final long createdTime; protected long modifiedTime; protected long scheduledTime; protected double speed = 0; protected WeakReference<Spell> spell; protected WeakReference<Batch> batch; protected UndoQueue undoQueue; // Doubly-linked list protected UndoList next; protected UndoList previous; protected String name; private boolean consumed = false; private boolean undoEntityEffects = true; private Set<EntityType> undoEntityTypes = null; protected boolean undoBreakable = false; protected boolean undoReflective = false; protected boolean sorted = true; protected boolean reverse = true; protected boolean unbreakable = false; public UndoList(Mage mage, String name) { this(mage); this.name = name; } public UndoList(@Nonnull MageController controller) { this.controller = controller; this.plugin = controller.getPlugin(); createdTime = System.currentTimeMillis(); modifiedTime = createdTime; } public UndoList(Mage mage) { setMage(mage); createdTime = System.currentTimeMillis(); modifiedTime = createdTime; } public void setMage(Mage mage) { this.owner = mage == null ? null : new WeakReference<>(mage); if (mage != null) { this.plugin = mage.getController().getPlugin(); this.controller = mage.getController(); } } @Override public void setBatch(Batch batch) { this.batch = batch == null ? null : new WeakReference<>(batch); } @Override public void setSpell(Spell spell) { this.spell = spell == null ? null : new WeakReference<>(spell); this.context = spell == null ? null : new WeakReference<>(spell.getCurrentCast()); } @Override public boolean isEmpty() { return ( (blockList == null || blockList.isEmpty()) && (spawnedEntities == null || spawnedEntities.isEmpty()) && (runnables == null || runnables.isEmpty())); } @Override public void setScheduleUndo(int ttl) { timeToLive = ttl; updateScheduledUndo(); } @Override public void updateScheduledUndo() { if (timeToLive > 0) { scheduledTime = System.currentTimeMillis() + timeToLive; } } @Override public int getScheduledUndo() { return timeToLive; } @Override public boolean hasChanges() { return size() > 0 || (runnables != null && !runnables.isEmpty()) || (spawnedEntities != null && !spawnedEntities.isEmpty()) || (undoEntityEffects && modifiedEntities != null && !modifiedEntities.isEmpty()); } @Override public void clearAttachables(Block block) { clearAttachables(block, BlockFace.NORTH, attachablesWall); clearAttachables(block, BlockFace.SOUTH, attachablesWall); clearAttachables(block, BlockFace.EAST, attachablesWall); clearAttachables(block, BlockFace.WEST, attachablesWall); clearAttachables(block, BlockFace.UP, attachables); clearAttachables(block, BlockFace.DOWN, attachablesDouble); } protected boolean clearAttachables(Block block, BlockFace direction, @Nonnull MaterialSet materials) { Block testBlock = block.getRelative(direction); long blockId = com.elmakers.mine.bukkit.block.BlockData.getBlockId(testBlock); if (!materials.testBlock(testBlock)) { return false; } // Don't clear it if we've already modified it if (blockIdMap != null && blockIdMap.containsKey(blockId)) { return false; } add(testBlock); MaterialAndData.clearItems(testBlock.getState()); DeprecatedUtils.setTypeAndData(testBlock, Material.AIR, (byte)0, false); return true; } @Override public boolean add(BlockData blockData) { if (finished) { controller.getLogger().warning("Trying to add to a finished UndoList, this may result in blocks that don't get cleaned up: " + name); Thread.dumpStack(); } if (bypass) return true; if (!controller.isUndoable(blockData.getMaterial())) { return false; } if (!super.add(blockData)) { return false; } worlds.add(blockData.getWorldName()); modifiedTime = System.currentTimeMillis(); if (watching != null) { BlockData attachedBlock = watching.remove(blockData.getId()); if (attachedBlock != null) { removeFromWatched(attachedBlock); } } register(blockData); blockData.setUndoList(this); if (loading) return true; addAttachable(blockData, BlockFace.NORTH, attachablesWall); addAttachable(blockData, BlockFace.SOUTH, attachablesWall); addAttachable(blockData, BlockFace.EAST, attachablesWall); addAttachable(blockData, BlockFace.WEST, attachablesWall); addAttachable(blockData, BlockFace.UP, attachables); addAttachable(blockData, BlockFace.DOWN, attachablesDouble); return true; } @Override public void add(Entity entity) { if (entity == null) return; if (spawnedEntities == null) spawnedEntities = new HashMap<>(); if (worldName != null && !entity.getWorld().getName().equals(worldName)) return; spawnedEntities.put(entity.getUniqueId(), new SpawnedEntity(entity)); if (this.isScheduled()) { EntityMetadataUtils.instance().setBoolean(entity, "magicspawned", true); } watch(entity); contain(entity.getLocation().toVector()); modifiedTime = System.currentTimeMillis(); } @Override public void add(Runnable runnable) { if (runnable == null) return; if (runnables == null) runnables = new ArrayDeque<>(); runnables.add(runnable); modifiedTime = System.currentTimeMillis(); } protected boolean addAttachable(BlockData block, BlockFace direction, @Nonnull MaterialSet materials) { Preconditions.checkNotNull(block, "block"); Preconditions.checkNotNull(direction, "direction"); Block baseBlock = block.getBlock(); if (baseBlock == null) { // World unloaded. // TODO: Move this check somewhere else? return false; } Block testBlock = baseBlock.getRelative(direction); Long blockId = com.elmakers.mine.bukkit.block.BlockData.getBlockId(testBlock); // This gets called recursively, so don't re-process anything if (blockIdMap != null && blockIdMap.containsKey(blockId)) { return false; } if (watching != null && watching.containsKey(blockId)) { return false; } // This may cause an occasional missed attachment for super large constructions, // but the alternative is either very complicated or very inefficient boolean isDifferentChunk = baseBlock.getX() >> 4 != testBlock.getX() >> 4 || baseBlock.getZ() >> 4 != testBlock.getZ() >> 4; if (isDifferentChunk && !CompatibilityUtils.isChunkLoaded(testBlock.getLocation())) { return false; } if (materials.testBlock(testBlock)) { BlockData newBlock = new com.elmakers.mine.bukkit.block.BlockData(testBlock); if (contain(newBlock)) { registerWatched(newBlock); newBlock.setUndoList(this); if (attachablesDouble.testBlock(testBlock)) { if (direction != BlockFace.UP) { add(newBlock); addAttachable(newBlock, BlockFace.DOWN, materials); } else if (direction != BlockFace.DOWN) { add(newBlock); addAttachable(newBlock, BlockFace.UP, materials); } } return true; } } return false; } public static BlockData register(Block block) { BlockData blockData = new com.elmakers.mine.bukkit.block.BlockData(block); registry.registerModified(blockData); return blockData; } public static void register(BlockData blockData) { registry.registerModified(blockData); } public void registerWatched(BlockData blockData) { registry.registerWatched(blockData); if (watching == null) { watching = new HashMap<>(); } watching.put(blockData.getId(), blockData); } @Override public void commit() { unlink(); unregisterWatched(); if (blockList == null) return; for (BlockData block : blockList) { commit(block); } clear(); } public static void commit(com.elmakers.mine.bukkit.api.block.BlockData block) { registry.commit(block); } public static void commitAll() { registry.commitAll(); } @Override public boolean remove(Object o) { if (o instanceof BlockData) { BlockData block = (BlockData)o; removeFromModified(block); } return super.remove(o); } @Override public void remove(Entity entity) { watchedEntities.remove(entity); UUID entityId = entity.getUniqueId(); if (spawnedEntities != null) { spawnedEntities.remove(entityId); } if (modifiedEntities != null) { modifiedEntities.remove(entityId); } modifiedTime = System.currentTimeMillis(); } protected static void removeFromModified(BlockData block) { registry.removeFromModified(block); } protected static void removeFromModified(BlockData block, BlockData priorState) { registry.removeFromModified(block, priorState); } protected static void removeFromWatched(BlockData block) { registry.removeFromWatched(block); } @Nullable @Override public BlockData undoNext(boolean applyPhysics) { if (blockList.size() == 0) { return null; } BlockData blockData = blockList.removeFirst(); BlockState currentState = blockData.getBlock().getState(); if (undo(blockData, applyPhysics)) { blockIdMap.remove(blockData.getId()); Mage owner = getOwner(); if (consumed && !isScheduled() && currentState.getType() != Material.AIR && owner != null) { owner.giveItem(new ItemStack(currentState.getType(), 1, DeprecatedUtils.getRawData(currentState))); } CastContext context = getContext(); if (context != null && context.hasEffects("undo_block")) { Block block = blockData.getBlock(); if (block.getType() != currentState.getType()) { context.playEffects("undo_block", 1.0f, null, null, block.getLocation(), null, block); } } return blockData; } blockList.addFirst(blockData); return null; } private boolean undo(BlockData undoBlock, boolean applyPhysics) { BlockData priorState = undoBlock.getPriorState(); // Remove any tagged metadata if (undoBreakable) { registry.removeBreakable(undoBlock); } if (undoReflective) { registry.removeReflective(undoBlock); } if (undoBlock.undo(applyPhysics ? ModifyType.NORMAL : modifyType)) { removeFromModified(undoBlock, priorState); // Continue watching this block until we completely finish the undo process registerWatched(undoBlock); Double remainingDamage = registry.removeDamage(undoBlock); if (remainingDamage != null) { if (remainingDamage <= 0) { CompatibilityUtils.clearBreaking(undoBlock.getBlock()); } else { CompatibilityUtils.setBreaking(undoBlock.getBlock(), remainingDamage); } } return true; } return false; } @Override public void undo() { undo(false); } @Override public void undo(boolean blocking) { Spell spell = getSpell(); if (spell != null) { spell.cancel(); } undo(blocking, true); } public void undo(boolean blocking, boolean undoEntities) { if (undone) return; undone = true; Batch batch = getBatch(); if (batch != null && !batch.isFinished()) { batch.finish(); } // This is a hack to make forced-undo happen instantly if (undoEntities) { this.speed = 0; } undoEntityEffects = undoEntityEffects || undoEntities; unlink(); CastContext context = getContext(); if (context != null) { context.cancelEffects(); } if (runnables != null) { for (Runnable runnable : runnables) { runnable.run(); } runnables = null; } if (blockList == null) { undoEntityEffects(); return; } // This will happen again when the batch is finished, but doing it first as well prevents // hanging entities from breaking undoEntityEffects(); // Block changes will be performed in a batch UndoBatch undoBatch = new UndoBatch(this); Mage owner = getOwner(); if (blocking || owner == null) { while (!undoBatch.isFinished()) { undoBatch.process(1000); } } else { owner.addUndoBatch(undoBatch); } } public void undoEntityEffects() { // This part doesn't happen in a batch, and may lag on large lists if (spawnedEntities != null || modifiedEntities != null) { if (spawnedEntities != null) { for (SpawnedEntity entity : spawnedEntities.values()) { entity.despawn(controller, getContext()); } spawnedEntities = null; } if (modifiedEntities != null) { for (EntityData data : modifiedEntities.values()) { Entity entity = data.getEntity(); if (entity != null) { setUndoList(entity, null); } if (!undoEntityEffects && undoEntityTypes != null && !undoEntityTypes.contains(data.getType())) continue; CastContext context = getContext(); if (context != null && entity != null && context.hasEffects("undo_entity")) { context.playEffects("undo_entity", 1.0f, null, null, entity.getLocation(), entity, null); } try { data.undo(); } catch (Exception ex) { if (context != null) { context.getLogger().log(Level.WARNING, "Error restoring entity on undo", ex); } else { ex.printStackTrace(); } } // Check for playing effects on resurrected entities if (entity == null && context != null) { entity = data.getEntity(); if (entity != null && context.hasEffects("undo_entity")) { context.playEffects("undo_entity", 1.0f, null, null, entity.getLocation(), entity, null); } } } modifiedEntities = null; } } } @Override public boolean isUndone() { return undone; } @Override public boolean isUnbreakable() { return unbreakable; } @Override public void setUnbreakable(boolean unbreakable) { this.unbreakable = unbreakable; } @Override public void undoScheduled(boolean blocking) { undo(blocking, false); Mage owner = getOwner(); if (isScheduled() && owner != null) { owner.getController().cancelScheduledUndo(this); } } @Override public void undoScheduled() { undo(false, false); } public void unregisterWatched() { if (watching != null) { for (BlockData block : watching.values()) { removeFromWatched(block); } watching = null; } } public void finish() { finished = true; } @Override public void load(ConfigurationSection node) { loading = true; super.load(node); loading = false; timeToLive = node.getInt("time_to_live", timeToLive); name = node.getString("name", name); String typeName = node.getString("mode", ""); if (!typeName.isEmpty()) { try { modifyType = ModifyType.valueOf(typeName); } catch (Exception ex) { ex.printStackTrace(); } } consumed = node.getBoolean("consumed", consumed); } @Override public void save(ConfigurationSection node) { super.save(node); node.set("time_to_live", timeToLive); node.set("name", name); if (modifyType != ModifyType.NORMAL) { node.set("mode", modifyType.name()); } if (consumed) node.set("consumed", true); } public void watch(Entity entity) { if (entity == null) return; if (worldName != null && !entity.getWorld().getName().equals(worldName)) return; if (worldName == null) worldName = entity.getWorld().getName(); setUndoList(entity, this); modifiedTime = System.currentTimeMillis(); } @Nullable @Override public EntityData modify(Entity entity) { EntityData entityData = null; if (entity == null || EntityMetadataUtils.instance().getBoolean(entity, "notarget")) return entityData; if (worldName != null && !entity.getWorld().getName().equals(worldName)) return entityData; if (worldName == null) worldName = entity.getWorld().getName(); // Check to see if this is something we spawned, and has now been destroyed UUID entityId = entity.getUniqueId(); if (spawnedEntities != null && spawnedEntities.containsKey(entityId) && !entity.isValid()) { spawnedEntities.remove(entityId); } else if (entity.isValid()) { if (modifiedEntities == null) modifiedEntities = new HashMap<>(); entityData = modifiedEntities.get(entityId); if (entityData == null) { entityData = new EntityData(controller, entity); modifiedEntities.put(entityId, entityData); watch(entity); } } modifiedTime = System.currentTimeMillis(); return entityData; } @Nullable @Override public EntityData damage(Entity entity) { EntityData data = modify(entity); // Kind of a hack to prevent dropping hanging entities that we're going to undo later if (undoEntityTypes != null && undoEntityTypes.contains(entity.getType())) { // Hacks upon hacks, this prevents item dupe exploits with shooting items out of item // frames. if (entity instanceof Hanging) { entity.remove(); } } if (data != null) { data.setRespawn(true); data.setDamaged(true); } return data; } @Override public void move(Entity entity) { EntityData entityData = modify(entity); if (entityData != null) { entityData.setHasMoved(true); } } @Override public void modifyVelocity(Entity entity) { EntityData entityData = modify(entity); if (entityData != null) { entityData.setHasVelocity(true); } } @Override public void addPotionEffects(Entity entity) { EntityData entityData = modify(entity); if (entityData != null) { entityData.setHasPotionEffects(true); } } @Override public void addPotionEffectForRemoval(Entity entity, PotionEffectType potionEffectType) { EntityData entityData = modify(entity); if (entityData != null) { entityData.addPotionEffectForRemoval(potionEffectType); } } @Override public void addModifier(Entity entity, com.elmakers.mine.bukkit.api.magic.MageModifier modifier) { EntityData entityData = modify(entity); if (entityData != null) { entityData.addModifier(modifier); } } @Override public void addModifierForRemoval(Entity entity, String modifierKey) { EntityData entityData = modify(entity); if (entityData != null) { entityData.addModifierForRemoval(modifierKey); } } @Override public void convert(Entity fallingBlock, Block block) { remove(fallingBlock); add(block); } @Override public void fall(Entity fallingBlock, Block block) { if (isScheduled() && fallingBlock instanceof FallingBlock) { ((FallingBlock)fallingBlock).setDropItem(false); } add(fallingBlock); add(block); modifiedTime = System.currentTimeMillis(); } @Override public void explode(Entity explodingEntity, List<Block> blocks) { for (Block block : blocks) { add(block); } modifiedTime = System.currentTimeMillis(); } @Override public void finalizeExplosion(Entity explodingEntity, List<Block> blocks) { remove(explodingEntity); // Prevent dropping items if this is going to auto-undo if (isScheduled()) { for (Block block : blocks) { BlockState state = block.getState(); if (state instanceof InventoryHolder) { InventoryHolder holder = (InventoryHolder)state; holder.getInventory().clear(); state.update(); } block.setType(Material.AIR); } } modifiedTime = System.currentTimeMillis(); } @Override public void cancelExplosion(Entity explodingEntity) { // Stop tracking this entity remove(explodingEntity); } @Override public boolean bypass() { return bypass; } @Override public void setBypass(boolean bypass) { this.bypass = bypass; } @Override public boolean isBypass() { return this.bypass; } @Override public long getCreatedTime() { return this.createdTime; } @Override public long getModifiedTime() { return this.modifiedTime; } @Override public boolean contains(Location location, int threshold) { if (location == null || area == null || worldName == null) return false; if (!location.getWorld().getName().equals(worldName)) return false; return area.contains(location.toVector(), threshold); } @Override public void prune() { if (blockList == null) return; Iterator<BlockData> iterator = iterator(); while (iterator.hasNext()) { BlockData block = iterator.next(); if (!block.isDifferent()) { removeFromMap(block); iterator.remove(); } } modifiedTime = System.currentTimeMillis(); } @Override public String getName() { return name; } @Nullable public Spell getSpell() { return spell == null ? null : spell.get(); } @Nullable public Batch getBatch() { return batch == null ? null : batch.get(); } @Override @Nullable public Mage getOwner() { return owner == null ? null : owner.get(); } public MageController getController() { return controller; } @Nullable @Override public CastContext getContext() { return context == null ? null : context.get(); } @Override public long getScheduledTime() { return scheduledTime; } @Override public boolean isScheduled() { return timeToLive > 0; } @Override public int compareTo(com.elmakers.mine.bukkit.api.block.UndoList o) { return Long.compare(scheduledTime, o.getScheduledTime()); } @Override public boolean hasBeenScheduled() { return hasBeenScheduled; } @Override public void setHasBeenScheduled() { hasBeenScheduled = true; } @Override public void setEntityUndo(boolean undoEntityEffects) { this.undoEntityEffects = undoEntityEffects; } @Override public void setSorted(boolean sorted) { this.sorted = sorted; } @Override public void setReversed(boolean reverse) { this.reverse = reverse; } @Override public void setEntityUndoTypes(Set<EntityType> undoTypes) { this.undoEntityTypes = undoTypes; } public void setNext(UndoList next) { this.next = next; } public void setPrevious(UndoList previous) { this.previous = previous; } public void setUndoQueue(com.elmakers.mine.bukkit.api.block.UndoQueue undoQueue) { if (undoQueue != null && undoQueue instanceof UndoQueue) { this.undoQueue = (UndoQueue)undoQueue; } } public boolean hasUndoQueue() { return this.undoQueue != null; } public void unlink() { if (undoQueue != null) { undoQueue.removed(this); undoQueue = null; } if (this.next != null) { this.next.previous = previous; } if (this.previous != null) { this.previous.next = next; } this.previous = null; this.next = null; } public UndoList getNext() { return next; } public UndoList getPrevious() { return previous; } @Override public void setApplyPhysics(boolean applyPhysics) { if (applyPhysics) { this.modifyType = ModifyType.NORMAL; } else if (this.modifyType != ModifyType.FAST) { this.modifyType = ModifyType.NO_PHYSICS; } } @Override public boolean getApplyPhysics() { return modifyType == ModifyType.NORMAL; } @Override public void setLockChunks(boolean lockChunks) { this.lockChunks = lockChunks; } public boolean getLockChunks() { return lockChunks; } @Override public void setModifyType(ModifyType modifyType) { this.modifyType = modifyType; } @Override public ModifyType getModifyType() { return modifyType; } @Nullable public static com.elmakers.mine.bukkit.api.block.UndoList getUndoList(Entity entity) { com.elmakers.mine.bukkit.api.block.UndoList blockList = entity != null ? watchedEntities.get(entity) : null; if (entity != null && blockList == null && entity instanceof FallingBlock) { // Falling blocks need to check their location to handle chain reaction effects Location entityLocation = entity.getLocation(); blockList = getUndoList(entityLocation); if (blockList == null) { // Check one block down as well, in case a spell removed the block underneath a falling block entityLocation.setY(entityLocation.getY() - 1); blockList = getUndoList(entityLocation); } } return blockList; } @Nullable public static com.elmakers.mine.bukkit.api.block.UndoList getUndoList(Location location) { BlockData blockData = getBlockData(location); return blockData == null ? null : blockData.getUndoList(); } public static void setUndoList(Entity entity, com.elmakers.mine.bukkit.api.block.UndoList list) { if (entity != null) { if (list != null) { watchedEntities.put(entity, list); } else { watchedEntities.remove(entity); } } } @Override public EntityData getEntityData(Entity entity) { return modifiedEntities.get(entity.getUniqueId()); } @Nullable public static BlockData getBlockData(Location location) { return registry.getBlockData(location); } public static UndoRegistry getRegistry() { return registry; } @Override public void setUndoBreakable(boolean breakable) { this.undoBreakable = breakable; } @Override public void setUndoReflective(boolean reflective) { this.undoReflective = reflective; } @Override @Deprecated public void setUndoBreaking(boolean breaking) { } @Override public void addDamage(Block block, double damage) { BlockData blockData = get(block); if (blockData != null) { blockData.addDamage(damage); } } @Override public void registerFakeBlock(Block block, Collection<WeakReference<Player>> players) { if (contains(block)) return; BlockData blockData = get(block); if (blockData != null) { blockData.setFake(players); } } @Override public Collection<Entity> getAllEntities() { ArrayList<Entity> entities = new ArrayList<>(); if (this.spawnedEntities != null) { for (SpawnedEntity spawnedEntity : this.spawnedEntities.values()) { Entity entity = spawnedEntity.getEntity(); if (entity != null) { entities.add(entity); } } } if (this.modifiedEntities != null) { for (EntityData entityData : this.modifiedEntities.values()) { Entity entity = entityData.getEntity(); if (entity != null) { entities.add(entity); } } } return entities; } public void sort(MaterialSet attachables) { if (blockList == null) return; List<BlockData> sortedList = new ArrayList<>(blockList); blockList.clear(); if (reverse) { Collections.reverse(sortedList); } if (attachables != null && sorted) { blockComparator.setAttachables(attachables); Collections.sort(sortedList, blockComparator); } blockList.addAll(sortedList); } public double getUndoSpeed() { return speed; } @Override public void setUndoSpeed(double speed) { this.speed = speed; } @Override public boolean isConsumed() { return consumed; } @Override public void setConsumed(boolean consumed) { this.consumed = consumed; } public void removeFromMap(BlockData blockData) { removeFromModified(blockData); blockIdMap.remove(blockData.getId()); } @Override public int getRunnableCount() { return runnables == null ? 0 : runnables.size(); } @Nullable @Override public Runnable undoNextRunnable() { Runnable undone = null; if (runnables != null && !runnables.isEmpty()) { undone = runnables.pop(); undone.run(); } return undone; } @Override public boolean isUndoType(EntityType entityType) { return undoEntityTypes != null && undoEntityTypes.contains(entityType); } @Override public boolean affectsWorld(@Nonnull World world) { Preconditions.checkNotNull(world); return worlds.contains(world.getName()); } }
package com.elmakers.mine.bukkit.block; import java.lang.ref.WeakReference; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.FallingBlock; import org.bukkit.entity.Hanging; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; import com.elmakers.mine.bukkit.api.action.CastContext; import com.elmakers.mine.bukkit.api.batch.Batch; import com.elmakers.mine.bukkit.api.block.BlockData; import com.elmakers.mine.bukkit.api.block.ModifyType; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.api.magic.MaterialSet; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.batch.UndoBatch; import com.elmakers.mine.bukkit.entity.EntityData; import com.elmakers.mine.bukkit.magic.MaterialSets; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.DeprecatedUtils; import com.google.common.base.Preconditions; /** * Implements a Collection of Blocks, for quick getting/putting while iterating * over a set or area of blocks. * * <p>This stores BlockData objects, which are hashable via their Persisted * inheritance, and their LocationData id (which itself has a hash function * based on world name and BlockVector's hash function) */ public class UndoList extends BlockList implements com.elmakers.mine.bukkit.api.block.UndoList { public static @Nonnull MaterialSet attachables = MaterialSets.empty(); public static @Nonnull MaterialSet attachablesWall = MaterialSets.empty(); public static @Nonnull MaterialSet attachablesDouble = MaterialSets.empty(); protected static final UndoRegistry registry = new UndoRegistry(); protected static BlockComparator blockComparator = new BlockComparator(); protected Map<Long, BlockData> watching; private Set<String> worlds = new HashSet<>(); private boolean loading = false; protected Set<Entity> entities; protected Deque<Runnable> runnables; protected HashMap<UUID, EntityData> modifiedEntities; protected WeakReference<CastContext> context; protected Mage owner; protected Plugin plugin; protected boolean undone = false; protected boolean finished = false; protected int timeToLive = 0; protected ModifyType modifyType = ModifyType.NO_PHYSICS; protected boolean bypass = false; protected boolean hasBeenScheduled = false; protected final long createdTime; protected long modifiedTime; protected long scheduledTime; protected double speed = 0; protected Spell spell; protected Batch batch; protected UndoQueue undoQueue; // Doubly-linked list protected UndoList next; protected UndoList previous; protected String name; private boolean consumed = false; private boolean undoEntityEffects = true; private Set<EntityType> undoEntityTypes = null; protected boolean undoBreakable = false; protected boolean undoReflective = false; protected boolean undoBreaking = false; protected boolean sorted = true; public UndoList(Mage mage, String name) { this(mage); this.name = name; } public UndoList(@Nonnull MageController controller) { this.plugin = controller.getPlugin(); createdTime = System.currentTimeMillis(); modifiedTime = createdTime; } public UndoList(Mage mage) { setMage(mage); createdTime = System.currentTimeMillis(); modifiedTime = createdTime; } public void setMage(Mage mage) { this.owner = mage; if (mage != null) { this.plugin = mage.getController().getPlugin(); } } @Override public void setBatch(Batch batch) { this.batch = batch; } @Override public void setSpell(Spell spell) { this.spell = spell; this.context = spell == null ? null : new WeakReference<>(spell.getCurrentCast()); } @Override public boolean isEmpty() { return ( (blockList == null || blockList.isEmpty()) && (entities == null || entities.isEmpty()) && (runnables == null || runnables.isEmpty())); } @Override public void setScheduleUndo(int ttl) { timeToLive = ttl; updateScheduledUndo(); } @Override public void updateScheduledUndo() { if (timeToLive > 0) { scheduledTime = System.currentTimeMillis() + timeToLive; } } @Override public int getScheduledUndo() { return timeToLive; } @Override public boolean hasChanges() { return size() > 0 || (runnables != null && !runnables.isEmpty()) || (entities != null && !entities.isEmpty()) || (undoEntityEffects && modifiedEntities != null && !modifiedEntities.isEmpty()); } @Override public void clearAttachables(Block block) { clearAttachables(block, BlockFace.NORTH, attachablesWall); clearAttachables(block, BlockFace.SOUTH, attachablesWall); clearAttachables(block, BlockFace.EAST, attachablesWall); clearAttachables(block, BlockFace.WEST, attachablesWall); clearAttachables(block, BlockFace.UP, attachables); clearAttachables(block, BlockFace.DOWN, attachablesDouble); } protected boolean clearAttachables(Block block, BlockFace direction, @Nonnull MaterialSet materials) { Block testBlock = block.getRelative(direction); long blockId = com.elmakers.mine.bukkit.block.BlockData.getBlockId(testBlock); if (!materials.testBlock(testBlock)) { return false; } // Don't clear it if we've already modified it if (blockIdMap != null && blockIdMap.contains(blockId)) { return false; } add(testBlock); MaterialAndData.clearItems(testBlock.getState()); DeprecatedUtils.setTypeAndData(testBlock, Material.AIR, (byte)0, false); return true; } @Override public boolean add(BlockData blockData) { if (finished && spell != null) { spell.getController().getLogger().warning("Trying to add to a finished UndoList, this may result in blocks that don't get cleaned up: " + name); Thread.dumpStack(); } if (bypass) return true; if (!super.add(blockData)) { return false; } worlds.add(blockData.getWorldName()); modifiedTime = System.currentTimeMillis(); if (watching != null) { BlockData attachedBlock = watching.remove(blockData.getId()); if (attachedBlock != null) { removeFromWatched(attachedBlock); } } register(blockData); blockData.setUndoList(this); if (loading) return true; addAttachable(blockData, BlockFace.NORTH, attachablesWall); addAttachable(blockData, BlockFace.SOUTH, attachablesWall); addAttachable(blockData, BlockFace.EAST, attachablesWall); addAttachable(blockData, BlockFace.WEST, attachablesWall); addAttachable(blockData, BlockFace.UP, attachables); addAttachable(blockData, BlockFace.DOWN, attachablesDouble); return true; } @Override public void add(Entity entity) { if (entity == null) return; if (entities == null) entities = new HashSet<>(); if (worldName != null && !entity.getWorld().getName().equals(worldName)) return; entities.add(entity); if (this.isScheduled()) { entity.setMetadata("temporary", new FixedMetadataValue(plugin, true)); } watch(entity); contain(entity.getLocation().toVector()); modifiedTime = System.currentTimeMillis(); } @Override public void add(Runnable runnable) { if (runnable == null) return; if (runnables == null) runnables = new ArrayDeque<>(); runnables.add(runnable); modifiedTime = System.currentTimeMillis(); } protected boolean addAttachable(BlockData block, BlockFace direction, @Nonnull MaterialSet materials) { Block testBlock = block.getBlock().getRelative(direction); Long blockId = com.elmakers.mine.bukkit.block.BlockData.getBlockId(testBlock); // This gets called recursively, so don't re-process anything if (blockIdMap != null && blockIdMap.contains(blockId)) { return false; } if (watching != null && watching.containsKey(blockId)) { return false; } if (materials.testBlock(testBlock)) { BlockData newBlock = new com.elmakers.mine.bukkit.block.BlockData(testBlock); if (contain(newBlock)) { registerWatched(newBlock); newBlock.setUndoList(this); if (attachablesDouble.testBlock(testBlock)) { if (direction != BlockFace.UP) { add(newBlock); addAttachable(newBlock, BlockFace.DOWN, materials); } else if (direction != BlockFace.DOWN) { add(newBlock); addAttachable(newBlock, BlockFace.UP, materials); } } return true; } } return false; } public static BlockData register(Block block) { BlockData blockData = new com.elmakers.mine.bukkit.block.BlockData(block); registry.registerModified(blockData); return blockData; } public static void register(BlockData blockData) { registry.registerModified(blockData); } public void registerWatched(BlockData blockData) { registry.registerWatched(blockData); if (watching == null) { watching = new HashMap<>(); } watching.put(blockData.getId(), blockData); } @Override public void commit() { unlink(); unregisterWatched(); if (blockList == null) return; for (BlockData block : blockList) { commit(block); } clear(); } public static void commit(com.elmakers.mine.bukkit.api.block.BlockData block) { registry.commit(block); } public static void commitAll() { registry.commitAll(); } @Override public boolean remove(Object o) { if (o instanceof BlockData) { BlockData block = (BlockData)o; removeFromModified(block); } return super.remove(o); } @Override public void remove(Entity entity) { entity.removeMetadata("MagicBlockList", plugin); if (entities != null) { entities.remove(entity); } UUID entityId = entity.getUniqueId(); if (modifiedEntities != null) { modifiedEntities.remove(entityId); } modifiedTime = System.currentTimeMillis(); } protected static void removeFromModified(BlockData block) { registry.removeFromModified(block); } protected static void removeFromModified(BlockData block, BlockData priorState) { registry.removeFromModified(block, priorState); } protected static void removeFromWatched(BlockData block) { registry.removeFromWatched(block); } @Nullable @Override public BlockData undoNext(boolean applyPhysics) { if (blockList.size() == 0) { return null; } BlockData blockData = blockList.removeFirst(); BlockState currentState = blockData.getBlock().getState(); if (undo(blockData, applyPhysics)) { blockIdMap.remove(blockData.getId()); if (consumed && !isScheduled() && currentState.getType() != Material.AIR && owner != null) { owner.giveItem(new ItemStack(currentState.getType(), 1, DeprecatedUtils.getRawData(currentState))); } CastContext context = getContext(); if (context != null && context.hasEffects("undo_block")) { Block block = blockData.getBlock(); if (block.getType() != currentState.getType()) { context.playEffects("undo_block", 1.0f, null, null, block.getLocation(), null, block); } } return blockData; } blockList.addFirst(blockData); return null; } private boolean undo(BlockData undoBlock, boolean applyPhysics) { BlockData priorState = undoBlock.getPriorState(); // Remove any tagged metadata if (undoBreakable) { registry.removeBreakable(undoBlock); } if (undoReflective) { registry.removeReflective(undoBlock); } boolean isTopOfQueue = undoBlock.getNextState() == null; if (undoBlock.undo(applyPhysics ? ModifyType.NORMAL : modifyType)) { removeFromModified(undoBlock, priorState); // Continue watching this block until we completely finish the undo process registerWatched(undoBlock); // Undo breaking state only if this was the top of the queue if (undoBreaking && isTopOfQueue) { // This may have been unregistered already, if the block was broken for instance. if (registry.removeBreaking(undoBlock) != null) { CompatibilityUtils.clearBreaking(undoBlock.getBlock()); } } return true; } return false; } @Override public void undo() { undo(false); } @Override public void undo(boolean blocking) { if (spell != null) { spell.cancel(); } undo(blocking, true); } public void undo(boolean blocking, boolean undoEntities) { if (undone) return; undone = true; if (batch != null && !batch.isFinished()) { batch.finish(); } // This is a hack to make forced-undo happen instantly if (undoEntities) { this.speed = 0; } undoEntityEffects = undoEntityEffects || undoEntities; unlink(); CastContext context = getContext(); if (context != null) { context.cancelEffects(); } if (runnables != null) { for (Runnable runnable : runnables) { runnable.run(); } runnables = null; } if (blockList == null) { undoEntityEffects(); return; } // Block changes will be performed in a batch UndoBatch batch = new UndoBatch(this); if (blocking) { while (!batch.isFinished()) { batch.process(1000); } } else { owner.addUndoBatch(batch); } } public void undoEntityEffects() { // This part doesn't happen in a batch, and may lag on large lists if (entities != null || modifiedEntities != null) { if (entities != null) { for (Entity entity : entities) { if (entity != null) { if (!entity.isValid()) { if (!entity.getLocation().getChunk().isLoaded()) { entity.getLocation().getChunk().load(); } entity = CompatibilityUtils.getEntity(entity.getWorld(), entity.getUniqueId()); } if (entity != null && entity.isValid()) { CastContext context = getContext(); if (context != null && context.hasEffects("undo_entity")) { context.playEffects("undo_entity", 1.0f, null, null, entity.getLocation(), entity, null); } setUndoList(plugin, entity, null); entity.remove(); } } } entities = null; } if (modifiedEntities != null) { for (EntityData data : modifiedEntities.values()) { Entity entity = data.getEntity(); if (entity != null) { setUndoList(plugin, entity, null); } if (!undoEntityEffects && undoEntityTypes != null && !undoEntityTypes.contains(data.getType())) continue; CastContext context = getContext(); if (context != null && entity != null && context.hasEffects("undo_entity")) { context.playEffects("undo_entity", 1.0f, null, null, entity.getLocation(), entity, null); } data.undo(); // Check for playing effects on resurrected entities if (entity == null && context != null) { entity = data.getEntity(); if (entity != null && context.hasEffects("undo_entity")) { context.playEffects("undo_entity", 1.0f, null, null, entity.getLocation(), entity, null); } } } modifiedEntities = null; } } } @Override public boolean isUndone() { return undone; } @Override public void undoScheduled(boolean blocking) { undo(blocking, false); if (isScheduled()) { owner.getController().cancelScheduledUndo(this); } } @Override public void undoScheduled() { undo(false, false); } public void unregisterWatched() { if (watching != null) { for (BlockData block : watching.values()) { removeFromWatched(block); } watching = null; } } public void finish() { finished = true; } @Override public void load(ConfigurationSection node) { loading = true; super.load(node); loading = false; timeToLive = node.getInt("time_to_live", timeToLive); name = node.getString("name", name); String typeName = node.getString("mode", ""); if (!typeName.isEmpty()) { try { modifyType = ModifyType.valueOf(typeName); } catch (Exception ex) { ex.printStackTrace(); } } consumed = node.getBoolean("consumed", consumed); } @Override public void save(ConfigurationSection node) { super.save(node); node.set("time_to_live", timeToLive); node.set("name", name); if (modifyType != ModifyType.NORMAL) { node.set("mode", modifyType.name()); } if (consumed) node.set("consumed", true); } public void watch(Entity entity) { if (entity == null) return; if (worldName != null && !entity.getWorld().getName().equals(worldName)) return; if (worldName == null) worldName = entity.getWorld().getName(); if (!entity.hasMetadata("MagicBlockList")) { setUndoList(plugin, entity, this); } modifiedTime = System.currentTimeMillis(); } @Nullable @Override public EntityData modify(Entity entity) { EntityData entityData = null; if (entity == null || entity.hasMetadata("notarget")) return entityData; if (worldName != null && !entity.getWorld().getName().equals(worldName)) return entityData; if (worldName == null) worldName = entity.getWorld().getName(); // Check to see if this is something we spawned, and has now been destroyed if (entities != null && entities.contains(entity) && !entity.isValid()) { entities.remove(entity); } else if (entity.isValid()) { if (modifiedEntities == null) modifiedEntities = new HashMap<>(); UUID entityId = entity.getUniqueId(); entityData = modifiedEntities.get(entityId); if (entityData == null) { entityData = new EntityData(entity); modifiedEntities.put(entityId, entityData); watch(entity); } } modifiedTime = System.currentTimeMillis(); return entityData; } @Nullable @Override public EntityData damage(Entity entity) { EntityData data = modify(entity); // Kind of a hack to prevent dropping hanging entities that we're going to undo later if (undoEntityTypes != null && undoEntityTypes.contains(entity.getType())) { // Hacks upon hacks, this prevents item dupe exploits with shooting items out of item // frames. if (entity instanceof Hanging) { entity.remove(); } } if (data != null) { data.setRespawn(true); data.setDamaged(true); } return data; } @Override public void move(Entity entity) { EntityData entityData = modify(entity); if (entityData != null) { entityData.setHasMoved(true); } } @Override public void modifyVelocity(Entity entity) { EntityData entityData = modify(entity); if (entityData != null) { entityData.setHasVelocity(true); } } @Override public void addPotionEffects(Entity entity) { EntityData entityData = modify(entity); if (entityData != null) { entityData.setHasPotionEffects(true); } } @Override public void convert(Entity fallingBlock, Block block) { remove(fallingBlock); add(block); } @Override public void fall(Entity fallingBlock, Block block) { if (isScheduled() && fallingBlock instanceof FallingBlock) { ((FallingBlock)fallingBlock).setDropItem(false); } add(fallingBlock); add(block); modifiedTime = System.currentTimeMillis(); } @Override public void explode(Entity explodingEntity, List<Block> blocks) { for (Block block : blocks) { add(block); } modifiedTime = System.currentTimeMillis(); } @Override public void finalizeExplosion(Entity explodingEntity, List<Block> blocks) { remove(explodingEntity); // Prevent dropping items if this is going to auto-undo if (isScheduled()) { for (Block block : blocks) { BlockState state = block.getState(); if (state instanceof InventoryHolder) { InventoryHolder holder = (InventoryHolder)state; holder.getInventory().clear(); state.update(); } block.setType(Material.AIR); } } modifiedTime = System.currentTimeMillis(); } @Override public void cancelExplosion(Entity explodingEntity) { // Stop tracking this entity remove(explodingEntity); } @Override public boolean bypass() { return bypass; } @Override public void setBypass(boolean bypass) { this.bypass = bypass; } @Override public long getCreatedTime() { return this.createdTime; } @Override public long getModifiedTime() { return this.modifiedTime; } @Override public boolean contains(Location location, int threshold) { if (location == null || area == null || worldName == null) return false; if (!location.getWorld().getName().equals(worldName)) return false; return area.contains(location.toVector(), threshold); } @Override public void prune() { if (blockList == null) return; Iterator<BlockData> iterator = iterator(); while (iterator.hasNext()) { BlockData block = iterator.next(); if (!block.isDifferent()) { removeFromMap(block); iterator.remove(); } } modifiedTime = System.currentTimeMillis(); } @Override public String getName() { return name; } public Spell getSpell() { return spell; } @Override public Mage getOwner() { return owner; } @Nullable @Override public CastContext getContext() { return context == null ? null : context.get(); } @Override public long getScheduledTime() { return scheduledTime; } @Override public boolean isScheduled() { return timeToLive > 0; } @Override public int compareTo(com.elmakers.mine.bukkit.api.block.UndoList o) { return Long.compare(scheduledTime, o.getScheduledTime()); } @Override public boolean hasBeenScheduled() { return hasBeenScheduled; } @Override public void setHasBeenScheduled() { hasBeenScheduled = true; } @Override public void setEntityUndo(boolean undoEntityEffects) { this.undoEntityEffects = undoEntityEffects; } @Override public void setSorted(boolean sorted) { this.sorted = sorted; } @Override public void setEntityUndoTypes(Set<EntityType> undoTypes) { this.undoEntityTypes = undoTypes; } public void setNext(UndoList next) { this.next = next; } public void setPrevious(UndoList previous) { this.previous = previous; } public void setUndoQueue(com.elmakers.mine.bukkit.api.block.UndoQueue undoQueue) { if (undoQueue != null && undoQueue instanceof UndoQueue) { this.undoQueue = (UndoQueue)undoQueue; } } public boolean hasUndoQueue() { return this.undoQueue != null; } public void unlink() { if (undoQueue != null) { undoQueue.removed(this); undoQueue = null; } if (this.next != null) { this.next.previous = previous; } if (this.previous != null) { this.previous.next = next; } this.previous = null; this.next = null; } public UndoList getNext() { return next; } public UndoList getPrevious() { return previous; } @Override public void setApplyPhysics(boolean applyPhysics) { if (applyPhysics) { this.modifyType = ModifyType.NORMAL; } else if (this.modifyType != ModifyType.FAST) { this.modifyType = ModifyType.NO_PHYSICS; } } @Override public boolean getApplyPhysics() { return modifyType == ModifyType.NORMAL; } @Override public void setModifyType(ModifyType modifyType) { this.modifyType = modifyType; } @Override public ModifyType getModifyType() { return modifyType; } @Nullable public static com.elmakers.mine.bukkit.api.block.UndoList getUndoList(Entity entity) { com.elmakers.mine.bukkit.api.block.UndoList blockList = null; if (entity != null && entity.hasMetadata("MagicBlockList")) { List<MetadataValue> values = entity.getMetadata("MagicBlockList"); for (MetadataValue metadataValue : values) { Object value = metadataValue.value(); if (value instanceof com.elmakers.mine.bukkit.api.block.UndoList) { blockList = (com.elmakers.mine.bukkit.api.block.UndoList)value; } } } else if (entity != null && entity instanceof FallingBlock) { // Falling blocks need to check their location to handle chain reaction effects Location entityLocation = entity.getLocation(); blockList = getUndoList(entityLocation); if (blockList == null) { // Check one block down as well, in case a spell removed the block underneath a falling block entityLocation.setY(entityLocation.getY() - 1); blockList = getUndoList(entityLocation); } } return blockList; } @Nullable public static com.elmakers.mine.bukkit.api.block.UndoList getUndoList(Location location) { BlockData blockData = getBlockData(location); return blockData == null ? null : blockData.getUndoList(); } public static void setUndoList(Plugin plugin, Entity entity, com.elmakers.mine.bukkit.api.block.UndoList list) { if (entity != null) { if (list != null) { entity.setMetadata("MagicBlockList", new FixedMetadataValue(plugin, list)); } else { entity.removeMetadata("MagicBlockList", plugin); } } } @Override public EntityData getEntityData(Entity entity) { return modifiedEntities.get(entity.getUniqueId()); } @Nullable public static BlockData getBlockData(Location location) { return registry.getBlockData(location); } public static UndoRegistry getRegistry() { return registry; } @Override public void setUndoBreakable(boolean breakable) { this.undoBreakable = breakable; } @Override public void setUndoReflective(boolean reflective) { this.undoReflective = reflective; } @Override public void setUndoBreaking(boolean breaking) { this.undoBreaking = breaking; } @Override public Collection<Entity> getAllEntities() { ArrayList<Entity> entities = new ArrayList<>(); if (this.entities != null) { for (Entity entity : this.entities) { if (entity != null) { entities.add(entity); } } } if (this.modifiedEntities != null) { for (EntityData entityData : this.modifiedEntities.values()) { Entity entity = entityData.getEntity(); if (entity != null) { entities.add(entity); } } } return entities; } public void sort(MaterialSet attachables) { if (blockList == null) return; List<BlockData> sortedList = new ArrayList<>(blockList); blockList.clear(); Collections.reverse(sortedList); if (attachables != null && sorted) { blockComparator.setAttachables(attachables); Collections.sort(sortedList, blockComparator); } blockList.addAll(sortedList); } public double getUndoSpeed() { return speed; } @Override public void setUndoSpeed(double speed) { this.speed = speed; } @Override public boolean isConsumed() { return consumed; } @Override public void setConsumed(boolean consumed) { this.consumed = consumed; } public void removeFromMap(BlockData blockData) { removeFromModified(blockData); blockIdMap.remove(blockData.getId()); } @Override public int getRunnableCount() { return runnables == null ? 0 : runnables.size(); } @Nullable @Override public Runnable undoNextRunnable() { Runnable undone = null; if (runnables != null && !runnables.isEmpty()) { undone = runnables.pop(); undone.run(); } return undone; } @Override public boolean isUndoType(EntityType entityType) { return undoEntityTypes != null && undoEntityTypes.contains(entityType); } @Override public boolean affectsWorld(@Nonnull World world) { Preconditions.checkNotNull(world); return worlds.contains(world.getName()); } }
package ch.openech.mj.edit; import ch.openech.mj.page.PageAction; public class EditorPageAction extends PageAction { public EditorPageAction(Class<? extends Editor<?>> editorClass, String... args) { super(EditorPage.class, getBaseName(editorClass), arguments(editorClass, args)); } private static String[] arguments(Class<? extends Editor<?>> editor, String... args) { // TODO Elegantere Kopiererei der Argument in EditorPageAction String[] strings = new String[args.length + 1]; strings[0] = editor.getName(); for (int i = 0; i<args.length; i++) { strings[i+1] = args[i]; } return strings; } private static String getBaseName(Class<? extends Editor<?>> editorClass) { return editorClass.getSimpleName(); } }
package org.osmdroid.mtp.util; import org.osmdroid.mtp.adt.OSMTileInfo; public class Util { // Constants // Fields // Constructors // Getter & Setter // Methods from SuperClass/Interfaces // Methods public static OSMTileInfo getMapTileFromCoordinates(final double aLat, final double aLon, final int zoom) { final int y = (int) Math.floor((1 - Math.log(Math.tan(aLat * Math.PI / 180) + 1 / Math.cos(aLat * Math.PI / 180)) / Math.PI) / 2 * (1 << zoom)); final int x = (int) Math.floor((aLon + 180) / 360 * (1 << zoom)); return new OSMTileInfo(x, y, zoom); } // Inner and Anonymous Classes }
package edisyn; import edisyn.gui.*; import java.util.*; import javax.sound.midi.*; /** Breaks up Sysex data into fragmented chunks suitable to send one at a time. Some synthesizers cannot receive a large sysex message due to limited buffers, or require that it be sent piecemeal. To accommodate this, Java has a mechanism which permits you to send a sysex message as a stream of SysexMessages. The first message starts with an 0xF0. Successive messages start with 0xF7, which is supposed to be stripped off. The final message starts with an 0xF7 and concludes with an 0xF7. <p>However two bugs complicate this. In Windows and Linux, you cannot send a (proper) sysex message fragment which starts with an 0xF7: it will bomb your program. Similarly, you cannot send a message fragment which contains nothing but a bare concluding 0xF7. On the Mac we use CoreMidi4J, which properly handles sysex message fragments starting with 0xF7. <p>To deal with this, DividedSysex will break the sysex message into fragments handled either by SysexMessage (in the case of the Mac) or by DividedSysex messages (in the case of Windows and Linux). */ public class DividedSysex extends MidiMessage { public byte[] getData() { return data; } public Object clone() { return new DividedSysex(getMessage()); } public DividedSysex(byte[] data) { super(data.clone()); } static boolean doHack() { // At present the Mac, which is using the latest versions of CoreMidi4J, can handle // properly split SysexMessage objects. However it can *also* hande DividedSysex // objects (the hack). Windows and Linux can only work with the hack. So we can // at present just return true here if we wished; but for now I am returning // true if we're Windows or Linux, and false if we're on a Mac. return !Style.isMac(); } /** Builds an array of either SysexMessage or DividedSysex messages, depending on the platform (windows and linux have a bug which causes them to bomb). These messages break up the given sysex message into objects of either *chunksize* or *chunksize - 1* (varying to work around another windows/linux bug), which can be sent in multiple pieces and can be separated by pauses. Do not insert other messages in-between them: it'll break things. Chunksize must be greater than 3. */ public static MidiMessage[] create(SysexMessage sysex, int chunksize) { return create(sysex.getMessage(), chunksize); } /** Builds an array of either SysexMessage or DividedSysex messages, depending on the platform (windows and linux have a bug which causes them to bomb). These messages break up the given sysex message into objects of either *chunksize* or *chunksize - 1* (varying to work around another windows/linux bug), with the last chunk possibly less in size, but always larger than 1. These messages can later be separated by pauses. Do not insert other messages in-between them: it'll break things. Chunksize must be greater than 2. */ public static MidiMessage[] create(byte[] sysex, int chunksize) { // we need a little headroom to guarantee we can't reduce chunksize to 1, not including the header. if (chunksize <= 2) throw new RuntimeException("Illegal chunksize in DivideSysex.create(), must be > 2, was " + chunksize); byte[][] newsysex = new byte[sysex.length / chunksize][]; // We're looking for a good revised chunk size. // First, revise chunksize if necessary. This will put the extra in the final array if (sysex.length % chunksize == 1) // otherwise the last chunk would be a bare F7, which bombs windows { chunksize // This might have made the last chunk too big. Let's try breaking it into two if (sysex.length % chunksize > 1) // if breaking it up into two will NOT leave the second chunk with only one byte { newsysex = new byte[newsysex.length + 1][]; } } // build the sysex chunks for(int i = 0; i < newsysex.length - 1; i++) // don't do the last chunk { newsysex[i] = new byte[chunksize]; System.arraycopy(sysex, chunksize * i, newsysex[i], 0, chunksize); } // do the last chunk, which may be different in length int i = newsysex.length - 1; newsysex[i] = new byte[sysex.length - chunksize * i]; System.arraycopy(sysex, chunksize * i, newsysex[i], 0, newsysex[i].length); return create(newsysex); } /** Given a sysex message which is broken into multiple fragments, builds an array of either SysexMessage or DividedSysex messages, depending on the platform (windows and linux have a bug which causes them to bomb). Each of these messages encapsulate one provided fragment. These messages can later be separated by pauses. Do not insert other messages in-between them: it'll break things. */ public static MidiMessage[] create(byte[][] sysex) { if (doHack()) // Windows and Linux { // We just break up the message into pieces and assign a DividedSysex // to each piece. DividedSysex[] div = new DividedSysex[sysex.length]; for(int i = 0; i < sysex.length; i++) { div[i] = new DividedSysex(sysex[i]); } return div; } else // MacOS { try { // We use SysexMessages. I hope this will work? Otherwise we can use // DividedSysex messages instead. In the first case break up the message into pieces and assign a DividedSysex // to each piece. For the first message (which contains an 0xF0) we build // a standard Sysex message that does NOT end in 0xF7. In the successive // messages, we make room for an extra 0xF7 at the beginning. SysexMessage[] div = new SysexMessage[sysex.length]; for(int i = 0; i < sysex.length; i++) { //System.err.println(edisyn.util.StringUtility.toHex(sysex[i])); if (i == 0) { div[i] = new SysexMessage(sysex[i], sysex[i].length); } else { byte[] sysex2 = new byte[sysex[i].length + 1]; System.arraycopy(sysex[i], 0, sysex2, 1, sysex[i].length); sysex2[0] = (byte)0xF7; div[i] = new SysexMessage(sysex2, sysex2.length); } } return div; } catch (InvalidMidiDataException ex) { ex.printStackTrace(); return new MidiMessage[0]; } } } }
package tech.pinto; import static tech.pinto.Pinto.toTableConsumer; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.text.MessageFormat; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.PrimitiveIterator.OfDouble; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleUnaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.Stream; import tech.pinto.time.Period; import tech.pinto.time.PeriodicRange; import tech.pinto.time.Periodicities; import tech.pinto.time.Periodicity; import tech.pinto.tools.DoubleCollector; import tech.pinto.tools.DoubleCollectors; public class StandardVocabulary extends Vocabulary { protected final Map<String,Name> names; @SuppressWarnings("unchecked") public StandardVocabulary() { names = new HashMap<String,Name>(); /* terminal */ names.put("def", new Name("def", p -> t -> { Pinto.State state = p.getState(); String name = state.getNameLiteral().orElseThrow(() -> new PintoSyntaxException("def requires a name literal.")); String desc = state.getExpression().get(); Consumer<Table> f = state.getPrevious().andThen(t2 -> { t2.decrementBase(); }); p.getNamespace().define(name, state.getNameIndexer(), desc, state.getDependencies().subList(0,state.getDependencies().size() - 1), f); t.setStatus("Defined " + name); }, Optional.empty(), Optional.of("[]"), "Defines the expression as the preceding name literal.", true, true, true)); names.put("undef", new Name("undef", p -> t -> { String name = p.getState().getNameLiteral().orElseThrow(() -> new PintoSyntaxException("del requires a name literal.")); p.getNamespace().undefine(name); t.setStatus("Undefined " + name); },"[]", "Deletes name specified by the preceding name literal.", true)); names.put("help", new Name("help", p -> t -> { StringBuilder sb = new StringBuilder(); String crlf = System.getProperty("line.separator"); if(p.getState().getNameLiteral().isPresent()) { String n = p.getState().getNameLiteral().get(); sb.append(p.getNamespace().getName(n).getHelp(n)).append(crlf); } else { sb.append("Pinto help").append(crlf); sb.append("Built-in names:").append(crlf); List<String> l = new ArrayList<>(p.getNamespace().getNames()); List<String> l2 = new ArrayList<>(); for(int i = 0; i < l.size(); i++) { if(p.getNamespace().getName(l.get(i)).builtIn()) { sb.append(l.get(i)).append(i == l.size()-1 || i > 0 && i % 7 == 0 ? crlf : ", "); } else { l2.add(l.get(i)); } } sb.append("Defined names:").append(crlf); for(int i = 0; i < l2.size(); i++) { sb.append(l2.get(i)).append(i == l2.size()-1 || i > 0 && i % 7 == 0 ? crlf : ", "); } sb.append(crlf).append("For help with a specific function type \":function help\"").append(crlf); } t.setStatus(sb.toString()); }, "[]", "Prints help for the preceding name literal or all names if one has not been specified.", true)); names.put("list", new Name("list", p -> t -> { StringBuilder sb = new StringBuilder(); String crlf = System.getProperty("line.separator"); p.getNamespace().getNames().stream().map(s -> p.getNamespace().getName(s)) .forEach(name -> { sb.append(name.toString()).append("|").append(name.getIndexString()).append("|") .append(name.getDescription()).append(crlf); }); t.setStatus(sb.toString()); }, "[]", "Shows description for all names.", true)); names.put("eval", new Name("eval", p -> toTableConsumer(s -> { Periodicity<?> periodicity = ((Column.OfConstantPeriodicities)s.removeFirst()).getValue(); LinkedList<LocalDate> dates = new LinkedList<>(); while((!s.isEmpty()) && dates.size() < 2 && s.peekFirst().getHeader().equals("date")) { dates.add(((Column.OfConstantDates)s.removeFirst()).getValue()); } PeriodicRange<?> range = periodicity.range(dates.removeLast(), dates.isEmpty() ? LocalDate.now() : dates.peek(), false); s.stream().forEach(c -> c.setRange(range)); }, true),"[periodicity=B,date=today today,:]", "Evaluates the expression over date range between two *date* columns over *periodicity*.", true )); names.put("import", new Name("import", p -> t -> { for(LinkedList<Column<?,?>> s : t.popStacks()) { while(!s.isEmpty()) { String filename = ((Column.OfConstantStrings)s.removeFirst()).getValue(); try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { String line = null; p.engineState.reset(); while ((line = reader.readLine()) != null) { p.eval(line); } } catch (FileNotFoundException e) { throw new IllegalArgumentException("Cannot find pinto file \"" + filename + "\" to execute"); } catch (IOException e1) { throw new IllegalArgumentException("IO error for pinto file \"" + filename + "\" in execute"); } catch (PintoSyntaxException e) { throw new IllegalArgumentException("Pinto syntax error in file \"" + filename + "\"", e); } } } t.setStatus("Successfully executed"); },"[:]", "Executes pinto expressions contained files specified by file names in string columns.", true)); names.put("to_csv", new Name("to_csv", p -> t -> { LinkedList<Column<?,?>> s = t.peekStack(); String filename = ((Column.OfConstantStrings)s.removeFirst()).getValue(); Periodicity<?> periodicity = ((Column.OfConstantPeriodicities)s.removeFirst()).getValue(); LinkedList<LocalDate> dates = new LinkedList<>(); while((!s.isEmpty()) && dates.size() < 2 && s.peekFirst().getHeader().equals("date")) { dates.add(((Column.OfConstantDates)s.removeFirst()).getValue()); } PeriodicRange<?> range = periodicity.range(dates.removeLast(), dates.isEmpty() ? LocalDate.now() : dates.peek(), false); s.stream().forEach(c -> c.setRange(range)); try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename)))) { out.print(t.toCsv()); } catch (IOException e) { throw new IllegalArgumentException("Unable to open file \"" + filename + "\" for export"); } t.setStatus("Successfully exported"); },"[filename,periodicity=B,date=today today,:]","Evaluates the expression over the date range " + "specified by *start, *end* and *freq* columns, exporting the resulting table to csv *filename*.", true)); /* stack manipulation */ names.put("only", new Name("only", toTableConsumer(s -> {}, true),"[:]", "Clears stack except for indexed columns.")); names.put("clear", new Name("clear", toTableConsumer(s -> s.clear()),"[:]", "Clears indexed columns from stack.")); names.put("rev", new Name("rev", toTableConsumer(s -> Collections.reverse(s)),"[:]","Reverses order of columns in stack.")); names.put("copy", new Name("copy", toTableConsumer(s -> { int times = (int) ((Column.OfConstantDoubles) s.removeFirst()).getValue().doubleValue(); LinkedList<Column<?,?>> temp = new LinkedList<>(); s.stream().forEach(temp::addFirst); for(int j = 0; j < times - 1; j++) { temp.stream().map(Column::clone).forEach(s::addFirst); } }), "[n=2,:]", "Copies indexed columns *n* times.")); names.put("roll", new Name("roll", toTableConsumer(s -> { int times = (int) ((Column.OfConstantDoubles) s.removeFirst()).getValue().doubleValue(); for(int j = 0; j < times; j++) { s.addFirst(s.removeLast()); } }), "[n=1,:]", "Permutes columns in stack *n* times.")); /* dates */ names.put("today", new Name("today", toTableConsumer(s -> { s.addFirst(new Column.OfConstantDates(LocalDate.now())); }),"[]", "Creates a constant date column with today's date.")); names.put("offset", new Name("offset", toTableConsumer(s -> { LocalDate date = ((Column.OfConstantDates)s.removeFirst()).getValue(); Periodicity<?> periodicity = ((Column.OfConstantPeriodicities)s.removeFirst()).getValue(); int count = ((Column.OfConstantDoubles)s.removeFirst()).getValue().intValue(); s.addFirst(new Column.OfConstantDates(periodicity.offset(count, date))); }),"[date=today,periodicity=B,count=-1]", "Offset a given number of periods from today's date.")); /* data creation/testing */ /* constants */ for(Entry<String, Supplier<Periodicity<?>>> e : Periodicities.map.entrySet()) { names.put(e.getKey(), new Name(e.getKey(), toTableConsumer(s -> { s.addFirst(new Column.OfConstantPeriodicities(e.getValue().get())); }),"[]", "Creates a constant periodcities column for " + e.getKey())); } names.put("pi", new Name("pi", toTableConsumer(s -> { s.addFirst(new Column.OfConstantDoubles(Math.PI)); }),"[]", "Creates a constant double column with the value pi.")); names.put("moon", new Name("moon", toTableConsumer(s -> { s.addFirst(new Column.OfDoubles(i -> "moon", inputs -> range -> { return range.dates().stream().mapToDouble(d -> { return new tech.pinto.tools.MoonPhase(d).getPhase(); }); })); }),"[]","Creates a double column with values corresponding the phase of the moon.")); names.put("range", new Name("range", toTableConsumer(s -> { int n = (int) ((Column.OfConstantDoubles) s.removeFirst()).getValue().doubleValue(); IntStream.range(1,n+1).mapToDouble(i -> (double)i).mapToObj( value -> new Column.OfConstantDoubles(value)).forEach(s::addFirst); }),"[n=3]", "Creates double columns corresponding to the first *n* positive integers.")); names.put("read_csv", new Name("read_csv", toTableConsumer(s -> { String source = ((Column.OfConstantStrings)s.removeFirst()).getValue(); boolean includesHeader = Boolean.parseBoolean(((Column.OfConstantStrings)s.removeFirst()).getValue()); try { List<String> lines = null; if(!source.contains("http")) { lines = Files.readAllLines(Paths.get(source)); } else { lines = new ArrayList<>(); BufferedReader in = new BufferedReader(new InputStreamReader(new URL(source).openStream())); String inputLine; while ((inputLine = in.readLine()) != null) lines.add(inputLine); in.close(); } if (lines.size() > 0) { String[] firstRow = lines.get(0).split(","); final String[] labels = includesHeader ? Arrays.copyOfRange(firstRow, 1, firstRow.length) : new String[firstRow.length]; final Map<LocalDate, String[]> data = lines.stream().skip(includesHeader ? 1 : 0).map(line -> line.split(",")) .collect(Collectors.toMap((r) -> LocalDate.parse(r[0]), Function.identity())); for(int i = 0; i < firstRow.length - 1; i++) { final int col = i; s.add(new Column.OfDoubles(inputs -> labels[col] != null ? labels[col] : "", inputs -> range -> { DoubleStream.Builder b = DoubleStream.builder(); for (Period per : range.values()) { if (data.containsKey(per.endDate())) { try { b.accept(Double.valueOf(data.get(per.endDate())[col + 1])); } catch(NumberFormatException nfe) { b.accept(Double.NaN); } } else { b.accept(Double.NaN); } } return b.build(); })); } } } catch (IOException e) { throw new PintoSyntaxException("Unable to import file \"" + source + "\".", e); } }),"[source,includes_header=\"true\"]", "Reads CSV formatted table from file or URL specified as *source*.")); /* data cleanup */ names.put("fill", new Name("fill", toTableConsumer(s-> { @SuppressWarnings("rawtypes") Periodicity p = ((Column.OfConstantPeriodicities)s.removeFirst()).getValue(); boolean lookBack = Boolean.parseBoolean(((Column.OfConstantStrings)s.removeFirst()).getValue()); s.replaceAll(function -> { return new Column.OfDoubles(inputs -> inputs[0].toString() + " fill", inputs -> range -> { DoubleStream input = null; int skip = 0; if (lookBack) { PeriodicRange<Period> r = (PeriodicRange<Period>) range.periodicity().range( p.previous(p.from(range.start().endDate())).endDate(), range.end().endDate(), range.clearCache()); skip = (int) r.indexOf(range.start()); inputs[0].setRange(r); } input = ((Column.OfDoubles)inputs[0]).rows(); final AtomicReference<Double> lastGoodValue = new AtomicReference<>(Double.NaN); return input.map(d -> { if (!Double.isNaN(d)) { lastGoodValue.set(d); } return lastGoodValue.get(); }).skip(skip); }, new Column<?,?>[] {function}); }); }),"[periodicity=BQ-DEC,lookback=\"true\",:]","Fills missing values with last good value, " + "looking back one period of *freq* if *lookback* is true.")); names.put("join", new Name("join", toTableConsumer(s-> { List<LocalDate> cutoverDates = Stream.of(((Column.OfConstantStrings)s.removeFirst()).getValue().split(",")).map(String::trim).map(LocalDate::parse).collect(Collectors.toList()); Column.OfDoubles[] inputStack = s.toArray(new Column.OfDoubles[] {}); s.clear(); s.add(new Column.OfDoubles(i -> "join", inputArray -> range -> { LinkedList<Column<?,?>> inputs = new LinkedList<>(Arrays.asList(inputArray)); Collections.reverse(inputs); DoubleStream ds = DoubleStream.empty().sequential(); List<Period> cutoverPeriods = cutoverDates.stream().map(range.periodicity()::from).collect(Collectors.toList()); Collections.sort(cutoverPeriods); Period current = range.start(); Periodicity<Period> freq = (Periodicity<Period>) range.periodicity(); int i = 0; while (i < cutoverPeriods.size() && !current.isAfter(range.end())) { if(inputs.isEmpty()) { throw new PintoSyntaxException("Not enough columns to join on " + cutoverDates.size() + " dates."); } Column.OfDoubles currentFunction = (Column.OfDoubles) inputs.removeFirst(); if (current.isBefore(cutoverPeriods.get(i))) { Period chunkEnd = range.end().isBefore(cutoverPeriods.get(i)) ? range.end() : freq.previous(cutoverPeriods.get(i)); currentFunction.setRange(freq.range(current, chunkEnd, range.clearCache())); ds = DoubleStream.concat(ds, currentFunction.rows()); current = freq.next(chunkEnd); } i++; } if (inputs.isEmpty()) { throw new IllegalArgumentException("Not enough columns to join on " + cutoverDates.size() + " dates."); } Column.OfDoubles currentFunction = (Column.OfDoubles) inputs.removeFirst(); if (!current.isAfter(range.end())) { currentFunction.setRange(range.periodicity().range(current, range.end(), range.clearCache())); ds = DoubleStream.concat(ds, currentFunction.rows()); } return ds; }, inputStack)); }),"[dates,:]", "Joins columns over time, switching between columns on dates supplied in \";\" denominated list *dates*.")); names.put("resample", new Name("resample", toTableConsumer(s-> { Periodicity<Period> newPeriodicity = Periodicities.get(((Column.OfConstantStrings)s.removeFirst()).getValue()); s.replaceAll(c -> { return new Column.OfDoubles(inputs -> inputs[0].toString() + " resample", inputs -> range -> { Period newStart = newPeriodicity.roundDown(range.start().endDate()); if(newStart.endDate().isAfter(range.start().endDate())) { newStart = newStart.previous(); } Period newEnd = newPeriodicity.from(range.end().endDate()); PeriodicRange<Period> newDr = newPeriodicity.range(newStart, newEnd, range.clearCache()); inputs[0].setRange(newDr); double[] d = ((DoubleStream) inputs[0].rows()).toArray(); DoubleStream.Builder b = DoubleStream.builder(); range.values().stream().map(Period::endDate).forEach( ed -> { b.accept(d[(int) newDr.indexOf(newPeriodicity.roundDown(ed))]); }); return b.build(); }, c); }); }),"[freq=\"BM\",:]", "Sets frequency of prior columns to periodicity *freq*, carrying values forward " + "if evaluation periodicity is more frequent.")); names.put("hformat", new Name("hformat", toTableConsumer(s-> { MessageFormat format = new MessageFormat(((Column.OfConstantStrings)s.removeFirst()).getValue().replaceAll("\\{\\}", "\\{0\\}")); s.replaceAll(c -> { String header = format.format(new Object[]{c.getHeader()}); c.setHeaderFunction(inputs -> header); return c; }); }),"[format,:]", "Formats headers, setting new value to *format* and substituting and occurences of \"{}\" with previous header value.")); /* array creation */ names.put("rolling", new Name("rolling", toTableConsumer(s-> { int size = (int) ((Column.OfConstantDoubles) s.removeFirst()).getValue().doubleValue(); String wfs = ((Column.OfConstantStrings)s.removeFirst()).getValue(); Optional<Periodicity<Period>> windowFreq = wfs.equals("eval") ? Optional.empty() : Optional.of(Periodicities.get(wfs)); s.replaceAll(c -> { return new Column.OfDoubleArray1Ds(inputs -> inputs[0].getHeader() + " rolling", inputs -> range -> { Periodicity<Period> wf = windowFreq.orElse((Periodicity<Period>) range.periodicity()); Stream.Builder<DoubleStream> b = Stream.builder(); Period expandedWindowStart = wf.offset(-1 * (size - 1), wf.from(range.start().endDate())); Period windowEnd = wf.from(range.end().endDate()); PeriodicRange<Period> expandedWindow = wf.range(expandedWindowStart, windowEnd, range.clearCache()); inputs[0].setRange(expandedWindow); double[] data = ((Column.OfDoubles)inputs[0]).rows().toArray(); for(Period p : range.values()) { long windowStartIndex = wf.distance(expandedWindowStart, wf.from(p.endDate())) - size + 1; b.accept(Arrays.stream(data, (int) windowStartIndex, (int) windowStartIndex + size)); } return b.build(); },size,c); }); }),"[size=2,freq=\"eval\",:]", "Creates double array columns for each input column with rows containing values "+ "from rolling window of past data where the window is *size* periods of periodicity *freq*, defaulting to the evaluation periodicity.")); names.put("cross", new Name("cross", toTableConsumer(s-> { Column.OfDoubles[] a = s.toArray(new Column.OfDoubles[]{}); s.clear(); s.add(new Column.OfDoubleArray1Ds(inputs -> "cross", inputs -> range -> { Stream.Builder<DoubleStream> b = Stream.builder(); List<OfDouble> l = Stream.of(inputs).map(c -> ((Column.OfDoubles) c).rows()) .map(DoubleStream::iterator).collect(Collectors.toList()); for(int i = 0; i < range.size(); i++) { DoubleStream.Builder db = DoubleStream.builder(); l.stream().mapToDouble(OfDouble::nextDouble).forEach(db::accept); b.accept(db.build()); } return b.build(); }, i -> Optional.of(new int[]{i.length}),a)); }),"[:]", "Creates a double array column with each row containing values of input columns.")); names.put("expanding", new Name("expanding", toTableConsumer(s-> { String startString = ((Column.OfConstantStrings)s.removeFirst()).getValue(); String freqString = ((Column.OfConstantStrings)s.removeFirst()).getValue(); boolean initialZero = Boolean.parseBoolean(((Column.OfConstantStrings)s.removeFirst()).getValue()); s.replaceAll(c -> { return new Column.OfDoubleArray1Ds(inputs -> inputs[0].getHeader() + " expanding", inputs -> range -> { LocalDate startDate = startString.equals("range") ? range.start().endDate() : LocalDate.parse(startString); Periodicity<Period> wf = freqString.equals("range") ? (Periodicity<Period>) range.periodicity() : Periodicities.get(freqString); Period windowStart = wf.from(startDate); Period windowEnd = wf.from(range.end().endDate()); windowEnd = windowEnd.isBefore(windowStart) ? windowStart : windowEnd; PeriodicRange<Period> window = wf.range(windowStart, windowEnd, range.clearCache()); Stream.Builder<DoubleStream> b = Stream.builder(); inputs[0].setRange(window); double[] data = ((Column.OfDoubles)inputs[0]).rows().toArray(); if(initialZero) { data[0] = 0.0d; } List<LocalDate> rangeDates = range.dates(); for(int i = 0; i < range.size(); i++) { int index = (int) window.indexOf(rangeDates.get(i)); if (index >= 0) { b.accept(Arrays.stream(data, 0, index + 1)); } else { b.accept(DoubleStream.iterate(Double.NaN, r -> Double.NaN).limit(range.size() + 1)); } } return b.build(); },c); }); }),"[start=\"range\",freq=\"range\",initial_zero=\"false\",:]", "Creates double array columns for each input column with rows " + "containing values from an expanding window of past data with periodicity *freq* that starts on date *start*.")); /* array operators */ for(DoubleCollectors dc : DoubleCollectors.values()) { names.put(dc.name(), new Name(dc.name(), makeOperator(dc.name(), dc),"[:]","Aggregates row values in double array " + "columns to a double value by " + dc.name())); } // names.put("rank", new Name("rank", toTableConsumer(s-> { // s.replaceAll(c -> { // return new Column.OfDoubleArray1Ds(inputs -> inputs[0].toString() + " rank", // inputs -> range -> { // Column.OfDoubleArray1Ds col = (Column.OfDoubleArray1Ds) inputs[0]; // col.setRange(range); // return col.rows().map(ds -> { // double[] d = ds.toArray(); // Double[] ranks = new Double[d.length]; // for(int i = 0; i < d.length; i++) { // ranks[i] = (double) i; // Arrays.sort(ranks, (i0,i1) -> (int) Math.signum(d[i0.intValue()] - d[i1.intValue()])); // return Arrays.stream(ranks).mapToDouble(Double::doubleValue); // }),"[:]", "Creates a double array column with each row containing values of input columns.")); /* binary operators */ names.put("+", makeOperator("+", (x,y) -> x + y)); names.put("-", makeOperator("-", (x,y) -> x - y)); names.put("*", makeOperator("*", (x,y) -> x * y)); names.put("/", makeOperator("/", (x,y) -> x / y)); names.put("%", makeOperator("%", (x,y) -> x % y)); names.put("^", makeOperator("^", (x,y) -> Math.pow(x, y))); names.put("==", makeOperator("==", (x,y) -> x == y ? 1.0 : 0.0)); names.put("!=", makeOperator("!=", (x,y) -> x != y ? 1.0 : 0.0)); names.put(">", makeOperator(">", (x,y) -> x > y ? 1.0 : 0.0)); names.put("<", makeOperator("<", (x,y) -> x < y ? 1.0 : 0.0)); names.put(">=", makeOperator(">=", (x,y) -> x >= y ? 1.0 : 0.0)); names.put("<=", makeOperator("<=", (x,y) -> x <= y ? 1.0 : 0.0)); /* unary operators */ names.put("abs", makeOperator("abs", (DoubleUnaryOperator) Math::abs)); names.put("sin", makeOperator("sin", Math::sin)); names.put("cos", makeOperator("cos", Math::cos)); names.put("tan", makeOperator("tan", Math::tan)); names.put("sqrt",makeOperator("sqrt", Math::sqrt)); names.put("log", makeOperator("log", Math::log)); names.put("log10", makeOperator("log10", Math::log10)); names.put("exp", makeOperator("exp", Math::exp)); names.put("signum", makeOperator("signum", (DoubleUnaryOperator)Math::signum)); names.put("asin", makeOperator("asin", Math::asin)); names.put("acos", makeOperator("acos", Math::acos)); names.put("atan", makeOperator("atan", Math::atan)); names.put("toRadians", makeOperator("toRadians", Math::toRadians)); names.put("toDegrees", makeOperator("toDegrees", Math::toDegrees)); names.put("cbrt", makeOperator("cbrt", Math::cbrt)); names.put("ceil", makeOperator("ceil", Math::ceil)); names.put("floor", makeOperator("floor", Math::floor)); names.put("rint", makeOperator("rint", Math::rint)); names.put("ulp", makeOperator("ulp", (DoubleUnaryOperator)Math::ulp)); names.put("sinh", makeOperator("sinh", Math::sinh)); names.put("cosh", makeOperator("cosh", Math::cosh)); names.put("tanh", makeOperator("tanh", Math::tanh)); names.put("expm1", makeOperator("expm1", Math::expm1)); names.put("log1p", makeOperator("log1p", Math::log1p)); names.put("nextUp", makeOperator("nextUp", (DoubleUnaryOperator)Math::nextUp)); names.put("nextDown", makeOperator("nextDown", (DoubleUnaryOperator)Math::nextDown)); names.put("neg", makeOperator("neg", x -> x * -1.0d)); names.put("inv", makeOperator("inv", x -> 1.0 / x)); names.put("acgbPrice", makeOperator("acgbPrice", quote -> { double TERM = 10, RATE = 6, price = 0; for (int i = 0; i < TERM * 2; i++) { price += RATE / 2 / Math.pow(1 + (100 - quote) / 2 / 100, i + 1); } return price + 100 / Math.pow(1 + (100 - quote) / 2 / 100, TERM * 2); })); } @Override protected Map<String, Name> getNameMap() { return names; } public static Name makePintoName(String name, String pintoCode, String defaultIndexer, String description) { return new Name(name, p -> t -> { Pinto.State state = new Pinto.State(false); p.evaluate(pintoCode, state); state.getCurrent().accept(t); }, defaultIndexer, description, false); } public static Name makeOperator(String name, DoubleBinaryOperator dbo) { return new Name(name, toTableConsumer(stack -> { int rightCount = (int) ((Column.OfConstantDoubles) stack.removeFirst()).getValue().doubleValue(); if (stack.size() < rightCount + 1) { throw new IllegalArgumentException("Not enough inputs for " + name); } LinkedList<Column<?,?>> rights = new LinkedList<>(stack.subList(0, rightCount)); List<Column<?,?>> lefts = new ArrayList<>(stack.subList(rightCount, stack.size())); stack.clear(); for (int i = 0; i < lefts.size(); i++) { Column<?,?> right = i >= rights.size() ? rights.getFirst().clone() : rights.getFirst(); rights.addLast(rights.removeFirst()); stack.add(new Column.OfDoubles(inputs -> inputs[1].toString() + " " + inputs[0].toString() + " " + name, inputs -> range -> { OfDouble leftIterator = ((Column.OfDoubles)inputs[1]).rows().iterator(); return ((Column.OfDoubles)inputs[0]).rows().map(r -> dbo.applyAsDouble(leftIterator.nextDouble(), r)); }, right, lefts.get(i))); } }),"[n=1,:]", "Binary double operator " + name + " that operates on *n* columns at a time with fixed right-side operand."); } public static Name makeOperator(String name, DoubleUnaryOperator duo) { return new Name(name, toTableConsumer(stack -> { stack.replaceAll(c -> { return new Column.OfDoubles(inputs -> inputs[0].toString() + " " + name, inputs -> range -> ((Column.OfDoubles)inputs[0]).rows().map(duo), c); }); }),"[:]", "Unary double operator " + name); } public static Consumer<Table> makeOperator(String name, Supplier<DoubleCollector> dc) { return Pinto.toTableConsumer(stack -> { stack.replaceAll(c -> { return new Column.OfDoubles(inputs -> Stream.of(inputs[0].toString(), name).collect(Collectors.joining(" ")), inputs -> range -> { return ((Column.OfDoubleArray1Ds)inputs[0]).rows().mapToDouble( s -> { return s.collect(dc, (v,d) -> v.add(d), (v,v1) -> v.combine(v1)).finish(); }); }, c); }); }); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import java.util.ArrayList; import java.util.Arrays; import java.util.logging.Level; import org.lwjgl.input.Mouse; import java.util.logging.Logger; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.omg.CORBA.BAD_INV_ORDER; import com.google.gson.Gson; import com.sun.org.apache.xerces.internal.util.SynchronizedSymbolTable; public class SimpleSlickGame extends BasicGame implements Runnable{ public static Train t; public static Stack t2; public static Stack t6; public static Stack t8; public static Connection t9; public static PlayerPiece t10; public static Card m1; //public static Town townA, townB; //commented these out, as the already existed in SimpleSlick public static Card missionCard; public static ArrayList<Integer> arrayTest; public static Town tempCityB, tempCityA; public static Card tempCard; static Board board; private Image summaryBackImage = null; private Image summaryFrontImage = null; private Image missionCardBack = null; private Image trainCardBack = null; private Image blackTrainCard = null; private Image blueTrainCard = null; private Image greenTrainCard = null; private Image orangeTrainCard = null; private Image pinkTrainCard = null; private Image redTrainCard = null; private Image whiteTrainCard = null; private Image yellowTrainCard = null; // private Image rainbowTrainCard = null; without jokers private Image[] missions = null; private Color red, green, blue, yellow; private Image map = null; private boolean completedActions = false; private boolean isYourTurn = true; private boolean youPickedTrainCards = false; private boolean youPickedMissionCards = false; private boolean youPlayedAConnection = false; int xpos; int ypos; Input input; private Town townA = null; private Town townB = null; String activater = null; public ArrayList<Connection> connectionsToDraw = new ArrayList<Connection>(); Players player1 = new Players(1, board.colors[0]); Players player2 = new Players(2, board.colors[1]); Players player3 = new Players(3, board.colors[2]); Players player4 = new Players(4, board.colors[3]); public Connection selectedConnection = null; public SimpleSlickGame(String gamename) { super("TicketToRide"); } @Override public void init(GameContainer gc) throws SlickException { // I don't know where this has to be loaded, but for now we can load all // images here // for (int flf = 0; flf < board.connections.size(); flf++) // connectionsToDraw.add(board.connections.get(5)); map = new Image("/pics/Map.jpg"); board.setBoardPic(map); // Setting som colors for the playerpieces red = new Color(255, 0, 0); green = new Color(0, 255, 0); blue = new Color(0, 0, 255); yellow = new Color(255, 255, 0); board.playerPieces[0].setColor(new Color(red)); board.playerPieces[1].setColor(new Color(green)); board.playerPieces[2].setColor(new Color(blue)); board.playerPieces[3].setColor(new Color(yellow)); // Setting the images for the summaryCard summaryBackImage = new Image("/pics/summaryBack.jpg"); summaryFrontImage = new Image("/pics/summaryFront.jpg"); board.summaryCard.setBackImage(summaryBackImage); board.summaryCard.setFrontImage(summaryFrontImage); // Setting cardback and cardfront for the trainCards // Cardback is the same for all the trainCards trainCardBack = new Image("/pics/trainCardBack.png"); for (int i = 0; i < board.trainCards.length; i++) { board.trainCards[i].setBackImage(trainCardBack); } // Setting the image for the stationaryCard board.stationaryCardT.setBackImage(trainCardBack); board.stationaryCardM.setBackImage(trainCardBack); // Loading all the trainCardImages blackTrainCard = new Image("/pics/blackTrainCard.png"); blueTrainCard = new Image("/pics/blueTrainCard.png"); greenTrainCard = new Image("/pics/greenTrainCard.png"); orangeTrainCard = new Image("/pics/orangeTrainCard.png"); pinkTrainCard = new Image("/pics/pinkTrainCard.png"); redTrainCard = new Image("/pics/redTrainCard.png"); whiteTrainCard = new Image("/pics/whiteTrainCard.png"); yellowTrainCard = new Image("/pics/yellowTrainCard.png"); // rainbowTrainCard = new Image("/rainbowTrainCard.png"); without jokers // Applying the trainCardImages to the correct spot within the array. for (int i = 0; i < 12; i++) { board.trainCards[i].setFrontImage(blueTrainCard); } for (int i = 12; i < 24; i++) { board.trainCards[i].setFrontImage(redTrainCard); } for (int i = 24; i < 36; i++) { board.trainCards[i].setFrontImage(orangeTrainCard); } for (int i = 36; i < 48; i++) { board.trainCards[i].setFrontImage(whiteTrainCard); } for (int i = 48; i < 60; i++) { board.trainCards[i].setFrontImage(yellowTrainCard); } for (int i = 60; i < 72; i++) { board.trainCards[i].setFrontImage(blackTrainCard); } for (int i = 72; i < 84; i++) { board.trainCards[i].setFrontImage(greenTrainCard); } for (int i = 84; i < 96; i++) { board.trainCards[i].setFrontImage(pinkTrainCard); } // for (int i = 96; i < 110; i++) { // board.trainCards[i].setFrontImage(rainbowTrainCard); // no jokers atm missions = new Image[30]; missionCardBack = new Image("/pics/missionCardBack.png"); // Loading and applying the missionCards and setting the cardback for // the missioncards for (int i = 0; i < board.missionCards.length; i++) { missions[i] = new Image("/pics/misssion(" + i + ").jpg"); board.missionCards[i].setFrontImage(missions[i]); board.missionCards[i].setBackImage(missionCardBack); } } @Override public void update(GameContainer gc, int i) throws SlickException { Input input = gc.getInput(); xpos = Mouse.getX(); ypos = Mouse.getY(); // int currentCard = 0; // Calling flipcard function if activated // Will implement what happens when you click a city in here. if (isYourTurn) { if (input.isMousePressed(0)) { for (int j = 0; j < board.towns.length; j++) { if (xpos < board.towns[j].getxPos() + 10 && xpos >= board.towns[j].getxPos() - 10 && ypos < board.towns[j].getyPos() + 10 && ypos > board.towns[j].getyPos() - 10) { System.out.println("You have selected " + board.towns[j].getName()); if (townA == null) { townA = board.towns[j]; System.out.println(townA.getName() + " has been clicked as town A"); } else if (townB == null) { townB = board.towns[j]; System.out.println(townB.getName() + " has been clicked as town B"); } } } if (townA != null && townB != null) { if (findConnectionToBuild(townA, townB) == null) { townA = null; townB = null; } else { selectedConnection = findConnectionToBuild(townA, townB); connectionsToDraw.add(selectedConnection); // playCards(); completedActions = true; youPlayedAConnection = true; System.out.println("The selected connection require " + selectedConnection.getLength() + " trains with the color " + selectedConnection.getColor().getColorName()); } } // System.out.println(townB.getName() + " " + townA.getName()); /* * SUMMARY CARD FLIP CARD */ if (xpos < board.summaryCard.xPos + board.summaryCard.width && xpos > board.summaryCard.xPos && ypos > 768 - board.summaryCard.height) { board.summaryCard.flipCard(); } /* * MISSIONCARDSTACK FLIP CARD */ if (xpos < board.missionCardStack.xPos + board.missionCardStack.width && xpos > board.missionCardStack.xPos && ypos > 768 - board.missionCardStack.height) { youPickedMissionCards= true; } /* * TRAINCARDSTACK FUNCTIONALITY */ // mouse input conditions for train card stack if (xpos < board.trainCardStack.xPos + board.trainCardStack.width && xpos > board.trainCardStack.xPos && ypos < 768 - board.trainCardStack.height && ypos > 768 - 2 * board.trainCardStack.height) { System.out.println("face-down train card stack has been clicked"); System.out.println(board.player1TrainHandStack.get(0).getColor().getColorName()); board.handTrainCardIncrementer = 73; board.player1TrainHandStack.add(board.arrayOfTrainCards.get(0)); for (int j = 0; j < board.player1TrainHandStack.size(); j++) { // position values for a drawn blue card if (board.player1TrainHandStack.get(j).getColor().getColorName() == board.colors[0].getColorName()) { board.player1TrainHandStack.get(j).yPos = 682; board.player1TrainHandStack.get(j).xPos = 0; board.blueColorCounter++; // position values for a drawn red card } else if (board.player1TrainHandStack.get(j).getColor().getColorName() == board.colors[1].getColorName()) { board.player1TrainHandStack.get(j).yPos = 682; board.player1TrainHandStack.get(j).xPos = board.handTrainCardIncrementer; board.redColorCounter++; // position values for a drawn orange card } else if (board.player1TrainHandStack.get(j).getColor().getColorName() == board.colors[2].getColorName() ) { board.player1TrainHandStack.get(j).yPos = 682; board.player1TrainHandStack.get(j).xPos = board.handTrainCardIncrementer * 2; board.orangeColorCounter++; // position values for a drawn white card } else if (board.player1TrainHandStack.get(j).getColor().getColorName() == board.colors[3].getColorName() ) { board.player1TrainHandStack.get(j).yPos = 682; board.player1TrainHandStack.get(j).xPos = board.handTrainCardIncrementer * 3; board.whiteColorCounter++; // position values for a drawn yellow card } else if (board.player1TrainHandStack.get(j).getColor().getColorName() == board.colors[4].getColorName() ) { board.player1TrainHandStack.get(j).yPos = 682; board.player1TrainHandStack.get(j).xPos = board.handTrainCardIncrementer * 4; board.yellowColorCounter++; // position values for a drawn black card } else if (board.player1TrainHandStack.get(j).getColor().getColorName() == board.colors[5].getColorName() ) { board.player1TrainHandStack.get(j).yPos = 682; board.player1TrainHandStack.get(j).xPos = board.handTrainCardIncrementer * 5; board.blackColorCounter++; // position values for a drawn green card. NOTE! // colors[6] is not used for the cards, only for the // connections } else if (board.player1TrainHandStack.get(j).getColor().getColorName() == board.colors[7].getColorName() ) { board.player1TrainHandStack.get(j).yPos = 682; board.player1TrainHandStack.get(j).xPos = board.handTrainCardIncrementer * 6; board.greenColorCounter++; // position values for a drawn pink card } else if (board.player1TrainHandStack.get(j).getColor().getColorName() == board.colors[8].getColorName() ) { board.player1TrainHandStack.get(j).yPos = 682; board.player1TrainHandStack.get(j).xPos = board.handTrainCardIncrementer * 7; board.pinkColorCounter++; } board.arrayOfTrainCards.remove(0); // card#deckOfA --> // remove } System.out.println( "Amount of cards in player 1 hand stack: " + board.player1TrainHandStack.size() + " "); // print the cards in the players hand stack System.out.println("Blue cards: " + board.blueColorCounter + ", Red cards: " + board.redColorCounter + ", Orange cards: " + board.orangeColorCounter + ", White cards: " + board.whiteColorCounter + ", Yellow cards: " + board.yellowColorCounter + ", Black cards: " + board.blackColorCounter + ", Green cards: " + board.greenColorCounter + ", Pink cards: " + board.pinkColorCounter); System.out.println("Amount of face-down cards in the train stack on the board: " + board.arrayOfTrainCards.size()); System.out.println(" "); // for spacing } /* * DISPLAYED STACK OF TRAINCARDS FUNCTIONALITY */ if (xpos < board.trainCardStack.xPos + board.trainCardStack.width && xpos > board.trainCardStack.xPos && ypos < 768 - 2 * board.trainCardStack.height && ypos > 768 - 3 * board.trainCardStack.height) { System.out.println("Displayed train card #0 has been clicked"); } if (xpos < board.trainCardStack.xPos + board.trainCardStack.width && xpos > board.trainCardStack.xPos && ypos < 768 - 3 * board.trainCardStack.height && ypos > 768 - 4 * board.trainCardStack.height) { System.out.println("Displayed train card #1 has been clicked"); } if (xpos < board.trainCardStack.xPos + board.trainCardStack.width && xpos > board.trainCardStack.xPos && ypos < 768 - 4 * board.trainCardStack.height && ypos > 768 - 5 * board.trainCardStack.height) { System.out.println("Displayed train card #2 has been clicked"); } if (xpos < board.trainCardStack.xPos + board.trainCardStack.width && xpos > board.trainCardStack.xPos && ypos < 768 - 5 * board.trainCardStack.height && ypos > 768 - 6 * board.trainCardStack.height) { System.out.println("Displayed train card #3 has been clicked"); } if (xpos < board.trainCardStack.xPos + board.trainCardStack.width && xpos > board.trainCardStack.xPos && ypos < 768 - 6 * board.trainCardStack.height && ypos > 768 - 7 * board.trainCardStack.height) { System.out.println("Displayed train card #4 has been clicked"); } if (xpos < board.button.getxPos() + board.button.getWidth() && xpos > board.button.getxPos() && ypos < 768 - board.button.getyPos() && ypos > 768 - board.button.getyPos() - board.button.getHeight() && completedActions == true) { if (youPickedMissionCards) { System.out.println("YouPickedMissionCards"); // Space for what should be send to the client activater = "state1"; isYourTurn = false; } if (youPickedTrainCards) { System.out.println("YouPickedTrainCards"); // Space for what should be send to the client activater = "state2"; isYourTurn = false; } if (youPlayedAConnection) { System.out.println("youPlayedAConnection"); // Space for what should be send to the client activater = "state3"; isYourTurn = false; } } } } /* * for(int flf = 0; flf < connectionsToDraw.size(); flf++){ * connectionsToDraw.get(flf).movePlayerPiece(); } */ } private Connection findConnectionToBuild(Town town1, Town town2) { for (int i = 0; i < board.connections.size(); i++) { if (board.connections.get(i).getTownA().getName() == town1.getName() || board.connections.get(i).getTownA().getName() == town2.getName()) { // Keeps looking for the right connection if (board.connections.get(i).getTownB().getName() == town1.getName() || board.connections.get(i).getTownB().getName() == town2.getName()) { System.out.println("These are neighbours"); if (!board.connections.get(i).getIsTaken()) return board.connections.get(i); } } /* * else { System.out.println( * "You probably didnt click two neighbouring cities, or no connections are available between these two cities" * ); } */ } return null; } @Override public void render(GameContainer gc, Graphics g) throws SlickException { // Loads the placement Map image used to detect cities board.getBoardPic().draw(); // Place it in (0,0) board.player1TrainHandStack.get(0).setVisible1(); board.summaryCard.setVisible(); board.stationaryCardT.setVisible(); board.stationaryCardM.setVisible(); // board.connections.get(2).setTakenByPlayer(player1, g); for (int i = 0; i < 5; i++) { board.displayedTrainStack.get(i).setVisible1(); } for (int i = 0; i < board.player1TrainHandStack.size(); i++) { board.player1TrainHandStack.get(i).setVisible1(); } for (int i = 0; i < 3; i++) { board.player1MissionHandStack.get(i).setVisible1(); } // Setting the visibility of the playerpieces for (int i = 0; i < board.playerPieces.length; i++) { board.playerPieces[i].setVisible(g); } board.button.setVisible(g, 0); if (completedActions) board.button.setVisible(g, 1); for (int j = 0; j < connectionsToDraw.size(); j++) { connectionsToDraw.get(j).drawConnection(player2, g); board.playerPieces[player1.playerNum].move(connectionsToDraw.get(j).getPoint()); } } public static void main(String[] args) throws SlickException { board = new Board(4); SimpleSlickGame client = new SimpleSlickGame("Ticket to Ride"); Thread t1 = new Thread(client); t1.start(); /* try { client.run(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } */ // GsonJson test with stacks of /* * System.out.println(board.trainCardStack.card[1].getColor(). * getColorNum()); * System.out.println(board.trainCardStack.card[50].getColor(). * getColorNum()); Gson serializer = new Gson(); String Jsontrain = * serializer.toJson(board); * * Board temp = new Gson().fromJson(Jsontrain, Board.class); * * System.out.println(temp.trainCardStack.card[1].getColor().getColorNum * ()); */ // JSON TEST END // GsonJson test with stacks of /* * System.out.println(board.trainCardStack.card[1].getColor(). * getColorNum()); * System.out.println(board.trainCardStack.card[50].getColor(). * getColorNum()); Gson serializer = new Gson(); String Jsontrain = * serializer.toJson(board); * * Board temp = new Gson().fromJson(Jsontrain, Board.class); * * System.out.println(temp.trainCardStack. * card[1].getColor().getColorNum()); */ // JSON TEST END try { AppGameContainer appgc; appgc = new AppGameContainer(new SimpleSlickGame("Simple Slick Game")); appgc.setDisplayMode(1024, 768, false); appgc.start(); } catch (SlickException ex) { Logger.getLogger(SimpleSlickGame.class.getName()).log(Level.SEVERE, null, ex); } } public void run() { try { Socket Sock = new Socket("172.20.10.2", 2222); PrintStream ps = new PrintStream(Sock.getOutputStream()); String activator = new String("1"); board = new Board(4); t = new Train(null); t.decrease(3); //t2 = new Stack(null); //t3 = new TrainCardStack(null); //t4 = new DisplayedTrainStack(null); //t5 = new HandMissionStack(5); //t6 = new Stack(null); //t7 = new TrainTrashStack(5); //t8 = new Stack(5); //t9 = new Connection(null, board.towns[1], board.towns[2], 5, 6); arrayTest = new ArrayList<Integer>(); arrayTest.add(2); arrayTest.add(5); arrayTest.add(100); Gson serializer = new Gson(); //Gson serializer2 = new GsonBuilder().create(); String json = serializer.toJson(t); String json1 = serializer.toJson(t2); String json5 = serializer.toJson(t6); String json7 = serializer.toJson(t8); String json8 = serializer.toJson(t9); String json9 = serializer.toJson(t10); String jsonTest = serializer.toJson(arrayTest); String missionTest = serializer.toJson(new MissionCard(new Town(board.towns[1].getName(), 4, board.connections.get(1).getTownA().getxPos(), board.towns[1].getyPos()), new Town(board.towns[4].getName(), 6, board.towns[4].getxPos(), board.towns[4].getxPos()), 2)); //String townTest = serializer.toJson(new Town(board.towns[1].getName(), 5, 74, 499)); //jsonTest2=null; /* String jsonTest2 = serializer.toJson( new Connection( new CustomColor("red", 2, new Color(255,0,0)), new Town("piK", 2, 3, 4), new Town("fisse", 5, 6, 7), 8, 9,1));*/ String jsontest2 = null; String[] jsontest3 = new String[board.connections.size()]; //sending the connections into a array of Strings. for (int i=0; i<board.connections.size(); i++){ String temp = serializer.toJson( new Connection( new CustomColor(board.connections.get(i).getColor().getColorName(), board.connections.get(i).getColor().getColorNum(), board.connections.get(i).getColor().getColor()), new Town(board.connections.get(i).getTownA().getName(), board.connections.get(i).getTownA().getAmountOfConnections(), board.connections.get(i).getTownA().getxPos(), board.connections.get(i).getTownA().getyPos()), new Town(board.connections.get(i).getTownB().getName(), board.connections.get(i).getTownB().getAmountOfConnections(), board.connections.get(i).getTownB().getxPos(), board.connections.get(i).getTownB().getyPos()), board.connections.get(i).getLength(), board.connections.get(i).getPoint(),1)); jsontest3[i]=temp; } //Sending all the traincard from the traincardstack to the arraystring String[] jsonTCS = new String[board.arrayOfTrainCards.size()]; System.out.println(board.arrayOfTrainCards.size()); for (int i =0; i<board.arrayOfTrainCards.size(); i++) { String temp = serializer.toJson(board.arrayOfTrainCards.get(i)); jsonTCS[i]=temp; } System.out.println(jsonTCS[4]); //DisplayedTrainStack to JSON string String[] jsonDTS = new String[board.displayedTrainStack.size()]; for (int i=0; i<board.displayedTrainStack.size(); i++) { String temp = serializer.toJson(board.displayedTrainStack.get(i)); jsonDTS[i] = temp; } // PlayerPiece to JSON string String[] jsonPlP = new String[board.playerPieces.length]; for (int i = 0; i < board.playerPieces.length; i++) { String temp = serializer.toJson(board.playerPieces[i]); jsonPlP[i] = temp; } String[] cStringsIsTaken = new String[board.connections.size()]; for (int i=0; i<board.connections.size();i++) { String temp = serializer.toJson(0+i); cStringsIsTaken[i]=temp; } /* //DisplayedMissionStack to JSON string String[] jsonMCS = new String[board.displayedMissionStack.size()];; for (int i=0; i<board.displayedMissionStack.size(); i++) { String temp = serializer.toJson(board.displayedMissionStack.get(i)); jsonMCS[i] = temp; } */ //Trains to JSON //String[] jsonTra = null; //Player to Json //TrashTrainCard to JSON //TrashMissionCard to JSON //MissionCards on hand to JSON //TrainCards on hand to JSON //This is where we start sending the JSONS ps.println(activator); //Sending all the connections. for (int i=0; i<board.connections.size();i++) { ps.println(jsontest3[i]); //ps.println(activator + "\n" + jsontest3[i] +/* "\n" + json1 + "\n"+ json2 + "\n" +json3 + "\n"+json4 + "\n"+json5 + "\n"+json6 + "\n"+json7 +*/ "\n"+ jsontest3[5] + "\n"+json9 + "\n"); } //sending the arrayoftraincards. for (int i =0; i<board.arrayOfTrainCards.size();i++) { ps.println(jsonTCS[i]); } //Sending displayedTrainStack for (int i=0; i<board.displayedTrainStack.size(); i++) { ps.println(jsonDTS[i]); } // Sending the playerpieces for (int i = 0; i < board.playerPieces.length; i++) { ps.println(jsonPlP[i]); } for (int i=0; i<board.connections.size();i++) { ps.println(0+i); } /* * //Sending the missionCardStack for (int i=0; * i<board.displayedMissionStack.size(); i++) { ps.println(jsonMCS[i]); } * */ InputStreamReader ir = new InputStreamReader(Sock.getInputStream()); BufferedReader br = new BufferedReader(ir); while (true) { String Message = br.readLine(); System.out.println(Message); if(br.readLine().contains("CanAct")){ isYourTurn= true; } if(activator == "state3"){ ps.println(activator); activator= null; } } }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SlickException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package Ventanas; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; /** * * @author sebas */ public class Inicio extends JFrame implements ActionListener { private JLabel labelClase; private JTextField textFieldRut, textFieldBuscar, textFieldNombre; private JButton botonBuscar, bt1, bt2, bt3, bt4, bt5, bt6, bt7, bt8, bt9, bt10, bt11, bt12, bt13, bt14, bt15, bt16, bt17, bt18, bt19,bt20, bt21, bt22, bt23, bt24, bt25, bt26,bt27, bt28, bt29, bt30, bt31, bt32, bt33, bt34, bt35, bt36, bt37, bt38, bt39, bt40, bt41,bt42,bt43,bt44,bt45,bt46,bt47,bt48,bt49,bt50; public Inicio() { super("UfroTrack"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//finaliza el programa cuando se da click en la X this.setSize(1000, 500); this.setResizable(false); //Labels labelClase = new JLabel("Rut"); labelClase.setText("Rut"); labelClase.setBounds(600, 10, 100, 25); this.add(labelClase); labelClase = new JLabel("Nombre"); labelClase.setText("Nombre"); labelClase.setBounds(10, 10, 100, 25); this.add(labelClase); labelClase = new JLabel("Lunes"); labelClase.setText("Lunes"); labelClase.setBounds(10, 60, 100, 25); this.add(labelClase); labelClase = new JLabel("Martes"); labelClase.setText("Martes"); labelClase.setBounds(110, 60, 100, 25); this.add(labelClase); labelClase = new JLabel("Miercoles"); labelClase.setText("Miercoles"); labelClase.setBounds(210, 60, 100, 25); this.add(labelClase); labelClase = new JLabel("Jueves"); labelClase.setText("Jueves"); labelClase.setBounds(310, 60, 100, 25); this.add(labelClase); labelClase = new JLabel("Viernes"); labelClase.setText("Viernes"); labelClase.setBounds(410, 60, 100, 25); this.add(labelClase); //TextFields textFieldRut = new JTextField(); textFieldRut.setEditable(false); textFieldRut.setBounds(700, 10, 100, 25); textFieldRut.setText(""); this.add(textFieldRut); textFieldBuscar = new JTextField(); textFieldBuscar.setBounds(600, 110, 100, 25); textFieldBuscar.setText("Buscar"); this.add(textFieldBuscar); textFieldNombre = new JTextField(); textFieldNombre.setEditable(false); textFieldNombre.setBounds(110, 10, 100, 25); textFieldNombre.setText(""); this.add(textFieldNombre); //JButtons bt1 = new JButton("Terminar"); bt1.setBounds(0, 100, 100, 25); this.add(bt1); setLayout(null); bt1.addActionListener(this); bt2 = new JButton("Terminar"); bt2.setBounds(0, 125, 100, 25); this.add(bt2); setLayout(null); bt2.addActionListener(this); bt3 = new JButton("Terminar"); bt3.setBounds(0, 175, 100, 25); this.add(bt3); setLayout(null); bt3.addActionListener(this); bt4 = new JButton("Terminar"); bt4.setBounds(0, 200, 100, 25); this.add(bt4); setLayout(null); bt4.addActionListener(this); bt5 = new JButton("Terminar"); bt5.setBounds(0, 250, 100, 25); this.add(bt5); setLayout(null); bt5.addActionListener(this); bt6 = new JButton("Terminar"); bt6.setBounds(0, 275, 100, 25); this.add(bt6); setLayout(null); bt6.addActionListener(this); bt7 = new JButton("Terminar"); bt7.setBounds(0, 325, 100, 25); this.add(bt7); setLayout(null); bt7.addActionListener(this); bt8 = new JButton("Terminar"); bt8.setBounds(0, 350, 100, 25); this.add(bt8); setLayout(null); bt8.addActionListener(this); bt9 = new JButton("Terminar"); bt9.setBounds(0, 400, 100, 25); this.add(bt9); setLayout(null); bt9.addActionListener(this); bt10 = new JButton("Terminar"); bt10.setBounds(0, 425, 100, 25); this.add(bt10); setLayout(null); bt10.addActionListener(this); bt11 = new JButton("Terminar"); bt11.setBounds(100, 100, 100, 25); this.add(bt11); setLayout(null); bt11.addActionListener(this); bt12 = new JButton("Terminar"); bt12.setBounds(100, 125, 100, 25); this.add(bt12); setLayout(null); bt12.addActionListener(this); bt13 = new JButton("Terminar"); bt13.setBounds(100, 175, 100, 25); this.add(bt13); setLayout(null); bt13.addActionListener(this); bt14 = new JButton("Terminar"); bt14.setBounds(100, 200, 100, 25); this.add(bt14); setLayout(null); bt14.addActionListener(this); bt15 = new JButton("Terminar"); bt15.setBounds(100, 250, 100, 25); this.add(bt15); setLayout(null); bt15.addActionListener(this); bt16 = new JButton("Terminar"); bt16.setBounds(100, 275, 100, 25); this.add(bt16); setLayout(null); bt16.addActionListener(this); bt17 = new JButton("Terminar"); bt17.setBounds(100, 325, 100, 25); this.add(bt17); setLayout(null); bt17.addActionListener(this); bt18 = new JButton("Terminar"); bt18.setBounds(100, 350, 100, 25); this.add(bt18); setLayout(null); bt18.addActionListener(this); bt19 = new JButton("Terminar"); bt19.setBounds(100, 400, 100, 25); this.add(bt19); setLayout(null); bt19.addActionListener(this); bt20 = new JButton("Terminar"); bt20.setBounds(100, 425, 100, 25); this.add(bt20); setLayout(null); bt20.addActionListener(this); bt21 = new JButton("Terminar"); bt21.setBounds(200, 100, 100, 25); this.add(bt21); setLayout(null); bt21.addActionListener(this); bt22 = new JButton("Terminar"); bt22.setBounds(200, 125, 100, 25); this.add(bt22); setLayout(null); bt22.addActionListener(this); bt23 = new JButton("Terminar"); bt23.setBounds(200, 175, 100, 25); this.add(bt23); setLayout(null); bt23.addActionListener(this); bt24 = new JButton("Terminar"); bt24.setBounds(200, 200, 100, 25); this.add(bt24); setLayout(null); bt24.addActionListener(this); bt25 = new JButton("Terminar"); bt25.setBounds(200, 250, 100, 25); this.add(bt25); setLayout(null); bt25.addActionListener(this); bt26 = new JButton("Terminar"); bt26.setBounds(200, 275, 100, 25); this.add(bt26); setLayout(null); bt26.addActionListener(this); bt27 = new JButton("Terminar"); bt27.setBounds(200, 325, 100, 25); this.add(bt27); setLayout(null); bt27.addActionListener(this); bt28 = new JButton("Terminar"); bt28.setBounds(200, 350, 100, 25); this.add(bt28); setLayout(null); bt28.addActionListener(this); bt29 = new JButton("Terminar"); bt29.setBounds(200, 400, 100, 25); this.add(bt29); setLayout(null); bt29.addActionListener(this); bt30 = new JButton("Terminar"); bt30.setBounds(200, 425, 100, 25); this.add(bt30); setLayout(null); bt30.addActionListener(this); bt31 = new JButton("Terminar"); bt31.setBounds(300, 100, 100, 25); this.add(bt31); setLayout(null); bt31.addActionListener(this); bt32 = new JButton("Terminar"); bt32.setBounds(300, 125, 100, 25); this.add(bt32); setLayout(null); bt32.addActionListener(this); bt33 = new JButton("Terminar"); bt33.setBounds(300, 175, 100, 25); this.add(bt33); setLayout(null); bt33.addActionListener(this); bt34 = new JButton("Terminar"); bt34.setBounds(300, 200, 100, 25); this.add(bt34); setLayout(null); bt34.addActionListener(this); bt35 = new JButton("Terminar"); bt35.setBounds(300, 250, 100, 25); this.add(bt35); setLayout(null); bt35.addActionListener(this); bt36 = new JButton("Terminar"); bt36.setBounds(300, 275, 100, 25); this.add(bt36); setLayout(null); bt36.addActionListener(this); bt37 = new JButton("Terminar"); bt37.setBounds(300, 325, 100, 25); this.add(bt37); setLayout(null); bt37.addActionListener(this); bt38 = new JButton("Terminar"); bt38.setBounds(300, 350, 100, 25); this.add(bt38); setLayout(null); bt38.addActionListener(this); bt39 = new JButton("Terminar"); bt39.setBounds(300, 400, 100, 25); this.add(bt39); setLayout(null); bt39.addActionListener(this); bt40 = new JButton("Terminar"); bt40.setBounds(300, 425, 100, 25); this.add(bt40); setLayout(null); bt40.addActionListener(this); bt41 = new JButton("Terminar"); bt41.setBounds(400, 100, 100, 25); this.add(bt41); setLayout(null); bt41.addActionListener(this); bt42 = new JButton("Terminar"); bt42.setBounds(400, 125, 100, 25); this.add(bt42); setLayout(null); bt42.addActionListener(this); bt43 = new JButton("Terminar"); bt43.setBounds(400, 175, 100, 25); this.add(bt43); setLayout(null); bt43.addActionListener(this); bt44 = new JButton("Terminar"); bt44.setBounds(400, 200, 100, 25); this.add(bt44); setLayout(null); bt44.addActionListener(this); bt45 = new JButton("Terminar"); bt45.setBounds(400, 250, 100, 25); this.add(bt45); setLayout(null); bt45.addActionListener(this); bt46 = new JButton("Terminar"); bt46.setBounds(400, 275, 100, 25); this.add(bt46); setLayout(null); bt46.addActionListener(this); bt47 = new JButton("Terminar"); bt47.setBounds(400, 325, 100, 25); this.add(bt47); setLayout(null); bt47.addActionListener(this); bt48 = new JButton("Terminar"); bt48.setBounds(400, 350, 100, 25); this.add(bt48); setLayout(null); bt48.addActionListener(this); bt49 = new JButton("Terminar"); bt49.setBounds(400, 400, 100, 25); this.add(bt49); setLayout(null); bt49.addActionListener(this); bt50 = new JButton("Terminar"); bt50.setBounds(400, 425, 100, 25); this.add(bt50); setLayout(null); bt50.addActionListener(this); botonBuscar = new JButton("Buscar"); botonBuscar.setBounds(600, 135, 100, 25); this.add(botonBuscar); setLayout(null); botonBuscar.addActionListener(this); } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Inicio().setVisible(true); } }); } @Override public void actionPerformed(ActionEvent ae) { if(ae.getSource() == botonBuscar ){ if(comboCategoria.getSelectedItem()=="Codigo"){ ResultadoBusqueda ventana = new ResultadoBusqueda(true,textFieldBuscar.getText()); ventana.setVisible(true); setVisible(false); } else if(comboCategoria.getSelectedItem()=="Profesor"){ ResultadoBusqueda ventana = new ResultadoBusqueda(false,textFieldBuscar.getText()); ventana.setVisible(true); setVisible(false); } } if (ae.getSource() == bt1) { } if (ae.getSource() == bt2) { } if (ae.getSource() == bt3) { } if (ae.getSource() == bt4) { } if (ae.getSource() == bt5) { } if (ae.getSource() == bt6) { } if (ae.getSource() == bt7) { } if (ae.getSource() == bt8) { } if (ae.getSource() == bt9) { } if (ae.getSource() == bt10) { } if (ae.getSource() == bt11) { } if (ae.getSource() == bt12) { } if (ae.getSource() == bt13) { } if (ae.getSource() == bt14) { } if (ae.getSource() == bt15) { } if (ae.getSource() == bt16) { } if (ae.getSource() == bt17) { } if (ae.getSource() == bt18) { } if (ae.getSource() == bt19) { } if (ae.getSource() == bt20) { } if (ae.getSource() == bt21) { } if (ae.getSource() == bt22) { } if (ae.getSource() == bt23) { } if (ae.getSource() == bt24) { } if (ae.getSource() == bt25) { } if (ae.getSource() == bt26) { } if (ae.getSource() == bt27) { } if (ae.getSource() == bt28) { } if (ae.getSource() == bt29) { } if (ae.getSource() == bt30) { } if (ae.getSource() == bt31) { } if (ae.getSource() == bt32) { } if (ae.getSource() == bt33) { } if (ae.getSource() == bt34) { } if (ae.getSource() == bt35) { } if (ae.getSource() == bt36) { } if (ae.getSource() == bt37) { } if (ae.getSource() == bt38) { } if (ae.getSource() == bt39) { } if (ae.getSource() == bt40) { } if (ae.getSource() == bt41) { } if (ae.getSource() == bt42) { } if (ae.getSource() == bt43) { } if (ae.getSource() == bt44) { } if (ae.getSource() == bt45) { } if (ae.getSource() == bt46) { } if (ae.getSource() == bt47) { } if (ae.getSource() == bt48) { } if (ae.getSource() == bt49) { } if (ae.getSource() == bt50) { } } }
package com.adobe.phonegap.csdk; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.util.Log; import com.adobe.creativesdk.typekit.AdobeTypekitFont; import com.adobe.creativesdk.typekit.AdobeTypekitFontBrowser; import com.adobe.creativesdk.typekit.AdobeTypekitManager; import com.adobe.creativesdk.foundation.auth.AdobeUXAuthManager; import com.adobe.creativesdk.typekit.TypekitNotification; import com.adobe.creativesdk.typekit.UserNotAuthenticatedException; import java.util.ArrayList; import java.util.Observable; import java.util.Observer; import java.util.concurrent.Future; /** * This class exposes methods in Cordova that can be called from JavaScript. */ public class Typekit extends CordovaPlugin implements Observer { private static final String LOG_TAG = "CreativeSDK_Typekit"; private AdobeUXAuthManager mUXAuthManager = AdobeUXAuthManager.getSharedAuthManager(); private AdobeTypekitManager mTypekitManager = AdobeTypekitManager.getInstance(); private static CallbackContext mCallbackContext; private static ArrayList<AdobeTypekitFont> syncList; /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext The callback context from which we were invoked. */ @SuppressLint("NewApi") public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { mCallbackContext = callbackContext; if (action.equals("launchFontBrowser")) { AdobeTypekitFontBrowser.launchActivity(this.cordova.getActivity()); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, args.getString(0))); } else if (action.equals("syncFonts")) { if (mUXAuthManager.isAuthenticated()) { // call sync try { mTypekitManager.init(this.cordova.getActivity()); mTypekitManager.addObserver(this); mTypekitManager.syncFonts(); PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } catch (UserNotAuthenticatedException e) { callbackContext.error("user not logged in"); } } else { callbackContext.error("user not logged in"); } } else if (action.equals("getFont")) { String fontName = args.getString(0); Log.d(LOG_TAG, "getting font named = " + fontName); boolean found = false; if (syncList != null) { for (int i=0; i<syncList.size(); i++) { AdobeTypekitFont font = syncList.get(i); if (font.postscriptName().equals(fontName)) { found = true; font.getFontFile(new AdobeTypekitFont.ITypekitCallback<java.util.concurrent.Future,java.lang.String>() { @Override public void onSuccess(AdobeTypekitFont adobeTypekitFont, Future future) { Log.d(LOG_TAG, "download started"); } @Override public void onError(AdobeTypekitFont adobeTypekitFont, String s) { callbackContext.error("could not download font"); } }, new AdobeTypekitFont.ITypekitCallback<AdobeTypekitFont.FontFilePath,java.lang.String>() { @Override public void onSuccess(AdobeTypekitFont adobeTypekitFont, AdobeTypekitFont.FontFilePath fontFilePath) { Log.d(LOG_TAG, "downloaded = " + adobeTypekitFont.isDownloaded()); Log.d(LOG_TAG, "file path = " + fontFilePath.assetFontFilePath); Log.d(LOG_TAG, "ack = " + fontFilePath.fontFile.getAbsolutePath()); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("name", adobeTypekitFont.postscriptName()); jsonObject.put("downloaded", adobeTypekitFont.isDownloaded()); jsonObject.put("filePath", "file://" + fontFilePath.fontFile.getAbsolutePath()); } catch (JSONException e) { // never happens } callbackContext.success(jsonObject); } @Override public void onError(AdobeTypekitFont adobeTypekitFont, String s) { callbackContext.error("could not download font"); } }); break; } } if (!found) { callbackContext.error("could not find font"); } } } else { return false; } return true; } public void update(Observable observable, Object data) { TypekitNotification notification = (TypekitNotification) data; switch (notification.getTypekitEvent()) { case TypekitNotification.Event.FONT_SELECTION_SYNC_START: Log.d(LOG_TAG, "Syncing Typekit Synced Fonts list..."); break; case TypekitNotification.Event.FONT_SELECTION_REFRESH: syncList = AdobeTypekitFont.getFonts(); JSONArray fontList = new JSONArray(); for (int i=0; i<syncList.size(); i++) { AdobeTypekitFont font = syncList.get(i); fontList.put(font.postscriptName()); Log.d(LOG_TAG, font.postscriptName()); } mCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fontList)); break; case TypekitNotification.Event.FONT_SELECTION_SYNC_ERROR: Log.d(LOG_TAG, "Error: " + notification.getTypekitEvent()); break; case TypekitNotification.Event.FONT_NETWORK_ERROR: Log.d(LOG_TAG, "Error: " + notification.getTypekitEvent()); break; case TypekitNotification.Event.FONT_CACHE_EXPIRY: Log.d(LOG_TAG, "Warning: " + notification.getTypekitEvent()); break; default: break; } } }
package com.shuimin.pond.db; import com.shuimin.common.S; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.InputStream; import java.lang.reflect.Type; import java.sql.*; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Set; import static com.shuimin.common.S.dump; /** * <pre> * jdbc operator * </pre> */ public class JDBCOper implements Closeable { private static final Type[] SUPPORTED_TYPES = new Type[]{ Byte.TYPE, Character.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE, Boolean.TYPE, String.class, InputStream.class }; public final Connection conn; static Logger logger = LoggerFactory.getLogger(JDBCOper.class); private PreparedStatement pstmt = null; // //use under jdk -1.4 // @SuppressWarnings("unused") // private Object guarder = new Object() { // public void finalize() throws Throwable // outer.disposeAll(); private ResultSet rs = null; public JDBCOper(Connection conn) { this.conn = conn; } /** * <pre> * ResultSet#getObject java.sql.* * * </pre> * * @param o in * @return out */ public static Object normalizeValue(Object o) { if (o instanceof java.sql.Date) { return new Date(((java.sql.Date) o).getTime()); } if (o instanceof java.sql.Time) { return new Date(((java.sql.Time) o).getTime()); } if (o instanceof Timestamp) { return new Date(((Timestamp) o).getTime()); } return o; } /** * release bo */ @Override public void close() { _closeRs(); _closeStmt(); _closeConn(); } private void _closeStmt() { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { _debug("sql except when closing stmt"); } } } private void _closeConn() { if (conn != null) { try { conn.close(); } catch (SQLException e) { _debug("sql except when closing conn"); } } } private void _closeRs() { if (rs != null) { try { rs.close(); } catch (SQLException e) { _debug("sql except when closing rs"); } } } public Set<String> getTableNames() throws SQLException { Set<String> tables = new HashSet<>(); DatabaseMetaData dbMeta = conn.getMetaData(); ResultSet rs = dbMeta.getTables( null, null, "%", new String[]{"TABLE"} ); while (rs.next()) { tables.add(rs.getString("table_name")); } return tables; } public Set<String> getTableAndViewNames() throws SQLException { Set<String> tables = new HashSet<>(); DatabaseMetaData dbMeta = conn.getMetaData(); ResultSet rs = dbMeta.getTables( null, null, "%", new String[]{"TABLE", "VIEW"} ); while (rs.next()) { tables.add(rs.getString("table_name")); } return tables; } public void dropTable(String name) throws SQLException { execute(String.format("DROP TABLE IF EXISTS %s", name)); } public void createIndex(String name, String table, String... columns) throws SQLException { execute(String.format("CREATE INDEX %s ON %s(%s)", name, table, String.join(", ", Arrays.asList(columns)))); } public void dropIndex(String name, String table) throws SQLException { execute(String.format("DROP INDEX %s", name)); } /** * @param sql sql * @param params sql,InputStream * @return */ public int execute(String sql, Object[] params) throws SQLException { if (pstmt != null) { _closeStmt(); } pstmt = conn.prepareStatement(sql); if (params != null) { for (int i = 0; i < params.length; i++) { setParam(pstmt, i + 1, params[i]); } } _debug(sql + "\n" + S.dump(params)); if (rs != null) { _closeRs(); } return pstmt.executeUpdate(); } public ResultSet query(String sql) throws SQLException { return query(sql, null); } /** * execute SQL statements to Query */ public ResultSet query(String sql, Object[] params) throws SQLException { if (pstmt != null) { _closeStmt(); } pstmt = conn.prepareStatement(sql); if (params != null) { for (int i = 0; i < params.length; i++) { //untested pstmt.setObject(i + 1, params[i]); } } _debug(sql + "\n" + S.dump(params)); if (rs != null) { _closeRs(); } rs = pstmt.executeQuery(); return rs; } public int execute(String sql) throws SQLException { return execute(sql, null); } // /** // * execute SQL statements to Update,Modify or Delete // */ // public int execute(String sql, String[] params) throws SQLException { // int num = 0; // if (pstmt != null) { // _closeStmt(); // pstmt = conn.prepareStatement(sql); // if (params != null) { // for (int i = 0; i < params.length; i++) { // pstmt.setString(i + 1, params[i]); // _debug(pstmt); // num = pstmt.execute(); // return num; public void transactionStart() throws SQLException { synchronized (conn) { conn.setAutoCommit(false); } } public void transactionCommit() throws SQLException { try { synchronized (conn) { conn.commit(); } } catch (SQLException e) { conn.rollback(); throw e; } finally { synchronized (conn) { conn.setAutoCommit(true); } } } /** * <p>jdbc RollBack * </p> */ public void rollback() throws SQLException { conn.rollback(); } private void _debug(Object o) { if (logger != null) { logger.debug(dump(o)); } } private void setParam(PreparedStatement pstmt, int idx, Object val) throws SQLException { if (val == null) throw new NullPointerException("Please use default value instead of null"); // if (val == null) { // //TODO ugly // try { // pstmt.setNull(idx, Types.VARCHAR); // } catch (SQLException e) { // try { // pstmt.setNull(idx, Types.NUMERIC); // } catch (SQLException e1) { // try { // pstmt.setNull(idx, Types.BLOB); // } catch (SQLException e2) { // logger.error(" :X setNull fail!" + e2.getMessage()); // e2.printStackTrace(); // return; if (setParam_try_primitive(pstmt, idx, val) // || setParam_try_UploadFile(pstmt, idx, val) || setParam_try_common(pstmt, idx, val)) return; throw new UnsupportedTypeException(val.getClass(), SUPPORTED_TYPES); } /* we`ve commented this because the dependency of UploadFile have been moved. */ // private boolean setParam_try_UploadFile(PreparedStatement pstmt, // int idx, // Object o) throws SQLException { // if (o instanceof UploadFile) { // pstmt.setBinaryStream(idx, ((UploadFile) o).inputStream()); // return true; // return false; private boolean setParam_try_common(PreparedStatement pstmt, int idx, Object o) throws SQLException { if (o instanceof String) { pstmt.setString(idx, (String) o); return true; } // else if (o instanceof Date) { // pstmt.setTimestamp(idx,new Timestamp(((Date) o).getTime())); // return true; if (o instanceof InputStream) { pstmt.setBinaryStream(idx, (InputStream) o); return true; } return false; } private boolean setParam_try_primitive(PreparedStatement pstmt, int idx, Object o) throws SQLException { if (o instanceof Integer) { pstmt.setInt(idx, (Integer) o); return true; } else if (o instanceof Long) { pstmt.setLong(idx, (Long) o); return true; } else if (o instanceof Short) { pstmt.setShort(idx, (Short) o); return true; } else if (o instanceof Character) { pstmt.setString(idx, String.valueOf(o)); return true; } else if (o instanceof Float) { pstmt.setFloat(idx, (Float) o); return true; } else if (o instanceof Double) { pstmt.setDouble(idx, (Double) o); return true; } else if (o instanceof Byte) { pstmt.setByte(idx, (Byte) o); return true; } else if (o instanceof Boolean) { pstmt.setBoolean(idx, (Boolean) o); return true; } return false; } }
/** * This file was automatically generated from Params.cs * w/ further modifications by: * @author Christoph M. Wintersteiger (cwinter) **/ package com.microsoft.z3; /** * A ParameterSet represents a configuration in the form of Symbol/value pairs. **/ public class Params extends Z3Object { /** * Adds a parameter setting. **/ public void Add(Symbol name, boolean value) throws Z3Exception { Native.paramsSetBool(Context().nCtx(), NativeObject(), name.NativeObject(), (value) ? true : false); } /** * Adds a parameter setting. **/ public void Add(Symbol name, double value) throws Z3Exception { Native.paramsSetDouble(Context().nCtx(), NativeObject(), name.NativeObject(), value); } /** * Adds a parameter setting. **/ public void Add(Symbol name, Symbol value) throws Z3Exception { Native.paramsSetSymbol(Context().nCtx(), NativeObject(), name.NativeObject(), value.NativeObject()); } /** * Adds a parameter setting. **/ public void Add(String name, boolean value) throws Z3Exception { Native.paramsSetBool(Context().nCtx(), NativeObject(), Context().MkSymbol(name).NativeObject(), value); } /** * Adds a parameter setting. **/ public void Add(String name, int value) throws Z3Exception { Native.paramsSetUint(Context().nCtx(), NativeObject(), Context() .MkSymbol(name).NativeObject(), value); } /** * Adds a parameter setting. **/ public void Add(String name, double value) throws Z3Exception { Native.paramsSetDouble(Context().nCtx(), NativeObject(), Context() .MkSymbol(name).NativeObject(), value); } /** * Adds a parameter setting. **/ public void Add(String name, Symbol value) throws Z3Exception { Native.paramsSetSymbol(Context().nCtx(), NativeObject(), Context() .MkSymbol(name).NativeObject(), value.NativeObject()); } /** * A string representation of the parameter set. **/ public String toString() { try { return Native.paramsToString(Context().nCtx(), NativeObject()); } catch (Z3Exception e) { return "Z3Exception: " + e.getMessage(); } } Params(Context ctx) throws Z3Exception { super(ctx, Native.mkParams(ctx.nCtx())); } void IncRef(long o) throws Z3Exception { Context().Params_DRQ().IncAndClear(Context(), o); super.IncRef(o); } void DecRef(long o) throws Z3Exception { Context().Params_DRQ().Add(o); super.DecRef(o); } }
package dnss.enums; public enum Advancement { PRIMARY (0), SECONDARY (1), TERTIARY (2); public final int advancement; Advancement(int job) { this.advancement = job; } public static Advancement getAdvancement(int job) { for (Advancement e : Advancement.values()) { if (e.advancement == job) { return e; } } throw new RuntimeException("Invalid Advancement: " + job); } public int toInt() { return advancement; } }
package mazegenerator; import java.util.ArrayList; import java.util.Arrays; import util.MathUtil; /** * * @author mallory */ public class MazeGenerator { public static void main(String[] args) throws Exception { // byte value = 0; // for(; value < 33; value++){ // MazeTile tile = new MazeTile(value); // System.out.println(tile + " " + value); // System.out.println(); // MazeTile[][] maze = new MazeTile[2][2]; // maze[0][0] = new MazeTile(true,false,true,false); // maze[0][1] = new MazeTile(false,true,true,false); // maze[1][0] = new MazeTile(true,false,false,true); // maze[1][1] = new MazeTile(false,true,false,true); Maze maze = new Maze(47, 11, 1,1); //Test //Test 2 maze.generate(); System.out.print(maze.toString()); } }
/** * Clase ventanaPrincipal * @author curso14/7803 * @version 1.0 * @since 19/11/2015 * <br> * <p> * Esta clase corresponde a la pantalla principal del programa y sus mens * </p> */ package ventanaPrincipal; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Scanner; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import alumnos.VentanaCalificaciones; //import alumnos.VentanaInteresado; import cursos.VentanaCursos; import cursos.VentanaGrupos; import cursos.ventanaModulo; import matricula.VentanaFormaPago; import matricula.VentanaMatricula; public class VentanaPrincipal extends JFrame implements ActionListener { private JMenuBar barraMenu; private JMenu menuAlumnos, menuCursos, menuCalificacion, menuMatricula, menuAyuda, menuSalir; private JMenuItem matriculado, interesado, cursos, grupos, modulos, calificacion, matricula, formaPago, ayuda, salir; public static String usuario = "root"; public static String pwd = "root"; public static String bd = "nowedb"; public static basedatos.ConexionBaseDatos conexion = null; public VentanaPrincipal () { setLayout(null); Fondo fondo; Toolkit t = Toolkit.getDefaultToolkit(); Dimension tamaoPantalla = Toolkit.getDefaultToolkit().getScreenSize(); this.setLayout(null); Image icon = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/img/logo_nowe.gif")); setIconImage(icon); this.setTitle("Programa de Gestin Nowe"); setSize(tamaoPantalla.width, tamaoPantalla.height); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); fondo = new Fondo(); add(fondo); barraMenu = new JMenuBar(); setJMenuBar(barraMenu); menuAlumnos = new JMenu ("Alumnos"); barraMenu.add(menuAlumnos); matriculado = new JMenuItem("Matriculado"); matriculado.addActionListener(this); menuAlumnos.add(matriculado); interesado = new JMenuItem("Interesado"); interesado.addActionListener(this); menuAlumnos.add(interesado); menuCursos = new JMenu ("Cursos"); barraMenu.add(menuCursos); cursos = new JMenuItem("Cursos"); cursos.addActionListener(this); menuCursos.add(cursos); grupos = new JMenuItem("Grupos"); grupos.addActionListener(this); menuCursos.add(grupos); modulos = new JMenuItem("Mdulos"); modulos.addActionListener(this); menuCursos.add(modulos); menuCalificacion = new JMenu ("Calificacin"); barraMenu.add(menuCalificacion); calificacion = new JMenuItem("Calificacin"); calificacion.addActionListener(this); menuCalificacion.add(calificacion); menuMatricula = new JMenu ("Matrcula"); barraMenu.add(menuMatricula); matricula = new JMenuItem("Matrcula"); matricula.addActionListener(this); menuMatricula.add(matricula); formaPago = new JMenuItem("Forma de Pago"); formaPago.addActionListener(this); menuMatricula.add(formaPago); menuAyuda = new JMenu ("Ayuda"); barraMenu.add(menuAyuda); ayuda = new JMenuItem("?"); ayuda.addActionListener(this); menuAyuda.add(ayuda); menuSalir = new JMenu ("Salir"); barraMenu.add(menuSalir); salir = new JMenuItem("Salir"); salir.addActionListener(this); menuSalir.add(salir);} public void actionPerformed(ActionEvent e) { if (e.getSource()== cursos) { conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaCursos ventana=new VentanaCursos(); ventana.setVisible(true); } if (e.getSource()== modulos){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); ventanaModulo ventana = new ventanaModulo(); ventana.setVisible(true); } /*if (e.getSource()== interesado){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaInteresado ne = new VentanaInteresado(); ne.setVisible(true); }*/ if (e.getSource()== grupos){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaGrupos ne = new VentanaGrupos(); ne.setVisible(true); } if (e.getSource()== matricula){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaMatricula ventana = new VentanaMatricula(); ventana.setVisible(true); } if (e.getSource()== calificacion){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaCalificaciones ventana = new VentanaCalificaciones(); ventana.setVisible(true); } if (e.getSource()== formaPago){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaFormaPago ventana = new VentanaFormaPago(); ventana.setVisible(true); } if (e.getSource()== salir){ System.exit(0); } } }
package eu.qualimaster.base.pipeline; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.apache.log4j.Logger; import eu.qualimaster.Configuration; import eu.qualimaster.common.switching.TupleSender; /** * Provide the information of the node host in Apache Storm. * @author Cui Qin * */ public class NodeHostStorm { private static final Logger LOGGER = Logger.getLogger(NodeHostStorm.class); /** * Return the node host based on the configuration in Storm. * @param topologyName the topology name * @param nodeName the host node * @return the host name */ public static String getHost(String topologyName, String nodeName) { String host = "localhost"; LOGGER.info("Getting the host with " + topologyName + ", " + nodeName + ", " + Configuration.getNimbus()); String nimbusHost = "192.168.0.1"; //Configuration.getNimbus() TODO: hardcode for now, need to be solved. host = new CollectingTopologyInfo(topologyName, nodeName, nimbusHost, Configuration.getThriftPort()).getExecutorHost(); return host; } public static List<TupleSender> createTupleSenders(String topologyName, String nodeName, int port) { List<TupleSender> senders = new ArrayList<TupleSender>(); LOGGER.info("Getting the host with " + topologyName + ", " + nodeName + ", " + Configuration.getNimbus()); String nimbusHost = "192.168.0.1"; //Configuration.getNimbus() TODO: hardcode for now, need to be solved. List<String> hosts = new CollectingTopologyInfo(topologyName, nodeName, nimbusHost, Configuration.getThriftPort()).getExecutorHostList(); LOGGER.info("The executor: " + nodeName + "-- host size: " + hosts.size()); for (String host : hosts) { TupleSender sender = new TupleSender(host, port); // while(!sender.isConnected()) { // sender.connect(); senders.add(sender); } return senders; } public static TupleSender shuffleSender(List<TupleSender> senders) { TupleSender result = null; if (!senders.isEmpty()) { int index = new Random().nextInt(senders.size()); result = senders.get(index); } return result; } }
package io.github.manami.cache; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Sets.newHashSet; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; import static org.apache.http.HttpVersion.HTTP_1_1; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.gson.Gson; import io.github.manami.cache.populate.AdbEntry; import io.github.manami.cache.populate.AnimeOfflineDatabase; import io.github.manami.cache.strategies.headlessbrowser.HeadlessBrowserRetrievalStrategy; import io.github.manami.dto.AnimeType; import io.github.manami.dto.entities.Anime; import io.github.manami.dto.entities.InfoLink; import io.github.manami.dto.entities.RecommendationList; import java.io.IOException; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.net.URL; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutionException; import javax.inject.Inject; import javax.inject.Named; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Pair; import org.apache.http.HttpStatus; 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.HttpClients; import org.apache.http.protocol.HttpProcessorBuilder; import org.slf4j.MDC; /** * Facade for all inquiries against a cache. * It orchestrates the use of concrete {@link io.github.manami.cache.Cache} * implementations. */ @Slf4j @Named public final class CacheManager implements Cache { private static final int TITLE_MAX_LENGTH = 200; private final HeadlessBrowserRetrievalStrategy headlessBrowserRetrievalStrategy; /** * Key: URL of the anime, Value: Instance of the anime including all meta * data. */ private LoadingCache<InfoLink, Optional<Anime>> animeEntryCache = null; /** * Key: URL of the anime, Value: Set of anime urls which are related to the * anime url in the key */ private LoadingCache<InfoLink, Set<InfoLink>> relatedAnimeCache = null; /** * Key: URL of the anime, Value: List of anime urls which are recommended * titles to the anime url with their amount of occurence */ private LoadingCache<InfoLink, RecommendationList> recommendationsCache = null; @Inject public CacheManager(final HeadlessBrowserRetrievalStrategy headlessBrowserRetrievalStrategy) { this.headlessBrowserRetrievalStrategy = headlessBrowserRetrievalStrategy; buildAnimeCache(); buildRelatedAnimeCache(); buildRecommendationsCache(); new Thread(() -> { try { populateCache(); } catch (Exception e) { log.error("Unable to populate cache.", e); } }).start(); } private void populateCache() throws IOException, URISyntaxException { final CloseableHttpClient hc = HttpClients .custom().setHttpProcessor(HttpProcessorBuilder.create().build()).build(); final HttpGet request = new HttpGet(new URL("https://raw.githubusercontent.com/manami-project/anime-offline-database/master/anime-offline-database.json").toURI()); newArrayList(request.getAllHeaders()).forEach(request::removeHeader); request.setProtocolVersion(HTTP_1_1); request.setHeader("Host", "raw.githubusercontent.com"); request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:66.0) Gecko/20100101 Firefox/66.0"); request.setHeader("Accept", "application/json"); final CloseableHttpResponse execute = hc.execute(request); if (execute.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IllegalStateException("Cache data download failed."); } List<AdbEntry> adbEntries = new Gson().fromJson( new InputStreamReader(execute.getEntity().getContent(), UTF_8), AnimeOfflineDatabase.class ).data .parallelStream() .peek(it -> it.sources = it.sources.stream() .filter(source -> source.startsWith("https://myanimelist.net")) .collect(toList())) .filter(it -> it.sources.size() == 1) .collect(toList()); adbEntries.parallelStream() .map(it -> { Anime anime = new Anime(it.title, new InfoLink(it.sources.get(0))); anime.setType(AnimeType.findByName(it.type)); anime.setEpisodes(it.episodes); anime.setPicture(it.picture); anime.setThumbnail(it.thumbnail); anime.setLocation("/"); Set<InfoLink> relations = it.relations.stream() .filter(source -> source.startsWith("https://myanimelist.net")) .map(InfoLink::new) .collect(toSet()); return Pair.of(anime, relations); }) .filter( it -> Anime.isValidAnime(it.getKey())) .map( it -> { relatedAnimeCache.put(it.getKey().getInfoLink(), it.getValue()); return it.getKey(); }) .forEach( it -> animeEntryCache.put(it.getInfoLink(), Optional.of(it))); } @Override public Optional<Anime> fetchAnime(final InfoLink infoLink) { MDC.put("infoLink", infoLink.getUrl()); Optional<Anime> cachedEntry = Optional.empty(); if (!infoLink.isValid()) { return cachedEntry; } try { cachedEntry = animeEntryCache.get(infoLink); if (!cachedEntry.isPresent() || cachedEntry.get().getTitle().length() > TITLE_MAX_LENGTH) { log.warn("No meta data entry extracted or title way too long. Invalidating cache entry and refetching it."); animeEntryCache.invalidate(infoLink); cachedEntry = animeEntryCache.get(infoLink); log.warn("Result after reinitialising cache entry [{}]", cachedEntry); } } catch (final ExecutionException e) { log.error("Error fetching anime entry from cache."); return Optional.empty(); } return cachedEntry; } @Override public Set<InfoLink> fetchRelatedAnime(final InfoLink infoLink) { Set<InfoLink> ret = newHashSet(); if (!infoLink.isValid()) { return ret; } try { ret = relatedAnimeCache.get(infoLink); if (ret == null) { log.warn("No related anime in cache. Invalidating cache entry and refetching it."); relatedAnimeCache.invalidate(infoLink); ret = relatedAnimeCache.get(infoLink); log.warn("Result after reinitialising cache entry for [{}]", ret); } } catch (final ExecutionException e) { log.error("Unable to fetch related anime list from cache."); } return ret; } @Override public RecommendationList fetchRecommendations(final InfoLink infoLink) { RecommendationList ret = new RecommendationList(); if (!infoLink.isValid()) { return ret; } try { ret = recommendationsCache.get(infoLink); if (ret == null || ret.isEmpty()) { log.warn("No recommendations in cache entry. Invalidating cache entry and refetching it."); recommendationsCache.invalidate(infoLink); ret = recommendationsCache.get(infoLink); log.warn("Result after reinitialising cache entry for [{}]", ret); } } catch (final ExecutionException e) { log.error("Unable to fetch recommendations from cache for."); } return ret; } private void buildAnimeCache() { animeEntryCache = CacheBuilder.newBuilder().build(new CacheLoader<InfoLink, Optional<Anime>>() { @Override public Optional<Anime> load(final InfoLink infoLink) throws Exception { return headlessBrowserRetrievalStrategy.fetchAnime(infoLink); } }); } private void buildRelatedAnimeCache() { relatedAnimeCache = CacheBuilder.newBuilder().build(new CacheLoader<InfoLink, Set<InfoLink>>() { @Override public Set<InfoLink> load(final InfoLink infoLink) throws Exception { log.debug("no cache hit for {}", infoLink); return headlessBrowserRetrievalStrategy.fetchRelatedAnime(infoLink); } }); } private void buildRecommendationsCache() { recommendationsCache = CacheBuilder.newBuilder().build(new CacheLoader<InfoLink, RecommendationList>() { @Override public RecommendationList load(final InfoLink infoLink) throws Exception { return headlessBrowserRetrievalStrategy.fetchRecommendations(infoLink); } }); } }
package mnm.mods.tabbychat; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.List; import java.util.regex.Pattern; import javax.annotation.Nullable; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import mnm.mods.tabbychat.api.AddonManager; import mnm.mods.tabbychat.api.Chat; import mnm.mods.tabbychat.api.TabbyAPI; import mnm.mods.tabbychat.api.filters.FilterVariable; import mnm.mods.tabbychat.core.GuiChatTC; import mnm.mods.tabbychat.core.GuiNewChatTC; import mnm.mods.tabbychat.core.GuiSleepTC; import mnm.mods.tabbychat.core.api.TabbyAddonManager; import mnm.mods.tabbychat.core.api.TabbyEvents; import mnm.mods.tabbychat.extra.ChatAddonAntiSpam; import mnm.mods.tabbychat.extra.ChatLogging; import mnm.mods.tabbychat.extra.filters.FilterAddon; import mnm.mods.tabbychat.gui.settings.GuiSettingsScreen; import mnm.mods.tabbychat.settings.ServerSettings; import mnm.mods.tabbychat.settings.TabbySettings; import mnm.mods.tabbychat.util.TabbyRef; import mnm.mods.util.MnmUtils; import mnm.mods.util.ReflectionHelper; import mnm.mods.util.gui.config.SettingPanel; import mnm.mods.util.update.UpdateChecker; import mnm.mods.util.update.UpdateRequest; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiChat; import net.minecraft.client.gui.GuiIngame; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiSleepMP; import net.minecraft.entity.player.EntityPlayer; public abstract class TabbyChat extends TabbyAPI { private static final Logger LOGGER = LogManager.getLogger(TabbyRef.MOD_ID); private static TabbyChat instance; private AddonManager addonManager; private TabbyEvents events; public TabbySettings settings; @Nullable public ServerSettings serverSettings; private File dataFolder; private InetSocketAddress currentServer; private boolean updateChecked; protected static void setInstance(TabbyChat inst) { instance = inst; setAPI(inst); } public static TabbyChat getInstance() { return instance; } public static Logger getLogger() { return LOGGER; } @Override public Chat getChat() { return GuiNewChatTC.getInstance().getChatManager(); } @Override public AddonManager getAddonManager() { return this.addonManager; } public TabbyEvents getEventManager() { return this.events; } public void openSettings(SettingPanel<?> setting) { GuiSettingsScreen screen = new GuiSettingsScreen(setting); Minecraft.getMinecraft().displayGuiScreen(screen); } public InetSocketAddress getCurrentServer() { return this.currentServer; } public File getDataFolder() { return dataFolder; } @Override public void registerSettings(Class<? extends SettingPanel<?>> setting) { GuiSettingsScreen.registerSetting(setting); } // Protected methods protected abstract void loadResourcePack(File source, String name); protected void setConfigFolder(File config) { this.dataFolder = new File(config, TabbyRef.MOD_ID); } protected void init() { loadUtils(); addonManager = new TabbyAddonManager(); events = new TabbyEvents(addonManager); // Set global settings settings = new TabbySettings(); // Load settings settings.loadSettingsFile(); // Save settings settings.saveSettingsFile(); addonManager.registerListener(new ChatAddonAntiSpam()); addonManager.registerListener(new FilterAddon()); addonManager.registerListener(new ChatLogging(new File("logs/chat"))); addFilterVariables(); MnmUtils.getInstance().setChatProxy(new TabbedChatProxy()); } private void addFilterVariables() { final Minecraft mc = Minecraft.getMinecraft(); addonManager.setFilterConstant("player", mc.getSession().getUsername()); final Function<EntityPlayer, String> names = new Function<EntityPlayer, String>() { @Override public String apply(EntityPlayer player) { return Pattern.quote(player.getCommandSenderName()); } }; addonManager.setFilterVariable("onlineplayer", new FilterVariable() { @Override public String getVar() { @SuppressWarnings("unchecked") List<String> playerNames = Lists.transform(mc.theWorld.playerEntities, names); return Joiner.on('|').appendTo(new StringBuilder("(?:"), playerNames).append(')').toString(); } }); } protected void onRender(GuiScreen currentScreen) { if (currentScreen instanceof GuiChat && !(currentScreen instanceof GuiChatTC)) { Minecraft mc = Minecraft.getMinecraft(); // Get the default text via Reflection String inputBuffer = ""; try { inputBuffer = (String) ReflectionHelper.getFieldValue(GuiChat.class, currentScreen, TabbyRef.DEFAULT_INPUT_FIELD_TEXT); } catch (Exception e) {} if (currentScreen instanceof GuiSleepMP) { mc.displayGuiScreen(new GuiSleepTC()); } else { mc.displayGuiScreen(new GuiChatTC(inputBuffer)); } } } protected void onJoin(SocketAddress address) { if (address instanceof InetSocketAddress) { this.currentServer = (InetSocketAddress) address; } // Set server settings serverSettings = new ServerSettings(currentServer); serverSettings.loadSettingsFile(); serverSettings.saveSettingsFile(); try { hookIntoChat(Minecraft.getMinecraft().ingameGUI); } catch (Exception e) { LOGGER.fatal("Unable to hook into chat. This is bad.", e); } // load chat File conf = serverSettings.getFile().getParentFile(); try { GuiNewChatTC.getInstance().getChatManager().loadFrom(conf); } catch (IOException e) { LOGGER.warn("Unable to load chat data.", e); } // update check updateCheck(); } protected void onDisconnect() { if (serverSettings == null) { return; } File conf = serverSettings.getFile().getParentFile(); try { GuiNewChatTC.getInstance().getChatManager().saveTo(conf); } catch (IOException e) { LOGGER.warn("Unable to save chat data.", e); } serverSettings = null; } private void updateCheck() { if (settings.general.checkUpdates.getValue() && !updateChecked) { UpdateRequest request = new UpdateRequest(TabbyRef.MOD_ID); UpdateChecker checker = new UpdateChecker(request, TabbyRef.MOD_REVISION); checker.start(); updateChecked = true; } } private void loadUtils() { File source = findClasspathRoot(MnmUtils.class); loadResourcePack(source, "Mnm Utils"); try { Minecraft.class.getMethod("getMinecraft"); // I'm in dev, fix things. loadResourcePack(findClasspathRoot(TabbyChat.class), "TabbyChat-Common"); } catch (Exception e) { // unimportant } } private File findClasspathRoot(Class<?> clas) { String str = clas.getProtectionDomain().getCodeSource().getLocation().toString(); str = str.replace("/" + clas.getCanonicalName().replace('.', '/').concat(".class"), ""); str = str.replace('\\', '/'); if (str.endsWith("!")) { str = str.substring(0, str.length() - 1); } if (str.startsWith("jar:")) { str = str.substring(4); } if (str.startsWith("file:/")) { str = str.substring(6); } return new File(str); } private void hookIntoChat(GuiIngame guiIngame) throws Exception { if (!GuiNewChatTC.class.isAssignableFrom(guiIngame.getChatGUI().getClass())) { // guiIngame.persistantChatGUI = GuiNewChatTC.getInstance(); ReflectionHelper.setFieldValue(GuiIngame.class, guiIngame, GuiNewChatTC.getInstance(), TabbyRef.PERSISTANT_CHAT_GUI); LOGGER.info("Successfully hooked into chat."); } } }
package Options; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import Controleurs.ControleurInterne; /**description de l'OptionMusique, une implementation de {@link Option} * @author p14005728 */ public class OptionMusique extends Option implements Cloneable { /**Permet de savoir si la fenetre de cette OptionMusique est ouverte. */ private boolean estFenetreOuverte; /**nom de la musique */ private String nomMusique = ""; private String[] listeMusiques = { "Carol Malus Deinheim - Symphogear GX - Tomorrow", "Toby Fox & Kenichi Matsubara - MegalovaniaVania" }; private Thread musique; /**Construit une OptionMusique et initialise {@link Option#controleurInt}. * @param controleurInt le {@link ControleurInterne} a affecter a cette OptionMusique. */ public OptionMusique (ControleurInterne controleurInt) { setControleurInterne(controleurInt); } /**Constructeur par defaut d'une OptionMusique. */ public OptionMusique () {} /**permet de lancer la musique, pour l'instant ne fait qu'une notification. */ private void lancerMusique (String cheminFichier) { setEstActivee(true); musique = new JouerFichierWAV(cheminFichier); musique.start(); JOptionPane.showMessageDialog(null, "the music : " + '"' + cheminFichier.substring(0, cheminFichier.length() - 4) + '"' + " is playing in lift " + getControleurInterne().getAscenseur().getNumAsc()); } /**permet d'arreter la musique, pour l'instant ne fait qu'une notification. */ @SuppressWarnings("deprecation") private void arreterMusique(String cheminFichier) { setEstActivee(false); musique.stop(); JOptionPane.showMessageDialog(null, "the music : " + '"' + cheminFichier.substring(0, cheminFichier.length() - 4) + '"' + " stopped in lift " + getControleurInterne().getAscenseur().getNumAsc()); } /** permet d'activer OptionMusique en utilisant {@link OptionMusique#lancerMusique}. * Cela creer une fenetre qui permet d'interagire avec cette OptionMusique. */ @Override public void activer() { if (!estFenetreOuverte) {//On verifie qu'il n'y ait pas d'autres fenetres d'ouvertes pour cette Option. estFenetreOuverte = true; //Creation de la fenetre JFrame fenetreMusique = new JFrame("Music"); fenetreMusique.setLayout(new FlowLayout()); JLabel labelNomMusique = new JLabel("music's name : "); fenetreMusique.add(labelNomMusique); final JComboBox<String> nomMusique = new JComboBox<String>(listeMusiques); fenetreMusique.add(nomMusique); //nomMusique.setPreferredSize(new Dimension(fenetreMusique.getWidth() / 2 - 10, nomMusique.getFont().getSize() + 8)); JButton lancerArreter = new JButton("Play/Stop"); lancerArreter.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setNomMusique(nomMusique.getSelectedItem().toString()); if (!isEstActivee()) { lancerMusique("music/" + nomMusique.getSelectedItem().toString() + ".wav"); } else { arreterMusique("music/" + nomMusique.getSelectedItem().toString() + ".wav"); } getControleurInterne().getAscenseur().notifyObservers(); } }); fenetreMusique.add(lancerArreter); fenetreMusique.setLocationRelativeTo(null); fenetreMusique.pack(); fenetreMusique.setVisible(true); estFenetreOuverte = false; } } /** Permet de connaitre l'etat de cette OptionMusique. * @see java.lang.Object#toString() */ @Override public String toString() { return "Music " + (nomMusique != null ? nomMusique : "") + (isEstActivee() ? " activated" : ""); } /**Permet de definire si la fenetre d'interaction est ouverte * @param estFenetreOuverte true si ouverte, false sinon. * @see #estFenetreOuverte */ public void setEstFenetreOuverte(boolean estFenetreOuverte) { this.estFenetreOuverte = estFenetreOuverte; } /**Permet d'obtenir le {@link #nomMusique} de cette OptionMusique * @return le {@link #nomMusique} de cette OptionMusique */ public String getNomMusique() { return nomMusique; } /**Permet de definir le {@link #nomMusique} de cette OptionMusique * @param nomMusique {@link #nomMusique} a definir pour cette de cette OptionMusique */ public void setNomMusique(String nomMusique) { this.nomMusique = nomMusique; } /** Permet d'obtenir une copie de cette OptionMusique. * @see Options.Option#clone() */ @Override public OptionMusique clone() { OptionMusique optionARetournee = new OptionMusique(); optionARetournee.setEstFenetreOuverte(estFenetreOuverte); optionARetournee.setEstActivee(isEstActivee()); if (this.nomMusique != null) { optionARetournee.setNomMusique(getNomMusique()); } if (getControleurInterne() != null) { optionARetournee.setControleurInterne(getControleurInterne()); } return optionARetournee; } }
package com.example.fragment; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.example.demoaerisproject.R; import com.hamweather.aeris.location.LocationHelper; import com.hamweather.aeris.maps.AerisMapView; import com.hamweather.aeris.maps.AerisMapView.AerisMapType; import com.hamweather.aeris.maps.MapOptionsActivity; import com.hamweather.aeris.maps.MapViewFragment; public class MapFragment extends MapViewFragment { public static final int OPTIONS_ACTIVITY = 1025; private LocationHelper locHelper; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_interactive_maps, container, false); mapView = (AerisMapView) view.findViewById(R.id.aerisfragment_map); mapView.init(savedInstanceState, AerisMapType.GOOGLE); initMap(); setHasOptionsMenu(true); return view; } /** * Inits the map with specific setting */ private void initMap() { locHelper = new LocationHelper(getActivity()); Location myLocation = locHelper.getCurrentLocation(); mapView.moveToLocation(myLocation, 7); } /* * (non-Javadoc) * * @see android.app.Fragment#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_weather_layers) { this.startActivityForResult(new Intent(getActivity(), MapOptionsActivity.class), OPTIONS_ACTIVITY); return false; } else { return super.onOptionsItemSelected(item); } } @Override public void onResume() { super.onResume(); } /* * (non-Javadoc) * * @see android.app.Fragment#onCreateOptionsMenu(android.view.Menu, * android.view.MenuInflater) */ @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_maps_fragment, menu); super.onCreateOptionsMenu(menu, inflater); } }
package com.example.fw; import java.util.ArrayList; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import com.example.tests.ContactData; import static org.testng.Assert.assertEquals; public class ContactHelper extends HelperBase { public ContactHelper(ApplicationManager manager) { super(manager); } public void submitContactForm() { click(By.name("submit")); } public void fillContactForm(ContactData contact) { // name type(By.name("firstname"), contact.getFirstName()); type(By.name("lastname"), contact.getLastName()); // address type(By.name("address"), contact.getAddress()); // contacts type(By.name("home"), contact.getHomePhone()); type(By.name("mobile"), contact.getMobilePhone()); type(By.name("work"), contact.getWorkPhone()); type(By.name("email"), contact.getEmail_1()); type(By.name("email2"), contact.getEmail_2()); // birth date select(By.name("bday"), contact.getBirthDay()); select(By.name("bmonth"), contact.getBirthMonth()); type(By.name("byear"), contact.getBirthYear()); // group select(By.name("new_group"), contact.getContactGroup()); // extra address type(By.name("address2"), contact.getAddressSecondary()); // extra contact type(By.name("phone2"), contact.getPhoneSecondary()); } public void returnToHomePage() { click(By.linkText("home page")); } public void initContactEdit(int index) { // (index + 2) - numiration from 1 and 1 is for table header String locator = "//table[@id='maintable']//tr[" + (index + 2) + "]/td/a/img[@title='Edit']"; click(By.xpath(locator)); } public void submitDeleteContact() { click(By.xpath("//input[@value='Delete']")); } public void submitUpdate() { click(By.xpath("//input[@value='Update']")); } public List<ContactData> getContacts() { List<ContactData> contacts = new ArrayList<ContactData>(); List<WebElement> tableRows = driver.findElements(By.xpath("//table[@id='maintable']/tbody/tr[@name='entry']")); for (WebElement tableRow : tableRows) { // prepare data // emails from attribute String[] emails = tableRow.findElement(By.xpath("td/input")).getAttribute("accept").split(";"); // display email String displayEmail = tableRow.findElement(By.xpath("td[4]")).getText(); ContactData contact = new ContactData() .withId(Integer.parseInt(tableRow.findElement(By.xpath("td/input")).getAttribute("value"))) .withLastName(tableRow.findElement(By.xpath("td[2]")).getText()) .withFirstName(tableRow.findElement(By.xpath("td[3]")).getText()) .withEmail_1((emails.length > 0 && emails[0].length() > 0) ? emails[0] : "") .withEmail_2(emails.length > 1 ? emails[1] : "") .withHomePhone(tableRow.findElement(By.xpath("td[5]")).getText()); // check displayEmail is the same with email_1 assertEquals(displayEmail, contact.getEmail_1()); contacts.add(contact); } return contacts; } public ArrayList<String> getGroupSelectOptions() { ArrayList<String> optionsList = new ArrayList<String>(); List<WebElement> optionsWebElements = driver.findElements(By.xpath("//select[@name='new_group']/option")); for (WebElement option : optionsWebElements) { optionsList.add(option.getText()); } return optionsList; } }
package io.agrest.runtime.entity; import io.agrest.AgException; import io.agrest.EntityProperty; import io.agrest.PathConstants; import io.agrest.ResourceEntity; import io.agrest.meta.AgAttribute; import io.agrest.meta.AgEntity; import io.agrest.meta.AgRelationship; import io.agrest.protocol.Include; import org.apache.cayenne.di.Inject; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import java.util.HashSet; import java.util.List; import java.util.Set; public class IncludeMerger implements IIncludeMerger { private ISortMerger sortMerger; private ICayenneExpMerger expMerger; private IMapByMerger mapByMerger; private ISizeMerger sizeMerger; public IncludeMerger( @Inject ICayenneExpMerger expMerger, @Inject ISortMerger sortMerger, @Inject IMapByMerger mapByMerger, @Inject ISizeMerger sizeMerger) { this.sortMerger = sortMerger; this.expMerger = expMerger; this.mapByMerger = mapByMerger; this.sizeMerger = sizeMerger; } /** * Records include path, returning null for the path corresponding to an * attribute, and a child {@link ResourceEntity} for the path corresponding * to relationship. */ @SuppressWarnings({"unchecked", "rawtypes"}) public static ResourceEntity<?> processIncludePath(ResourceEntity<?> parent, String path, Set<ResourceEntity<?>> mayNeedDefaults) { int dot = path.indexOf(PathConstants.DOT); if (dot == 0) { throw new AgException(Status.BAD_REQUEST, "Include starts with dot: " + path); } if (dot == path.length() - 1) { throw new AgException(Status.BAD_REQUEST, "Include ends with dot: " + path); } String property = dot > 0 ? path.substring(0, dot) : path; AgEntity<?> agEntity = parent.getAgEntity(); if (dot < 0) { EntityProperty requestProperty = parent.getExtraProperties().get(property); if (requestProperty != null) { parent.getIncludedExtraProperties().put(property, requestProperty); return null; } AgAttribute attribute = agEntity.getAttribute(property); if (attribute != null) { parent.getAttributes().put(property, attribute); return null; } } AgRelationship relationship = agEntity.getRelationship(property); if (relationship != null) { ResourceEntity<?> childEntity = parent .getChildren() .computeIfAbsent(property, p -> new ResourceEntity(relationship.getTargetEntity(), relationship)); if (dot > 0) { // phantom entities do not need defaults return processIncludePath(childEntity, path.substring(dot + 1), mayNeedDefaults); } else { // explicit relationship includes may need defaults mayNeedDefaults.add(childEntity); return childEntity; } } // this is root entity id and it's included explicitly if (property.equals(PathConstants.ID_PK_ATTRIBUTE)) { parent.includeId(); return null; } throw new AgException(Status.BAD_REQUEST, "Invalid include path: " + path); } private static void processDefaultIncludes(ResourceEntity<?> resourceEntity) { if (!resourceEntity.isIdIncluded() && resourceEntity.getAttributes().isEmpty() && resourceEntity.getIncludedExtraProperties().isEmpty()) { for (AgAttribute a : resourceEntity.getAgEntity().getAttributes()) { resourceEntity.getAttributes().put(a.getName(), a); resourceEntity.getDefaultProperties().add(a.getName()); } resourceEntity.getIncludedExtraProperties().putAll(resourceEntity.getExtraProperties()); resourceEntity.getDefaultProperties().addAll(resourceEntity.getExtraProperties().keySet()); resourceEntity.includeId(); } } /** * Sanity check. We don't want to get a stack overflow. */ public static void checkTooLong(String path) { if (path != null && path.length() > PathConstants.MAX_PATH_LENGTH) { throw new AgException(Response.Status.BAD_REQUEST, "Include/exclude path too long: " + path); } } /** * @since 2.13 */ @Override public void merge(ResourceEntity<?> entity, List<Include> includes) { // included attribute sets of the root entity and entities that are included explicitly via relationship includes // may need to get expanded if they don't have any explicit includes otherwise. Will track them here... Entities // that are NOT expanded are those that are "phantom" entities included as a part of the longer path. Set<ResourceEntity<?>> mayNeedDefaults = new HashSet<>(); // root entity always needed default includes mayNeedDefaults.add(entity); for (Include include : includes) { mergeInclude(entity, include, mayNeedDefaults); } for (ResourceEntity<?> e : mayNeedDefaults) { processDefaultIncludes(e); } } private void mergeInclude(ResourceEntity<?> entity, Include include, Set<ResourceEntity<?>> mayNeedDefaults) { ResourceEntity<?> includeEntity; String path = include.getPath(); if (path == null || path.isEmpty()) { // root node includeEntity = entity; } else { IncludeMerger.checkTooLong(path); ResourceEntity<?> maybeIncludeEntity = IncludeMerger.processIncludePath(entity, path, mayNeedDefaults); // either attribute or relationship... if includeEntity = maybeIncludeEntity != null ? maybeIncludeEntity : entity; } mapByMerger.mergeIncluded(includeEntity, include.getMapBy()); sortMerger.merge(includeEntity, include.getSort()); expMerger.merge(includeEntity, include.getCayenneExp()); sizeMerger.merge(includeEntity, include.getStart(), include.getLimit()); } }
package org.lotus.algorithm.strings; import org.junit.Test; import java.util.Arrays; public class Strings { public static char[] str= {'a','b','c','d','e','f','g','h'}; private static char[] getStr(){ return Arrays.copyOf(str,str.length); } public static void revertChar(char[] str , int m){ //0,n-1 //x= str[0],str[n-1-m] , y = n-1-m+1 , n-1 if(m>=str.length){ System.out.print("invalid param m"); } revert(str,0,str.length-1-m); revert(str,str.length-m,str.length-1); revert(str,0,str.length-1); System.out.println(str); } private static void revert(char[] str , int start ,int end){ int j=start; int k=end; while(j < k){ char v = str[j]; str[j]=str[k]; str[k]= v; j++; k } } @Test public void testRevert(){ revertChar(getStr(),3); revertChar(getStr(),4); revertChar(getStr(),5); } private static void revertWord(){ } /** * 1.manacher # 2N-1 * 2. i */ private static void palindromic(char[] str){ char[] extend = new char[str.length*2-1]; for(int i=0,j=0;i<str.length;i++,j++){ extend[j]=str[i]; j++; if (j<extend.length) extend[j]=' } int[] mp = new int[extend.length]; int m=0,r=0; for(int i=0;i<extend.length;i++){ mp[i]= i < r ? Math.min(mp[2*m-i],r-i):1; while(i-mp[i]>=0 && i+mp[i]<extend.length && extend[i-mp[i]]==extend[i+mp[i]]){ mp[i]++; } //ii r , r=i,m=i if(i+mp[i] > r) { r=i+mp[i]; m=i; } } int max=0; for(int i=0;i<mp.length;i++){ if (mp[i]>mp[max]){ max=i; } } if (mp[max]>1) { int left = max-mp[max]+1; int right = max+mp[max]-1; left = (left+1)/2; right = (right-1)/2; for (int i=left;i<=right;i++){ System.out.print(str[i]); } } } @Test public void testPalindromic(){ char[] origin = "abcdeffeffedcab".toCharArray(); palindromic(origin); } /** * h(s[i])= s[i]*b^i mod M * h(s) = h(s[0])+...+ h(s[n]) * h(s[l,r]) = h(s[0,r])-h(s[0,l-1]) * h(s[l,r])=h(s[l-1,r-1]) - h(s[l-1]) + h(s[r]); * target pattern * * O(N+M) ,O(N*M) */ public static int patternMatch( char[] target,char[] pattern){ //hash //hash --Rabin-Karp if(pattern.length>target.length){ return -1; } //long int b = 233; int M = 1000000007; long hashPattern = 0; long hashTarget = 0; long bl = 1; for(int i=1;i<pattern.length;i++){ bl = bl*b; } bl=bl%M; for(int i=0;i<pattern.length;i++){ hashPattern = (hashPattern*b+pattern[i])%M; hashTarget = (hashTarget*b+target[i])%M; } int pos = -1; for(int i=0;i<target.length-pattern.length;i++){ if (hashPattern == hashTarget){ pos=i; //hash hash break; } hashTarget = (hashTarget*b - (target[i]*bl*b)%M + target[i+pattern.length])%M; } return pos; } @Test public void testPatternMatch(){ char[] target = ("afhkcvaofaaamvakidwvbhadoavbiqqqqhsdlkczovoavaqafbmkginl" + "ogapipahnfjadnvcxbxdiazdlkfdfeeigdbjvqweqiutfafpvpzvbadbahufu").toCharArray(); char[] pattern = "lkfdf".toCharArray(); int pos = patternMatch(target,pattern); System.out.println(pos); } public int BMPattern(char[] target, char[] pattern){ //move /** * pattern + + + + + + + + + [i + + + ] + + + [+ + + +] * + + + + + + + + + [+ + + + ] + + + [+ + + +] * length=4 , k ,m */ int length=0; int[] move = new int[pattern.length]; int j=-1; int k=-1; int l=-1; int tail= pattern.length-1; for(int i=tail;i>=0;i int old_l=l; if (l<=0){ //tail if (pattern[i]==pattern[tail]){ k=i; l=l+1; } } else { if(j>l){ k=i; l=j; } // move //move if(l>old_l){ move[tail-l+1]=tail-l+1-k; } } if (j=-1) j= (pattern[i]==pattern[tail-j])?j+1:0; } //move for(int i=0;i<=tail-l;i++){ move[i]= move[tail-l+1]; } for (int i=0;i<pattern.length;i++){ System.out.print(pattern[i]+" "); } System.out.println(); for (int i=0;i<move.length;i++){ System.out.print(move[i]+" "); } System.out.println(); return 0; } @Test public void testBMPattern(){ char[] target = ("afhkcvaofaaamvakidwvbhadoavbiqqqqhsdlkczovoavaqafbmkginl" + "ogapipahnfjadnvcxbxdiazdlkfdfeeigdbjvqweqiutfafpvpzvbadbahufu").toCharArray(); char[] pattern = "xc dcbacba nbmbadcba".toCharArray(); int pos = BMPattern(target,pattern); System.out.println(pos); } /*private long hash(char[] str,int dwHashType){ long seed1= 0x7FED7FED; long seed2= 0xEEEEEEEE; long[] cryptTable=prepareCryptTable(); int ch; for (int i=0;i<str.length;i++) { ch = str[i]; seed1 = cryptTable[(dwHashType << 8) + ch] ^ (seed1 + seed2); seed2 = ch + seed1 + seed2 + (seed2 << 5) + 3; } return seed1; } static long[] prepareCryptTable() { long seed = 0x00100001; int index2=0,index1=0, i=0; long[] cryptTable = new long[256]; for(index1 = 0; index1 < 256; index1++) { for(index2 = index1, i = 0; i < 5; i++, index2 += 256) { long temp1, temp2; seed = (seed * 125 + 3) % 0x2AAAAB; temp1 = (seed & 0xFFFF) << 0x10; seed = (seed * 125 + 3) % 0x2AAAAB; temp2 = (seed & 0xFFFF); cryptTable[index2] = ( temp1 | temp2 ); } } return cryptTable; }*/ }
package com.anywarelabs.algorithms; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * * @author Marcio Fonseca */ public class Sorting { /** * Sorts the specified list into ascending order, according to the * {@linkplain Comparable natural ordering} of its elements. * All elements in the list must implement the {@link Comparable} * interface. Furthermore, all elements in the list must be * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)} * must not throw a {@code ClassCastException} for any elements * {@code e1} and {@code e2} in the list). * * The implementation uses a modified version of merge sort algorithm that * counts the number of inversions found in the original list. * * @param <T> * @param list the list to be sorted. * @return the number of inversions found in the original list. */ public <T extends Comparable> long mergeSort(List<T> list) { return mergeSortImpl(list, 0, list.size() - 1); } /** * Merge sort implementation. The original list parameter is modified to * avoid using additional space. * * @param list the list to be sorted. * @param start * @param end * @return the number of inversions found in the original list. */ private <T extends Comparable> long mergeSortImpl(List<T> list, int start, int end) { if (end - start + 1 == 1) { return 0; } int mid = (start + end) >>> 1; long leftInversions = mergeSortImpl(list, start, mid); long rightInversions = mergeSortImpl(list, mid + 1, end); long crossInversions = merge(list, start, mid, end); return leftInversions + rightInversions + crossInversions; } /** * Merge step for the merge sort algorithm. * * @param list the list to be sorted. * @param start * @param mid * @param end * @return */ private <T extends Comparable> long merge(List<T> list, int start, int mid, int end) { int i = start; int j = mid + 1; long inversions = 0; List merged = new ArrayList(end - start + 1); for (int k = start; k <= end; k++) { merged.add(null); } int mergedIndex = 0; while (mergedIndex < merged.size() && (i <= mid || j <= end)) { if (i <= mid && (j > end || list.get(i).compareTo(list.get(j)) <= 0)) { merged.set(mergedIndex, list.get(i++)); } else { merged.set(mergedIndex, list.get(j++)); inversions += (mid - i + 1); } mergedIndex++; } for (Iterator it = merged.iterator(); it.hasNext();) { T val = (T) it.next(); list.set(start++, val); } return inversions; } }
package com.wscodelabs.callLogs; import android.provider.CallLog; import android.provider.CallLog.Calls; import android.database.Cursor; import android.content.Context; import java.text.SimpleDateFormat; import java.util.Date; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; public class CallLogModule extends ReactContextBaseJavaModule { private Context context; public CallLogModule(ReactApplicationContext reactContext) { super(reactContext); this.context = reactContext; } @Override public String getName() { return "CallLogs"; } @ReactMethod public void loadAll(Promise promise) { load(-1, promise); } @ReactMethod public void load(int limit, Promise promise) { Cursor cursor = this.context.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, CallLog.Calls.DATE + " DESC"); WritableArray result = Arguments.createArray(); if (cursor == null) { promise.resolve(result); return; } int callLogCount = 0; final int NUMBER_COLUMN_INDEX = cursor.getColumnIndex(Calls.NUMBER); final int TYPE_COLUMN_INDEX = cursor.getColumnIndex(Calls.TYPE); final int DATE_COLUMN_INDEX = cursor.getColumnIndex(Calls.DATE); final int DURATION_COLUMN_INDEX = cursor.getColumnIndex(Calls.DURATION); final int NAME_COLUMN_INDEX = cursor.getColumnIndex(Calls.CACHED_NAME); while (cursor.moveToNext() && this.shouldContinue(limit, callLogCount++)) { String phoneNumber = cursor.getString(NUMBER_COLUMN_INDEX); int duration = cursor.getInt(DURATION_COLUMN_INDEX); String name = cursor.getString(NAME_COLUMN_INDEX); int timestamp = cursor.getInt(DATE_COLUMN_INDEX); String dateTime = SimpleDateFormat.getDateTimeInstance().format(new Date(timestamp)); String type = this.resolveCallType(cursor.getInt(TYPE_COLUMN_INDEX)); WritableMap callLog = Arguments.createMap(); callLog.putString("phoneNumber", phoneNumber); callLog.putInt("duration", duration); callLog.putString("name", name); callLog.putInt("timestamp", timestamp); callLog.putString("dateTime", dateTime); callLog.putString("type", type); result.pushMap(callLog); } cursor.close(); promise.resolve(result); } private String resolveCallType(int callTypeCode) { switch (callTypeCode) { case Calls.OUTGOING_TYPE: return "OUTGOING"; case Calls.INCOMING_TYPE: return "INCOMING"; case Calls.MISSED_TYPE: return "MISSED"; default: return "UNKNOWN"; } } private boolean shouldContinue(int limit, int count) { return limit < 0 || count < limit; } }
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.time.*; import java.time.format.*; import java.time.temporal.*; import java.util.*; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.*; import javax.swing.*; public final class MainPanel extends JPanel { public final Dimension size = new Dimension(10, 10); public final LocalDate currentLocalDate = LocalDate.now(); public final JList<Contribution> weekList = new JList<Contribution>(new CalendarViewListModel(currentLocalDate)) { @Override public void updateUI() { setCellRenderer(null); super.updateUI(); setLayoutOrientation(JList.VERTICAL_WRAP); setVisibleRowCount(DayOfWeek.values().length); // ensure 7 rows in the list setFixedCellWidth(size.width); setFixedCellHeight(size.height); setCellRenderer(new ContributionListRenderer()); getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); } }; public final Color color = new Color(50, 200, 50); public final List<Icon> activityIcons = Arrays.asList( new ColorIcon(new Color(200, 200, 200)), new ColorIcon(color.brighter()), new ColorIcon(color), new ColorIcon(color.darker()), new ColorIcon(color.darker().darker())); private MainPanel() { super(new BorderLayout()); Font font = weekList.getFont().deriveFont(size.height - 1f); Locale l = Locale.getDefault(); WeekFields weekFields = WeekFields.of(l); DefaultListModel<String> weekModel = new DefaultListModel<>(); DayOfWeek firstDayOfWeek = weekFields.getFirstDayOfWeek(); for (int i = 0; i < DayOfWeek.values().length; i++) { boolean isEven = i % 2 == 0; if (isEven) { weekModel.add(i, ""); } else { weekModel.add(i, firstDayOfWeek.plus(i).getDisplayName(TextStyle.SHORT_STANDALONE, l)); } } JList<String> rowHeader = new JList<>(weekModel); rowHeader.setEnabled(false); rowHeader.setFont(font); rowHeader.setLayoutOrientation(JList.VERTICAL_WRAP); rowHeader.setVisibleRowCount(DayOfWeek.values().length); rowHeader.setFixedCellHeight(size.height); JPanel colHeader = new JPanel(new GridBagLayout()); colHeader.setBackground(Color.WHITE); GridBagConstraints cc = new GridBagConstraints(); for (int i = 0; i < CalendarViewListModel.WEEK_VIEW; i++) { // cc.gridwidth = 1; cc.gridx = i; // cc.gridy = 0; colHeader.add(Box.createHorizontalStrut(size.width), cc); // grid guides } cc.anchor = GridBagConstraints.LINE_START; JLabel label = null; cc.gridy = 1; int minGridWidth = 4; for (int i = 0; i < CalendarViewListModel.WEEK_VIEW - minGridWidth + 1; i++) { cc.gridx = i; LocalDate date = weekList.getModel().getElementAt(i * DayOfWeek.values().length).date; // int weekNumberOfMonth = date.get(weekFields.weekOfMonth()); // System.out.println(weekNumberOfMonth); boolean isSimplyFirstWeekOfMonth = date.getMonth() != date.minusWeeks(1).getMonth(); // ignore WeekFields#getMinimalDaysInFirstWeek() if (isSimplyFirstWeekOfMonth) { // weekNumberOfMonth == 2) { label = makeLabel(date.getMonth().getDisplayName(TextStyle.SHORT, l), font); cc.gridwidth = minGridWidth; colHeader.add(label, cc); } else if (Objects.isNull(label)) { cc.gridwidth = 1; colHeader.add(Box.createHorizontalStrut(size.width), cc); } } JScrollPane scroll = new JScrollPane(weekList); scroll.setBorder(BorderFactory.createEmptyBorder()); scroll.setColumnHeaderView(colHeader); scroll.setRowHeaderView(rowHeader); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scroll.setBackground(Color.WHITE); Box box = Box.createHorizontalBox(); box.add(makeLabel("Less", font)); box.add(Box.createHorizontalStrut(2)); activityIcons.forEach(icon -> { box.add(new JLabel(icon)); box.add(Box.createHorizontalStrut(2)); }); box.add(makeLabel("More", font)); JPanel p = new JPanel(new GridBagLayout()); p.setBorder(BorderFactory.createEmptyBorder(10, 2, 10, 10)); p.setBackground(Color.WHITE); GridBagConstraints c = new GridBagConstraints(); p.add(scroll, c); c.insets = new Insets(10, 0, 2, 0); c.gridy = 1; c.anchor = GridBagConstraints.LINE_END; p.add(box, c); add(p, BorderLayout.NORTH); add(new JScrollPane(new JTextArea())); setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); setPreferredSize(new Dimension(320, 240)); } private class ContributionListRenderer implements ListCellRenderer<Contribution> { private final ListCellRenderer<? super Contribution> renderer = new DefaultListCellRenderer(); @Override public Component getListCellRendererComponent(JList<? extends Contribution> list, Contribution value, int index, boolean isSelected, boolean cellHasFocus) { JLabel l = (JLabel) renderer.getListCellRendererComponent(list, null, index, isSelected, cellHasFocus); if (value.date.isAfter(currentLocalDate)) { l.setIcon(new ColorIcon(Color.WHITE)); l.setToolTipText(null); } else { l.setIcon(activityIcons.get(value.activity)); String actTxt = value.activity == 0 ? "No" : Objects.toString(value.activity); l.setToolTipText(actTxt + " contribution on " + value.date.toString()); } return l; } } private static JLabel makeLabel(String title, Font font) { JLabel label = new JLabel(title); label.setFont(font); label.setEnabled(false); return label; } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class Contribution { public final LocalDate date; public final int activity; protected Contribution(LocalDate date, int activity) { this.date = date; this.activity = activity; } } class CalendarViewListModel extends AbstractListModel<Contribution> { public static final int WEEK_VIEW = 27; private final LocalDate startDate; private final Map<LocalDate, Integer> contributionActivity = new ConcurrentHashMap<>(getSize()); protected CalendarViewListModel(LocalDate date) { super(); WeekFields weekFields = WeekFields.of(Locale.getDefault()); int dow = date.get(weekFields.dayOfWeek()) - 1; // int wby = date.get(weekFields.weekOfWeekBasedYear()); startDate = date.minusWeeks(WEEK_VIEW - 1).minusDays(dow); Random rnd = new Random(); int size = DayOfWeek.values().length * WEEK_VIEW; IntStream.range(0, size).forEach(i -> contributionActivity.put(startDate.plusDays(i), rnd.nextInt(5))); } @Override public int getSize() { return DayOfWeek.values().length * WEEK_VIEW; } @Override public Contribution getElementAt(int index) { LocalDate date = startDate.plusDays(index); return new Contribution(date, contributionActivity.get(date)); } } class ColorIcon implements Icon { private final Color color; protected ColorIcon(Color color) { this.color = color; } @Override public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2 = (Graphics2D) g.create(); g2.translate(x, y); g2.setPaint(color); g2.fillRect(0, 0, getIconWidth(), getIconHeight()); g2.dispose(); } @Override public int getIconWidth() { return 8; } @Override public int getIconHeight() { return 8; } }
package at.irian.ankor.big; import at.irian.ankor.messaging.AnkorIgnore; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.util.*; /** * @author Manfred Geiler */ @SuppressWarnings("UnusedDeclaration") public abstract class AbstractBigList<E> extends AbstractList<E> implements BigList<E> { //private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(Lazy.class); @AnkorIgnore private NavigableMap<Integer, Reference> elements; private int size; public AbstractBigList(int size) { this.elements = new TreeMap<Integer, Reference>(); this.size = size; } public AbstractBigList(Collection<? extends E> c) { this(c.size()); int idx = 0; for (E e : c) { elements.put(idx++, createReferenceFor(e)); } } @SuppressWarnings("unchecked") protected Reference createReferenceFor(E element) { return element != null ? new SoftReference(element) : new SoftReference(new NullDummy()); //return element != null ? new WeakReference(element) : new WeakReference(new NullDummy()); } @Override public int size() { return size; } public void setSize(int size) { this.size = size; } @Override public E get(int index) { Reference elementReference = elements.get(index); if (elementReference == null) { return getMissingElement(index); } Object item = elementReference.get(); if (item instanceof NullDummy) { return null; } else if (item == null) { return getMissingElement(index); } else { //noinspection unchecked return (E)item; } } protected abstract E getMissingElement(int index); @Override public E set(int index, E element) { Reference prev = elements.put(index, createReferenceFor(element)); adjustSize(); return getReferencedValue(prev); } private E getReferencedValue(Reference referenced) { if (referenced != null) { Object prevItem = referenced.get(); if (prevItem instanceof NullDummy) { return null; } else { //noinspection unchecked return (E)prevItem; } } else { return null; } } @Override public void add(int index, E element) { if (index < 0) { throw new IndexOutOfBoundsException("Index: " + index); } NavigableMap<Integer, Reference> tailMap = elements.tailMap(index, true); List<Map.Entry<Integer, Reference>> copyOfDescendingTailMapEntries = new ArrayList<Map.Entry<Integer, Reference>>(tailMap.descendingMap().entrySet()); tailMap.clear(); elements.put(index, createReferenceFor(element)); for (Map.Entry<Integer, Reference> entry : copyOfDescendingTailMapEntries) { elements.put(entry.getKey() + 1, entry.getValue()); } this.size++; adjustSize(); } @Override public E remove(int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index: " + index); } NavigableMap<Integer, Reference> tailMap = elements.tailMap(index, false); List<Map.Entry<Integer, Reference>> copyOfTailMapEntries = new ArrayList<Map.Entry<Integer, Reference>>(tailMap.entrySet()); Reference removed = elements.remove(index); for (Map.Entry<Integer, Reference> entry : copyOfTailMapEntries) { Integer idx = entry.getKey(); Reference value = entry.getValue(); // !!! never inline this entry.getValue() call because entries seem to get reused in elements map causing nasty side effects... elements.remove(idx); elements.put(idx - 1, value); } this.size adjustSize(); return getReferencedValue(removed); } private void adjustSize() { int realSize = elements.isEmpty() ? 0 : elements.lastEntry().getKey() + 1; this.size = Math.max(this.size, realSize); } @Override public void clear() { this.elements.clear(); this.size = 0; } @Override public void reset() { this.elements.clear(); } @Override public void cleanup() { for (Map.Entry<Integer, Reference> entry : elements.entrySet()) { if (entry.getValue().get() == null) { entry.setValue(null); } } } @Override public boolean isAvailable(int index) { Reference elementReference = elements.get(index); if (elementReference == null) { return false; } Object item = elementReference.get(); return item instanceof NullDummy || item != null; } private static class NullDummy {} }
package ProjectEuler; import java.util.ArrayList; /** * Project Euler Problems * @author wangshuai * @since 2013-09-02 */ public class Problems { public static void main(String[] args){ Problems problems = new Problems(); // problems.problem1(); // problems.problem2(); // problems.problem3(); // problems.newProblem3(); // problems.problem4(); // problems.problem5(); // problems.problem6(); // problems.problem7(); // problems.problem9(); // problems.problem10(); // problems.fib(); // System.out.println("fib_recur="+problems.fib_recur(1, 1)); problems.problem14(); } public void problem1(){ int sum = 0; for(int i=3;i<1000;i++){ if(i%3==0||i%5==0){ sum += i; } } System.out.println("sum="+sum); } public void problem2(){ int sum = 0; int front = 1; int back = 1; while(front<4000000){ int tmp = back; back = front; front = front + tmp; System.out.println("front: "+front); if(front%2==0){ sum += front; } } System.out.println("sum="+sum); } public void problem3(){ long goalnum = 600851475143L; long sqrt_goalnum = (long) Math.sqrt(goalnum); long maxprime = 0; ArrayList<Long> primelist = getPrimeList(sqrt_goalnum); for(long prime:primelist){ if(goalnum%prime==0){ maxprime = prime; } } System.out.println("maxprime="+maxprime); } private ArrayList<Long> getPrimeList(long sqrt_goalnum) { ArrayList<Long> primelist = new ArrayList<Long>(); primelist.add((long) 2); for(long i=3;i<sqrt_goalnum;i+=2){ if(isPrime(i,primelist)){ primelist.add(i); } } return primelist; } private boolean isPrime(long i, ArrayList<Long> primelist) { for(long prime:primelist){ if(i%prime==0){ return false; } } return true; } public void newProblem3(){ long goalnum = 600851475143L; long maxfactor = 3; long factor = 3; while(goalnum>1){ if(goalnum%factor==0){ goalnum /= factor; }else{ factor += 2; maxfactor = factor; } } System.out.println("maxfactor="+maxfactor); } public void problem4(){ int goalnum = 999*999; for(;goalnum>10000;goalnum if(isPalind(goalnum)){ if(isDivBy3Digit(goalnum)){ break; } } } System.out.println("largest palindrome is "+goalnum); } private boolean isPalind(int goalnum){ String goalnString = Integer.toString(goalnum); int length = goalnString.length(); for(int i=0,j=length-1;i<=j;i++,j if(goalnString.charAt(i)!=goalnString.charAt(j)){ return false; } } return true; } private boolean isDivBy3Digit(int goalnum){ for(int i=999;i>0;i if(goalnum%i==0){ int num = goalnum/i; if(num>=100&&num<=999){ return true; } } } return false; } public void problem5(){ int goalnum = 20; while(true){ if(isDivided(goalnum)) break; else goalnum += 2; } System.out.println("smallest positive number is "+goalnum); } private boolean isDivided(int goalnum){ for(int i=2;i<=20;i++){ if(goalnum%i!=0){ goalnum += 2; return false; } } return true; } public void problem6(){ int sumofsquare = 0;//The sum of the squares int squareofsum = 0;//The square of the sum for(int i=1;i<=100;i++){ sumofsquare += i*i; } int sum = 0; for(int j=1;j<=100;j++){ sum += j; } squareofsum = sum*sum; System.out.println("the difference is "+(squareofsum-sumofsquare)); } public void problem7(){ ArrayList<Long> primelist = new ArrayList<Long>(); primelist.add((long) 2); for(long prime=3,i=1;i<10001;prime+=2){ if(isPrime(prime, primelist)){ primelist.add(prime); ++i; } } System.out.println("10001st prime number is "+primelist.get(primelist.size()-1)); } public void problem9(){ for(int a=1;a<999;a++){ for(int b=999;b>0;b for(int c=a+b;c>0;c if((a+b+c)!=1000) continue; if(a*a+b*b==c*c){ System.out.println("a="+a+" b="+b+" c="+c+", a*b*c="+a*b*c); return; } } } } } public void problem10(){ ArrayList<Long> primelist = new ArrayList<Long>(); primelist.add((long) 2); long primesum = 2; for(long prime=3;prime<2000000;prime+=2){ if(isPrime(prime, primelist)){ primesum += prime; primelist.add(prime); } } System.out.println("sum of primes below 2 million is "+primesum); } public void fib(){ long front=1,back=1; while(front<1000000000){ long tmp = back; back = front; front += tmp; } System.out.println("fib="+front); } public long fib_recur(long back,long front){ if(front>1000000000) return front; return fib_recur(front, back+front); } public void problem14(){ int max_number = 1;//start number int max_chain = 1;//chain length for(int ixnumber=1;ixnumber<1000000;ixnumber++){ int chainnum = getChainNum(ixnumber); if(chainnum>max_chain){ max_number = ixnumber; max_chain = chainnum; } } System.out.println("demand number is "+max_number); System.out.println("max chain length "+max_chain); } private int getChainNum(long ixnumber){ int chainnum = 1; while(ixnumber>1){ if(ixnumber%2==0) ixnumber /= 2;//even else ixnumber = ixnumber*3 + 1;//odd ++chainnum; } return chainnum; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ciscoroutertool.utils; import java.net.InetAddress; /** * Holds the host-specific information * @version 0.01ALPHA * @author Andrew Johnston */ public class Host { private InetAddress ip_addr; private String user; private String pass; public Host(InetAddress ip, String _user, String _pass) { ip_addr = ip; user = _user; pass = _pass; } public InetAddress getAddress() { return ip_addr; } public String getUser() { return user; } public String getPass() { return pass; } }
package com.andryr.musicplayer.utils; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Build; import android.support.v4.app.NotificationCompat; import android.widget.RemoteViews; import com.andryr.musicplayer.MainActivity; import com.andryr.musicplayer.PlaybackService; import com.andryr.musicplayer.R; import com.andryr.musicplayer.images.ArtworkCache; import com.andryr.musicplayer.images.BitmapCache; public class Notification { private static int NOTIFY_ID = 32; public static void updateNotification(final PlaybackService playbackService) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { updateSupportNotification(playbackService); return; } RemoteViews contentViews = new RemoteViews(playbackService.getPackageName(), R.layout.notification); contentViews.setTextViewText(R.id.song_title, playbackService.getSongTitle()); contentViews.setTextViewText(R.id.song_artist, playbackService.getArtistName()); // ArtworkHelper.loadArtworkAsync(this, getAlbumId(), contentViews, R.id.album_artwork); PendingIntent togglePlayIntent = PendingIntent.getService(playbackService, 0, new Intent(playbackService, PlaybackService.class) .setAction(PlaybackService.ACTION_TOGGLE), 0); contentViews.setOnClickPendingIntent(R.id.quick_play_pause_toggle, togglePlayIntent); PendingIntent nextIntent = PendingIntent.getService(playbackService, 0, new Intent(playbackService, PlaybackService.class).setAction(PlaybackService.ACTION_NEXT), 0); contentViews.setOnClickPendingIntent(R.id.quick_next, nextIntent); PendingIntent previousIntent = PendingIntent.getService(playbackService, 0, new Intent(playbackService, PlaybackService.class) .setAction(PlaybackService.ACTION_PREVIOUS), 0); contentViews.setOnClickPendingIntent(R.id.quick_prev, previousIntent); PendingIntent stopIntent = PendingIntent.getService(playbackService, 0, new Intent(playbackService, PlaybackService.class).setAction(PlaybackService.ACTION_STOP), 0); contentViews.setOnClickPendingIntent(R.id.close, stopIntent); if (playbackService.isPlaying()) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { contentViews.setImageViewResource(R.id.quick_play_pause_toggle, R.drawable.ic_pause); } else { contentViews.setImageViewResource(R.id.quick_play_pause_toggle, R.drawable.ic_pause_black); } // contentView.setContentDescription(R.id.play_pause_toggle, // getString(R.string.pause)); } else { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { contentViews.setImageViewResource(R.id.quick_play_pause_toggle, R.drawable.ic_play_small); } else { contentViews.setImageViewResource(R.id.quick_play_pause_toggle, R.drawable.ic_play_black); } // contentView.setContentDescription(R.id.play_pause_toggle, // getString(R.string.play)); } final NotificationCompat.Builder builder = new NotificationCompat.Builder( playbackService); Intent intent = new Intent(playbackService, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendInt = PendingIntent.getActivity(playbackService, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pendInt) .setOngoing(true).setContent(contentViews); builder.setSmallIcon(R.drawable.ic_stat_note); Resources res = playbackService.getResources(); final int height = (int) res.getDimension(android.R.dimen.notification_large_icon_height); final int width = (int) res.getDimension(android.R.dimen.notification_large_icon_width); ArtworkCache artworkCache = ArtworkCache.getInstance(); Bitmap b = artworkCache.getCachedBitmap(playbackService.getAlbumId(), width, height); if(b != null) { builder.setLargeIcon(b); playbackService.startForeground(NOTIFY_ID, builder.build()); } else { ArtworkCache.getInstance().loadBitmap(playbackService.getAlbumId(), width, height, new BitmapCache.Callback() { @Override public void onBitmapLoaded(Bitmap bitmap) { setBitmap(playbackService, builder, bitmap); playbackService.startForeground(NOTIFY_ID, builder.build()); } }); } } private static void setBitmap(Context context, NotificationCompat.Builder builder, Bitmap bitmap) { if (bitmap != null) { //bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false); builder.setLargeIcon(bitmap); } else { BitmapDrawable d = ((BitmapDrawable) context.getResources().getDrawable(R.drawable.ic_stat_note)); builder.setLargeIcon(d.getBitmap()); } } private static void updateSupportNotification(PlaybackService playbackService) { NotificationCompat.Builder builder = new NotificationCompat.Builder( playbackService); Intent intent = new Intent(playbackService, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendInt = PendingIntent.getActivity(playbackService, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pendInt) .setOngoing(true) .setContentTitle(playbackService.getSongTitle()) .setContentText(playbackService.getArtistName()); builder.setSmallIcon(R.drawable.ic_stat_note); playbackService.startForeground(NOTIFY_ID, builder.build()); } }
package com.apps.anker.facepunchdroid; import android.Manifest; import android.app.ActionBar; import android.app.DownloadManager; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.webkit.MimeTypeMap; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Toast; import com.apps.anker.facepunchdroid.Tools.Downloading; import com.apps.anker.facepunchdroid.Tools.Language; import com.koushikdutta.async.future.FutureCallback; import com.koushikdutta.ion.Ion; import com.nbsp.materialfilepicker.MaterialFilePicker; import java.util.regex.Pattern; import uk.co.senab.photoview.PhotoViewAttacher; public class ImageViewer extends AppCompatActivity { PhotoViewAttacher mAttacher; ImageView imgView; String url; String fileType; private SharedPreferences sharedPref; String selectedLang; ProgressBar pb; @Override protected void onCreate(Bundle savedInstanceState) { sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // Update language selectedLang = sharedPref.getString("language", "system"); Language.setLanguage(selectedLang, getResources()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_viewer); pb = (ProgressBar) findViewById(R.id.progressBarIMGViewer); Intent intent = getIntent(); url = intent.getStringExtra("url"); fileType = MimeTypeMap.getFileExtensionFromUrl(url); Log.d("FILETYPE", fileType); getSupportActionBar().setTitle(""); getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.ImageViewerBackground))); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); imgView = (ImageView) findViewById(R.id.imageView); FutureCallback<ImageView> imageLoadedCallback = new FutureCallback<ImageView>() { @Override public void onCompleted(Exception e, ImageView result) { pb.setVisibility(View.GONE); if(fileType != "gif") { if (mAttacher != null) { mAttacher.update(); } else { mAttacher = new PhotoViewAttacher(imgView); } mAttacher.setOnPhotoTapListener(new PhotoTapListener()); mAttacher.setMaximumScale(5); } } }; Ion.with(this) .load(url) .progressBar(pb) .withBitmap() .deepZoom() .intoImageView(imgView) .setCallback(imageLoadedCallback); } private class PhotoTapListener implements PhotoViewAttacher.OnPhotoTapListener { @Override public void onPhotoTap(View view, float x, float y) { float xPercentage = x * 100f; float yPercentage = y * 100f; finish(); } @Override public void onOutsidePhotoTap() { finish(); } } public void onViewTap(View view, float x, float y) { finish(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.activity_imageviewer_actionbar, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; case R.id.action_download: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2); } else { Downloading.downloadImage(getIntent(), Uri.parse(url).toString(), this); } break; case R.id.openinbrowser: Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; case R.id.sharepage: Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, url); sendIntent.setType("text/plain"); startActivity(sendIntent); } return true; } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case 2: { if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Downloading.downloadImage(getIntent(), Uri.parse(url).toString(), this); return; } } } } }
package net.p316.news.newscat; import java.io.IOException; import java.sql.Date; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import net.p316.news.newscat.DAO.GraphDAO; import net.p316.news.newscat.DAO.WordTableDAO; import net.p316.news.newscat.DTO.GraphDTO; import net.p316.news.newscat.DTO.WordTableDTO; import net.p316.news.newscat.util.graph.JLink; import net.p316.news.newscat.util.graph.JNode; /** * Servlet implementation class Graph */ @WebServlet("/Graph") public class Graph extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Graph() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // check request getParam int sDay = 0; int dDay = 3; if(request.getParameterMap().containsKey("sDay")) dDay = Integer.parseInt(request.getParameter("sDay")); if(request.getParameterMap().containsKey("dDay")) dDay = Integer.parseInt(request.getParameter("dDay")) + 1; Date sdate = Date.valueOf("2016-10-25"); Date edate = Date.valueOf("2016-11-13"); int saddDay = 0; // TimeStamp if(sDay < 6){ saddDay = 26; saddDay += sDay; sdate = Date.valueOf("2016-10-" + Integer.toString(saddDay)); }else{ saddDay = 0; saddDay += sDay-5; sdate = Date.valueOf("2016-11-" + Integer.toString(saddDay)); } int addDay = 0; // TimeStamp if(dDay < 6){ addDay = 26; addDay += dDay; edate = Date.valueOf("2016-10-" + Integer.toString(addDay)); }else{ addDay = 0; addDay += dDay-5; edate = Date.valueOf("2016-11-" + Integer.toString(addDay)); } // get DB GraphDAO graphDAO = new GraphDAO(); ArrayList<GraphDTO> gto = graphDAO.getTable(sdate, edate); WordTableDAO wordTableDAO = new WordTableDAO(); ArrayList<WordTableDTO> wto = wordTableDAO.getWordTable(); // run Algorithm int size = 400; int cutLine = 2; int[][] matrix = new int[size][size]; String[] wordID = new String[size]; double[] wordCate = new double[size]; boolean[] usedID = new boolean[size]; int[] cntID = new int[size]; Iterator<WordTableDTO> itw = wto.iterator(); WordTableDTO wo = null; while(itw.hasNext()){ wo = itw.next(); // 0.0x else // 0.1x // 0.2x // 0.3x // 0.4x // 0.5x // 0.6x // 0.7x // 0.8x // 0.9x double color = 0.0; if(wo.getCate1().equals("")) color = 0.2; if(wo.getCate1().equals("")) color = 0.4; if(wo.getCate1().equals("")) color = 0.6; if(wo.getCate1().equals("")) color = 0.8; wordCate[wo.getIdx()] = color; wordID[wo.getIdx()] = wo.getWord(); } // create Matrix int w = 0; int maxNodes = 0; for(int i=1; i<gto.size(); i++){ usedID[gto.get(i).getIdx_word()] = true; if(gto.get(i-1).getIdx_title() != gto.get(i).getIdx_title()){ for(int j=w; j<i; j++){ for(int k=j; k<i; k++){ if(j == k) continue; if(gto.get(j).getIdx_word() == gto.get(k).getIdx_word()) continue; matrix[gto.get(j).getIdx_word()][gto.get(k).getIdx_word()]++; matrix[gto.get(k).getIdx_word()][gto.get(j).getIdx_word()]++; cntID[gto.get(j).getIdx_word()]++; cntID[gto.get(k).getIdx_word()]++; if(maxNodes < cntID[gto.get(j).getIdx_word()]) maxNodes = cntID[gto.get(j).getIdx_word()]; if(maxNodes < cntID[gto.get(k).getIdx_word()]) maxNodes = cntID[gto.get(k).getIdx_word()]; } } w = i; } } for(int j=w; j<=gto.size(); j++){ for(int k=j; k<gto.size(); k++){ if(j == k) continue; if(gto.get(j).getIdx_word() == gto.get(k).getIdx_word()) continue; matrix[gto.get(j).getIdx_word()][gto.get(k).getIdx_word()]++; matrix[gto.get(k).getIdx_word()][gto.get(j).getIdx_word()]++; cntID[gto.get(j).getIdx_word()]++; cntID[gto.get(k).getIdx_word()]++; if(maxNodes < cntID[gto.get(j).getIdx_word()]) maxNodes = cntID[gto.get(j).getIdx_word()]; if(maxNodes < cntID[gto.get(k).getIdx_word()]) maxNodes = cntID[gto.get(k).getIdx_word()]; } } // normalize ArrayList<Integer> newMap = new ArrayList<Integer>(); int[][] newMatrics = new int[size][size]; // Map for(int t=1; t<size; t++){ int maxValue = 0; int maxIndex = -1; for(int i=1; i<size; i++){ int chkExist = newMap.indexOf(i); if(usedID[i] && chkExist < 0){ if(cntID[i] > cutLine){ if(cntID[i] > maxValue){ maxValue = cntID[i]; maxIndex = i; } } } } if(maxIndex >= 0){ newMap.add(maxIndex); } else { break; } } //Collections.sort(newMap); //newMap = new ArrayList<Integer>(newMap.subList(0, 50)); int[] connectedCnt = new int[size]; for(int i=0; i<newMap.size(); i++){ int oi = newMap.get(i); for(int oj=0; oj<size; oj++){ if(matrix[oi][oj] > 0){ int j = newMap.indexOf(oj); if(j >= 0){ // matrix[oi][oj] 3 , 100 boolean flag = false; if(matrix[oi][oj] > 100) flag = true; if(!flag){ // Dynamic, int maxCnt = 0; for(int l=0; l<size; l++){ if(oj == l) continue; if(matrix[oi][oj] < matrix[oi][l]) maxCnt++; } if(maxCnt < 2) flag = true; } if(flag && connectedCnt[j] < 4){ newMatrics[i][j] = matrix[oi][oj]; connectedCnt[j]++; } } } } } // make JSON response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); Gson gson = new Gson(); String json = "{ \"graph\" : [], "; ArrayList<JLink> links = new ArrayList<JLink>(); for(int i=0; i<newMap.size(); i++){ for(int j=0; j<i; j++){ if(newMatrics[i][j] > 0) { links.add(new JLink(i, j)); } } } ArrayList<JNode> nodes = new ArrayList<JNode>(); for(int i=0; i<newMap.size(); i++){ int nodeSize = 10; /* int vCntID = cntID[newMap.get(i)]; if(vCntID > 5) nodeSize += 10; if(vCntID > 10) nodeSize += 10; if(vCntID > 20) nodeSize += 10; if(vCntID > 50) nodeSize += 10; if(vCntID > 100) nodeSize += 10; if(vCntID > 250) nodeSize += 10; if(vCntID > 500) nodeSize += 10; if(vCntID > 1000) nodeSize += 10; if(vCntID > 3000) nodeSize += 20; if(vCntID > 5000) nodeSize += 20; */ if(i < newMap.size()/10) nodeSize = 80; else if(i < newMap.size()/3) nodeSize = 60; else if(i < newMap.size()/2) nodeSize = 40; else if(i < newMap.size()/1.5) nodeSize = 30; else nodeSize = 20; /* boolean chkEdge = false; for(int j=0; j<newMap.size(); j++){ if(newMatrics[i][j] > 0){ chkEdge = true; break; } } if(chkEdge)*/ nodes.add(new JNode(nodeSize, wordCate[newMap.get(i)], wordID[newMap.get(i)])); } json += "\"links\" :" + new Gson().toJson(links) + ", "; json += "\"nodes\" :" + new Gson().toJson(nodes) + ", "; json += "\"directed\": false, \"multigraph\": false }"; response.getWriter().append(json); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package net.p316.news.newscat; import java.io.IOException; import java.sql.Date; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import net.p316.news.newscat.DAO.GraphDAO; import net.p316.news.newscat.DAO.WordTableDAO; import net.p316.news.newscat.DTO.GraphDTO; import net.p316.news.newscat.DTO.WordTableDTO; import net.p316.news.newscat.util.graph.JLink; import net.p316.news.newscat.util.graph.JNode; /** * Servlet implementation class Graph */ @WebServlet("/Graph") public class Graph extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Graph() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // check request getParam int dDay = 0; if(request.getParameterMap().containsKey("dDay")) dDay = Integer.parseInt(request.getParameter("dDay")); Date sdate = Date.valueOf("2016-10-25"); Date edate = Date.valueOf("2016-11-13"); int addDay = 0; // TimeStamp if(dDay < 6){ addDay = 26; addDay += dDay; edate = Date.valueOf("2016-10-" + Integer.toString(addDay)); }else{ addDay = 0; addDay += dDay-5; edate = Date.valueOf("2016-11-" + Integer.toString(addDay)); } // get DB GraphDAO graphDAO = new GraphDAO(); ArrayList<GraphDTO> gto = graphDAO.getTable(sdate, edate); WordTableDAO wordTableDAO = new WordTableDAO(); ArrayList<WordTableDTO> wto = wordTableDAO.getWordTable(); // run Algorithm int size = 400; int cutLine = 5; int[][] matrix = new int[size][size]; String[] wordID = new String[size]; double[] wordCate = new double[size]; boolean[] usedID = new boolean[size]; int[] cntID = new int[size]; Iterator<WordTableDTO> itw = wto.iterator(); WordTableDTO wo = null; while(itw.hasNext()){ wo = itw.next(); // 0.0x else // 0.1x // 0.2x // 0.3x // 0.4x // 0.5x // 0.6x // 0.7x // 0.8x // 0.9x double color = 0.0; if(wo.getCate1().equals("")) color = 0.2; if(wo.getCate1().equals("")) color = 0.4; if(wo.getCate1().equals("")) color = 0.6; if(wo.getCate1().equals("")) color = 0.8; wordCate[wo.getIdx()] = color; wordID[wo.getIdx()] = wo.getWord(); } // create Matrix int w = 0; int maxNodes = 0; for(int i=1; i<gto.size(); i++){ usedID[gto.get(i).getIdx_word()] = true; if(gto.get(i-1).getIdx_title() != gto.get(i).getIdx_title()){ for(int j=w; j<i; j++){ for(int k=j; k<i; k++){ if(j == k) continue; if(gto.get(j).getIdx_word() == gto.get(k).getIdx_word()) continue; matrix[gto.get(j).getIdx_word()][gto.get(k).getIdx_word()]++; matrix[gto.get(k).getIdx_word()][gto.get(j).getIdx_word()]++; cntID[gto.get(j).getIdx_word()]++; cntID[gto.get(k).getIdx_word()]++; if(maxNodes < cntID[gto.get(j).getIdx_word()]) maxNodes = cntID[gto.get(j).getIdx_word()]; if(maxNodes < cntID[gto.get(k).getIdx_word()]) maxNodes = cntID[gto.get(k).getIdx_word()]; } } w = i; } } for(int j=w; j<=gto.size(); j++){ for(int k=j; k<gto.size(); k++){ if(j == k) continue; if(gto.get(j).getIdx_word() == gto.get(k).getIdx_word()) continue; matrix[gto.get(j).getIdx_word()][gto.get(k).getIdx_word()]++; matrix[gto.get(k).getIdx_word()][gto.get(j).getIdx_word()]++; cntID[gto.get(j).getIdx_word()]++; cntID[gto.get(k).getIdx_word()]++; if(maxNodes < cntID[gto.get(j).getIdx_word()]) maxNodes = cntID[gto.get(j).getIdx_word()]; if(maxNodes < cntID[gto.get(k).getIdx_word()]) maxNodes = cntID[gto.get(k).getIdx_word()]; } } // normalize ArrayList<Integer> newMap = new ArrayList<Integer>(); int[][] newMatrics = new int[size][size]; // Map for(int i=1; i<size; i++){ if(usedID[i]){ if(cntID[i] > cutLine){ newMap.add(i); } } } //Collections.sort(newMap); //newMap = new ArrayList<Integer>(newMap.subList(0, 50)); for(int i=0; i<newMap.size(); i++){ int oi = newMap.get(i); for(int oj=0; oj<size; oj++){ if(matrix[oi][oj] > cutLine){ int j = newMap.indexOf(oj); newMatrics[i][j] = matrix[oi][oj]; } } } // make JSON response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); Gson gson = new Gson(); String json = "{ \"graph\" : [], "; ArrayList<JLink> links = new ArrayList<JLink>(); for(int i=0; i<newMap.size(); i++){ for(int j=0; j<i; j++){ if(newMatrics[i][j] > 0) { links.add(new JLink(i, j)); } } } ArrayList<JNode> nodes = new ArrayList<JNode>(); for(int i=0; i<newMap.size(); i++){ int nodeSize = 10; int vCntID = cntID[newMap.get(i)]; if(vCntID > 10) nodeSize += 10; if(vCntID > 20) nodeSize += 10; if(vCntID > 30) nodeSize += 10; if(vCntID > 50) nodeSize += 10; if(vCntID > 100) nodeSize += 10; if(vCntID > 150) nodeSize += 10; if(vCntID > 500) nodeSize += 10; if(vCntID > 1000) nodeSize += 10; if(vCntID > 2000) nodeSize += 10; nodes.add(new JNode(nodeSize, wordCate[newMap.get(i)], wordID[newMap.get(i)])); } json += "\"links\" :" + new Gson().toJson(links) + ", "; json += "\"nodes\" :" + new Gson().toJson(nodes) + ", "; json += "\"directed\": false, \"multigraph\": false }"; response.getWriter().append(json); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package com.jaguarlandrover.hvacdemo; import android.content.Intent; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.*; import android.os.Handler; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class MainActivity extends ActionBarActivity implements HVACManager.HVACManagerListener { private final static String TAG = "HVACDemo:MainActivity"; private final Handler mHandler = new Handler(); private Runnable mRunnable; private HashMap<Integer, String> mViewIdsToServiceIds; private HashMap<String, Integer> mServiceIdsToViewIds; private HashMap<Integer, Integer> mButtonOffImages; private HashMap<Integer, Integer> mButtonOnImages; private HashMap<Integer, List> mSeatTempImages; private List<Integer> mSeatTempValues = Arrays.asList(0, 5, 3, 1); private int mLeftSeatTempState = 0; private int mRightSeatTempState = 0; private boolean mMaxDefrostIsOn; private boolean mAutoIsOn; private HVACState mSavedState; private boolean mHazardsAreFlashing = false; private boolean mHazardsImageIsOn; private ImageButton mHazardButton; private SeekBar mFanSpeedSeekBar; private Menu mMenu; private SeekBar.OnSeekBarChangeListener mFanSpeedSeekBarListener; private final static Integer DEFAULT_FAN_SPEED = 3; private final static Integer MAX_FAN_SPEED = 8; @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mViewIdsToServiceIds = MainActivityUtil.initializeViewToServiceIdMap(); mServiceIdsToViewIds = MainActivityUtil.initializeServiceToViewIdMap(); mButtonOffImages = MainActivityUtil.initializeButtonOffImagesMap(); mButtonOnImages = MainActivityUtil.initializeButtonOnImagesMap(); mSeatTempImages = MainActivityUtil.initializeSeatTempImagesMap(); mHazardButton = (ImageButton) findViewById(R.id.hazard_button); configurePicker((NumberPicker) findViewById(R.id.left_temp_picker)); configurePicker((NumberPicker) findViewById(R.id.right_temp_picker)); configureSeekBar((SeekBar) findViewById(R.id.fan_speed_seekbar)); mFanSpeedSeekBar = (SeekBar) findViewById(R.id.fan_speed_seekbar); findViewById(R.id.logo_graphic).setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { HVACManager.subscribeToHvacRvi(); Toast.makeText(getApplicationContext(), "Subscribed", Toast.LENGTH_SHORT).show(); return true; } }); } @Override protected void onResume() { super.onResume(); HVACManager.setListener(this); if (!HVACManager.isRviConfigured()) startActivity(new Intent(this, SettingsActivity.class)); else HVACManager.start(); } private void configureSeekBar(SeekBar seekBar) { seekBar.setMax(MAX_FAN_SPEED); seekBar.setOnSeekBarChangeListener(mFanSpeedSeekBarListener = new SeekBar.OnSeekBarChangeListener() { /* USER INTERFACE CALLBACK */ @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { Log.d(TAG, Util.getMethodName()); if (fromUser) { HVACManager.invokeService(getServiceIdentifiersFromViewId(seekBar.getId()), Integer.toString(progress)); if (progress == 0) { setAirflowDirectionButtons(0); HVACManager.invokeService(HVACServiceIdentifier.AIRFLOW_DIRECTION.value(), Integer.toString(0)); } } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } private void configurePicker(NumberPicker picker) { picker.setMinValue(15); picker.setMaxValue(29); picker.setWrapSelectorWheel(false); picker.setDisplayedValues(new String[]{"LO", "16˚", "17˚", "18˚", "19˚", "20˚", "21˚", "22˚", "23˚", "24˚", "25˚", "26˚", "27˚", "28˚", "HI"}); picker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS); picker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() { /* USER INTERFACE CALLBACK */ @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { Log.d(TAG, Util.getMethodName()); HVACManager.invokeService(getServiceIdentifiersFromViewId(picker.getId()), Integer.toString(newVal)); } }); } private void stepAnimation() { Log.d(TAG, Util.getMethodName()); if (mHazardsImageIsOn) mHazardButton.setImageResource(R.drawable.hazard_off); else mHazardButton.setImageResource(R.drawable.hazard_on); mHazardsImageIsOn = !mHazardsImageIsOn; } public void startAnimation() { Log.d(TAG, Util.getMethodName()); mHandler.postDelayed(mRunnable = new Runnable() { @Override public void run() { /* do what you need to do */ stepAnimation(); /* and here comes the "trick" */ mHandler.postDelayed(this, 1000); } }, 0); } public void stopAnimation() { Log.d(TAG, Util.getMethodName()); if (mRunnable != null) mHandler.removeCallbacks(mRunnable); } private void toggleHazardButtonFlashing(boolean shouldBeFlashing) { mHazardsAreFlashing = shouldBeFlashing; if (mHazardsAreFlashing) { startAnimation(); } else { /* if (!mHazardsAreFlashing) */ stopAnimation(); mHazardButton.setImageResource(R.drawable.hazard_off); } } /* USER INTERFACE CALLBACK */ public void hazardButtonPressed(View view) { Log.d(TAG, Util.getMethodName()); toggleHazardButtonFlashing(!mHazardsAreFlashing); HVACManager.invokeService(getServiceIdentifiersFromViewId(view.getId()), Boolean.toString(mHazardsAreFlashing)); } public void updateToggleButtonImage(ImageButton toggleButton) { if (toggleButton.isSelected()) toggleButton.setImageResource(mButtonOnImages.get(toggleButton.getId())); else toggleButton.setImageResource(mButtonOffImages.get(toggleButton.getId())); } private void toggleTheButton(ImageButton toggleButton) { toggleButton.setSelected(!toggleButton.isSelected()); updateToggleButtonImage(toggleButton); } private Integer getAirflowDirectionValue() { return ((findViewById(R.id.fan_down_button)).isSelected() ? 1 : 0) + ((findViewById(R.id.fan_right_button)).isSelected() ? 2 : 0) + ((findViewById(R.id.fan_up_button)).isSelected() ? 4 : 0); } private void setAirflowDirectionButtons (Integer value) { findViewById(R.id.fan_down_button) .setSelected(value % 2 == 1); value /= 2; findViewById(R.id.fan_right_button).setSelected(value % 2 == 1); value /= 2; findViewById(R.id.fan_up_button) .setSelected(value % 2 == 1); updateToggleButtonImage((ImageButton) findViewById(R.id.fan_down_button)); updateToggleButtonImage((ImageButton) findViewById(R.id.fan_right_button)); updateToggleButtonImage((ImageButton) findViewById(R.id.fan_up_button)); } /* USER INTERFACE CALLBACK */ public void seatTempButtonPressed(View view) { Log.d(TAG, Util.getMethodName()); ImageButton seatTempButton = (ImageButton) view; int newSeatTempState; if (seatTempButton == findViewById(R.id.left_seat_temp_button)) newSeatTempState = ++mLeftSeatTempState % 4; else newSeatTempState = ++mRightSeatTempState % 4; seatTempButton.setImageResource((Integer) mSeatTempImages.get(seatTempButton.getId()).get(newSeatTempState)); HVACManager.invokeService(getServiceIdentifiersFromViewId(seatTempButton.getId()), Integer.toString(mSeatTempValues.get(newSeatTempState))); } public void setSeatTempImageFromValue(ImageButton seatTempButton, Integer value) { int index = mSeatTempValues.indexOf(value); seatTempButton.setImageResource((Integer) mSeatTempImages.get(seatTempButton.getId()).get(index)); } private boolean shouldBreakOutOfMaxDefrost(HVACServiceIdentifier serviceIdentifier) { switch (serviceIdentifier) { case DEFROST_REAR: case DEFROST_FRONT: case AUTO: return true; } return false; } private boolean shouldBreakOutOfAuto(HVACServiceIdentifier serviceIdentifier) { switch (serviceIdentifier) { case FAN_SPEED: case AIRFLOW_DIRECTION: case DEFROST_MAX: case AIR_CIRC: case AC: case AUTO: return true; } return false; } private void breakOutOfAuto(HVACServiceIdentifier serviceIdentifier) { mAutoIsOn = false; if (serviceIdentifier != HVACServiceIdentifier.FAN_SPEED && mSavedState.getFanSpeed() != 0 && serviceIdentifier!= HVACServiceIdentifier.DEFROST_MAX) { mFanSpeedSeekBar.setProgress(mSavedState.getFanSpeed()); HVACManager.invokeService(HVACServiceIdentifier.FAN_SPEED.value(), Integer.toString(mSavedState.getFanSpeed())); } if (serviceIdentifier != HVACServiceIdentifier.AIRFLOW_DIRECTION && serviceIdentifier!= HVACServiceIdentifier.DEFROST_MAX) { setAirflowDirectionButtons(mSavedState.getAirDirection()); HVACManager.invokeService(HVACServiceIdentifier.AIRFLOW_DIRECTION.value(), Integer.toString(mSavedState.getAirDirection())); } if (serviceIdentifier != HVACServiceIdentifier.AC) { if (findViewById(R.id.ac_button).isSelected() != mSavedState.getAc()) toggleButtonPressed(findViewById(R.id.ac_button)); // toggleTheButton((ImageButton) findViewById(R.id.ac_button)); // HVACManager.invokeService(HVACServiceIdentifier.AC.value(), Boolean.toString(mSavedState.getAc())); } if (serviceIdentifier != HVACServiceIdentifier.AIR_CIRC) { if (findViewById(R.id.circ_button).isSelected() != mSavedState.getCirc()) toggleButtonPressed(findViewById(R.id.circ_button)); // toggleTheButton((ImageButton) findViewById(R.id.circ_button)); // HVACManager.invokeService(HVACServiceIdentifier.AIR_CIRC.value(), Boolean.toString(mSavedState.getCirc())); } if (serviceIdentifier != HVACServiceIdentifier.DEFROST_MAX) { if (findViewById(R.id.defrost_max_button).isSelected() != mSavedState.getDefrostMax()) toggleButtonPressed(findViewById(R.id.defrost_max_button)); // toggleTheButton((ImageButton) findViewById(R.id.defrost_max_button)); // HVACManager.invokeService(HVACServiceIdentifier.DEFROST_MAX.value(), Boolean.toString(mSavedState.getDefrostMax())); } if (serviceIdentifier != HVACServiceIdentifier.AUTO) { // if (findViewById(R.id.auto_button).isSelected() != mSavedState.getCirc()) toggleTheButton((ImageButton) findViewById(R.id.auto_button)); HVACManager.invokeService(HVACServiceIdentifier.AUTO.value(), Boolean.toString(false)); } } /* USER INTERFACE CALLBACK */ public void toggleButtonPressed(View view) { Log.d(TAG, Util.getMethodName()); ImageButton toggleButton = (ImageButton) view; String serviceIdentifier = getServiceIdentifiersFromViewId(toggleButton.getId()); /* Toggle the state of the toggle button */ toggleTheButton(toggleButton); if (mAutoIsOn && shouldBreakOutOfAuto(HVACServiceIdentifier.get(serviceIdentifier))) breakOutOfAuto(HVACServiceIdentifier.get(serviceIdentifier)); if (mMaxDefrostIsOn && shouldBreakOutOfMaxDefrost(HVACServiceIdentifier.get(serviceIdentifier))) toggleButtonPressed(findViewById(R.id.defrost_max_button)); switch (toggleButton.getId()) { case R.id.fan_down_button: case R.id.fan_up_button: case R.id.fan_right_button: /* If the fan speed is off, turn it on */ if (mFanSpeedSeekBar.getProgress() == 0) { mFanSpeedSeekBar.setProgress(DEFAULT_FAN_SPEED); HVACManager.invokeService(HVACServiceIdentifier.FAN_SPEED.value(), Integer.toString(DEFAULT_FAN_SPEED)); } if (getAirflowDirectionValue() == 0) { mFanSpeedSeekBar.setProgress(0); HVACManager.invokeService(HVACServiceIdentifier.FAN_SPEED.value(), Integer.toString(0)); } HVACManager.invokeService(getServiceIdentifiersFromViewId(toggleButton.getId()), Integer.toString(getAirflowDirectionValue())); break; case R.id.auto_button: if (toggleButton.isSelected()) { mSavedState = new HVACState(getAirflowDirectionValue(), mFanSpeedSeekBar.getProgress(), findViewById(R.id.ac_button).isSelected(), findViewById(R.id.circ_button).isSelected(), findViewById(R.id.defrost_max_button).isSelected()); setAirflowDirectionButtons(0); HVACManager.invokeService(HVACServiceIdentifier.AIRFLOW_DIRECTION.value(), Integer.toString(0)); mFanSpeedSeekBar.setProgress(0); HVACManager.invokeService(HVACServiceIdentifier.FAN_SPEED.value(), Integer.toString(0)); if (!findViewById(R.id.ac_button).isSelected()) toggleButtonPressed(findViewById(R.id.ac_button)); if (findViewById(R.id.circ_button).isSelected()) toggleButtonPressed(findViewById(R.id.circ_button)); if (findViewById(R.id.defrost_max_button).isSelected()) toggleButtonPressed(findViewById(R.id.defrost_max_button)); mAutoIsOn = true; } HVACManager.invokeService(getServiceIdentifiersFromViewId(toggleButton.getId()), Boolean.toString(toggleButton.isSelected())); break; case R.id.defrost_max_button: if (toggleButton.isSelected()) { if (!findViewById(R.id.defrost_front_button).isSelected()) toggleButtonPressed(findViewById(R.id.defrost_front_button)); if (!findViewById(R.id.defrost_rear_button).isSelected()) toggleButtonPressed(findViewById(R.id.defrost_rear_button)); setAirflowDirectionButtons(4); HVACManager.invokeService(HVACServiceIdentifier.AIRFLOW_DIRECTION.value(), Integer.toString(4)); mFanSpeedSeekBar.setProgress(5); HVACManager.invokeService(HVACServiceIdentifier.FAN_SPEED.value(), Integer.toString(5)); mMaxDefrostIsOn = true; } else { mMaxDefrostIsOn = false; } case R.id.ac_button: case R.id.defrost_rear_button: case R.id.defrost_front_button: case R.id.circ_button: HVACManager.invokeService(getServiceIdentifiersFromViewId(toggleButton.getId()), Boolean.toString(toggleButton.isSelected())); break; } } /* RVI SERVICE INVOCATION CALLBACK */ @Override public void onServiceInvoked(String serviceIdentifierString, Object value) { Integer id; View view = null; HVACServiceIdentifier serviceIdentifier = HVACServiceIdentifier.get(serviceIdentifierString); if ((id = getViewIdFromServiceIdentifier(serviceIdentifierString)) != null) view = findViewById(id); switch (serviceIdentifier) { case DEFROST_MAX: case AUTO: Boolean newToggleButtonState = Boolean.parseBoolean((String) value);//(Boolean) value; /* Special extra work for auto/max_defrost */ if (newToggleButtonState) mSavedState = new HVACState(getAirflowDirectionValue(), mFanSpeedSeekBar.getProgress(), findViewById(R.id.ac_button).isSelected(), findViewById(R.id.circ_button).isSelected(), findViewById(R.id.defrost_max_button).isSelected()); if (serviceIdentifier == HVACServiceIdentifier.AUTO) mAutoIsOn = newToggleButtonState; if (serviceIdentifier == HVACServiceIdentifier.DEFROST_MAX) mMaxDefrostIsOn = newToggleButtonState; /* Pass through... */ case AC: case AIR_CIRC: case DEFROST_FRONT: case DEFROST_REAR: if (view != null && view.isSelected() != Boolean.parseBoolean((String) value))//(Boolean) value) toggleTheButton((ImageButton) view); break; case AIRFLOW_DIRECTION: setAirflowDirectionButtons(Integer.parseInt((String) value));//((Double) value).intValue()); break; case FAN_SPEED: if (view != null) ((SeekBar) view).setProgress(Integer.parseInt((String) value));//((Double) value).intValue()); break; case SEAT_HEAT_LEFT: case SEAT_HEAT_RIGHT: setSeatTempImageFromValue((ImageButton) view, Integer.parseInt((String) value));//((Double) value).intValue()); break; case TEMP_LEFT: case TEMP_RIGHT: if (view != null) ((NumberPicker) view).setValue(Integer.parseInt((String) value));//((Double) value).intValue()); break; case HAZARD: toggleHazardButtonFlashing(Boolean.parseBoolean((String) value));//(Boolean) value); break; case SUBSCRIBE: case UNSUBSCRIBE: case NONE: break; } } @Override public void onNodeConnected() { mMenu.getItem(0).setIcon(ContextCompat.getDrawable(this, R.drawable.connected_car)); Toast.makeText(MainActivity.this, "Vehicle connected", Toast.LENGTH_SHORT).show(); } @Override public void onNodeDisconnected() { mMenu.getItem(0).setIcon(ContextCompat.getDrawable(this, R.drawable.disconnected_car)); Toast.makeText(MainActivity.this, "Vehicle disconnected", Toast.LENGTH_SHORT).show(); } String getServiceIdentifiersFromViewId(Integer uiControlId) { return mViewIdsToServiceIds.get(uiControlId); } Integer getViewIdFromServiceIdentifier(String serviceIdentifier) { return mServiceIdsToViewIds.get(serviceIdentifier); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); this.mMenu = menu; return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); return true; } else if (id == R.id.action_reconnect) { HVACManager.restart(); } return super.onOptionsItemSelected(item); } }
package com.ls.ui.activity; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.analytics.GoogleAnalytics; import com.ls.drupalconapp.R; import com.ls.drupalconapp.app.App; import com.ls.drupalconapp.model.Model; import com.ls.drupalconapp.model.UpdatesManager; import com.ls.drupalconapp.model.dao.EventDao; import com.ls.drupalconapp.model.data.Speaker; import com.ls.drupalconapp.model.data.SpeakerDetailsEvent; import com.ls.drupalconapp.model.managers.SpeakerManager; import com.ls.ui.view.CircleImageView; import com.ls.ui.view.NotifyingScrollView; import com.ls.utils.AnalyticsManager; import com.ls.utils.DateUtils; import com.ls.utils.UIUtils; import com.nirhart.parallaxscroll.views.ParallaxScrollView; import java.util.List; public class SpeakerDetailsActivity extends StackKeeperActivity implements ParallaxScrollView.OnParallaxViewScrolledListener, View.OnClickListener { public static final String EXTRA_SPEAKER = "EXTRA_SPEAKER"; public static final String EXTRA_SPEAKER_ID = "EXTRA_SPEAKER_ID"; private static final String TWITTER_URL = "https://twitter.com/"; private static final String TWITTER_APP_URL = "twitter://user?screen_name="; private View inspectView; private int mActionBarBottomCoordinate = -1; private Speaker mSpeaker; private long mSpeakerId = -1; private Toolbar mToolbar; private String mSpeakerName; //ActionBar flags private boolean isTransparentBbSet = true; private boolean isTitleBgSet = false; private SpeakerManager mSpeakerManager; private View mViewToolbar; private TextView mTitle; private NotifyingScrollView mScrollView; private boolean isWebViewLoaded; private boolean isDataLoaded; private UpdatesManager.DataUpdatedListener updateListener = new UpdatesManager.DataUpdatedListener() { @Override public void onDataUpdated(List<Integer> requestIds) { Log.d("UPDATED", "SpeakerDetailsActivity"); loadSpeakerFromDb(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ac_speaker_details); mSpeakerManager = Model.instance().getSpeakerManager(); handleExtras(getIntent()); initToolbar(); initView(); loadSpeakerFromDb(); Model.instance().getUpdatesManager().registerUpdateListener(updateListener); } @Override protected void onDestroy() { super.onDestroy(); Model.instance().getUpdatesManager().unregisterUpdateListener(updateListener); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); long oldSpeakerId = mSpeaker.getId(); handleExtras(intent); if (oldSpeakerId != mSpeaker.getId()) { fillView(mSpeaker); } } @Override protected void onStart() { super.onStart(); GoogleAnalytics.getInstance(this).reportActivityStart(this); } @Override protected void onStop() { super.onStop(); GoogleAnalytics.getInstance(this).reportActivityStop(this); } @Override public void onScrolled(int horPos, int verPos, int oldHorPos, int oldVerPos) { handleScrolling(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } private void initToolbar() { mViewToolbar = findViewById(R.id.viewToolbar); mViewToolbar.setAlpha(0); mTitle = (TextView) findViewById(R.id.toolbarTitle); mTitle.setText(mSpeakerName); mTitle.setAlpha(0); mToolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolBar); if (mToolbar != null) { mToolbar.setTitle(""); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } private void handleExtras(Intent intent) { if (intent == null) return; mSpeaker = intent.getParcelableExtra(EXTRA_SPEAKER); mSpeakerId = intent.getLongExtra(EXTRA_SPEAKER_ID, -1); if (mSpeaker != null) { mSpeakerName = String.format("%s %s", mSpeaker.getFirstName(), mSpeaker.getLastName()); } AnalyticsManager.sendEvent(this, R.string.speaker_category, R.string.action_open, mSpeakerId); } private void initView() { mScrollView = (NotifyingScrollView) findViewById(R.id.scrollView); mScrollView.setOnScrollChangedListener(onScrollChangedListener); mScrollView.setAlpha(0); mActionBarBottomCoordinate = (int) getResources().getDimension(R.dimen.action_bar_height) + (int) UIUtils.dipToPixels(SpeakerDetailsActivity.this, 24); // + height of top bar } private void loadSpeakerFromDb() { if (mSpeakerId == -1) return; new AsyncTask<Void, Void, Speaker>() { @Override protected Speaker doInBackground(Void... params) { return mSpeakerManager.getSpeakerById(mSpeakerId); } @Override protected void onPostExecute(Speaker speaker) { fillView(speaker); } }.execute(); } private void fillView(Speaker speaker) { if (speaker == null) { finish(); return; } mSpeaker = speaker; // Speaker image CircleImageView imgPhoto = (CircleImageView) findViewById(R.id.imgPhoto); String imageUrl = mSpeaker.getAvatarImageUrl(); imgPhoto.setImageWithURL(imageUrl); // Speaker name String speakerName = TextUtils.isEmpty(mSpeaker.getFirstName()) ? "" : mSpeaker.getFirstName() + " "; speakerName += TextUtils.isEmpty(mSpeaker.getLastName()) ? "" : mSpeaker.getLastName(); ((TextView) findViewById(R.id.txtSpeakerName)).setText(speakerName); // ((TextView) findViewById(R.id.txtScreenTitle)).setText(speakerName); if (TextUtils.isEmpty(mSpeaker.getJobTitle()) && TextUtils.isEmpty(mSpeaker.getOrganization())) { findViewById(R.id.txtSpeakerPosition).setVisibility(View.GONE); inspectView = findViewById(R.id.holderButtons); } else { findViewById(R.id.txtSpeakerPosition).setVisibility(View.VISIBLE); inspectView = findViewById(R.id.txtSpeakerPosition); } // Speaker job title if (!TextUtils.isEmpty(mSpeaker.getJobTitle())) { ((TextView) findViewById(R.id.txtSpeakerPosition)).setText(mSpeaker.getJobTitle()); } // Speaker organization if (!TextUtils.isEmpty(mSpeaker.getOrganization())) { TextView jobTxt = (TextView) findViewById(R.id.txtSpeakerPosition); String text = jobTxt.getText().toString() + " at " + mSpeaker.getOrganization(); jobTxt.setText(text); } // Link to Twitter if (TextUtils.isEmpty(mSpeaker.getTwitterName())) { findViewById(R.id.holderBtnTwitter).setVisibility(View.GONE); } else { findViewById(R.id.btnTwitter).setOnClickListener(this); } // Link to Website if (TextUtils.isEmpty(mSpeaker.getWebSite())) { findViewById(R.id.holderBtnWebsite).setVisibility(View.GONE); } else { findViewById(R.id.btnWebsite).setOnClickListener(this); } // Speaker details WebView webView = (WebView) findViewById(R.id.webView); if (!TextUtils.isEmpty(speaker.getCharact())) { webView.setVisibility(View.VISIBLE); webView.loadUrl("about:blank"); String css = "<link rel='stylesheet' href='css/style.css' type='text/css'>"; String html = "<html><header>" + css + "</header>" + "<body>" + mSpeaker.getCharact() + "</body></html>"; webView.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "UTF-8", null); webView.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { isWebViewLoaded = true; checkForLoadingComplete(); } }); } else { isWebViewLoaded = true; } // Events related to the speaker LinearLayout layoutEvents = (LinearLayout) findViewById(R.id.layoutEvents); addEventsToContainer(layoutEvents, mSpeaker); mScrollView.fullScroll(ScrollView.FOCUS_UP); isDataLoaded = true; checkForLoadingComplete(); } private void addEventsToContainer(final LinearLayout layoutEvents, final Speaker speaker) { new AsyncTask<Void, Void, List<SpeakerDetailsEvent>>() { @Override protected List<SpeakerDetailsEvent> doInBackground(Void... params) { EventDao eventDao = new EventDao(App.getContext()); return eventDao.getEventsBySpeakerId(speaker.getId()); } @Override protected void onPostExecute(List<SpeakerDetailsEvent> events) { findViewById(R.id.scrollView).setVisibility(View.VISIBLE); LayoutInflater inflater = LayoutInflater.from(SpeakerDetailsActivity.this); layoutEvents.removeAllViews(); for (SpeakerDetailsEvent event : events) { View eventView = inflater.inflate(R.layout.item_speakers_event, null); fillEventView(event, eventView); layoutEvents.addView(eventView); } } }.execute(); } private void fillEventView(final SpeakerDetailsEvent event, View eventView) { ((TextView) eventView.findViewById(R.id.txtArticleName)).setText(event.getEventName()); TextView txtTrack = (TextView) eventView.findViewById(R.id.txtTrack); if (!TextUtils.isEmpty(event.getTrackName())) { txtTrack.setText(event.getTrackName()); txtTrack.setVisibility(View.VISIBLE); } String weekDay = DateUtils.getInstance().getWeekDay(event.getFrom()); String fromTime = DateUtils.getInstance().getTime(this, event.getFrom()); String toTime = DateUtils.getInstance().getTime(this, event.getTo()); if (android.text.format.DateFormat.is24HourFormat(this)) { if (fromTime != null && toTime != null) { fromTime = DateUtils.getInstance().get24HoursTime(fromTime); toTime = DateUtils.getInstance().get24HoursTime(toTime); } } TextView txtWhere = (TextView) eventView.findViewById(R.id.txtWhere); String date = String.format("%s, %s - %s", weekDay, fromTime, toTime); txtWhere.setText(date); if (!event.getPlace().equals("")) { txtWhere.append(String.format(" in %s", event.getPlace())); } initEventExpLevel(eventView, event); eventView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { EventDetailsActivity.startThisActivity(SpeakerDetailsActivity.this, event.getEventId(), event.getFrom()); } }); } private void sendEventDetailsBroadcast() { Intent intent = new Intent(); intent.setAction("com.tutorialspoint.CUSTOM_INTENT"); sendBroadcast(intent); } private void initEventExpLevel(View eventView, SpeakerDetailsEvent event) { TextView txtExpLevel = (TextView) eventView.findViewById(R.id.txtExpLevel); ImageView imgExpLevel = (ImageView) eventView.findViewById(R.id.imgExpLevel); String expLevel = event.getLevelName(); if (!TextUtils.isEmpty(expLevel)) { String expText = String.format("%s %s", getResources().getString(R.string.experience_level), expLevel); txtExpLevel.setText(expText); txtExpLevel.setVisibility(View.VISIBLE); switch (expLevel) { case "Beginner": imgExpLevel.setImageResource(R.drawable.ic_experience_beginner); imgExpLevel.setVisibility(View.VISIBLE); break; case "Intermediate": imgExpLevel.setImageResource(R.drawable.ic_experience_intermediate); imgExpLevel.setVisibility(View.VISIBLE); break; case "Advanced": imgExpLevel.setImageResource(R.drawable.ic_experience_advanced); imgExpLevel.setVisibility(View.VISIBLE); break; } } } private void handleScrolling() { int locations[] = new int[2]; inspectView.getLocationOnScreen(locations); int verCoordinate = locations[1]; if (mActionBarBottomCoordinate > verCoordinate && !isTitleBgSet) { mToolbar.setBackgroundColor(getResources().getColor(R.color.primary)); isTitleBgSet = true; isTransparentBbSet = false; mToolbar.setTitle(mSpeakerName); } else if (mActionBarBottomCoordinate < verCoordinate && !isTransparentBbSet) { mToolbar.setBackgroundColor(getResources().getColor(android.R.color.transparent)); isTitleBgSet = false; isTransparentBbSet = true; mToolbar.setTitle(""); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btnTwitter: try { String url = TWITTER_APP_URL + mSpeaker.getTwitterName(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); } catch (Exception e) { String url = TWITTER_URL + mSpeaker.getTwitterName(); openBrowser(url); } break; case R.id.btnWebsite: String url = mSpeaker.getWebSite(); openBrowser(url); break; } } private NotifyingScrollView.OnScrollChangedListener onScrollChangedListener = new NotifyingScrollView.OnScrollChangedListener() { @Override public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) { int headerHeight = findViewById(R.id.imgHeader).getHeight(); float headerRatio = (float) Math.min(Math.max(t, 0), headerHeight) / headerHeight; fadeActionBar(headerRatio); } private void fadeActionBar(float headerRatio) { mTitle.setAlpha(headerRatio); mViewToolbar.setAlpha(headerRatio); } }; private void openBrowser(String url) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (Exception e) { Toast.makeText(this, getString(R.string.no_apps_can_perform_this_action), Toast.LENGTH_SHORT).show(); } } private void checkForLoadingComplete() { if (isDataLoaded && isWebViewLoaded) { findViewById(R.id.progressBar).setVisibility(View.GONE); mScrollView.setAlpha(1.0f); } } }
package com.marverenic.music.player; import android.app.ActivityManager; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.IBinder; import android.os.RemoteException; import android.support.annotation.IdRes; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.view.KeyEvent; import android.widget.RemoteViews; import com.crashlytics.android.Crashlytics; import com.marverenic.music.BuildConfig; import com.marverenic.music.IPlayerService; import com.marverenic.music.R; import com.marverenic.music.activity.LibraryActivity; import com.marverenic.music.instances.Song; import java.io.IOException; import java.util.List; public class PlayerService extends Service implements MusicPlayer.OnPlaybackChangeListener { private static final String TAG = "PlayerService"; private static final boolean DEBUG = BuildConfig.DEBUG; public static final int NOTIFICATION_ID = 1; // Intent Action & Extra names /** * Toggle between play and pause */ public static final String ACTION_TOGGLE_PLAY = "com.marverenic.music.action.TOGGLE_PLAY"; /** * Skip to the previous song */ public static final String ACTION_PREV = "com.marverenic.music.action.PREVIOUS"; /** * Skip to the next song */ public static final String ACTION_NEXT = "com.marverenic.music.action.NEXT"; /** * Stop playback and kill service */ public static final String ACTION_STOP = "com.marverenic.music.action.STOP"; /** * The service instance in use (singleton) */ private static PlayerService instance; /** * Used in binding and unbinding this service to the UI process */ private static IBinder binder; // Instance variables /** * The media player for the service instance */ private MusicPlayer musicPlayer; private boolean finished = false; // Don't attempt to release resources more than once @Override public IBinder onBind(Intent intent) { if (binder == null) { binder = new Stub(); } return binder; } /** * @inheritDoc */ @Override public void onCreate() { super.onCreate(); if (DEBUG) Log.i(TAG, "onCreate() called"); if (instance == null) { instance = this; } else { if (DEBUG) Log.w(TAG, "Attempted to create a second PlayerService"); stopSelf(); return; } if (musicPlayer == null) { musicPlayer = new MusicPlayer(this); } musicPlayer.setPlaybackChangeListener(this); musicPlayer.loadState(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); return START_STICKY; } @Override public void onDestroy() { if (DEBUG) Log.i(TAG, "Called onDestroy()"); try { musicPlayer.saveState(null); } catch (Exception ignored) { } finish(); super.onDestroy(); } public static PlayerService getInstance() { return instance; } /** * Generate and post a notification for the current player status * Posts the notification by starting the service in the foreground */ public void notifyNowPlaying() { if (DEBUG) Log.i(TAG, "notifyNowPlaying() called"); if (musicPlayer.getNowPlaying() == null) { if (DEBUG) Log.i(TAG, "Not showing notification -- nothing is playing"); return; } // Create the compact view RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.notification); // Create the expanded view RemoteViews notificationViewExpanded = new RemoteViews(getPackageName(), R.layout.notification_expanded); // Set the artwork for the notification if (musicPlayer.getArtwork() != null) { notificationView.setImageViewBitmap(R.id.notificationIcon, musicPlayer.getArtwork()); notificationViewExpanded.setImageViewBitmap(R.id.notificationIcon, musicPlayer.getArtwork()); } else { notificationView.setImageViewResource(R.id.notificationIcon, R.drawable.art_default); notificationViewExpanded .setImageViewResource(R.id.notificationIcon, R.drawable.art_default); } // If the player is playing music, set the track info and the button intents if (musicPlayer.getNowPlaying() != null) { // Update the info for the compact view notificationView.setTextViewText(R.id.notificationContentTitle, musicPlayer.getNowPlaying().getSongName()); notificationView.setTextViewText(R.id.notificationContentText, musicPlayer.getNowPlaying().getAlbumName()); notificationView.setTextViewText(R.id.notificationSubText, musicPlayer.getNowPlaying().getArtistName()); // Update the info for the expanded view notificationViewExpanded.setTextViewText(R.id.notificationContentTitle, musicPlayer.getNowPlaying().getSongName()); notificationViewExpanded.setTextViewText(R.id.notificationContentText, musicPlayer.getNowPlaying().getAlbumName()); notificationViewExpanded.setTextViewText(R.id.notificationSubText, musicPlayer.getNowPlaying().getArtistName()); } // Set the button intents for the compact view setNotificationButton(notificationView, R.id.notificationSkipPrevious, ACTION_PREV); setNotificationButton(notificationView, R.id.notificationSkipNext, ACTION_NEXT); setNotificationButton(notificationView, R.id.notificationPause, ACTION_TOGGLE_PLAY); setNotificationButton(notificationView, R.id.notificationStop, ACTION_STOP); // Set the button intents for the expanded view setNotificationButton(notificationViewExpanded, R.id.notificationSkipPrevious, ACTION_PREV); setNotificationButton(notificationViewExpanded, R.id.notificationSkipNext, ACTION_NEXT); setNotificationButton(notificationViewExpanded, R.id.notificationPause, ACTION_TOGGLE_PLAY); setNotificationButton(notificationViewExpanded, R.id.notificationStop, ACTION_STOP); // Update the play/pause button icon to reflect the player status if (!(musicPlayer.isPlaying() || musicPlayer.isPreparing())) { notificationView.setImageViewResource(R.id.notificationPause, R.drawable.ic_play_arrow_36dp); notificationViewExpanded.setImageViewResource(R.id.notificationPause, R.drawable.ic_play_arrow_36dp); } else { notificationView.setImageViewResource(R.id.notificationPause, R.drawable.ic_pause_36dp); notificationViewExpanded.setImageViewResource(R.id.notificationPause, R.drawable.ic_pause_36dp); } // Build the notification NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon( (musicPlayer.isPlaying() || musicPlayer.isPreparing()) ? R.drawable.ic_play_arrow_24dp : R.drawable.ic_pause_24dp) .setOnlyAlertOnce(true) .setOngoing(true) .setPriority(NotificationCompat.PRIORITY_LOW) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setCategory(NotificationCompat.CATEGORY_TRANSPORT) .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, LibraryActivity.class), PendingIntent.FLAG_UPDATE_CURRENT)); Notification notification = builder.build(); // Manually set the expanded and compact views notification.contentView = notificationView; if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { notification.bigContentView = notificationViewExpanded; } startForeground(NOTIFICATION_ID, notification); } private void setNotificationButton(RemoteViews notificationView, @IdRes int viewId, String action) { notificationView.setOnClickPendingIntent(viewId, PendingIntent.getBroadcast(this, 1, new Intent(this, Listener.class).setAction(action), 0)); } public void stop() { if (DEBUG) Log.i(TAG, "stop() called"); // If the UI process is still running, don't kill the process, only remove its notification ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses(); for (int i = 0; i < procInfos.size(); i++) { if (procInfos.get(i).processName.equals(BuildConfig.APPLICATION_ID)) { musicPlayer.pause(); stopForeground(true); return; } } // If the UI process has already ended, kill the service and close the player finish(); } public void finish() { if (DEBUG) Log.i(TAG, "finish() called"); if (!finished) { musicPlayer.release(); musicPlayer = null; stopForeground(true); instance = null; stopSelf(); finished = true; } } @Override public void onPlaybackChange() { notifyNowPlaying(); } public static class Listener extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent == null || intent.getAction() == null) { if (DEBUG) Log.i(TAG, "Intent received (action = null)"); return; } if (DEBUG) Log.i(TAG, "Intent received (action = \"" + intent.getAction() + "\")"); if (instance == null) { if (DEBUG) Log.i(TAG, "Service not initialized"); return; } if (instance.musicPlayer.getNowPlaying() != null) { try { instance.musicPlayer.saveState(intent.getAction()); } catch (IOException e) { Crashlytics.logException(e); if (DEBUG) e.printStackTrace(); } } switch (intent.getAction()) { case (ACTION_TOGGLE_PLAY): instance.musicPlayer.togglePlay(); instance.musicPlayer.updateUi(); break; case (ACTION_PREV): instance.musicPlayer.skipPrevious(); instance.musicPlayer.updateUi(); break; case (ACTION_NEXT): instance.musicPlayer.skip(); instance.musicPlayer.updateUi(); break; case (ACTION_STOP): instance.stop(); if (instance != null) { instance.musicPlayer.updateUi(); } break; } } } /** * Receives media button presses from in line remotes, input devices, and other sources */ public static class RemoteControlReceiver extends BroadcastReceiver { public RemoteControlReceiver() { } @Override public void onReceive(Context context, Intent intent) { // Handle Media button Intents if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) { KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); if (event.getAction() == KeyEvent.ACTION_UP) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: instance.musicPlayer.togglePlay(); break; case KeyEvent.KEYCODE_MEDIA_PLAY: instance.musicPlayer.play(); break; case KeyEvent.KEYCODE_MEDIA_PAUSE: instance.musicPlayer.pause(); break; case KeyEvent.KEYCODE_MEDIA_NEXT: instance.musicPlayer.skip(); break; case KeyEvent.KEYCODE_MEDIA_PREVIOUS: instance.musicPlayer.skipPrevious(); break; } } } } } public static class Stub extends IPlayerService.Stub { @Override public void stop() throws RemoteException { instance.stop(); } @Override public void skip() throws RemoteException { instance.musicPlayer.skip(); } @Override public void previous() throws RemoteException { instance.musicPlayer.skipPrevious(); } @Override public void begin() throws RemoteException { instance.musicPlayer.prepare(true); } @Override public void togglePlay() throws RemoteException { instance.musicPlayer.togglePlay(); } @Override public void play() throws RemoteException { instance.musicPlayer.play(); } @Override public void pause() throws RemoteException { instance.musicPlayer.play(); } @Override public void setShuffle(boolean shuffle) throws RemoteException { instance.musicPlayer.setShuffle(shuffle); } @Override public void setRepeat(int repeat) throws RemoteException { instance.musicPlayer.setRepeat(repeat); } @Override public void setQueue(List<Song> newQueue, int newPosition) throws RemoteException { instance.musicPlayer.setQueue(newQueue, newPosition); } @Override public void changeSong(int position) throws RemoteException { instance.musicPlayer.changeSong(position); } @Override public void editQueue(List<Song> newQueue, int newPosition) throws RemoteException { instance.musicPlayer.editQueue(newQueue, newPosition); } @Override public void queueNext(Song song) throws RemoteException { instance.musicPlayer.queueNext(song); } @Override public void queueNextList(List<Song> songs) throws RemoteException { instance.musicPlayer.queueNext(songs); } @Override public void queueLast(Song song) throws RemoteException { instance.musicPlayer.queueLast(song); } @Override public void queueLastList(List<Song> songs) throws RemoteException { instance.musicPlayer.queueLast(songs); } @Override public void seekTo(int position) throws RemoteException { instance.musicPlayer.seekTo(position); } @Override public boolean isPlaying() throws RemoteException { return instance.musicPlayer.isPlaying(); } @Override public Song getNowPlaying() throws RemoteException { return instance.musicPlayer.getNowPlaying(); } @Override public List<Song> getQueue() throws RemoteException { return instance.musicPlayer.getQueue(); } @Override public int getQueuePosition() throws RemoteException { return instance.musicPlayer.getQueuePosition(); } @Override public int getQueueSize() throws RemoteException { return instance.musicPlayer.getQueueSize(); } @Override public int getCurrentPosition() throws RemoteException { return instance.musicPlayer.getCurrentPosition(); } @Override public int getDuration() throws RemoteException { return instance.musicPlayer.getDuration(); } @Override public int getAudioSessionId() throws RemoteException { return instance.musicPlayer.getAudioSessionId(); } } }
package io.sweers.catchup.injection; import com.bluelinelabs.conductor.Controller; import dagger.MapKey; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.METHOD; /** {@link MapKey} annotation to key bindings by a type of a {@link Controller}. */ @MapKey @Target(METHOD) public @interface ControllerKey { Class<? extends Controller> value(); }
package org.sil.bloom.reader; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.webkit.DownloadListener; import android.webkit.WebSettings; import android.webkit.WebView; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; // BloomLibraryActivity is used to interact with the online BloomLibrary. It uses special URLs // with a leading app-hosted-v1 element which result in a layout optimized for downloading books // to a device. Most of the content is a WebView hosting BloomLibrary.org. A small view at the // bottom can show progress and results of downloads. public class BloomLibraryActivity extends BaseActivity implements MessageReceiver { WebView mBrowser; WebAppInterface mAppInterface; DownloadsView mDownloads; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Adds back button ActionBar actionBar = getSupportActionBar(); if (actionBar != null) actionBar.setDisplayHomeAsUpEnabled(true); // Allows remote debugging of the WebView content using Chrome over a USB cable. WebView.setWebContentsDebuggingEnabled(true); setContentView(R.layout.activity_bloom_library); mBrowser = this.findViewById(R.id.browser); // BL-7567 fixes "cross-pollination" of images. // This is only marginally necessary here, but the user CAN actually read a book directly in // the browser. mBrowser.clearCache(false); mBrowser.getSettings().setUserAgentString(mBrowser.getSettings().getUserAgentString() + ";sil-bloom"); mAppInterface = new WebAppInterface(this); // See the class comment on WebAppInterface for how this allows Javascript in // the WebView to make callbacks to our receiveMessage method. mBrowser.addJavascriptInterface(mAppInterface, "ParentProxy"); final WebSettings webSettings = mBrowser.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setMediaPlaybackRequiresUserGesture(false); mDownloads = (DownloadsView) BloomLibraryActivity.this .findViewById(R.id.download_books); // Inform our download-handling component when the browser asks to download something. mBrowser.setDownloadListener(new DownloadListener() { public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { mDownloads.onDownloadStart(url, userAgent, contentDisposition, mimetype, contentLength, mBrowser.getUrl()); } }); try { mBrowser.setWebViewClient(new BloomLibraryWebViewClient(this)); mBrowser.setWebChromeClient(new BloomLibraryWebChromeClient(this)); // I'm not sure if this really a helpful setting or if we are actually just working around a bug in Android Webview... // Randomly, some devices started having display issues with videos. They would be very jerky or skip. // It seemed to be related to a recent version of Android colorWebview as uninstalling updates seemed to fix it // and reinstalling seemed to break it. But we could never prove it definitively. // (This was copied from the init of the WebView for BloomPlayer. Probably not needed here, but harmless AFAIK.) mBrowser.setLayerType(View.LAYER_TYPE_HARDWARE, null); String host = "https://bloomlibrary.org"; if (BuildConfig.DEBUG || BuildConfig.FLAVOR.equals("alpha") || BuildConfig.FLAVOR.equals("beta")) host = "https://alpha.bloomlibrary.org"; // Note: if you configure a host that needs to use the dev parse server, // you will need to add a case to the code in BloomLibraryWebViewClient.shouldInterceptRequest // which sets X-Parse-Application-Id, and have it set the appropriate key for dev. // Use this to test running local bloomlibrary in a BR emulator. // 10.0.2.2 is the host machine's localhost. // Use something like this to test a real device with a local build. // Get the right IP address for your serving computer using ipconfig or similar; // the one that yarn start-performance reports ("On Your Network:") is WRONG. // Also enable this URL in res/xml/network_security_config.xml // We start the browser showing this specialized page in BloomLibrary. mBrowser.loadUrl(host + "/app-hosted-v1/langs"); } catch (Exception e) { Log.e("Load", e.getMessage()); } } @Override protected void onResume() { super.onResume(); // Set the bottom panel to indicate any downloads that are still in progress. mDownloads.updateUItoCurrentState(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.bloom_library_menu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.bloom_library_home) { finish(); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return false; } // At one point this seemed to be necessary to make the back button or gesture useful within // the web page rather than always immediately ending the BL activity. Later experiments made // me more doubtful...something else may have been preventing the browser from going back. // But it's the recommended way to do this so I'm leaving it in. @Override public void onBackPressed() { if (mBrowser.canGoBack()) { mBrowser.goBack(); } else { super.onBackPressed(); } } // Not actually needed except it's required to be a subclass of BaseActivity. @Override protected void onNewOrUpdatedBook(String fullPath) { } // This function can receive messages sent by Javascript in BloomLibrary, in a way explained // in WebAppInterface. @Override public void receiveMessage(String message) { if (message.equals("go_home")) { // Unexpectedly, this takes us back to the home page in the webview. //super.onBackPressed(); // This terminates the whole activity and takes us back to the main view. // We would need to do something more if this activity could be launched from somewhere // other than the home screen, but that isn't currently the case. finish(); } else if (message.equals("close_keyboard")) { InputMethodManager imm = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mBrowser.getWindowToken(), 0); } } }
package org.commcare.dalvik.activities; import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.content.res.Configuration; import android.database.DataSetObserver; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.commcare.android.adapters.EntityListAdapter; import org.commcare.android.framework.CommCareActivity; import org.commcare.android.logic.DetailCalloutListenerDefaultImpl; import org.commcare.android.models.AndroidSessionWrapper; import org.commcare.android.models.Entity; import org.commcare.android.models.NodeEntityFactory; import org.commcare.android.tasks.EntityLoaderListener; import org.commcare.android.tasks.EntityLoaderTask; import org.commcare.android.util.CommCareInstanceInitializer; import org.commcare.android.util.DetailCalloutListener; import org.commcare.android.util.SerializationUtil; import org.commcare.android.util.SessionUnavailableException; import org.commcare.android.view.EntityView; import org.commcare.android.view.TabbedDetailView; import org.commcare.android.view.ViewUtil; import org.commcare.dalvik.R; import org.commcare.dalvik.application.CommCareApplication; import org.commcare.dalvik.preferences.DeveloperPreferences; import org.commcare.suite.model.Action; import org.commcare.suite.model.Callout; import org.commcare.suite.model.CalloutData; import org.commcare.suite.model.Detail; import org.commcare.suite.model.DetailField; import org.commcare.suite.model.SessionDatum; import org.commcare.util.CommCareSession; import org.commcare.util.SessionFrame; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.AbstractTreeElement; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.services.locale.Localization; import org.javarosa.model.xform.XPathReference; import java.io.IOException; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Timer; import java.util.TimerTask; /** * * TODO: Lots of locking and state-based cleanup * * @author ctsims * */ public class EntitySelectActivity extends CommCareActivity implements TextWatcher, EntityLoaderListener, OnItemClickListener, TextToSpeech.OnInitListener, DetailCalloutListener { private CommCareSession session; private AndroidSessionWrapper asw; public static final String EXTRA_ENTITY_KEY = "esa_entity_key"; public static final String EXTRA_IS_MAP = "is_map"; private static final int CONFIRM_SELECT = 0; private static final int BARCODE_FETCH = 1; private static final int MAP_SELECT = 2; private static final int CALLOUT = 3; private static final int MENU_SORT = Menu.FIRST; private static final int MENU_MAP = Menu.FIRST + 1; private static final int MENU_ACTION = Menu.FIRST + 2; EditText searchbox; TextView searchResultStatus; EntityListAdapter adapter; LinearLayout header; ImageButton calloutButton; TextToSpeech tts; SessionDatum selectDatum; EvaluationContext entityContext; boolean mResultIsMap = false; boolean mMappingEnabled = false; // Is the detail screen for showing entities, without option for moving // forward on to form manipulation? boolean mViewMode = false; // Has a detail screen not been defined? boolean mNoDetailMode = false; private EntityLoaderTask loader; private boolean inAwesomeMode = false; FrameLayout rightFrame; TabbedDetailView detailView; Intent selectedIntent = null; String filterString = ""; private Detail shortSelect; private DataSetObserver mListStateObserver; /* * (non-Javadoc) * @see org.commcare.android.framework.CommCareActivity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.createDataSetObserver(); EntitySelectActivity oldActivity = (EntitySelectActivity)this.getDestroyedActivityState(); if(savedInstanceState != null) { mResultIsMap = savedInstanceState.getBoolean(EXTRA_IS_MAP, false); } try { asw = CommCareApplication._().getCurrentSessionWrapper(); session = asw.getSession(); } catch(SessionUnavailableException sue){ //The user isn't logged in! bounce this back to where we came from this.setResult(Activity.RESULT_CANCELED); this.finish(); return; } selectDatum = session.getNeededDatum(); shortSelect = session.getDetail(selectDatum.getShortDetail()); mNoDetailMode = selectDatum.getLongDetail() == null; if(this.getString(R.string.panes).equals("two") && !mNoDetailMode) { //See if we're on a big 'ol screen. if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { //If we're in landscape mode, we can display this with the awesome UI. //Inflate and set up the normal view for now. setContentView(R.layout.screen_compound_select); View.inflate(this, R.layout.entity_select_layout, (ViewGroup)findViewById(R.id.screen_compound_select_left_pane)); inAwesomeMode = true; rightFrame = (FrameLayout)findViewById(R.id.screen_compound_select_right_pane); TextView message = (TextView)findViewById(R.id.screen_compound_select_prompt); //use the old method here because some Android versions don't like Spannables for titles message.setText(Localization.get("select.placeholder.message", new String[]{Localization.get("cchq.case")})); } else { setContentView(R.layout.entity_select_layout); //So we're not in landscape mode anymore, but were before. If we had something selected, we //need to go to the detail screen instead. if (oldActivity != null) { Intent intent = this.getIntent(); TreeReference selectedRef = SerializationUtil.deserializeFromIntent(intent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class); if (selectedRef != null) { // remove the reference from this intent, ensuring we // don't re-launch the detail for an entity even after // it being de-selected. intent.removeExtra(EntityDetailActivity.CONTEXT_REFERENCE); // attach the selected entity to the new detail intent // we're launching Intent detailIntent = getDetailIntent(selectedRef, null); startOther = true; startActivityForResult(detailIntent, CONFIRM_SELECT); } } } } else { setContentView(R.layout.entity_select_layout); } ((ListView)this.findViewById(R.id.screen_entity_select_list)).setOnItemClickListener(this); TextView searchLabel = (TextView)findViewById(R.id.screen_entity_select_search_label); //use the old method here because some Android versions don't like Spannables for titles searchLabel.setText(Localization.get("select.search.label")); searchLabel.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // get the focus on the edittext by performing click searchbox.performClick(); // then force the keyboard up since performClick() apparently isn't enough on some devices InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); // only will trigger it if no physical keyboard is open inputMethodManager.showSoftInput(searchbox, InputMethodManager.SHOW_IMPLICIT); } }); searchbox = (EditText)findViewById(R.id.searchbox); searchbox.setMaxLines(3); searchbox.setHorizontallyScrolling(false); searchResultStatus = (TextView) findViewById(R.id.no_search_results); header = (LinearLayout)findViewById(R.id.entity_select_header); mViewMode = session.isViewCommand(session.getCommand()); Callout callout = shortSelect.getCallout(); calloutButton = (ImageButton)findViewById(R.id.barcodeButton); if (callout == null) { // Default to barcode scanning if no callout defined in the detail calloutButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent("com.google.zxing.client.android.SCAN"); try { startActivityForResult(i, BARCODE_FETCH); } catch (ActivityNotFoundException anfe) { Toast.makeText(EntitySelectActivity.this, "No barcode reader available! You can install one " + "from the android market.", Toast.LENGTH_LONG).show(); } } }); } else { CalloutData calloutData = callout.evaluate(); if (calloutData.getImage() != null) { setupImageLayout(calloutButton, calloutData.getImage()); } final String actionName = calloutData.getActionName(); final Hashtable<String, String> extras = calloutData.getExtras(); calloutButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(actionName); for(String key: extras.keySet()){ i.putExtra(key, extras.get(key)); } try { startActivityForResult(i, CALLOUT); } catch (ActivityNotFoundException anfe) { Toast.makeText(EntitySelectActivity.this, "No application found for action: " + actionName, Toast.LENGTH_LONG).show(); } } }); } searchbox.addTextChangedListener(this); searchbox.requestFocus(); if(oldActivity != null) { adapter = oldActivity.adapter; //not sure how this happens, but seem plausible. if(adapter != null) { adapter.setController(this); ((ListView)this.findViewById(R.id.screen_entity_select_list)).setAdapter(adapter); findViewById(R.id.entity_select_loading).setVisibility(View.GONE); //Disconnect the old adapter adapter.unregisterDataSetObserver(oldActivity.mListStateObserver); //connect the new one adapter.registerDataSetObserver(this.mListStateObserver); } } //cts: disabling for non-demo purposes //tts = new TextToSpeech(this, this); } /** * Updates the ImageView layout that is passed in, based on the * new id and source */ public void setupImageLayout(View layout, final String imagePath) { ImageView iv = (ImageView)layout; Bitmap b; if (!imagePath.equals("")) { try { b = BitmapFactory.decodeStream(ReferenceManager._().DeriveReference(imagePath).getStream()); if (b == null) { // Input stream could not be used to derive bitmap, so // showing error-indicating image iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } else { iv.setImageBitmap(b); } } catch (IOException ex) { ex.printStackTrace(); // Error loading image, default to folder button iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } catch (InvalidReferenceException ex) { ex.printStackTrace(); // No image, default to folder button iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } } else { // no image passed in, draw a white background iv.setImageDrawable(getResources().getDrawable(R.color.white)); } } private void createDataSetObserver() { mListStateObserver = new DataSetObserver() { @Override public void onChanged() { super.onChanged(); //update the search results box String query = searchbox.getText().toString(); if (!"".equals(query)) { searchResultStatus.setText(Localization.get("select.search.status", new String[] { ""+adapter.getCount(true, false), ""+adapter.getCount(true, true), query })); searchResultStatus.setVisibility(View.VISIBLE); } else { searchResultStatus.setVisibility(View.GONE); } } }; } /* * (non-Javadoc) * @see org.commcare.android.framework.CommCareActivity#isTopNavEnabled() */ @Override protected boolean isTopNavEnabled() { return true; } /* * (non-Javadoc) * @see org.commcare.android.framework.CommCareActivity#getActivityTitle() */ @Override public String getActivityTitle() { //Skipping this until it's a more general pattern // String title = Localization.get("select.list.title"); // try { // Detail detail = session.getDetail(selectDatum.getShortDetail()); // title = detail.getTitle().evaluate(); // } catch(Exception e) { // return title; return null; } boolean resuming = false; boolean startOther = false; public void onResume() { super.onResume(); //Don't go through making the whole thing if we're finishing anyway. if (this.isFinishing() || startOther) { return; } if(!resuming && !mNoDetailMode && this.getIntent().hasExtra(EXTRA_ENTITY_KEY)) { TreeReference entity = selectDatum.getEntityFromID(asw.getEvaluationContext(), this.getIntent().getStringExtra(EXTRA_ENTITY_KEY)); if(entity != null) { if(inAwesomeMode) { if (adapter != null) { displayReferenceAwesome(entity, adapter.getPosition(entity)); adapter.setAwesomeMode(true); updateSelectedItem(entity, true); } } else { //Once we've done the initial dispatch, we don't want to end up triggering it later. this.getIntent().removeExtra(EXTRA_ENTITY_KEY); Intent i = getDetailIntent(entity, null); if (adapter != null) { i.putExtra("entity_detail_index", adapter.getPosition(entity)); i.putExtra(EntityDetailActivity.DETAIL_PERSISTENT_ID, selectDatum.getShortDetail()); } startActivityForResult(i, CONFIRM_SELECT); return; } } } refreshView(); } /** * Get form list from database and insert into view. */ private void refreshView() { try { //TODO: Get ec into these text's String[] headers = new String[shortSelect.getFields().length]; for(int i = 0 ; i < headers.length ; ++i) { headers[i] = shortSelect.getFields()[i].getHeader().evaluate(); if("address".equals(shortSelect.getFields()[i].getTemplateForm())) { this.mMappingEnabled = true; } } //Hm, sadly we possibly need to rebuild this each time. EntityView v = new EntityView(this, shortSelect, headers); header.removeAllViews(); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); v.setBackgroundResource(R.drawable.blue_tabbed_box); // only add headers if we're not using grid mode if(!shortSelect.usesGridView()){ header.addView(v,params); } if(adapter == null && loader == null && !EntityLoaderTask.attachToActivity(this)) { EntityLoaderTask theloader = new EntityLoaderTask(shortSelect, asw.getEvaluationContext()); theloader.attachListener(this); theloader.execute(selectDatum.getNodeset()); } else { startTimer(); } } catch(SessionUnavailableException sue) { //TODO: login and return } } @Override protected void onPause() { super.onPause(); stopTimer(); } @Override public void onStop() { super.onStop(); stopTimer(); } protected Intent getDetailIntent(TreeReference contextRef, Intent detailIntent) { if (detailIntent == null) { detailIntent = new Intent(getApplicationContext(), EntityDetailActivity.class); } // grab the session's (form) element reference, and load it. TreeReference elementRef = XPathReference.getPathExpr(selectDatum.getValue()).getReference(true); AbstractTreeElement element = asw.getEvaluationContext().resolveReference(elementRef.contextualize(contextRef)); String value = ""; // get the case id and add it to the intent if(element != null && element.getValue() != null) { value = element.getValue().uncast().getString(); } detailIntent.putExtra(SessionFrame.STATE_DATUM_VAL, value); // Include long datum info if present. Otherwise that'll be the queue // to just return if (selectDatum.getLongDetail() != null) { detailIntent.putExtra(EntityDetailActivity.DETAIL_ID, selectDatum.getLongDetail()); detailIntent.putExtra(EntityDetailActivity.DETAIL_PERSISTENT_ID, selectDatum.getPersistentDetail()); } SerializationUtil.serializeToIntent(detailIntent, EntityDetailActivity.CONTEXT_REFERENCE, contextRef); return detailIntent; } /* * (non-Javadoc) * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long) */ @Override public void onItemClick(AdapterView<?> listView, View view, int position, long id) { if(id == EntityListAdapter.SPECIAL_ACTION) { triggerDetailAction(); return; } TreeReference selection = adapter.getItem(position); if(inAwesomeMode) { displayReferenceAwesome(selection, position); updateSelectedItem(selection, false); } else { Intent i = getDetailIntent(selection, null); i.putExtra("entity_detail_index", position); if (mNoDetailMode) { returnWithResult(i); } else { startActivityForResult(i, CONFIRM_SELECT); } } } /* * (non-Javadoc) * @see android.app.Activity#onActivityResult(int, int, android.content.Intent) */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { switch(requestCode){ case BARCODE_FETCH: if(resultCode == Activity.RESULT_OK) { String result = intent.getStringExtra("SCAN_RESULT"); this.searchbox.setText(result); } break; case CALLOUT: if (resultCode == Activity.RESULT_OK) { boolean resultSet = false; String result = intent.getStringExtra("odk_intent_data"); if (result != null) { this.searchbox.setText(result); resultSet = true; } Callout callout = shortSelect.getCallout(); for (String key : callout.getResponses()) { result = intent.getExtras().getString(key); if (!resultSet) { resultSet = true; this.searchbox.setText(result); break; } } } break; case CONFIRM_SELECT: resuming = true; if(resultCode == RESULT_OK && !mViewMode) { // create intent for return and store path returnWithResult(intent); return; } else { //Did we enter the detail from mapping mode? If so, go back to that if(mResultIsMap) { mResultIsMap = false; Intent i = new Intent(this, EntityMapActivity.class); this.startActivityForResult(i, MAP_SELECT); return; } if (inAwesomeMode) { // Retain original element selection TreeReference r = SerializationUtil.deserializeFromIntent(intent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class); if (r != null && adapter != null) { // TODO: added 'adapter != null' due to a // NullPointerException, we need to figure out how to // make sure adapter is never null -- PLM this.displayReferenceAwesome(r, adapter.getPosition(r)); updateSelectedItem(r, true); } releaseCurrentMediaEntity(); } return; } case MAP_SELECT: if(resultCode == RESULT_OK) { TreeReference r = SerializationUtil.deserializeFromIntent(intent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class); if(inAwesomeMode) { this.displayReferenceAwesome(r, adapter.getPosition(r)); } else { Intent i = this.getDetailIntent(r, null); if(mNoDetailMode) { returnWithResult(i); } else { //To go back to map mode if confirm is false mResultIsMap = true; i.putExtra("entity_detail_index", adapter.getPosition(r)); startActivityForResult(i, CONFIRM_SELECT); } return; } } else { refreshView(); return; } default: super.onActivityResult(requestCode, resultCode, intent); } } private void returnWithResult(Intent intent) { Intent i = new Intent(this.getIntent()); i.putExtras(intent.getExtras()); setResult(RESULT_OK, i); finish(); } public void afterTextChanged(Editable s) { if(searchbox.getText() == s) { filterString = s.toString(); if(adapter != null) { adapter.applyFilter(filterString); } } } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } /* * (non-Javadoc) * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); //use the old method here because some Android versions don't like Spannables for titles menu.add(0, MENU_SORT, MENU_SORT, Localization.get("select.menu.sort")).setIcon( android.R.drawable.ic_menu_sort_alphabetically); if(mMappingEnabled) { menu.add(0, MENU_MAP, MENU_MAP, Localization.get("select.menu.map")).setIcon( android.R.drawable.ic_menu_mapmode); } Action action = shortSelect.getCustomAction(); if(action != null) { ViewUtil.addDisplayToMenu(this, menu, MENU_ACTION, action.getDisplay().evaluate()); } return true; } /* (non-Javadoc) * @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu) */ @Override public boolean onPrepareOptionsMenu(Menu menu) { //only display the sort menu if we're going to be able to sort //(IE: not until the items have loaded) menu.findItem(MENU_SORT).setEnabled(adapter != null); return super.onPrepareOptionsMenu(menu); } /* * (non-Javadoc) * @see org.commcare.android.framework.CommCareActivity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_SORT: createSortMenu(); return true; case MENU_MAP: Intent i = new Intent(this, EntityMapActivity.class); this.startActivityForResult(i, MAP_SELECT); return true; case MENU_ACTION: triggerDetailAction(); return true; } return super.onOptionsItemSelected(item); } private void triggerDetailAction() { Action action = shortSelect.getCustomAction(); asw.executeStackActions(action.getStackOperations()); this.setResult(CommCareHomeActivity.RESULT_RESTART); this.finish(); } private void createSortMenu() { AlertDialog.Builder builder = new AlertDialog.Builder(this); //use the old method here because some Android versions don't like Spannables for titles builder.setTitle(Localization.get("select.menu.sort")); SessionDatum datum = session.getNeededDatum(); DetailField[] fields = session.getDetail(datum.getShortDetail()).getFields(); List<String> namesList = new ArrayList<String>(); final int[] keyarray = new int[fields.length]; int[] sorts = adapter.getCurrentSort(); int currentSort = sorts.length == 1 ? sorts[0] : -1; boolean reversed = adapter.isCurrentSortReversed(); int added = 0; for(int i = 0 ; i < fields.length ; ++i) { String result = fields[i].getHeader().evaluate(); if(!"".equals(result)) { String prepend = ""; if(currentSort == -1) { for(int j = 0 ; j < sorts.length ; ++ j) { if(sorts[j] == i) { prepend = (j+1) + " " + (fields[i].getSortDirection() == DetailField.DIRECTION_DESCENDING ? "(v) " : "(^) "); } } } else if(currentSort == i) { prepend = reversed ^ fields[i].getSortDirection() == DetailField.DIRECTION_DESCENDING ? "(v) " : "(^) "; } namesList.add(prepend + result); keyarray[added] = i; added++; } } final String[] names = namesList.toArray(new String[0]); builder.setItems(names, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { adapter.sortEntities(new int[] { keyarray[item]}); adapter.applyFilter(searchbox.getText().toString()); } }); builder.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { } }); AlertDialog alert = builder.create(); alert.show(); } /* * (non-Javadoc) * @see org.commcare.android.framework.CommCareActivity#onDestroy() */ @Override public void onDestroy() { super.onDestroy(); if(loader != null) { if(isFinishing()) { loader.cancel(false); } else { loader.detachActivity(); } } if(adapter != null) { adapter.signalKilled(); } if (tts != null) { tts.stop(); tts.shutdown(); } } /* * (non-Javadoc) * @see android.speech.tts.TextToSpeech.OnInitListener#onInit(int) */ @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { //using the default speech engine for now. } else { } } /* * (non-Javadoc) * @see org.commcare.android.tasks.EntityLoaderListener#deliverResult(java.util.List, java.util.List) */ @Override public void deliverResult(List<Entity<TreeReference>> entities, List<TreeReference> references, NodeEntityFactory factory) { loader = null; Detail detail = session.getDetail(selectDatum.getShortDetail()); int[] order = detail.getSortOrder(); for(int i = 0 ; i < detail.getFields().length ; ++i) { String header = detail.getFields()[i].getHeader().evaluate(); if(order.length == 0 && !"".equals(header)) { order = new int[] {i}; } } ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list)); adapter = new EntityListAdapter(EntitySelectActivity.this, detail, references, entities, order, tts, this, factory); view.setAdapter(adapter); adapter.registerDataSetObserver(this.mListStateObserver); findViewById(R.id.entity_select_loading).setVisibility(View.GONE); if(adapter != null && filterString != null && !"".equals(filterString)) { adapter.applyFilter(filterString); } //In landscape we want to select something now. Either the top item, or the most recently selected one if(inAwesomeMode) { updateSelectedItem(true); } this.startTimer(); } private void updateSelectedItem(boolean forceMove) { TreeReference chosen = null; if(selectedIntent != null) { chosen = SerializationUtil.deserializeFromIntent(selectedIntent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class); } updateSelectedItem(chosen, forceMove); } private void updateSelectedItem(TreeReference selected, boolean forceMove) { if(adapter == null) {return;} if(selected != null) { adapter.notifyCurrentlyHighlighted(selected); if(forceMove) { ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list)); view.setSelection(adapter.getPosition(selected)); } return; } } /* * (non-Javadoc) * @see org.commcare.android.tasks.EntityLoaderListener#attach(org.commcare.android.tasks.EntityLoaderTask) */ @Override public void attach(EntityLoaderTask task) { findViewById(R.id.entity_select_loading).setVisibility(View.VISIBLE); this.loader = task; } public boolean inAwesomeMode(){ return inAwesomeMode; } boolean rightFrameSetup = false; NodeEntityFactory factory; private void select() { // create intent for return and store path Intent i = new Intent(EntitySelectActivity.this.getIntent()); i.putExtra(SessionFrame.STATE_DATUM_VAL, selectedIntent.getStringExtra(SessionFrame.STATE_DATUM_VAL)); setResult(RESULT_OK, i); finish(); } // CommCare-159503: implementing DetailCalloutListener so it will not crash the app when requesting call/sms public void callRequested(String phoneNumber) { DetailCalloutListenerDefaultImpl.callRequested(this, phoneNumber); } public void addressRequested(String address) { DetailCalloutListenerDefaultImpl.addressRequested(this, address); } public void playVideo(String videoRef) { DetailCalloutListenerDefaultImpl.playVideo(this, videoRef); } public void performCallout(CalloutData callout, int id) { DetailCalloutListenerDefaultImpl.performCallout(this, callout, id); } public void displayReferenceAwesome(final TreeReference selection, int detailIndex) { selectedIntent = getDetailIntent(selection, getIntent()); //this should be 100% "fragment" able if(!rightFrameSetup) { findViewById(R.id.screen_compound_select_prompt).setVisibility(View.GONE); View.inflate(this, R.layout.entity_detail, rightFrame); Button next = (Button)findViewById(R.id.entity_select_button); //use the old method here because some Android versions don't like Spannables for titles next.setText(Localization.get("select.detail.confirm")); next.setOnClickListener(new OnClickListener() { public void onClick(View v) { select(); return; } }); if (mViewMode) { next.setVisibility(View.GONE); } String passedCommand = selectedIntent.getStringExtra(SessionFrame.STATE_COMMAND_ID); if (passedCommand != null) { mViewMode = session.isViewCommand(passedCommand); } else { mViewMode = session.isViewCommand(session.getCommand()); } detailView = new TabbedDetailView(this); detailView.setRoot((ViewGroup) rightFrame.findViewById(R.id.entity_detail_tabs)); factory = new NodeEntityFactory(session.getDetail(selectedIntent.getStringExtra(EntityDetailActivity.DETAIL_ID)), session.getEvaluationContext(new CommCareInstanceInitializer(session))); Detail detail = factory.getDetail(); detailView.setDetail(detail); if (detail.isCompound()) { // border around right panel doesn't look right when there are tabs rightFrame.setBackgroundDrawable(null); } rightFrameSetup = true; } detailView.refresh(factory.getDetail(), selection, detailIndex, false); } /* * (non-Javadoc) * @see org.commcare.android.tasks.EntityLoaderListener#deliverError(java.lang.Exception) */ @Override public void deliverError(Exception e) { displayException(e); } /* * (non-Javadoc) * @see org.commcare.android.framework.CommCareActivity#onForwardSwipe() */ @Override protected boolean onForwardSwipe() { // If user has picked an entity, move along to form entry if (selectedIntent != null) { if (inAwesomeMode && detailView != null && detailView.getCurrentTab() < detailView.getTabCount() - 1) { return false; } if (!mViewMode) { select(); } } return true; } /* * (non-Javadoc) * @see org.commcare.android.framework.CommCareActivity#onBackwardSwipe() */ @Override protected boolean onBackwardSwipe() { if (inAwesomeMode && detailView != null && detailView.getCurrentTab() > 0) { return false; } finish(); return true; } //Below is helper code for the Refresh Feature. //this is a dev feature and should get restructured before release in prod. //If the devloper setting is turned off this code should do nothing. private void triggerRebuild() { if(loader == null && !EntityLoaderTask.attachToActivity(this)) { EntityLoaderTask theloader = new EntityLoaderTask(shortSelect, asw.getEvaluationContext()); theloader.attachListener(this); theloader.execute(selectDatum.getNodeset()); } } private Timer myTimer; private Object timerLock = new Object(); boolean cancelled; private void startTimer() { if(!DeveloperPreferences.isListRefreshEnabled()) { return; } synchronized(timerLock) { if(myTimer == null) { myTimer = new Timer(); myTimer.schedule(new TimerTask() { @Override public void run() { runOnUiThread( new Runnable() { @Override public void run() { if(!cancelled) { triggerRebuild(); } } }); } }, 15*1000, 15 * 1000); cancelled = false; } } } private void stopTimer() { synchronized(timerLock) { if(myTimer != null) { myTimer.cancel(); myTimer = null; cancelled = true; } } } }
package org.commcare.dalvik.activities; import android.annotation.TargetApi; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.database.DataSetObserver; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.LayerDrawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.FragmentManager; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.util.TypedValue; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SearchView; import android.widget.TextView; import android.widget.Toast; import org.commcare.android.adapters.EntityListAdapter; import org.commcare.android.fragments.ContainerFragment; import org.commcare.android.framework.CommCareActivity; import org.commcare.android.framework.SaveSessionCommCareActivity; import org.commcare.android.logic.DetailCalloutListenerDefaultImpl; import org.commcare.android.models.AndroidSessionWrapper; import org.commcare.android.models.Entity; import org.commcare.android.models.NodeEntityFactory; import org.commcare.android.tasks.EntityLoaderListener; import org.commcare.android.tasks.EntityLoaderTask; import org.commcare.android.util.AndroidInstanceInitializer; import org.commcare.android.util.DetailCalloutListener; import org.commcare.android.util.SerializationUtil; import org.commcare.android.view.EntityView; import org.commcare.android.view.TabbedDetailView; import org.commcare.android.view.ViewUtil; import org.commcare.dalvik.R; import org.commcare.dalvik.activities.utils.EntityDetailUtils; import org.commcare.dalvik.activities.utils.EntitySelectRefreshTimer; import org.commcare.dalvik.application.CommCareApplication; import org.commcare.dalvik.dialogs.DialogChoiceItem; import org.commcare.dalvik.dialogs.PaneledChoiceDialog; import org.commcare.dalvik.geo.HereFunctionHandler; import org.commcare.dalvik.preferences.CommCarePreferences; import org.commcare.session.CommCareSession; import org.commcare.session.SessionFrame; import org.commcare.suite.model.Action; import org.commcare.suite.model.Callout; import org.commcare.suite.model.CalloutData; import org.commcare.suite.model.Detail; import org.commcare.suite.model.DetailField; import org.commcare.suite.model.SessionDatum; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.xpath.XPathTypeMismatchException; import org.odk.collect.android.utilities.GeoUtils; import org.odk.collect.android.views.media.AudioController; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author ctsims */ public class EntitySelectActivity extends SaveSessionCommCareActivity implements TextWatcher, EntityLoaderListener, OnItemClickListener, DetailCalloutListener { private static final String TAG = EntitySelectActivity.class.getSimpleName(); private CommCareSession session; private AndroidSessionWrapper asw; public static final String EXTRA_ENTITY_KEY = "esa_entity_key"; private static final String EXTRA_IS_MAP = "is_map"; private static final String CONTAINS_HERE_FUNCTION = "contains_here_function"; private static final String LOCATION_CHANGED_WHILE_LOADING = "location_changed_while_loading"; private static final int CONFIRM_SELECT = 0; private static final int MAP_SELECT = 2; private static final int BARCODE_FETCH = 1; private static final int CALLOUT = 3; private static final int MENU_SORT = Menu.FIRST + 1; private static final int MENU_MAP = Menu.FIRST + 2; private static final int MENU_ACTION = Menu.FIRST + 3; private EditText searchbox; private TextView searchResultStatus; private EntityListAdapter adapter; private LinearLayout header; private ImageButton barcodeButton; private SearchView searchView; private MenuItem searchItem; private SessionDatum selectDatum; private boolean mResultIsMap = false; private boolean mMappingEnabled = false; // Is the detail screen for showing entities, without option for moving // forward on to form manipulation? private boolean mViewMode = false; // No detail confirm screen is defined for this entity select private boolean mNoDetailMode = false; private EntityLoaderTask loader; private boolean inAwesomeMode = false; private FrameLayout rightFrame; private TabbedDetailView detailView; private Intent selectedIntent = null; private String filterString = ""; private Detail shortSelect; private DataSetObserver mListStateObserver; private OnClickListener barcodeScanOnClickListener; private boolean resuming = false; private boolean isStartingDetailActivity = false; private boolean rightFrameSetup = false; private NodeEntityFactory factory; private ContainerFragment<EntityListAdapter> containerFragment; private EntitySelectRefreshTimer refreshTimer; // Function handler for handling XPath evaluation of the function here(). // Although only one instance is created, which is used by NodeEntityFactory, // every instance of EntitySelectActivity registers itself (one at a time) // to listen to the handler and refresh whenever a new location is obtained. private static final HereFunctionHandler hereFunctionHandler = new HereFunctionHandler(); private boolean containsHereFunction = false; private boolean locationChangedWhileLoading = false; // Handler for displaying alert dialog when no location providers are found private final LocationNotificationHandler locationNotificationHandler = new LocationNotificationHandler(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); createDataSetObserver(); restoreSavedState(savedInstanceState); if (savedInstanceState == null) { hereFunctionHandler.refreshLocation(); } refreshTimer = new EntitySelectRefreshTimer(); asw = CommCareApplication._().getCurrentSessionWrapper(); session = asw.getSession(); // avoid session dependent when there is no command if (session.getCommand() != null) { selectDatum = session.getNeededDatum(); shortSelect = session.getDetail(selectDatum.getShortDetail()); mNoDetailMode = selectDatum.getLongDetail() == null; boolean isOrientationChange = savedInstanceState != null; setupUI(isOrientationChange); } } private void createDataSetObserver() { mListStateObserver = new DataSetObserver() { @Override public void onChanged() { super.onChanged(); //update the search results box String query = getSearchText().toString(); if (!"".equals(query)) { searchResultStatus.setText(Localization.get("select.search.status", new String[]{ "" + adapter.getCount(true, false), "" + adapter.getCount(true, true), query })); searchResultStatus.setVisibility(View.VISIBLE); } else { searchResultStatus.setVisibility(View.GONE); } } }; } private void restoreSavedState(Bundle savedInstanceState) { if (savedInstanceState != null) { this.mResultIsMap = savedInstanceState.getBoolean(EXTRA_IS_MAP, false); this.containsHereFunction = savedInstanceState.getBoolean(CONTAINS_HERE_FUNCTION); this.locationChangedWhileLoading = savedInstanceState.getBoolean( LOCATION_CHANGED_WHILE_LOADING); } } private void setupUI(boolean isOrientationChange) { if (this.getString(R.string.panes).equals("two") && !mNoDetailMode) { //See if we're on a big 'ol screen. if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { setupLandscapeDualPaneView(); } else { setContentView(R.layout.entity_select_layout); restoreExistingSelection(isOrientationChange); } } else { setContentView(R.layout.entity_select_layout); } ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list)); view.setOnItemClickListener(this); setupDivider(view); setupToolbar(view); } private void setupLandscapeDualPaneView() { //Inflate and set up the normal view for now. setContentView(R.layout.screen_compound_select); View.inflate(this, R.layout.entity_select_layout, (ViewGroup)findViewById(R.id.screen_compound_select_left_pane)); inAwesomeMode = true; rightFrame = (FrameLayout)findViewById(R.id.screen_compound_select_right_pane); TextView message = (TextView)findViewById(R.id.screen_compound_select_prompt); //use the old method here because some Android versions don't like Spannables for titles message.setText(Localization.get("select.placeholder.message", new String[]{Localization.get("cchq.case")})); } private void restoreExistingSelection(boolean isOrientationChange) { //So we're not in landscape mode anymore, but were before. If we had something selected, we //need to go to the detail screen instead. if (isOrientationChange) { Intent intent = this.getIntent(); TreeReference selectedRef = SerializationUtil.deserializeFromIntent(intent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class); if (selectedRef != null) { // remove the reference from this intent, ensuring we // don't re-launch the detail for an entity even after // it being de-selected. intent.removeExtra(EntityDetailActivity.CONTEXT_REFERENCE); // attach the selected entity to the new detail intent // we're launching Intent detailIntent = EntityDetailUtils.getDetailIntent(getApplicationContext(), selectedRef, null, selectDatum, asw); isStartingDetailActivity = true; startActivityForResult(detailIntent, CONFIRM_SELECT); } } } private void setupDivider(ListView view) { boolean useNewDivider = shortSelect.usesGridView(); if (useNewDivider) { int viewWidth = view.getWidth(); // sometimes viewWidth is 0, and in this case we default to a reasonable value taken from dimens.xml int dividerWidth; if (viewWidth == 0) { dividerWidth = (int)getResources().getDimension(R.dimen.entity_select_divider_left_inset); } else { dividerWidth = (int)(viewWidth / 6.0); } dividerWidth += (int)getResources().getDimension(R.dimen.row_padding_horizontal); LayerDrawable dividerDrawable = (LayerDrawable)getResources().getDrawable(R.drawable.divider_case_list_modern); dividerDrawable.setLayerInset(0, dividerWidth, 0, 0, 0); view.setDivider(dividerDrawable); } else { view.setDivider(null); } view.setDividerHeight((int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics())); } private void setupToolbar(ListView view) { TextView searchLabel = (TextView)findViewById(R.id.screen_entity_select_search_label); //use the old method here because some Android versions don't like Spannables for titles searchLabel.setText(Localization.get("select.search.label")); searchLabel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // get the focus on the edittext by performing click searchbox.performClick(); // then force the keyboard up since performClick() apparently isn't enough on some devices InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); // only will trigger it if no physical keyboard is open inputMethodManager.showSoftInput(searchbox, InputMethodManager.SHOW_IMPLICIT); } }); searchbox = (EditText)findViewById(R.id.searchbox); searchbox.setMaxLines(3); searchbox.setHorizontallyScrolling(false); searchResultStatus = (TextView)findViewById(R.id.no_search_results); header = (LinearLayout)findViewById(R.id.entity_select_header); mViewMode = session.isViewCommand(session.getCommand()); barcodeButton = (ImageButton)findViewById(R.id.barcodeButton); Callout callout = shortSelect.getCallout(); if (callout == null) { barcodeScanOnClickListener = makeBarcodeClickListener(); } else { barcodeScanOnClickListener = makeCalloutClickListener(callout); } barcodeButton.setOnClickListener(barcodeScanOnClickListener); searchbox.addTextChangedListener(this); searchbox.requestFocus(); persistAdapterState(view); restoreLastQueryString(); if (!isUsingActionBar()) { searchbox.setText(lastQueryString); } } private void persistAdapterState(ListView view) { FragmentManager fm = this.getSupportFragmentManager(); containerFragment = (ContainerFragment)fm.findFragmentByTag("entity-adapter"); // stateHolder and its previous state aren't null if the activity is // being created due to an orientation change. if (containerFragment == null) { containerFragment = new ContainerFragment<>(); fm.beginTransaction().add(containerFragment, "entity-adapter").commit(); } else { adapter = containerFragment.getData(); // on orientation change if (adapter != null) { view.setAdapter(adapter); setupDivider(view); findViewById(R.id.entity_select_loading).setVisibility(View.GONE); } } } /** * @return A click listener that launches QR code scanner */ private View.OnClickListener makeBarcodeClickListener() { return new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent("com.google.zxing.client.android.SCAN"); try { EntitySelectActivity.this.startActivityForResult(i, BARCODE_FETCH); } catch (ActivityNotFoundException anfe) { Toast.makeText(EntitySelectActivity.this, "No barcode reader available! You can install one " + "from the android market.", Toast.LENGTH_LONG).show(); } } }; } /** * Build click listener from callout: set button's image, get intent action, * and copy extras into intent. * * @param callout contains intent action and extras, and sometimes button image * @return click listener that launches the callout's activity with the * associated callout extras */ private View.OnClickListener makeCalloutClickListener(Callout callout) { final CalloutData calloutData = callout.getRawCalloutData(); if (calloutData.getImage() != null) { setupImageLayout(barcodeButton, calloutData.getImage()); } final Intent i = new Intent(calloutData.getActionName()); for (Map.Entry<String, String> keyValue : calloutData.getExtras().entrySet()) { i.putExtra(keyValue.getKey(), keyValue.getValue()); } return new View.OnClickListener() { @Override public void onClick(View v) { try { EntitySelectActivity.this.startActivityForResult(i, CALLOUT); } catch (ActivityNotFoundException anfe) { Toast.makeText(EntitySelectActivity.this, "No application found for action: " + i.getAction(), Toast.LENGTH_LONG).show(); } } }; } /** * Updates the ImageView layout that is passed in, based on the * new id and source */ private void setupImageLayout(View layout, final String imagePath) { ImageView iv = (ImageView)layout; Bitmap b; if (!imagePath.equals("")) { try { b = BitmapFactory.decodeStream(ReferenceManager._().DeriveReference(imagePath).getStream()); if (b == null) { // Input stream could not be used to derive bitmap, so // showing error-indicating image iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } else { iv.setImageBitmap(b); } } catch (IOException | InvalidReferenceException ex) { ex.printStackTrace(); // Error loading image, default to folder button iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } } else { // no image passed in, draw a white background iv.setImageDrawable(getResources().getDrawable(R.color.white)); } } @Override protected void onResume() { super.onResume(); if (!(isFinishing() || isStartingDetailActivity)) { if (adapter != null) { adapter.registerDataSetObserver(mListStateObserver); } if (!resuming && !mNoDetailMode && this.getIntent().hasExtra(EXTRA_ENTITY_KEY)) { if (resumeSelectedEntity()) { return; } } hereFunctionHandler.registerEvalLocationListener(this); if (containsHereFunction) { hereFunctionHandler.allowGpsUse(); } refreshView(); } } private boolean resumeSelectedEntity() { TreeReference selectedEntity = selectDatum.getEntityFromID(asw.getEvaluationContext(), this.getIntent().getStringExtra(EXTRA_ENTITY_KEY)); if (selectedEntity != null) { if (inAwesomeMode) { if (adapter != null) { displayReferenceAwesome(selectedEntity, adapter.getPosition(selectedEntity)); updateSelectedItem(selectedEntity, true); } } else { //Once we've done the initial dispatch, we don't want to end up triggering it later. this.getIntent().removeExtra(EXTRA_ENTITY_KEY); Intent i = EntityDetailUtils.getDetailIntent(getApplicationContext(), selectedEntity, null, selectDatum, asw); if (adapter != null) { i.putExtra("entity_detail_index", adapter.getPosition(selectedEntity)); i.putExtra(EntityDetailActivity.DETAIL_PERSISTENT_ID, selectDatum.getShortDetail()); } startActivityForResult(i, CONFIRM_SELECT); return true; } } return false; } /** * Get form list from database and insert into view. */ private void refreshView() { try { //TODO: Get ec into these text's String[] headers = new String[shortSelect.getFields().length]; for (int i = 0; i < headers.length; ++i) { headers[i] = shortSelect.getFields()[i].getHeader().evaluate(); if ("address".equals(shortSelect.getFields()[i].getTemplateForm())) { this.mMappingEnabled = true; } } header.removeAllViews(); // only add headers if we're not using grid mode if (!shortSelect.usesGridView()) { //Hm, sadly we possibly need to rebuild this each time. EntityView v = EntityView.buildHeadersEntityView(this, shortSelect, headers); header.addView(v); } if (adapter == null) { loadEntities(); } else { refreshTimer.start(this); } } catch (RuntimeException re) { createErrorDialog(re.getMessage(), true); } } public boolean loadEntities() { if (loader == null && !EntityLoaderTask.attachToActivity(this)) { Log.i(TAG, "entities reloading"); EntityLoaderTask entityLoader = new EntityLoaderTask(shortSelect, asw.getEvaluationContext()); entityLoader.attachListener(this); entityLoader.execute(selectDatum.getNodeset()); return true; } return false; } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putBoolean(CONTAINS_HERE_FUNCTION, containsHereFunction); savedInstanceState.putBoolean(LOCATION_CHANGED_WHILE_LOADING, locationChangedWhileLoading); } @Override protected void onPause() { super.onPause(); refreshTimer.stop(); if (adapter != null) { adapter.unregisterDataSetObserver(mListStateObserver); } hereFunctionHandler.forbidGpsUse(); hereFunctionHandler.unregisterEvalLocationListener(); } @Override protected void onStop() { super.onStop(); refreshTimer.stop(); saveLastQueryString(); } @Override protected void onDestroy() { super.onDestroy(); if (loader != null) { if (isFinishing()) { loader.cancel(false); } else { loader.detachActivity(); } } if (adapter != null) { adapter.signalKilled(); } } @Override public void onItemClick(AdapterView<?> listView, View view, int position, long id) { if (id == EntityListAdapter.SPECIAL_ACTION) { triggerDetailAction(); return; } TreeReference selection = adapter.getItem(position); if (CommCarePreferences.isEntityDetailLoggingEnabled()) { Logger.log(EntityDetailActivity.class.getSimpleName(), selectDatum.getLongDetail()); } if (inAwesomeMode) { displayReferenceAwesome(selection, position); updateSelectedItem(selection, false); } else { Intent i = EntityDetailUtils.getDetailIntent(getApplicationContext(), selection, null, selectDatum, asw); i.putExtra("entity_detail_index", position); if (mNoDetailMode) { // Not actually launching detail intent because there's no confirm detail available returnWithResult(i); } else { startActivityForResult(i, CONFIRM_SELECT); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { switch (requestCode) { case BARCODE_FETCH: processBarcodeFetch(resultCode, intent); break; case CALLOUT: processCalloutResult(resultCode, intent); break; case CONFIRM_SELECT: resuming = true; if (resultCode == RESULT_OK && !mViewMode) { // create intent for return and store path returnWithResult(intent); return; } else { //Did we enter the detail from mapping mode? If so, go back to that if (mResultIsMap) { mResultIsMap = false; Intent i = new Intent(this, EntityMapActivity.class); this.startActivityForResult(i, MAP_SELECT); return; } if (inAwesomeMode) { // Retain original element selection TreeReference r = SerializationUtil.deserializeFromIntent(intent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class); if (r != null && adapter != null) { // TODO: added 'adapter != null' due to a // NullPointerException, we need to figure out how to // make sure adapter is never null -- PLM this.displayReferenceAwesome(r, adapter.getPosition(r)); updateSelectedItem(r, true); } AudioController.INSTANCE.releaseCurrentMediaEntity(); } return; } case MAP_SELECT: if (resultCode == RESULT_OK) { TreeReference r = SerializationUtil.deserializeFromIntent(intent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class); if (inAwesomeMode) { this.displayReferenceAwesome(r, adapter.getPosition(r)); } else { Intent i = EntityDetailUtils.getDetailIntent(getApplicationContext(), r, null, selectDatum, asw); if (mNoDetailMode) { returnWithResult(i); } else { //To go back to map mode if confirm is false mResultIsMap = true; i.putExtra("entity_detail_index", adapter.getPosition(r)); startActivityForResult(i, CONFIRM_SELECT); } return; } } else { refreshView(); return; } default: super.onActivityResult(requestCode, resultCode, intent); } } private void processBarcodeFetch(int resultCode, Intent intent) { if (resultCode == Activity.RESULT_OK) { String result = intent.getStringExtra("SCAN_RESULT"); if (result != null) { result = result.trim(); } setSearchText(result); } } private void processCalloutResult(int resultCode, Intent intent) { if (resultCode == Activity.RESULT_OK) { String result = intent.getStringExtra("odk_intent_data"); if (result != null){ setSearchText(result.trim()); } else { for (String key : shortSelect.getCallout().getResponses()) { result = intent.getExtras().getString(key); if (result != null) { setSearchText(result); return; } } } } } /** * Finish this activity, including all extras from the given intent in the finishing intent */ private void returnWithResult(Intent intent) { Intent i = new Intent(this.getIntent()); i.putExtras(intent.getExtras()); setResult(RESULT_OK, i); finish(); } @Override public void afterTextChanged(Editable incomingEditable) { final String incomingString = incomingEditable.toString(); final String currentSearchText = getSearchText().toString(); if (incomingString.equals(currentSearchText)) { filterString = currentSearchText; if (adapter != null) { adapter.applyFilter(filterString); } } if (!isUsingActionBar()) { lastQueryString = filterString; } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); //use the old method here because some Android versions don't like Spannables for titles menu.add(0, MENU_SORT, MENU_SORT, Localization.get("select.menu.sort")).setIcon( android.R.drawable.ic_menu_sort_alphabetically); if (mMappingEnabled) { menu.add(0, MENU_MAP, MENU_MAP, Localization.get("select.menu.map")).setIcon( android.R.drawable.ic_menu_mapmode); } if (shortSelect != null) { Action action = shortSelect.getCustomAction(); if (action != null) { ViewUtil.addDisplayToMenu(this, menu, MENU_ACTION, action.getDisplay().evaluate()); } } tryToAddActionSearchBar(this, menu, new ActionBarInstantiator() { // again, this should be unnecessary... @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public void onActionBarFound(MenuItem searchItem, SearchView searchView) { EntitySelectActivity.this.searchItem = searchItem; EntitySelectActivity.this.searchView = searchView; // restore last query string in the searchView if there is one if (lastQueryString != null && lastQueryString.length() > 0) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { searchItem.expandActionView(); } searchView.setQuery(lastQueryString, false); if (adapter != null) { adapter.applyFilter(lastQueryString == null ? "" : lastQueryString); } } EntitySelectActivity.this.searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return true; } @Override public boolean onQueryTextChange(String newText) { lastQueryString = newText; filterString = newText; if (adapter != null) { adapter.applyFilter(newText); } return false; } }); } }); return true; } /** * Checks if this activity uses the ActionBar */ private boolean isUsingActionBar() { return searchView != null; } @SuppressWarnings("NewApi") private CharSequence getSearchText() { if (isUsingActionBar()) { return searchView.getQuery(); } return searchbox.getText(); } @SuppressWarnings("NewApi") private void setSearchText(CharSequence text) { if (isUsingActionBar()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { searchItem.expandActionView(); } searchView.setQuery(text, false); } searchbox.setText(text); } @Override public boolean onPrepareOptionsMenu(Menu menu) { // only enable sorting once entity loading is complete menu.findItem(MENU_SORT).setEnabled(adapter != null); // hide sorting menu when using async loading strategy menu.findItem(MENU_SORT).setVisible((shortSelect == null || !shortSelect.useAsyncStrategy())); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_SORT: createSortMenu(); return true; case MENU_MAP: Intent i = new Intent(this, EntityMapActivity.class); this.startActivityForResult(i, MAP_SELECT); return true; case MENU_ACTION: triggerDetailAction(); return true; // handling click on the barcode scanner's actionbar // trying to set the onclicklistener in its view in the onCreateOptionsMenu method does not work because it returns null case R.id.barcode_scan_action_bar: barcodeScanOnClickListener.onClick(null); return true; // this is needed because superclasses do not implement the menu_settings click case R.id.menu_settings: CommCareHomeActivity.createPreferencesMenu(this); return true; } return super.onOptionsItemSelected(item); } private void triggerDetailAction() { Action action = shortSelect.getCustomAction(); try { asw.executeStackActions(action.getStackOperations()); } catch (XPathTypeMismatchException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), true); return; } this.setResult(CommCareHomeActivity.RESULT_RESTART); this.finish(); } private void createSortMenu() { final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, Localization.get("select.menu.sort")); dialog.setChoiceItems(getSortOptionsList(dialog)); dialog.show(); } private DialogChoiceItem[] getSortOptionsList(final PaneledChoiceDialog dialog) { SessionDatum datum = session.getNeededDatum(); DetailField[] fields = session.getDetail(datum.getShortDetail()).getFields(); List<String> namesList = new ArrayList<>(); final int[] keyArray = new int[fields.length]; int[] sorts = adapter.getCurrentSort(); int currentSort = sorts.length == 1 ? sorts[0] : -1; boolean reversed = adapter.isCurrentSortReversed(); int added = 0; for (int i = 0; i < fields.length; ++i) { String result = fields[i].getHeader().evaluate(); if (!"".equals(result)) { String prepend = ""; if (currentSort == -1) { for (int j = 0; j < sorts.length; ++j) { if (sorts[j] == i) { prepend = (j + 1) + " " + (fields[i].getSortDirection() == DetailField.DIRECTION_DESCENDING ? "(v) " : "(^) "); } } } else if (currentSort == i) { prepend = reversed ^ fields[i].getSortDirection() == DetailField.DIRECTION_DESCENDING ? "(v) " : "(^) "; } namesList.add(prepend + result); keyArray[added] = i; added++; } } DialogChoiceItem[] choiceItems = new DialogChoiceItem[namesList.size()]; for (int i = 0; i < namesList.size(); i++) { final int index = i; View.OnClickListener listener = new View.OnClickListener() { public void onClick(View v) { adapter.sortEntities(new int[]{keyArray[index]}); adapter.applyFilter(getSearchText().toString()); dialog.dismiss(); } }; DialogChoiceItem item = new DialogChoiceItem(namesList.get(i), -1, listener); choiceItems[i] = item; } return choiceItems; } @Override public void deliverResult(List<Entity<TreeReference>> entities, List<TreeReference> references, NodeEntityFactory factory) { loader = null; Detail detail = session.getDetail(selectDatum.getShortDetail()); int[] order = detail.getSortOrder(); for (int i = 0; i < detail.getFields().length; ++i) { String header = detail.getFields()[i].getHeader().evaluate(); if (order.length == 0 && !"".equals(header)) { order = new int[]{i}; } } ListView view = ((ListView) this.findViewById(R.id.screen_entity_select_list)); setupDivider(view); adapter = new EntityListAdapter(EntitySelectActivity.this, detail, references, entities, order, null, factory); view.setAdapter(adapter); adapter.registerDataSetObserver(this.mListStateObserver); containerFragment.setData(adapter); // Pre-select entity if one was provided in original intent if (!resuming && !mNoDetailMode && inAwesomeMode && this.getIntent().hasExtra(EXTRA_ENTITY_KEY)) { TreeReference entity = selectDatum.getEntityFromID(asw.getEvaluationContext(), this.getIntent().getStringExtra(EXTRA_ENTITY_KEY)); if (entity != null) { displayReferenceAwesome(entity, adapter.getPosition(entity)); updateSelectedItem(entity, true); } } findViewById(R.id.entity_select_loading).setVisibility(View.GONE); if (adapter != null && filterString != null && !"".equals(filterString)) { adapter.applyFilter(filterString); } //In landscape we want to select something now. Either the top item, or the most recently selected one if (inAwesomeMode) { updateSelectedItem(true); } refreshTimer.start(this); if (locationChangedWhileLoading) { Log.i("HereFunctionHandler", "location changed while reloading"); locationChangedWhileLoading = false; loadEntities(); } } private void updateSelectedItem(boolean forceMove) { TreeReference chosen = null; if (selectedIntent != null) { chosen = SerializationUtil.deserializeFromIntent(selectedIntent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class); } updateSelectedItem(chosen, forceMove); } private void updateSelectedItem(TreeReference selected, boolean forceMove) { if (adapter == null) { return; } if (selected != null) { adapter.notifyCurrentlyHighlighted(selected); if (forceMove) { ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list)); view.setSelection(adapter.getPosition(selected)); } } } @Override public void attach(EntityLoaderTask task) { findViewById(R.id.entity_select_loading).setVisibility(View.VISIBLE); this.loader = task; } @Override public void callRequested(String phoneNumber) { DetailCalloutListenerDefaultImpl.callRequested(this, phoneNumber); } @Override public void addressRequested(String address) { DetailCalloutListenerDefaultImpl.addressRequested(this, address); } @Override public void playVideo(String videoRef) { DetailCalloutListenerDefaultImpl.playVideo(this, videoRef); } @Override public void performCallout(CalloutData callout, int id) { DetailCalloutListenerDefaultImpl.performCallout(this, callout, id); } private void displayReferenceAwesome(final TreeReference selection, int detailIndex) { selectedIntent = EntityDetailUtils.getDetailIntent(getApplicationContext(), selection, getIntent(), selectDatum, asw); //this should be 100% "fragment" able if (!rightFrameSetup) { findViewById(R.id.screen_compound_select_prompt).setVisibility(View.GONE); View.inflate(this, R.layout.entity_detail, rightFrame); Button next = (Button)findViewById(R.id.entity_select_button); //use the old method here because some Android versions don't like Spannables for titles next.setText(Localization.get("select.detail.confirm")); next.setOnClickListener(new OnClickListener() { public void onClick(View v) { select(); } }); if (mViewMode) { next.setVisibility(View.GONE); next.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); } String passedCommand = selectedIntent.getStringExtra(SessionFrame.STATE_COMMAND_ID); if (passedCommand != null) { mViewMode = session.isViewCommand(passedCommand); } else { mViewMode = session.isViewCommand(session.getCommand()); } detailView = (TabbedDetailView)rightFrame.findViewById(R.id.entity_detail_tabs); detailView.setRoot(detailView); factory = new NodeEntityFactory(session.getDetail(selectedIntent.getStringExtra(EntityDetailActivity.DETAIL_ID)), session.getEvaluationContext(new AndroidInstanceInitializer(session))); Detail detail = factory.getDetail(); detailView.showMenu(); if (detail.isCompound()) { // border around right panel doesn't look right when there are tabs rightFrame.setBackgroundDrawable(null); } rightFrameSetup = true; } detailView.refresh(factory.getDetail(), selection, detailIndex); } private void select() { // create intent for return and store path Intent i = new Intent(EntitySelectActivity.this.getIntent()); i.putExtra(SessionFrame.STATE_DATUM_VAL, selectedIntent.getStringExtra(SessionFrame.STATE_DATUM_VAL)); setResult(RESULT_OK, i); finish(); } @Override public void deliverError(Exception e) { displayException(e); } @Override protected boolean onForwardSwipe() { // If user has picked an entity, move along to form entry if (selectedIntent != null) { if (inAwesomeMode && detailView != null && detailView.getCurrentTab() < detailView.getTabCount() - 1) { return false; } if (!mViewMode) { select(); } } return true; } @Override protected boolean onBackwardSwipe() { if (inAwesomeMode && detailView != null && detailView.getCurrentTab() > 0) { return false; } finish(); return true; } public void onEvalLocationChanged() { boolean loaded = loadEntities(); if (!loaded) { locationChangedWhileLoading = true; } } public static HereFunctionHandler getHereFunctionHandler() { return hereFunctionHandler; } public void onHereFunctionEvaluated() { if (!containsHereFunction) { // First time here() is evaluated hereFunctionHandler.refreshLocation(); hereFunctionHandler.allowGpsUse(); containsHereFunction = true; if (!hereFunctionHandler.locationProvidersFound()) { locationNotificationHandler.sendEmptyMessage(0); } } } /** * Handler class for displaying alert dialog when no location providers are found. * Message-passing is necessary because the dialog is displayed during the course of evaluation * of the here() function, which occurs in a background thread (EntityLoaderTask). */ private static class LocationNotificationHandler extends Handler { // Use a weak reference to avoid potential memory leaks private final WeakReference<EntitySelectActivity> mActivity; public LocationNotificationHandler(EntitySelectActivity activity) { mActivity = new WeakReference<>(activity); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); final EntitySelectActivity activity = mActivity.get(); if (activity != null) { DialogInterface.OnClickListener onChangeListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); activity.startActivity(intent); hereFunctionHandler.allowGpsUse(); break; case DialogInterface.BUTTON_NEGATIVE: break; } dialog.dismiss(); } }; GeoUtils.showNoGpsDialog(activity, onChangeListener); } // else handler has outlived activity, do nothing } } @Override protected boolean isTopNavEnabled() { return true; } @Override public String getActivityTitle() { return null; } }
package org.clapper.rssget; import java.io.File; import java.io.IOException; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.Collection; import java.util.Collections; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import java.net.URL; import java.net.MalformedURLException; import org.clapper.util.text.TextUtils; import org.clapper.util.config.Configuration; import org.clapper.util.config.NoSuchVariableException; import org.clapper.util.config.ConfigurationException; /** * <p><tt>ConfigFile</tt> uses the <tt>Configuration</tt> class (part of * the <i>clapper.org</i> Java Utility library) to parse and validate the * <i>rssget</i> configuration file, holding the results in memory for easy * access.</p> * * @version <tt>$Revision$</tt> */ public class ConfigFile extends Configuration { /** * Main section name */ private static final String MAIN_SECTION = "rssget"; /** * Variable names */ private static final String VAR_CACHE_FILE = "CacheFile"; private static final String VAR_NO_CACHE_UPDATE = "NoCacheUpdate"; private static final String VAR_QUIET = "Quiet"; private static final String VAR_SUMMARY_ONLY = "SummaryOnly"; private static final String VAR_VERBOSITY_LEVEL = "Verbosity"; private static final String VAR_SMTPHOST = "SMTPHost"; private static final String VAR_DEFAULT_MAIL_FROM = "DefaultMailFrom"; private static final String VAR_MAIL_SUBJECT = "Subject"; private static final String VAR_DAYS_TO_CACHE = "DaysToCache"; private static final String VAR_PARSER_CLASS_NAME = "ParserClass"; private static final String VAR_PRUNE_URLS = "PruneURLs"; private static final String VAR_SHOW_RSS_VERSION = "ShowRSSVersion"; private static final String VAR_OUTPUT_CLASSES = "OutputHandlerClasses"; private static final String VAR_SMTP_HOST = "SMTPHost"; private static final String VAR_DEF_EMAIL_SENDER = "MailFrom"; private static final String VAR_EMAIL_SUBJECT = "MailSubject"; private static final String VAR_SHOW_DATES = "ShowDates"; private static final String VAR_TITLE_OVERRIDE = "TitleOverride"; private static final String VAR_EDIT_ITEM_URL = "EditItemURL"; private static final String VAR_DISABLE_FEED = "Disabled"; /** * Default values */ private static final int DEF_DAYS_TO_CACHE = 5; private static final int DEF_VERBOSITY_LEVEL = 0; private static final boolean DEF_PRUNE_URLS = false; private static final boolean DEF_QUIET = false; private static final boolean DEF_NO_CACHE_UPDATE = false; private static final boolean DEF_SUMMARY_ONLY = false; private static final boolean DEF_SHOW_RSS_VERSION = false; private static final boolean DEF_SHOW_DATES = false; private static final String DEF_SMTP_HOST = "localhost"; private static final String DEF_EMAIL_SUBJECT = "RSS Feeds"; private static final String DEF_PARSER_CLASS_NAME = "org.clapper.rssget.parser.minirss.MiniRSSParser"; private static final String DEF_OUTPUT_CLASS = "org.clapper.rssget.TextOutputHandler"; private File cacheFile = null; private int defaultCacheDays = DEF_DAYS_TO_CACHE; private boolean updateCache = true; private boolean quiet = false; private boolean summaryOnly = false; private boolean showRSSFormat = false; private boolean showDates = false; private int verboseness = 0; private Collection feeds = new ArrayList(); private Map feedMap = new HashMap(); private String parserClassName = DEF_PARSER_CLASS_NAME; private Collection outputClassNames = new ArrayList(); private String smtpHost = DEF_SMTP_HOST; private String emailSender = null; private String emailSubject = DEF_EMAIL_SUBJECT; /** * Construct an <tt>ConfigFile</tt> object that parses data * from the specified file. * * @param f The <tt>File</tt> to open and parse * * @throws IOException can't open or read file * @throws ConfigurationException error in configuration data */ ConfigFile (File f) throws IOException, ConfigurationException { super (f); validate(); } /** * Construct an <tt>ConfigFile</tt> object that parses data * from the specified file. * * @param path the path to the file to parse * * @throws FileNotFoundException specified file doesn't exist * @throws IOException can't open or read file * @throws ConfigurationException error in configuration data */ ConfigFile (String path) throws FileNotFoundException, IOException, ConfigurationException { super (path); validate(); } /** * Construct an <tt>ConfigFile</tt> object that parses data * from the specified URL. * * @param url the URL to open and parse * * @throws IOException can't open or read URL * @throws ConfigurationException error in configuration data */ ConfigFile (URL url) throws IOException, ConfigurationException { super (url); validate(); } /** * Construct an <tt>ConfigFile</tt> object that parses data * from the specified <tt>InputStream</tt>. * * @param iStream the <tt>InputStream</tt> * * @throws IOException can't open or read URL * @throws ConfigurationException error in configuration data */ ConfigFile (InputStream iStream) throws IOException, ConfigurationException { super (iStream); validate(); } /** * Get the name of the RSS parser class to use. The caller is responsible * for loading the returned class name and verifying that it implements * the appropriate interface(s). * * @return the full class name */ public String getRSSParserClassName() { return parserClassName; } /** * Get the names of the classes that handle output. The caller is * responsible for loading the returned class names and verifying that * they implements the appropriate interface(s). * * @return a <tt>Collection</tt> of strings containing full class names */ public Collection getOutputHandlerClassNames() { return outputClassNames; } /** * Get the configured cache file. * * @return the cache file * * @see #mustUpdateCache * @see #setMustUpdateCacheFlag */ public File getCacheFile() { return cacheFile; } /** * Determine whether the cache should be updated. * * @return <tt>true</tt> if the cache should be updated, <tt>false</tt> * if it should not. * * @see #getCacheFile * @see #setMustUpdateCacheFlag */ public boolean mustUpdateCache() { return updateCache; } /** * Change the "update cache" flag. * * @param val <tt>true</tt> if the cache should be updated, <tt>false</tt> * if it should not * * @see #mustUpdateCache * @see #getCacheFile */ public void setMustUpdateCacheFlag (boolean val) { updateCache = val; } /** * Return the value of the "quiet" flag. * * @return <tt>true</tt> if "quiet" flag is set, <tt>false</tt> * otherwise * * @see #setQuietFlag */ public boolean beQuiet() { return quiet; } /** * Set the value of the "quiet" flag. * * @param val <tt>true</tt> to set the "quiet" flag, <tt>false</tt> * to clear it * * @see #beQuiet */ public void setQuietFlag (boolean val) { this.quiet = val; } /** * Return the value of the "show dates" flag. This flag controls whether * to display the dates associated with each feed and item, if available. * * @return <tt>true</tt> if "show dates" flag is set, <tt>false</tt> * otherwise * * @see #setShowDatesFlag */ public boolean showDates() { return showDates; } /** * Set the value of the "show dates" flag. This flag controls whether * to display the dates associated with each feed and item, if available. * * @param val <tt>true</tt> to set the "show dates" flag, <tt>false</tt> * to clear it * * @see #showDates */ public void setShowDatesFlag (boolean val) { this.showDates = val; } /** * Return the value of "show RSS version" flag. * * @return <tt>true</tt> if flag is set, <tt>false</tt> if it isn't * * @see #setShowRSSVersionFlag */ public boolean showRSSVersion() { return showRSSFormat; } /** * Set the value of the "show RSS version" flag. * * @param val <tt>true</tt> to set the flag, * <tt>false</tt> to clear it * * @see #showRSSVersion */ public void setShowRSSVersionFlag (boolean val) { this.showRSSFormat = val; } /** * Get the SMTP host to use when sending email. * * @return the SMTP host. Never null. * * @see #setSMTPHost */ public String getSMTPHost() { return smtpHost; } /** * Set the SMTP host to use when sending email. * * @param host the SMTP host, or null to revert to the default value * * @see #getSMTPHost */ public void setSMTPHost (String host) { smtpHost = (host == null) ? DEF_SMTP_HOST : host; } /** * Get the email address to use as the sender for email messages. * * @return the email address, or null if not specified * * @see #setEmailSender */ public String getEmailSender() { return emailSender; } /** * Set the email address to use as the sender for email messages. * * @param address the new address, or null to clear the field * * @see #getEmailSender */ public void setEmailSender (String address) { this.emailSender = address; } /** * Get the subject to use in email messages, if email is being sent. * * @return the subject. Never null. * * @see #setEmailSubject */ public String getEmailSubject() { return emailSubject; } /** * Set the subject to use in email messages, if email is being sent. * * @param subject the subject, or null to reset to the default * * @see #getEmailSubject */ public void setEmailSubject (String subject) { this.emailSubject = (subject == null) ? DEF_EMAIL_SUBJECT : subject; } /** * Get the verbosity level. * * @return the verbosity level * * @see #setVerbosityLevel */ public int verbosityLevel() { return verboseness; } /** * Set the verbosity level * * @param val the new level * * @see #verbosityLevel */ public void setVerbosityLevel (int val) { this.verboseness = val; } /** * Get the configured RSS feeds. * * @return a <tt>Collection</tt> of <tt>FeedInfo</tt> objects. * * @see #hasFeed * @see #getFeedInfoFor(String) * @see #getFeedInfoFor(URL) */ public Collection getFeeds() { return Collections.unmodifiableCollection (feeds); } /** * Determine whether the specified URL is one of the configured RSS * feeds. * * @param url the URL * * @return <tt>true</tt> if it's there, <tt>false</tt> if not * * @see #getFeeds * @see #getFeedInfoFor(String) * @see #getFeedInfoFor(URL) */ public boolean hasFeed (URL url) { return feedMap.containsKey (url); } /** * Get the feed data for a given URL. * * @param url the URL * * @return the corresponding <tt>RSSFeedInfo</tt> object, or null * if not found * * @see #getFeeds * @see #hasFeed * @see #getFeedInfoFor(String) * @see FeedInfo */ public FeedInfo getFeedInfoFor (URL url) { return (FeedInfo) feedMap.get (url); } /** * Get the feed data for a given URL. * * @param url the URL, as a string * * @return the corresponding <tt>FeedInfo</tt> object, or null * if not found * * @see #getFeeds * @see #hasFeed * @see #getFeedInfoFor(URL) * @see FeedInfo */ public FeedInfo getFeedInfoFor (String url) { try { return (FeedInfo) feedMap.get (new URL (url)); } catch (MalformedURLException ex) { return null; } } /** * Validate the loaded configuration. * * @throws ConfigurationException on error */ private void validate() throws ConfigurationException { // First, verify that the main section is there and process it. processMainSection(); // Each remaining section should be a URL of an RSS site. for (Iterator it = getSectionNames (new ArrayList()).iterator(); it.hasNext(); ) { String sectionName = (String) it.next(); if (sectionName.equals (MAIN_SECTION)) continue; processSiteURLSection (sectionName); } } /** * Verify existence of main section and process it. * * @throws ConfigurationException on error */ private void processMainSection() throws ConfigurationException { if (! this.containsSection (MAIN_SECTION)) { throw new ConfigurationException ("Configuration file is missing " + "required \"" + MAIN_SECTION + "\" section."); } try { String s; cacheFile = new File (getVariableValue (MAIN_SECTION, VAR_CACHE_FILE)); if (cacheFile.isDirectory()) { throw new ConfigurationException ("Specified cache file \"" + cacheFile.getPath() + "\" is a directory."); } defaultCacheDays = getOptionalIntegerValue (MAIN_SECTION, VAR_DAYS_TO_CACHE, DEF_DAYS_TO_CACHE); verboseness = getOptionalIntegerValue (MAIN_SECTION, VAR_VERBOSITY_LEVEL, DEF_VERBOSITY_LEVEL); updateCache = (!getOptionalBooleanValue (MAIN_SECTION, VAR_NO_CACHE_UPDATE, DEF_NO_CACHE_UPDATE)); quiet = getOptionalBooleanValue (MAIN_SECTION, VAR_QUIET, DEF_QUIET); summaryOnly = getOptionalBooleanValue (MAIN_SECTION, VAR_SUMMARY_ONLY, DEF_SUMMARY_ONLY); showRSSFormat = getOptionalBooleanValue (MAIN_SECTION, VAR_SHOW_RSS_VERSION, DEF_SHOW_RSS_VERSION); showDates = getOptionalBooleanValue (MAIN_SECTION, VAR_SHOW_DATES, DEF_SHOW_DATES); parserClassName = getOptionalStringValue (MAIN_SECTION, VAR_PARSER_CLASS_NAME, DEF_PARSER_CLASS_NAME); s = getOptionalStringValue (MAIN_SECTION, VAR_OUTPUT_CLASSES, DEF_OUTPUT_CLASS); TextUtils.split (s, " \t", outputClassNames); smtpHost = getOptionalStringValue (MAIN_SECTION, VAR_SMTP_HOST, DEF_SMTP_HOST); emailSender = getOptionalStringValue (MAIN_SECTION, VAR_DEF_EMAIL_SENDER, null); emailSubject = getOptionalStringValue (MAIN_SECTION, VAR_EMAIL_SUBJECT, DEF_EMAIL_SUBJECT); } catch (NoSuchVariableException ex) { throw new ConfigurationException ("Missing required variable \"" + ex.getVariableName() + "\" in section \"" + ex.getSectionName() + "\"."); } } /** * Process a section that identifies a site's RSS URL. * * @param sectionName the section name (which is also the URL) * * @throws ConfigurationException configuration error */ private void processSiteURLSection (String sectionName) throws ConfigurationException { try { URL url = new URL (sectionName); url = Util.normalizeURL (url); FeedInfo feedInfo = new FeedInfo (url); feedInfo.setDaysToCache (getOptionalIntegerValue (sectionName, VAR_DAYS_TO_CACHE, defaultCacheDays)); feedInfo.setPruneURLsFlag (getOptionalBooleanValue (sectionName, VAR_PRUNE_URLS, DEF_PRUNE_URLS)); feedInfo.setSummarizeOnlyFlag (getOptionalBooleanValue (sectionName, VAR_SUMMARY_ONLY, summaryOnly)); feedInfo.setEnabledFlag (! getOptionalBooleanValue (sectionName, VAR_DISABLE_FEED, false)); String s = getOptionalStringValue (sectionName, VAR_TITLE_OVERRIDE, null); if (s != null) feedInfo.setTitleOverride (s); s = getOptionalStringValue (sectionName, VAR_EDIT_ITEM_URL, null); if (s != null) feedInfo.setItemURLEditCommand (s); feeds.add (feedInfo); feedMap.put (url, feedInfo); } catch (MalformedURLException ex) { throw new ConfigurationException ("Bad RSS site URL: \"" + sectionName + "\""); } } }
package org.dcache.xdr; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Logger; import org.glassfish.grizzly.Connection; import org.glassfish.grizzly.ConnectorHandler; import org.glassfish.grizzly.Transport; import org.glassfish.grizzly.filterchain.FilterChainBuilder; import org.glassfish.grizzly.filterchain.TransportFilter; import org.glassfish.grizzly.nio.transport.TCPNIOTransport; import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder; import org.glassfish.grizzly.nio.transport.UDPNIOTransport; import org.glassfish.grizzly.nio.transport.UDPNIOTransportBuilder; import static org.dcache.xdr.GrizzlyUtils.*; import org.glassfish.grizzly.strategies.SameThreadIOStrategy; public class OncRpcClient { private final static Logger _log = Logger.getLogger(OncRpcClient.class.getName()); private final InetSocketAddress _socketAddress; private final Transport _transport; private Connection<InetSocketAddress> _connection; private final ReplyQueue<Integer, RpcReply> _replyQueue = new ReplyQueue<Integer, RpcReply>(); public OncRpcClient(InetAddress address, int protocol, int port) { _socketAddress = new InetSocketAddress(address, port); if (protocol == IpProtocolType.TCP) { final TCPNIOTransport tcpTransport = TCPNIOTransportBuilder.newInstance().build(); _transport = tcpTransport; } else if (protocol == IpProtocolType.UDP) { final UDPNIOTransport udpTransport = UDPNIOTransportBuilder.newInstance().build(); _transport = udpTransport; } else { throw new IllegalArgumentException("Unsupported protocol type: " + protocol); } FilterChainBuilder filterChain = FilterChainBuilder.stateless(); filterChain.add(new TransportFilter()); filterChain.add(rpcMessageReceiverFor(_transport)); filterChain.add(new RpcProtocolFilter(_replyQueue)); _transport.setProcessor(filterChain.build()); _transport.setIOStrategy(SameThreadIOStrategy.getInstance()); } public XdrTransport connect() throws IOException { return connect(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } public XdrTransport connect(long timeout, TimeUnit timeUnit) throws IOException { _transport.start(); Future<Connection> future = ((ConnectorHandler) _transport).connect(_socketAddress); try { _connection = future.get(timeout, timeUnit); } catch (TimeoutException e) { throw new IOException(e.toString(), e); } catch (InterruptedException e) { throw new IOException(e.toString(), e); } catch (ExecutionException e) { throw new IOException(e.toString(), e); } return new ClientTransport(_connection, _replyQueue); } public void close() throws IOException { _connection.close(); _transport.stop(); } }
package org.hcjf.layers.query; import org.hcjf.log.Log; import org.hcjf.properties.SystemProperties; import org.hcjf.utils.Introspection; import org.hcjf.utils.Strings; import java.text.NumberFormat; import java.text.ParseException; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * This class contains all the parameter needed to create a query. * This kind of queries works over any data collection. * @author javaito * @mail javaito@gmail.com */ public class Query extends EvaluatorCollection { private final QueryId id; private final QueryResource resource; private Integer limit; private Object start; private final List<QueryOrderParameter> orderParameters; private final List<QueryReturnParameter> returnParameters; private final List<Join> joins; public Query(String resource, QueryId id) { this.id = id; this.orderParameters = new ArrayList<>(); this.returnParameters = new ArrayList<>(); this.joins = new ArrayList<>(); this.resource = new QueryResource(resource); } public Query(String resource){ this(resource, new QueryId()); } private Query(Query source) { super(source); this.id = new QueryId(); this.resource = source.resource; this.limit = source.limit; this.start = source.start; this.orderParameters = new ArrayList<>(); this.orderParameters.addAll(source.orderParameters); this.returnParameters = new ArrayList<>(); this.returnParameters.addAll(source.returnParameters); this.joins = new ArrayList<>(); this.joins.addAll(source.joins); } private QueryParameter checkQueryParameter(QueryParameter queryParameter) { if(queryParameter instanceof QueryField) { QueryField queryField = (QueryField) queryParameter; QueryResource resource = queryField.getResource(); if (resource == null) { queryField.setResource(getResource()); } } else if(queryParameter instanceof QueryFunction) { QueryFunction function = (QueryFunction) queryParameter; for(Object functionParameter : function.getParameters()) { if(functionParameter instanceof QueryParameter) { checkQueryParameter((QueryParameter) functionParameter); } } } return queryParameter; } @Override protected Evaluator checkEvaluator(Evaluator evaluator) { if(evaluator instanceof FieldEvaluator) { checkQueryParameter(((FieldEvaluator)evaluator).getQueryParameter()); } return evaluator; } /** * Return the id of the query. * @return Id of the query. */ public final QueryId getId() { return id; } /** * Return the list of joins. * @return Joins. */ public List<Join> getJoins() { return Collections.unmodifiableList(joins); } /** * Return the resource query object. * @return Resource query. */ public QueryResource getResource() { return resource; } /** * Return the resource name. * @return Resource name. */ public final String getResourceName() { return resource.getResourceName(); } /** * Return the limit of the query. * @return Query limit. */ public final Integer getLimit() { return limit; } /** * Set the query limit. * @param limit Query limit. */ public final void setLimit(Integer limit) { this.limit = limit; } /** * Return the object that represents the first element of the result. * @return Firts object of the result. */ public final Object getStart() { return start; } /** * Set the first object of the result. * @param start First object of the result. */ public final void setStart(Object start) { this.start = start; } /** * Return the unmodifiable list with order fields. * @return Order fields. */ public final List<QueryOrderParameter> getOrderParameters() { return Collections.unmodifiableList(orderParameters); } /** * Add a name of the field for order the data collection. This name must be exist * like a setter/getter method in the instances of the data collection. * @param orderField Name of the pair getter/setter. * @return Return the same instance of this class. */ public final Query addOrderField(String orderField) { return addOrderField(orderField, SystemProperties.getBoolean(SystemProperties.Query.DEFAULT_DESC_ORDER)); } /** * Add a name of the field for order the data collection. This name must be exist * like a setter/getter method in the instances of the data collection. * @param orderField Name of the pair getter/setter. * @param desc Desc property. * @return Return the same instance of this class. */ public final Query addOrderField(String orderField, boolean desc) { return addOrderField(new QueryOrderField(orderField, desc)); } /** * Add a name of the field for order the data collection. This name must be exist * like a setter/getter method in the instances of the data collection. * @param orderParameter Order parameter. * @return Return the same instance of this class. */ public final Query addOrderField(QueryOrderParameter orderParameter) { orderParameters.add((QueryOrderParameter) checkQueryParameter((QueryParameter) orderParameter)); return this; } /** * Return an unmodifiable list with the return fields. * @return Return fields. */ public final List<QueryReturnParameter> getReturnParameters() { return Collections.unmodifiableList(returnParameters); } /** * Add the name of the field to be returned in the result set. * @param returnField Field name. * @return Return the same instance of this class. */ public final Query addReturnField(String returnField) { return addReturnField(new QueryReturnField(returnField)); } /** * Add the name of the field to be returned in the result set. * @param returnParameter Return parameter. * @return Return the same instance of this class. */ public final Query addReturnField(QueryReturnParameter returnParameter) { returnParameters.add((QueryReturnParameter) checkQueryParameter((QueryParameter) returnParameter)); return this; } /** * Add join instance to the query. * @param join Join instance. */ public final void addJoin(Join join) { if(join != null && !joins.contains(join)) { joins.add(join); } else { if(join == null) { throw new NullPointerException("Null join instance"); } } } /** * This method evaluate each object of the collection and sort filtered * object to create a result add with the object filtered and sorted. * If there are order fields added then the result implementation is a * {@link TreeSet} implementation else the result implementation is a * {@link LinkedHashSet} implementation in order to guarantee the data order * from the source * @param dataSource Data source to evaluate the query. * @param <O> Kind of instances of the data collection. * @return Result add filtered and sorted. */ public final <O extends Object> Set<O> evaluate(Collection<O> dataSource, Object... parameters) { return evaluate((query) -> dataSource, new IntrospectionConsumer<>(), parameters); } /** * This method evaluate each object of the collection and sort filtered * object to create a result add with the object filtered and sorted. * If there are order fields added then the result implementation is a * {@link TreeSet} implementation else the result implementation is a * {@link LinkedHashSet} implementation in order to guarantee the data order * from the source * @param dataSource Data source to evaluate the query. * @param consumer Data source consumer. * @param <O> Kind of instances of the data collection. * @return Result add filtered and sorted. */ public final <O extends Object> Set<O> evaluate(Collection<O> dataSource, Consumer<O> consumer, Object... parameters) { return evaluate((query) -> dataSource, consumer, parameters); } /** * This method evaluate each object of the collection and sort filtered * object to create a result add with the object filtered and sorted. * If there are order fields added then the result implementation is a * {@link TreeSet} implementation else the result implementation is a * {@link LinkedHashSet} implementation in order to guarantee the data order * from the source * @param dataSource Data source to evaluate the query. * @param <O> Kind of instances of the data collection. * @return Result add filtered and sorted. */ public final <O extends Object> Set<O> evaluate(DataSource<O> dataSource, Object... parameters) { return evaluate(dataSource, new IntrospectionConsumer<>(), parameters); } /** * This method evaluate each object of the collection and sort filtered * object to create a result add with the object filtered and sorted. * If there are order fields added then the result implementation is a * {@link TreeSet} implementation else the result implementation is a * {@link LinkedHashSet} implementation in order to guarantee the data order * from the source * @param dataSource Data source to evaluate the query. * @param consumer Data source consumer. * @param <O> Kind of instances of the data collection. * @return Result add filtered and sorted. */ public final <O extends Object> Set<O> evaluate(DataSource<O> dataSource, Consumer<O> consumer, Object... parameters) { Set<O> result; //Creating result data collection. if(orderParameters.size() > 0) { //If the query has order fields then creates a tree set with //a comparator using the order fields. result = new TreeSet<>((o1, o2) -> { int compareResult = 0; Comparable<Object> comparable1; Comparable<Object> comparable2; for (QueryOrderParameter orderField : orderParameters) { try { comparable1 = consumer.get(o1, (QueryParameter) orderField); comparable2 = consumer.get(o2, (QueryParameter) orderField); } catch (ClassCastException ex) { throw new IllegalArgumentException("Order field must be comparable"); } if(comparable1 == null ^ comparable2 == null) { compareResult = (comparable1 == null) ? -1 : 1; } else if(comparable1 == null && comparable2 == null) { compareResult = 0; } else { compareResult = comparable1.compareTo(comparable2) * (orderField.isDesc() ? -1 : 1); } } if (compareResult == 0) { compareResult = o1.hashCode() - o2.hashCode(); } return compareResult; }); } else { //If the query has not order fields then creates a linked hash set to //maintain the natural order of the data. result = new LinkedHashSet<>(); } //Getting data from data source. Collection<O> data; if(joins.size() > 0) { //If the query has joins then data source must return the joined data //collection using all the resources data = (Collection<O>) join((DataSource<Joinable>) dataSource, (Consumer<Joinable>) consumer); } else { //If the query has not joins then data source must return data from //resource of the query. data = dataSource.getResourceData(this); } //Filtering data boolean add; for(O object : data) { add = true; for(Evaluator evaluator : getEvaluators()) { add = evaluator.evaluate(object, dataSource, consumer, parameters); if(!add) { break; } } if(add) { result.add(object); } if(getLimit() != null && result.size() == getLimit()) { break; } } return result; } /** * Create a joined data from data source using the joins instances stored in the query. * @param dataSource Data souce. * @param consumer Consumer. * @return Joined data collection. */ private final Collection<Joinable> join(DataSource<Joinable> dataSource, Consumer<Joinable> consumer) { Collection<Joinable> result = new ArrayList<>(); //Creates the first query for the original resource. Query joinQuery = new Query(getResourceName()); joinQuery.returnParameters.addAll(this.returnParameters); for(Evaluator evaluator : getEvaluatorsFromResource(this, joinQuery, getResource())) { joinQuery.addEvaluator(evaluator); } //Set the first query as start by default Query startQuery = joinQuery; //Put the first query in the list List<Query> queries = new ArrayList<>(); queries.add(joinQuery); //Build a query for each join and evaluate the better filter to start int queryStart = 0; int joinStart = 0; for (int i = 0; i < joins.size(); i++) { Join join = joins.get(i); joinQuery = new Query(join.getResourceName()); joinQuery.addReturnField("*"); for (Evaluator evaluator : getEvaluatorsFromResource(this, joinQuery, join.getResource())) { joinQuery.addEvaluator(evaluator); } queries.add(joinQuery); if(joinQuery.getEvaluators().size() > startQuery.getEvaluators().size()) { startQuery = joinQuery; queryStart = i+1; joinStart = i; } } Map<Object, Set<Joinable>> indexedJoineables; Collection<Joinable> leftJoinables = new ArrayList<>(); Collection<Joinable> rightJoinables = new ArrayList<>(); In in; Join queryJoin = null; Set<Object> keys; //Evaluate from the start query to right int j = joinStart; for (int i = queryStart; i < queries.size(); i++) { joinQuery = queries.get(i); if(leftJoinables.isEmpty()) { leftJoinables.addAll(dataSource.getResourceData(joinQuery)); } else { queryJoin = joins.get(j); indexedJoineables = index(leftJoinables, queryJoin.getLeftField(), consumer); leftJoinables.clear(); keys = indexedJoineables.keySet(); joinQuery.addEvaluator(new In(queryJoin.getRightField().toString(), keys)); rightJoinables.addAll(dataSource.getResourceData(joinQuery)); for (Joinable rightJoinable : rightJoinables) { for (Joinable leftJoinable : indexedJoineables.get(rightJoinable.get(queryJoin.getRightField().getFieldName()))) { leftJoinables.add(leftJoinable.join(rightJoinable)); } } j++; } } rightJoinables = leftJoinables; leftJoinables = new ArrayList<>(); //Evaluate from the start query to left j = joinStart; for (int i = queryStart - 1; i >= 0; i joinQuery = queries.get(i); queryJoin = joins.get(j); indexedJoineables = index(rightJoinables, queryJoin.getRightField(), consumer); rightJoinables.clear(); keys = indexedJoineables.keySet(); joinQuery.addEvaluator(new In(queryJoin.getLeftField().toString(), keys)); leftJoinables.addAll(dataSource.getResourceData(joinQuery)); for (Joinable leftJoinable : leftJoinables) { for (Joinable rightJoinable : indexedJoineables.get(leftJoinable.get(queryJoin.getLeftField().getFieldName()))) { rightJoinables.add(rightJoinable.join(leftJoinable)); } } } result.addAll(rightJoinables); return result; } /** * * @param collection * @param resource * @return */ private List<Evaluator> getEvaluatorsFromResource(EvaluatorCollection collection, EvaluatorCollection parent, QueryResource resource) { List<Evaluator> result = new ArrayList<>(); for(Evaluator evaluator : collection.getEvaluators()) { if(evaluator instanceof FieldEvaluator) { QueryParameter queryParameter = ((FieldEvaluator) evaluator).getQueryParameter(); if((queryParameter instanceof QueryField && ((QueryField)queryParameter).getResource().equals(resource)) || (queryParameter instanceof QueryFunction && ((QueryFunction)queryParameter).getResources().contains(resource))){ result.add(evaluator); } } else if(evaluator instanceof EvaluatorCollection) { EvaluatorCollection subCollection = null; if(evaluator instanceof And) { subCollection = new And(parent); } else if(evaluator instanceof Or) { subCollection = new Or(parent); } for(Evaluator subEvaluator : getEvaluatorsFromResource((EvaluatorCollection)evaluator, subCollection, resource)) { subCollection.addEvaluator(subEvaluator); } } } return result; } /** * This method evaluate all the values of the collection and put each of values * into a map indexed by the value of the parameter field. * @param objects Collection of data to evaluate. * @param fieldIndex Field to index result. * @param consumer Implementation to get the value from the collection * @return Return the filtered data indexed by value of the parameter field. */ private final Map<Object, Set<Joinable>> index(Collection<Joinable> objects, QueryField fieldIndex, Consumer<Joinable> consumer) { Map<Object, Set<Joinable>> result = new HashMap<>(); Object key; Set<Joinable> set; for(Joinable joinable : objects) { key = consumer.get(joinable, fieldIndex); set = result.get(key); if(set == null) { set = new HashSet<>(); result.put(key, set); } set.add(joinable); } return result; } /** * Return a copy of this query without all the evaluator and order fields of the * parameter collections. * @param evaluatorsToRemove Evaluators to reduce. * @return Reduced copy of the query. */ public final Query reduce(Collection<Evaluator> evaluatorsToRemove) { Query copy = new Query(this); copy.evaluators.addAll(this.evaluators); if(evaluatorsToRemove != null && !evaluatorsToRemove.isEmpty()) { reduceCollection(copy, evaluatorsToRemove); } return copy; } /** * Reduce recursively all the collection into the query. * @param collection Collection to reduce. * @param evaluatorsToRemove Evaluator to remove. */ private final void reduceCollection(EvaluatorCollection collection, Collection<Evaluator> evaluatorsToRemove) { for(Evaluator evaluatorToRemove : evaluatorsToRemove) { collection.evaluators.remove(evaluatorToRemove); collection.addEvaluator(new TrueEvaluator()); } for(Evaluator evaluator : collection.evaluators) { if(evaluator instanceof Or || evaluator instanceof And) { reduceCollection((EvaluatorCollection)evaluator, evaluatorsToRemove); } } } @Override public String toString() { StringBuilder result = new StringBuilder(); //Print select result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.SELECT)); result.append(Strings.WHITE_SPACE); String separator = Strings.EMPTY_STRING; for(QueryReturnParameter field : getReturnParameters()) { result.append(separator).append(field); if(field.getAlias() != null) { result.append(Strings.WHITE_SPACE).append(SystemProperties.get(SystemProperties.Query.ReservedWord.AS)); result.append(Strings.WHITE_SPACE).append(field.getAlias()); } separator = SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR); } //Print from result.append(Strings.WHITE_SPACE); result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.FROM)); result.append(Strings.WHITE_SPACE); result.append(getResourceName()); result.append(Strings.WHITE_SPACE); //Print joins for(Join join : joins) { if(!(join.getType() == Join.JoinType.JOIN)) { result.append(join.getType()); result.append(Strings.WHITE_SPACE); } result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.JOIN)).append(Strings.WHITE_SPACE); result.append(join.getResourceName()).append(Strings.WHITE_SPACE); result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.ON)).append(Strings.WHITE_SPACE); result.append(join.getLeftField()).append(Strings.WHITE_SPACE); result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.EQUALS)).append(Strings.WHITE_SPACE); result.append(join.getRightField()).append(Strings.WHITE_SPACE); } if(evaluators.size() > 0) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.WHERE)).append(Strings.WHITE_SPACE); toStringEvaluatorCollection(result, this); } if(orderParameters.size() > 0) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.ORDER_BY)).append(Strings.WHITE_SPACE); separator = Strings.EMPTY_STRING; for(QueryOrderParameter orderField : orderParameters) { result.append(separator).append(orderField); if(orderField.isDesc()) { result.append(Strings.WHITE_SPACE).append(SystemProperties.get(SystemProperties.Query.ReservedWord.DESC)); } separator = SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR); } } if(getLimit() != null) { result.append(Strings.WHITE_SPACE).append(SystemProperties.get(SystemProperties.Query.ReservedWord.LIMIT)); result.append(Strings.WHITE_SPACE).append(getLimit()); } return result.toString(); } private void toStringEvaluatorCollection(StringBuilder result, EvaluatorCollection collection) { String separator = Strings.EMPTY_STRING; String separatorValue = collection instanceof Or ? SystemProperties.get(SystemProperties.Query.ReservedWord.OR) : SystemProperties.get(SystemProperties.Query.ReservedWord.AND); for(Evaluator evaluator : collection.getEvaluators()) { result.append(separator); if(evaluator instanceof Or) { result.append(Strings.START_GROUP); toStringEvaluatorCollection(result, (Or)evaluator); result.append(Strings.END_GROUP); } else if(evaluator instanceof And) { if(collection instanceof Query) { toStringEvaluatorCollection(result, (And) evaluator); } else { result.append(Strings.START_GROUP); toStringEvaluatorCollection(result, (And) evaluator); result.append(Strings.END_GROUP); } } else if(evaluator instanceof FieldEvaluator) { FieldEvaluator fieldEvaluator = (FieldEvaluator) evaluator; result.append(fieldEvaluator.getQueryParameter()).append(Strings.WHITE_SPACE); if (fieldEvaluator instanceof Distinct) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.DISTINCT)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof Equals) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.EQUALS)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof GreaterThanOrEqual) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN_OR_EQUALS)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof GreaterThan) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof In) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.IN)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof Like) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.LIKE)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof NotIn) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.NOT_IN)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof SmallerThanOrEqual) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN_OR_EQUALS)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof SmallerThan) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN)).append(Strings.WHITE_SPACE); } if(fieldEvaluator.getRawValue() == null) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.NULL)); } else { result = toStringFieldEvaluatorValue(fieldEvaluator.getRawValue(), fieldEvaluator.getValueType(), result); } result.append(Strings.WHITE_SPACE); } separator = separatorValue + Strings.WHITE_SPACE; } } private static StringBuilder toStringFieldEvaluatorValue(Object value, Class type, StringBuilder result) { if(FieldEvaluator.ReplaceableValue.class.isAssignableFrom(type)) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.REPLACEABLE_VALUE)); } else if(FieldEvaluator.QueryValue.class.isAssignableFrom(type)) { result.append(Strings.START_GROUP); result.append(((FieldEvaluator.QueryValue)value).getQuery().toString()); result.append(Strings.END_GROUP); } else if(String.class.isAssignableFrom(type)) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER)); result.append(value); result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER)); } else if(Date.class.isAssignableFrom(type)) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER)); result.append(SystemProperties.getDateFormat(SystemProperties.Query.DATE_FORMAT).format((Date)value)); result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER)); } else if(Collection.class.isAssignableFrom(type)) { result.append(Strings.START_GROUP); String separator = Strings.EMPTY_STRING; for(Object object : (Collection)value) { result.append(separator); result = toStringFieldEvaluatorValue(object, object.getClass(), result); separator = SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR); } result.append(Strings.END_GROUP); } else { result.append(value.toString()); } return result; } /** * Create a query instance from sql definition. * @param sql Sql definition. * @return Query instance. */ public static Query compile(String sql) { List<String> groups = Strings.replaceableGroup(sql); return compile(groups, groups.size() -1); } /** * Create a query instance from sql definition. * @param groups * @param startGroup * @return Query instance. */ private static Query compile(List<String> groups, Integer startGroup) { Query query; Pattern pattern = SystemProperties.getPattern(SystemProperties.Query.SELECT_REGULAR_EXPRESSION); Matcher matcher = pattern.matcher(groups.get(startGroup)); if(matcher.matches()) { String selectBody = matcher.group(SystemProperties.getInteger(SystemProperties.Query.SELECT_GROUP_INDEX)); selectBody = selectBody.replaceFirst(Strings.CASE_INSENSITIVE_REGEX_FLAG+SystemProperties.get(SystemProperties.Query.ReservedWord.SELECT), Strings.EMPTY_STRING); String fromBody = matcher.group(SystemProperties.getInteger(SystemProperties.Query.FROM_GROUP_INDEX)); fromBody = fromBody.replaceFirst(Strings.CASE_INSENSITIVE_REGEX_FLAG+SystemProperties.get(SystemProperties.Query.ReservedWord.FROM), Strings.EMPTY_STRING); String conditionalBody = matcher.group(SystemProperties.getInteger(SystemProperties.Query.CONDITIONAL_GROUP_INDEX)); if(conditionalBody != null && conditionalBody.endsWith(SystemProperties.get(SystemProperties.Query.ReservedWord.STATEMENT_END))) { conditionalBody = conditionalBody.substring(0, conditionalBody.indexOf(SystemProperties.get(SystemProperties.Query.ReservedWord.STATEMENT_END))-1); } query = new Query(fromBody.trim()); for(String returnField : selectBody.split(SystemProperties.get( SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR))) { query.addReturnField((QueryReturnParameter) processStringValue(groups, returnField, null, QueryReturnParameter.class)); } if(conditionalBody != null) { Pattern conditionalPatter = SystemProperties.getPattern(SystemProperties.Query.CONDITIONAL_REGULAR_EXPRESSION, Pattern.CASE_INSENSITIVE); String[] conditionalElements = conditionalPatter.split(conditionalBody); String element; String elementValue; for (int i = 0; i < conditionalElements.length; i++) { element = conditionalElements[i++].trim(); elementValue = conditionalElements[i].trim(); if (element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.JOIN)) || element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.INNER_JOIN)) || element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.LEFT_JOIN)) || element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.RIGHT_JOIN))) { String[] joinElements = elementValue.split(SystemProperties.get(SystemProperties.Query.JOIN_REGULAR_EXPRESSION)); Join join = new Join( joinElements[SystemProperties.getInteger(SystemProperties.Query.JOIN_RESOURCE_NAME_INDEX)].trim(), new QueryField(joinElements[SystemProperties.getInteger(SystemProperties.Query.JOIN_LEFT_FIELD_INDEX)].trim()), new QueryField(joinElements[SystemProperties.getInteger(SystemProperties.Query.JOIN_RIGHT_FIELD_INDEX)].trim()), Join.JoinType.valueOf(element.toUpperCase())); query.addJoin(join); } else if (element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.WHERE))) { completeWhere(elementValue, groups, query, 0, new AtomicInteger(0)); } else if (element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.ORDER_BY))) { for (String orderField : elementValue.split(SystemProperties.get( SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR))) { query.addOrderField((QueryOrderParameter) processStringValue(groups, orderField, null, QueryOrderParameter.class)); } } else if (element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.LIMIT))) { query.setLimit(Integer.parseInt(elementValue)); } } } } else { MatchResult mr = matcher.toMatchResult(); throw new IllegalArgumentException(); } return query; } /** * Complete the evaluator collections with all the evaluator definitions in the groups. * @param groups Where groups. * @param parentCollection Parent collection. * @param definitionIndex Definition index into the groups. */ private static final void completeWhere(String startElement, List<String> groups, EvaluatorCollection parentCollection, Integer definitionIndex, AtomicInteger placesIndex) { Pattern wherePatter = SystemProperties.getPattern(SystemProperties.Query.WHERE_REGULAR_EXPRESSION, Pattern.CASE_INSENSITIVE); String[] evaluatorDefinitions; if(startElement != null) { evaluatorDefinitions = wherePatter.split(startElement); } else { evaluatorDefinitions = wherePatter.split(groups.get(definitionIndex)); } EvaluatorCollection collection = null; List<String> pendingDefinitions = new ArrayList<>(); for(String definition : evaluatorDefinitions) { definition = definition.trim(); if (definition.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.AND))) { if (collection == null) { if(parentCollection instanceof Query || parentCollection instanceof And) { collection = parentCollection; } else { collection = parentCollection.and(); } } else if (collection instanceof Or) { if(parentCollection instanceof Query || parentCollection instanceof And) { collection = parentCollection; } else { collection = parentCollection.and(); } } } else if (definition.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.OR))) { if (collection == null) { if(parentCollection instanceof Or) { collection = parentCollection; } else { collection = parentCollection.or(); } } else if (collection instanceof And) { if(parentCollection instanceof Or) { collection = parentCollection; } else { collection = parentCollection.or(); } } } else { pendingDefinitions.add(definition); if(collection != null) { for(String pendingDefinition : pendingDefinitions) { processDefinition(pendingDefinition, collection, groups, placesIndex); } pendingDefinitions.clear(); } else if(pendingDefinitions.size() > 1) { throw new IllegalArgumentException(""); } } } for(String pendingDefinition : pendingDefinitions) { if(collection != null) { processDefinition(pendingDefinition, collection, groups, placesIndex); } else { processDefinition(pendingDefinition, parentCollection, groups, placesIndex); } } } /** * * @param definition * @param collection * @param groups * @param placesIndex */ private static void processDefinition(String definition, EvaluatorCollection collection, List<String> groups, AtomicInteger placesIndex) { String[] evaluatorValues; Object firstObject; Object secondObject; String firstArgument; String secondArgument; String operator; Evaluator evaluator = null; QueryParameter queryParameter; Object value; if (definition.startsWith(Strings.REPLACEABLE_GROUP)) { Integer index = Integer.parseInt(definition.replace(Strings.REPLACEABLE_GROUP, Strings.EMPTY_STRING)); completeWhere(null, groups, collection, index, placesIndex); } else { evaluatorValues = definition.split(SystemProperties.get(SystemProperties.Query.OPERATION_REGULAR_EXPRESSION)); if (evaluatorValues.length >= 3) { boolean operatorDone = false; firstArgument = Strings.EMPTY_STRING; secondArgument = Strings.EMPTY_STRING; operator = null; for (String evaluatorValue : evaluatorValues) { if (!operatorDone && (evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.DISTINCT)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.EQUALS)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN_OR_EQUALS)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.IN)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.LIKE)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.NOT_IN)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN_OR_EQUALS)))) { operator = evaluatorValue.trim(); operatorDone = true; } else if (operatorDone) { secondArgument += evaluatorValue + Strings.WHITE_SPACE; } else { firstArgument += evaluatorValue + Strings.WHITE_SPACE; } } if (operator == null) { throw new IllegalArgumentException("Operator not found for expression: " + definition); } firstObject = processStringValue(groups, firstArgument.trim(), placesIndex, QueryParameter.class); secondObject = processStringValue(groups, secondArgument.trim(), placesIndex, QueryParameter.class); operator = operator.trim(); if(firstObject instanceof QueryParameter) { queryParameter = (QueryParameter) firstObject; if(secondObject instanceof QueryParameter) { value = new FieldEvaluator.QueryFieldValue((QueryParameter) secondObject); } else { value = secondObject; } } else if(secondObject instanceof QueryParameter) { queryParameter = (QueryParameter) secondObject; value = firstObject; } else { throw new IllegalArgumentException(""); } if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.DISTINCT))) { evaluator = new Distinct(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.EQUALS))) { evaluator = new Equals(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN))) { evaluator = new GreaterThan(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN_OR_EQUALS))) { evaluator = new GreaterThanOrEqual(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.IN))) { evaluator = new In(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.LIKE))) { evaluator = new Like(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.NOT_IN))) { evaluator = new NotIn(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN))) { evaluator = new SmallerThan(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN_OR_EQUALS))) { evaluator = new SmallerThanOrEqual(queryParameter, value); } collection.addEvaluator(evaluator); } else { throw new IllegalArgumentException("Syntax error for expression: " + definition + ", expected {field} {operator} {value}"); } } } /** * * @param groups * @param stringValue * @param placesIndex * @param parameterClass * @return */ private static Object processStringValue(List<String> groups, String stringValue, AtomicInteger placesIndex, Class parameterClass) { Object result = null; if(stringValue.equals(SystemProperties.get(SystemProperties.Query.ReservedWord.REPLACEABLE_VALUE))) { //If the string value is equals than "?" then the value object is an instance of ReplaceableValue. result = new FieldEvaluator.ReplaceableValue(placesIndex.getAndAdd(1)); } else if(stringValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.NULL))) { result = null; } else if(stringValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.TRUE))) { result = true; } else if(stringValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.FALSE))) { result = false; } else if(stringValue.startsWith(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER))) { if (stringValue.endsWith(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER))) { //If the string value start and end with "'" then the value can be a string or a date object. stringValue = stringValue.substring(1, stringValue.length() - 1); try { result = SystemProperties.getDateFormat(SystemProperties.Query.DATE_FORMAT).parse(stringValue); } catch (Exception ex) { //The value is not a date result = stringValue; } } else { throw new IllegalArgumentException(""); } } else if(stringValue.startsWith(Strings.REPLACEABLE_GROUP)) { Integer index = Integer.parseInt(stringValue.replace(Strings.REPLACEABLE_GROUP, Strings.EMPTY_STRING)); String group = groups.get(index); if(group.toUpperCase().startsWith(SystemProperties.get(SystemProperties.Query.ReservedWord.SELECT))) { result = new FieldEvaluator.QueryValue(Query.compile(groups, index)); } else { //If the string value start with "(" and end with ")" then the value is a collection. Collection<Object> collection = new ArrayList<>(); for (String subStringValue : group.split(SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR))) { collection.add(processStringValue(groups, subStringValue.trim(), placesIndex, parameterClass)); } result = collection; } } else if(stringValue.matches(SystemProperties.get(SystemProperties.HCJF_UUID_REGEX))) { result = UUID.fromString(stringValue); } else if(stringValue.matches(SystemProperties.get(SystemProperties.HCJF_NUMBER_REGEX))) { try { result = NumberFormat.getInstance().parse(stringValue); } catch (ParseException e) { throw new IllegalArgumentException(""); } } else { //Default case, only must be a query parameter. String functionName = null; String originalValue = null; String replaceValue = null; String group = null; List<Object> functionParameters = null; Boolean function = false; if(stringValue.contains(Strings.REPLACEABLE_GROUP)) { replaceValue = Strings.getGroupIndex(stringValue); group = groups.get(Integer.parseInt(replaceValue.replace(Strings.REPLACEABLE_GROUP,Strings.EMPTY_STRING))); functionName = stringValue.substring(0, stringValue.indexOf(Strings.REPLACEABLE_GROUP)); originalValue = stringValue.replace(replaceValue, Strings.START_GROUP + group + Strings.END_GROUP); functionParameters = new ArrayList<>(); for(String param : group.split(SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR))) { functionParameters.add(processStringValue(groups, param, placesIndex, parameterClass)); } function = true; } else { originalValue = stringValue; } if(parameterClass.equals(QueryParameter.class)) { if(function) { result = new QueryFunction(originalValue, functionName, functionParameters); } else { result = new QueryField(stringValue); } } else if(parameterClass.equals(QueryReturnParameter.class)) { String alias = null; String[] parts = originalValue.split(SystemProperties.get(SystemProperties.Query.AS_REGULAR_EXPRESSION)); if(parts.length == 3) { originalValue = parts[0]; alias = parts[2]; } if(function) { result = new QueryReturnFunction(originalValue, functionName, functionParameters, alias); } else { result = new QueryReturnField(originalValue, alias); } } else if(parameterClass.equals(QueryOrderParameter.class)) { boolean desc = false; if(originalValue.contains(SystemProperties.get(SystemProperties.Query.ReservedWord.DESC))) { originalValue = originalValue.substring(0, originalValue.indexOf(SystemProperties.get(SystemProperties.Query.ReservedWord.DESC))).trim(); desc = true; } if(function) { result = new QueryOrderFunction(originalValue, functionName, functionParameters, desc) ; } else { result = new QueryOrderField(originalValue, desc); } } } return result; } /** * Represents an query id. Wrapper of the UUID class. */ public static final class QueryId { private final UUID id; private QueryId() { this.id = UUID.randomUUID(); } public QueryId(UUID id) { this.id = id; } /** * Get the UUID instance. * @return UUID instance. */ public UUID getId() { return id; } } /** * This class provides an interface to consume a * different collection of naming data to be useful in evaluation * process. */ public interface Consumer<O extends Object> { /** * Get naming information from an instance. * @param instance Data source. * @param queryParameter Query parameter. * @return Return the data storage in the data source indexed * by the parameter name. */ public <R extends Object> R get(O instance, QueryParameter queryParameter); } /** * This private class is the default consume method of the queries. */ private static class IntrospectionConsumer<O extends Object> implements Consumer<O> { /** * Get naming information from an instance. * * @param instance Data source. * @param queryParameter Query parameter. * @return Return the data storage in the data source indexed * by the parameter name. */ @Override public <R extends Object> R get(O instance, QueryParameter queryParameter) { Object result = null; if(queryParameter instanceof QueryField) { String fieldName = ((QueryField)queryParameter).getFieldName(); try { if (instance instanceof JoinableMap) { result = ((JoinableMap) instance).get(fieldName); } else { Introspection.Getter getter = Introspection.getGetters(instance.getClass()).get(fieldName); if (getter != null) { result = getter.get(instance); } else { Log.w(SystemProperties.get(SystemProperties.Query.LOG_TAG), "Order field not found: %s", fieldName); } } } catch (Exception ex) { throw new IllegalArgumentException("Unable to obtain order field value", ex); } } else if(queryParameter instanceof QueryFunction) { throw new UnsupportedOperationException("Function: " + ((QueryFunction)queryParameter).getFunctionName()); } return (R) result; } } /** * This interface must implements a provider to obtain the data collection * for diferents resources. */ public interface DataSource<O extends Object> { /** * This method musr return the data of diferents resources using some query. * @param query Query object. * @return Data collection from the resource. */ public Collection<O> getResourceData(Query query); } /** * Group all the query components. */ public interface QueryComponent {} /** * Represents any kind of resource. */ public static class QueryResource implements Comparable<QueryResource>, QueryComponent { private final String resourceName; public QueryResource(String resourceName) { this.resourceName = resourceName; } /** * Return the resource name. * @return Resource name. */ public String getResourceName() { return resourceName; } @Override public boolean equals(Object obj) { return resourceName.equals(obj); } @Override public int compareTo(QueryResource o) { return resourceName.compareTo(o.getResourceName()); } @Override public String toString() { return getResourceName(); } } public static abstract class QueryParameter implements Comparable<QueryParameter>, QueryComponent { private final String originalValue; public QueryParameter(String originalValue) { this.originalValue = originalValue.trim(); } /** * Return the original representation of the field. * @return Original representation. */ @Override public String toString() { return originalValue; } /** * Compare the original value of the fields. * @param obj Other field. * @return True if the fields are equals. */ @Override public boolean equals(Object obj) { boolean result = false; if(obj instanceof QueryParameter) { result = toString().equals(obj.toString()); } return result; } /** * Compare the string representation of both objects. * @param o Other object. * @return Magnitude of the difference between both objects. */ @Override public int compareTo(QueryParameter o) { return toString().compareTo(o.toString()); } } public static class QueryFunction extends QueryParameter { private final String functionName; private final List<Object> parameters; public QueryFunction(String originalFunction, String functionName, List<Object> parameters) { super(originalFunction); this.functionName = functionName; this.parameters = parameters; } public String getFunctionName() { return functionName; } public List<Object> getParameters() { return parameters; } public Set<QueryResource> getResources() { Set<QueryResource> queryResources = new TreeSet<>(); for(Object parameter : parameters) { if(parameter instanceof QueryField) { queryResources.add(((QueryField)parameter).getResource()); } else if(parameter instanceof QueryFunction) { queryResources.addAll(((QueryFunction)parameter).getResources()); } } return queryResources; } } /** * This class represents any kind of query fields. */ public static class QueryField extends QueryParameter { private QueryResource resource; private String fieldName; private final String index; public QueryField(String field) { super(field); if(field.contains(Strings.CLASS_SEPARATOR)) { resource = new QueryResource(field.substring(0, field.lastIndexOf(Strings.CLASS_SEPARATOR))); this.fieldName = field.substring(field.lastIndexOf(Strings.CLASS_SEPARATOR) + 1).trim(); } else { resource = null; this.fieldName = field.trim(); } if(fieldName.contains(Strings.START_SUB_GROUP)) { fieldName = fieldName.substring(0, field.indexOf(Strings.START_SUB_GROUP)).trim(); index = fieldName.substring(field.indexOf(Strings.START_SUB_GROUP) + 1, field.indexOf(Strings.END_SUB_GROUP)).trim(); } else { index = null; } } /** * Return the resource of the field. * @param resource Field resource. */ protected void setResource(QueryResource resource) { this.resource = resource; } /** * Return the resource associated to the field. * @return Resource name, can be null. */ public QueryResource getResource() { return resource; } /** * Return the field name without associated resource or index. * @return Field name. */ public String getFieldName() { return fieldName; } /** * Return the index associated to the field. * @return Index, can be null. */ public String getIndex() { return index; } } public interface QueryReturnParameter extends QueryComponent { /** * Return the field alias, can be null. * @return Field alias. */ public String getAlias(); } /** * This kind of component represent the fields to be returned into the query. */ public static class QueryReturnField extends QueryField implements QueryReturnParameter { private final String alias; public QueryReturnField(String field) { this(field, null); } public QueryReturnField(String field, String alias) { super(field); this.alias = alias; } /** * Return the field alias, can be null. * @return Field alias. */ public String getAlias() { return alias; } } public static class QueryReturnFunction extends QueryFunction implements QueryReturnParameter { private final String alias; public QueryReturnFunction(String originalFunction, String functionName, List<Object> parameters, String alias) { super(originalFunction, functionName, parameters); this.alias = alias; } /** * Return the field alias, can be null. * @return Field alias. */ public String getAlias() { return alias; } } public interface QueryOrderParameter extends QueryComponent { /** * Return the desc property. * @return Desc property. */ public boolean isDesc(); } /** * This class represents a order field with desc property */ public static class QueryOrderField extends QueryField implements QueryOrderParameter { private final boolean desc; public QueryOrderField(String field, boolean desc) { super(field); this.desc = desc; } /** * Return the desc property. * @return Desc property. */ public boolean isDesc() { return desc; } } public static class QueryOrderFunction extends QueryFunction implements QueryOrderParameter { private final boolean desc; public QueryOrderFunction(String originalFunction, String functionName, List<Object> parameters, boolean desc) { super(originalFunction, functionName, parameters); this.desc = desc; } /** * Return the desc property. * @return Desc property. */ public boolean isDesc() { return desc; } } }
package uk.ac.ebi.gxa.loader; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import uk.ac.ebi.gxa.efo.Efo; import uk.ac.ebi.gxa.efo.EfoImpl; import uk.ac.ebi.gxa.efo.EfoTerm; import uk.ac.ebi.gxa.loader.dao.LoaderDAO; import uk.ac.ebi.gxa.loader.service.PropertyValueMergeService; import uk.ac.ebi.gxa.utils.Pair; import uk.ac.ebi.microarray.atlas.model.ArrayDesign; import uk.ac.ebi.microarray.atlas.model.Organism; import uk.ac.ebi.microarray.atlas.model.Property; import uk.ac.ebi.microarray.atlas.model.PropertyValue; import java.util.Collection; import java.util.Collections; import java.util.Map; import static com.google.common.collect.Maps.newHashMap; import static uk.ac.ebi.microarray.atlas.model.Property.createProperty; public class MockFactory { public static LoaderDAO createLoaderDAO() { return new MockLoaderDAO(); } static class MockLoaderDAO extends LoaderDAO { public MockLoaderDAO() { super(null, null, null, null); } private Map<String, Organism> os = newHashMap(); private Map<String, Property> ps = newHashMap(); private Map<Pair<String, String>, PropertyValue> pvs = newHashMap(); private Map<String, ArrayDesign> ads = newHashMap(); @Override public PropertyValue getOrCreatePropertyValue(String name, String value) { PropertyValue pv = pvs.get(Pair.create(name, value)); if (pv == null) { Property p = ps.get(name); if (p == null) { ps.put(name, p = createProperty(name)); } pvs.put(Pair.create(name, value), pv = new PropertyValue(null, p, value)); } return pv; } @Override public ArrayDesign getArrayDesignShallow(String accession) { ArrayDesign ad = ads.get(accession); if (ad == null) { ads.put(accession, ad = new ArrayDesign(accession)); } return ad; } @Override public Organism getOrCreateOrganism(String name) { Organism o = os.get(name); if (o == null) { os.put(name, o = new Organism(null, name)); } return o; } } public static PropertyValueMergeService createPropertyValueMergeService() { return new MockPropertyValueMergeService(); } static class MockPropertyValueMergeService extends PropertyValueMergeService { public MockPropertyValueMergeService() { super(); } } }
package org.hcjf.layers.query; import org.hcjf.log.Log; import org.hcjf.properties.SystemProperties; import org.hcjf.utils.Introspection; import org.hcjf.utils.Strings; import java.text.NumberFormat; import java.text.ParseException; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * This class contains all the parameter needed to create a query. * This kind of queries works over any data collection. * @author javaito * @mail javaito@gmail.com */ public class Query extends EvaluatorCollection { private final QueryId id; private final QueryResource resource; private Integer limit; private Object start; private final List<QueryOrderParameter> orderParameters; private final List<QueryReturnParameter> returnParameters; private final List<Join> joins; public Query(String resource, QueryId id) { this.id = id; this.orderParameters = new ArrayList<>(); this.returnParameters = new ArrayList<>(); this.joins = new ArrayList<>(); this.resource = new QueryResource(resource); } public Query(String resource){ this(resource, new QueryId()); } private Query(Query source) { super(source); this.id = new QueryId(); this.resource = source.resource; this.limit = source.limit; this.start = source.start; this.orderParameters = new ArrayList<>(); this.orderParameters.addAll(source.orderParameters); this.returnParameters = new ArrayList<>(); this.returnParameters.addAll(source.returnParameters); this.joins = new ArrayList<>(); this.joins.addAll(source.joins); } private QueryParameter checkQueryParameter(QueryParameter queryParameter) { if(queryParameter instanceof QueryField) { QueryField queryField = (QueryField) queryParameter; QueryResource resource = queryField.getResource(); if (resource == null) { queryField.setResource(getResource()); } } else if(queryParameter instanceof QueryFunction) { QueryFunction function = (QueryFunction) queryParameter; for(Object functionParameter : function.getParameters()) { if(functionParameter instanceof QueryParameter) { checkQueryParameter((QueryParameter) functionParameter); } } } return queryParameter; } @Override protected Evaluator checkEvaluator(Evaluator evaluator) { if(evaluator instanceof FieldEvaluator) { checkQueryParameter(((FieldEvaluator)evaluator).getQueryParameter()); } return evaluator; } /** * Return the id of the query. * @return Id of the query. */ public final QueryId getId() { return id; } /** * Return the list of joins. * @return Joins. */ public List<Join> getJoins() { return Collections.unmodifiableList(joins); } /** * Return the resource query object. * @return Resource query. */ public QueryResource getResource() { return resource; } /** * Return the resource name. * @return Resource name. */ public final String getResourceName() { return resource.getResourceName(); } /** * Return the limit of the query. * @return Query limit. */ public final Integer getLimit() { return limit; } /** * Set the query limit. * @param limit Query limit. */ public final void setLimit(Integer limit) { this.limit = limit; } /** * Return the object that represents the first element of the result. * @return Firts object of the result. */ public final Object getStart() { return start; } /** * Set the first object of the result. * @param start First object of the result. */ public final void setStart(Object start) { this.start = start; } /** * Return the unmodifiable list with order fields. * @return Order fields. */ public final List<QueryOrderParameter> getOrderParameters() { return Collections.unmodifiableList(orderParameters); } /** * Add a name of the field for order the data collection. This name must be exist * like a setter/getter method in the instances of the data collection. * @param orderField Name of the pair getter/setter. * @return Return the same instance of this class. */ public final Query addOrderField(String orderField) { addOrderField(orderField, SystemProperties.getBoolean(SystemProperties.Query.DEFAULT_DESC_ORDER)); return this; } /** * Add a name of the field for order the data collection. This name must be exist * like a setter/getter method in the instances of the data collection. * @param orderField Name of the pair getter/setter. * @param desc Desc property. * @return Return the same instance of this class. */ public final Query addOrderField(String orderField, boolean desc) { orderParameters.add((QueryOrderField) checkQueryParameter(new QueryOrderField(orderField, desc))); return this; } /** * Add a name of the field for order the data collection. This name must be exist * like a setter/getter method in the instances of the data collection. * @param orderParameter Order parameter. * @return Return the same instance of this class. */ public final Query addOrderField(QueryOrderParameter orderParameter) { orderParameters.add(orderParameter); return this; } /** * Return an unmodifiable list with the return fields. * @return Return fields. */ public final List<QueryReturnParameter> getReturnParameters() { return Collections.unmodifiableList(returnParameters); } /** * Add the name of the field to be returned in the result set. * @param returnField Field name. * @return Return the same instance of this class. */ public final Query addReturnField(String returnField) { returnParameters.add((QueryReturnField) checkQueryParameter(new QueryReturnField(returnField))); return this; } /** * Add the name of the field to be returned in the result set. * @param returnParameter Return parameter. * @return Return the same instance of this class. */ public final Query addReturnField(QueryReturnParameter returnParameter) { returnParameters.add(returnParameter); return this; } /** * Add join instance to the query. * @param join Join instance. */ public final void addJoin(Join join) { if(join != null && !joins.contains(join)) { joins.add(join); } else { if(join == null) { throw new NullPointerException("Null join instance"); } } } /** * This method evaluate each object of the collection and sort filtered * object to create a result add with the object filtered and sorted. * If there are order fields added then the result implementation is a * {@link TreeSet} implementation else the result implementation is a * {@link LinkedHashSet} implementation in order to guarantee the data order * from the source * @param dataSource Data source to evaluate the query. * @param <O> Kind of instances of the data collection. * @return Result add filtered and sorted. */ public final <O extends Object> Set<O> evaluate(Collection<O> dataSource, Object... parameters) { return evaluate((query) -> dataSource, new IntrospectionConsumer<>(), parameters); } /** * This method evaluate each object of the collection and sort filtered * object to create a result add with the object filtered and sorted. * If there are order fields added then the result implementation is a * {@link TreeSet} implementation else the result implementation is a * {@link LinkedHashSet} implementation in order to guarantee the data order * from the source * @param dataSource Data source to evaluate the query. * @param consumer Data source consumer. * @param <O> Kind of instances of the data collection. * @return Result add filtered and sorted. */ public final <O extends Object> Set<O> evaluate(Collection<O> dataSource, Consumer<O> consumer, Object... parameters) { return evaluate((query) -> dataSource, consumer, parameters); } /** * This method evaluate each object of the collection and sort filtered * object to create a result add with the object filtered and sorted. * If there are order fields added then the result implementation is a * {@link TreeSet} implementation else the result implementation is a * {@link LinkedHashSet} implementation in order to guarantee the data order * from the source * @param dataSource Data source to evaluate the query. * @param <O> Kind of instances of the data collection. * @return Result add filtered and sorted. */ public final <O extends Object> Set<O> evaluate(DataSource<O> dataSource, Object... parameters) { return evaluate(dataSource, new IntrospectionConsumer<>(), parameters); } /** * This method evaluate each object of the collection and sort filtered * object to create a result add with the object filtered and sorted. * If there are order fields added then the result implementation is a * {@link TreeSet} implementation else the result implementation is a * {@link LinkedHashSet} implementation in order to guarantee the data order * from the source * @param dataSource Data source to evaluate the query. * @param consumer Data source consumer. * @param <O> Kind of instances of the data collection. * @return Result add filtered and sorted. */ public final <O extends Object> Set<O> evaluate(DataSource<O> dataSource, Consumer<O> consumer, Object... parameters) { Set<O> result; //Creating result data collection. if(orderParameters.size() > 0) { //If the query has order fields then creates a tree set with //a comparator using the order fields. result = new TreeSet<>((o1, o2) -> { int compareResult = 0; Comparable<Object> comparable1; Comparable<Object> comparable2; for (QueryOrderParameter orderField : orderParameters) { try { comparable1 = consumer.get(o1, (QueryParameter) orderField); comparable2 = consumer.get(o2, (QueryParameter) orderField); } catch (ClassCastException ex) { throw new IllegalArgumentException("Order field must be comparable"); } if(comparable1 == null ^ comparable2 == null) { compareResult = (comparable1 == null) ? -1 : 1; } else if(comparable1 == null && comparable2 == null) { compareResult = 0; } else { compareResult = comparable1.compareTo(comparable2) * (orderField.isDesc() ? -1 : 1); } } if (compareResult == 0) { compareResult = o1.hashCode() - o2.hashCode(); } return compareResult; }); } else { //If the query has not order fields then creates a linked hash set to //maintain the natural order of the data. result = new LinkedHashSet<>(); } //Getting data from data source. Collection<O> data; if(joins.size() > 0) { //If the query has joins then data source must return the joined data //collection using all the resources data = (Collection<O>) join((DataSource<Joinable>) dataSource, (Consumer<Joinable>) consumer); } else { //If the query has not joins then data source must return data from //resource of the query. data = dataSource.getResourceData(this); } //Filtering data boolean add; for(O object : data) { add = true; for(Evaluator evaluator : getEvaluators()) { add = evaluator.evaluate(object, dataSource, consumer, parameters); if(!add) { break; } } if(add) { result.add(object); } if(getLimit() != null && result.size() == getLimit()) { break; } } return result; } /** * Create a joined data from data source using the joins instances stored in the query. * @param dataSource Data souce. * @param consumer Consumer. * @return Joined data collection. */ private final Collection<Joinable> join(DataSource<Joinable> dataSource, Consumer<Joinable> consumer) { Collection<Joinable> result = new ArrayList<>(); //Creates the first query for the original resource. Query joinQuery = new Query(getResourceName()); joinQuery.returnParameters.addAll(this.returnParameters); for(Evaluator evaluator : getEvaluatorsFromResource(this, joinQuery, getResource())) { joinQuery.addEvaluator(evaluator); } //Set the first query as start by default Query startQuery = joinQuery; //Put the first query in the list List<Query> queries = new ArrayList<>(); queries.add(joinQuery); //Build a query for each join and evaluate the better filter to start int queryStart = 0; int joinStart = 0; for (int i = 0; i < joins.size(); i++) { Join join = joins.get(i); joinQuery = new Query(join.getResourceName()); joinQuery.addReturnField("*"); for (Evaluator evaluator : getEvaluatorsFromResource(this, joinQuery, join.getResource())) { joinQuery.addEvaluator(evaluator); } queries.add(joinQuery); if(joinQuery.getEvaluators().size() > startQuery.getEvaluators().size()) { startQuery = joinQuery; queryStart = i+1; joinStart = i; } } Map<Object, Set<Joinable>> indexedJoineables; Collection<Joinable> leftJoinables = new ArrayList<>(); Collection<Joinable> rightJoinables = new ArrayList<>(); In in; Join queryJoin = null; Set<Object> keys; //Evaluate from the start query to right int j = joinStart; for (int i = queryStart; i < queries.size(); i++) { joinQuery = queries.get(i); if(leftJoinables.isEmpty()) { leftJoinables.addAll(dataSource.getResourceData(joinQuery)); } else { queryJoin = joins.get(j); indexedJoineables = index(leftJoinables, queryJoin.getLeftField(), consumer); leftJoinables.clear(); keys = indexedJoineables.keySet(); joinQuery.addEvaluator(new In(queryJoin.getRightField().toString(), keys)); rightJoinables.addAll(dataSource.getResourceData(joinQuery)); for (Joinable rightJoinable : rightJoinables) { for (Joinable leftJoinable : indexedJoineables.get(rightJoinable.get(queryJoin.getRightField().getFieldName()))) { leftJoinables.add(leftJoinable.join(rightJoinable)); } } j++; } } rightJoinables = leftJoinables; leftJoinables = new ArrayList<>(); //Evaluate from the start query to left j = joinStart; for (int i = queryStart - 1; i >= 0; i joinQuery = queries.get(i); queryJoin = joins.get(j); indexedJoineables = index(rightJoinables, queryJoin.getRightField(), consumer); rightJoinables.clear(); keys = indexedJoineables.keySet(); joinQuery.addEvaluator(new In(queryJoin.getLeftField().toString(), keys)); leftJoinables.addAll(dataSource.getResourceData(joinQuery)); for (Joinable leftJoinable : leftJoinables) { for (Joinable rightJoinable : indexedJoineables.get(leftJoinable.get(queryJoin.getLeftField().getFieldName()))) { rightJoinables.add(rightJoinable.join(leftJoinable)); } } } result.addAll(rightJoinables); return result; } /** * * @param collection * @param resource * @return */ private List<Evaluator> getEvaluatorsFromResource(EvaluatorCollection collection, EvaluatorCollection parent, QueryResource resource) { List<Evaluator> result = new ArrayList<>(); for(Evaluator evaluator : collection.getEvaluators()) { if(evaluator instanceof FieldEvaluator) { QueryParameter queryParameter = ((FieldEvaluator) evaluator).getQueryParameter(); if((queryParameter instanceof QueryField && ((QueryField)queryParameter).getResource().equals(resource)) || (queryParameter instanceof QueryFunction && ((QueryFunction)queryParameter).getResources().contains(resource))){ result.add(evaluator); } } else if(evaluator instanceof EvaluatorCollection) { EvaluatorCollection subCollection = null; if(evaluator instanceof And) { subCollection = new And(parent); } else if(evaluator instanceof Or) { subCollection = new Or(parent); } for(Evaluator subEvaluator : getEvaluatorsFromResource((EvaluatorCollection)evaluator, subCollection, resource)) { subCollection.addEvaluator(subEvaluator); } } } return result; } /** * This method evaluate all the values of the collection and put each of values * into a map indexed by the value of the parameter field. * @param objects Collection of data to evaluate. * @param fieldIndex Field to index result. * @param consumer Implementation to get the value from the collection * @return Return the filtered data indexed by value of the parameter field. */ private final Map<Object, Set<Joinable>> index(Collection<Joinable> objects, QueryField fieldIndex, Consumer<Joinable> consumer) { Map<Object, Set<Joinable>> result = new HashMap<>(); Object key; Set<Joinable> set; for(Joinable joinable : objects) { key = consumer.get(joinable, fieldIndex); set = result.get(key); if(set == null) { set = new HashSet<>(); result.put(key, set); } set.add(joinable); } return result; } /** * Return a copy of this query without all the evaluator and order fields of the * parameter collections. * @param evaluatorsToRemove Evaluators to reduce. * @return Reduced copy of the query. */ public final Query reduce(Collection<Evaluator> evaluatorsToRemove) { Query copy = new Query(this); copy.evaluators.addAll(this.evaluators); if(evaluatorsToRemove != null && !evaluatorsToRemove.isEmpty()) { reduceCollection(copy, evaluatorsToRemove); } return copy; } /** * Reduce recursively all the collection into the query. * @param collection Collection to reduce. * @param evaluatorsToRemove Evaluator to remove. */ private final void reduceCollection(EvaluatorCollection collection, Collection<Evaluator> evaluatorsToRemove) { for(Evaluator evaluatorToRemove : evaluatorsToRemove) { collection.evaluators.remove(evaluatorToRemove); collection.addEvaluator(new TrueEvaluator()); } for(Evaluator evaluator : collection.evaluators) { if(evaluator instanceof Or || evaluator instanceof And) { reduceCollection((EvaluatorCollection)evaluator, evaluatorsToRemove); } } } @Override public String toString() { StringBuilder result = new StringBuilder(); //Print select result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.SELECT)); result.append(Strings.WHITE_SPACE); String separator = Strings.EMPTY_STRING; for(QueryReturnParameter field : getReturnParameters()) { result.append(separator).append(field); if(field.getAlias() != null) { result.append(Strings.WHITE_SPACE).append(SystemProperties.get(SystemProperties.Query.ReservedWord.AS)); result.append(Strings.WHITE_SPACE).append(field.getAlias()); } separator = SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR); } //Print from result.append(Strings.WHITE_SPACE); result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.FROM)); result.append(Strings.WHITE_SPACE); result.append(getResourceName()); result.append(Strings.WHITE_SPACE); //Print joins for(Join join : joins) { if(!(join.getType() == Join.JoinType.JOIN)) { result.append(join.getType()); result.append(Strings.WHITE_SPACE); } result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.JOIN)).append(Strings.WHITE_SPACE); result.append(join.getResourceName()).append(Strings.WHITE_SPACE); result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.ON)).append(Strings.WHITE_SPACE); result.append(join.getLeftField()).append(Strings.WHITE_SPACE); result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.EQUALS)).append(Strings.WHITE_SPACE); result.append(join.getRightField()).append(Strings.WHITE_SPACE); } if(evaluators.size() > 0) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.WHERE)).append(Strings.WHITE_SPACE); toStringEvaluatorCollection(result, this); } if(orderParameters.size() > 0) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.ORDER_BY)).append(Strings.WHITE_SPACE); separator = Strings.EMPTY_STRING; for(QueryOrderParameter orderField : orderParameters) { result.append(separator).append(orderField); if(orderField.isDesc()) { result.append(Strings.WHITE_SPACE).append(SystemProperties.get(SystemProperties.Query.ReservedWord.DESC)); } separator = SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR); } } if(getLimit() != null) { result.append(Strings.WHITE_SPACE).append(SystemProperties.get(SystemProperties.Query.ReservedWord.LIMIT)); result.append(Strings.WHITE_SPACE).append(getLimit()); } return result.toString(); } private void toStringEvaluatorCollection(StringBuilder result, EvaluatorCollection collection) { String separator = Strings.EMPTY_STRING; String separatorValue = collection instanceof Or ? SystemProperties.get(SystemProperties.Query.ReservedWord.OR) : SystemProperties.get(SystemProperties.Query.ReservedWord.AND); for(Evaluator evaluator : collection.getEvaluators()) { result.append(separator); if(evaluator instanceof Or) { result.append(Strings.START_GROUP); toStringEvaluatorCollection(result, (Or)evaluator); result.append(Strings.END_GROUP); } else if(evaluator instanceof And) { if(collection instanceof Query) { toStringEvaluatorCollection(result, (And) evaluator); } else { result.append(Strings.START_GROUP); toStringEvaluatorCollection(result, (And) evaluator); result.append(Strings.END_GROUP); } } else if(evaluator instanceof FieldEvaluator) { FieldEvaluator fieldEvaluator = (FieldEvaluator) evaluator; result.append(fieldEvaluator.getQueryParameter()).append(Strings.WHITE_SPACE); if (fieldEvaluator instanceof Distinct) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.DISTINCT)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof Equals) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.EQUALS)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof GreaterThanOrEqual) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN_OR_EQUALS)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof GreaterThan) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof In) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.IN)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof Like) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.LIKE)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof NotIn) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.NOT_IN)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof SmallerThanOrEqual) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN_OR_EQUALS)).append(Strings.WHITE_SPACE); } else if (fieldEvaluator instanceof SmallerThan) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN)).append(Strings.WHITE_SPACE); } if(fieldEvaluator.getRawValue() == null) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.NULL)); } else { result = toStringFieldEvaluatorValue(fieldEvaluator.getRawValue(), fieldEvaluator.getValueType(), result); } result.append(Strings.WHITE_SPACE); } separator = separatorValue + Strings.WHITE_SPACE; } } private static StringBuilder toStringFieldEvaluatorValue(Object value, Class type, StringBuilder result) { if(FieldEvaluator.ReplaceableValue.class.isAssignableFrom(type)) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.REPLACEABLE_VALUE)); } else if(FieldEvaluator.QueryValue.class.isAssignableFrom(type)) { result.append(Strings.START_GROUP); result.append(((FieldEvaluator.QueryValue)value).getQuery().toString()); result.append(Strings.END_GROUP); } else if(String.class.isAssignableFrom(type)) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER)); result.append(value); result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER)); } else if(Date.class.isAssignableFrom(type)) { result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER)); result.append(SystemProperties.getDateFormat(SystemProperties.Query.DATE_FORMAT).format((Date)value)); result.append(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER)); } else if(Collection.class.isAssignableFrom(type)) { result.append(Strings.START_GROUP); String separator = Strings.EMPTY_STRING; for(Object object : (Collection)value) { result.append(separator); result = toStringFieldEvaluatorValue(object, object.getClass(), result); separator = SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR); } result.append(Strings.END_GROUP); } else { result.append(value.toString()); } return result; } /** * Create a query instance from sql definition. * @param sql Sql definition. * @return Query instance. */ public static Query compile(String sql) { List<String> groups = Strings.replaceableGroup(sql); return compile(groups, groups.size() -1); } /** * Create a query instance from sql definition. * @param groups * @param startGroup * @return Query instance. */ private static Query compile(List<String> groups, Integer startGroup) { Query query; Pattern pattern = SystemProperties.getPattern(SystemProperties.Query.SELECT_REGULAR_EXPRESSION); Matcher matcher = pattern.matcher(groups.get(startGroup)); if(matcher.matches()) { String selectBody = matcher.group(SystemProperties.getInteger(SystemProperties.Query.SELECT_GROUP_INDEX)); selectBody = selectBody.replaceFirst(Strings.CASE_INSENSITIVE_REGEX_FLAG+SystemProperties.get(SystemProperties.Query.ReservedWord.SELECT), Strings.EMPTY_STRING); String fromBody = matcher.group(SystemProperties.getInteger(SystemProperties.Query.FROM_GROUP_INDEX)); fromBody = fromBody.replaceFirst(Strings.CASE_INSENSITIVE_REGEX_FLAG+SystemProperties.get(SystemProperties.Query.ReservedWord.FROM), Strings.EMPTY_STRING); String conditionalBody = matcher.group(SystemProperties.getInteger(SystemProperties.Query.CONDITIONAL_GROUP_INDEX)); if(conditionalBody != null && conditionalBody.endsWith(SystemProperties.get(SystemProperties.Query.ReservedWord.STATEMENT_END))) { conditionalBody = conditionalBody.substring(0, conditionalBody.indexOf(SystemProperties.get(SystemProperties.Query.ReservedWord.STATEMENT_END))-1); } query = new Query(fromBody.trim()); for(String returnField : selectBody.split(SystemProperties.get( SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR))) { query.addReturnField((QueryReturnParameter) processStringValue(groups, returnField, null, QueryReturnParameter.class)); } if(conditionalBody != null) { Pattern conditionalPatter = SystemProperties.getPattern(SystemProperties.Query.CONDITIONAL_REGULAR_EXPRESSION, Pattern.CASE_INSENSITIVE); String[] conditionalElements = conditionalPatter.split(conditionalBody); String element; String elementValue; for (int i = 0; i < conditionalElements.length; i++) { element = conditionalElements[i++].trim(); elementValue = conditionalElements[i].trim(); if (element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.JOIN)) || element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.INNER_JOIN)) || element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.LEFT_JOIN)) || element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.RIGHT_JOIN))) { String[] joinElements = elementValue.split(SystemProperties.get(SystemProperties.Query.JOIN_REGULAR_EXPRESSION)); Join join = new Join( joinElements[SystemProperties.getInteger(SystemProperties.Query.JOIN_RESOURCE_NAME_INDEX)].trim(), new QueryField(joinElements[SystemProperties.getInteger(SystemProperties.Query.JOIN_LEFT_FIELD_INDEX)].trim()), new QueryField(joinElements[SystemProperties.getInteger(SystemProperties.Query.JOIN_RIGHT_FIELD_INDEX)].trim()), Join.JoinType.valueOf(element)); query.addJoin(join); } else if (element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.WHERE))) { completeWhere(elementValue, groups, query, 0, new AtomicInteger(0)); } else if (element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.ORDER_BY))) { for (String orderField : elementValue.split(SystemProperties.get( SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR))) { query.addOrderField((QueryOrderParameter) processStringValue(groups, orderField, null, QueryOrderParameter.class)); } } else if (element.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.LIMIT))) { query.setLimit(Integer.parseInt(elementValue)); } } } } else { MatchResult mr = matcher.toMatchResult(); throw new IllegalArgumentException(); } return query; } /** * Complete the evaluator collections with all the evaluator definitions in the groups. * @param groups Where groups. * @param parentCollection Parent collection. * @param definitionIndex Definition index into the groups. */ private static final void completeWhere(String startElement, List<String> groups, EvaluatorCollection parentCollection, Integer definitionIndex, AtomicInteger placesIndex) { Pattern wherePatter = SystemProperties.getPattern(SystemProperties.Query.WHERE_REGULAR_EXPRESSION, Pattern.CASE_INSENSITIVE); String[] evaluatorDefinitions; if(startElement != null) { evaluatorDefinitions = wherePatter.split(startElement); } else { evaluatorDefinitions = wherePatter.split(groups.get(definitionIndex)); } EvaluatorCollection collection = null; List<String> pendingDefinitions = new ArrayList<>(); for(String definition : evaluatorDefinitions) { definition = definition.trim(); if (definition.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.AND))) { if (collection == null) { if(parentCollection instanceof Query || parentCollection instanceof And) { collection = parentCollection; } else { collection = parentCollection.and(); } } else if (collection instanceof Or) { if(parentCollection instanceof Query || parentCollection instanceof And) { collection = parentCollection; } else { collection = parentCollection.and(); } } } else if (definition.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.OR))) { if (collection == null) { if(parentCollection instanceof Or) { collection = parentCollection; } else { collection = parentCollection.or(); } } else if (collection instanceof And) { if(parentCollection instanceof Or) { collection = parentCollection; } else { collection = parentCollection.or(); } } } else { pendingDefinitions.add(definition); if(collection != null) { for(String pendingDefinition : pendingDefinitions) { processDefinition(pendingDefinition, collection, groups, placesIndex); } pendingDefinitions.clear(); } else if(pendingDefinitions.size() > 1) { throw new IllegalArgumentException(""); } } } for(String pendingDefinition : pendingDefinitions) { if(collection != null) { processDefinition(pendingDefinition, collection, groups, placesIndex); } else { processDefinition(pendingDefinition, parentCollection, groups, placesIndex); } } } private static void processDefinition(String definition, EvaluatorCollection collection, List<String> groups, AtomicInteger placesIndex) { String[] evaluatorValues; Object firstObject; Object secondObject; String firstArgument; String secondArgument; String operator; Evaluator evaluator = null; QueryParameter queryParameter; Object value; if (definition.startsWith(Strings.REPLACEABLE_GROUP)) { Integer index = Integer.parseInt(definition.replace(Strings.REPLACEABLE_GROUP, Strings.EMPTY_STRING)); completeWhere(null, groups, collection, index, placesIndex); } else { evaluatorValues = definition.split(SystemProperties.get(SystemProperties.Query.OPERATION_REGULAR_EXPRESSION)); if (evaluatorValues.length >= 3) { boolean operatorDone = false; firstArgument = Strings.EMPTY_STRING; secondArgument = Strings.EMPTY_STRING; operator = null; for (String evaluatorValue : evaluatorValues) { if (!operatorDone && (evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.DISTINCT)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.EQUALS)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN_OR_EQUALS)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.IN)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.LIKE)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.NOT_IN)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN)) || evaluatorValue.trim().equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN_OR_EQUALS)))) { operator = evaluatorValue.trim(); operatorDone = true; } else if (operatorDone) { secondArgument += evaluatorValue + Strings.WHITE_SPACE; } else { firstArgument += evaluatorValue + Strings.WHITE_SPACE; } } if (operator == null) { throw new IllegalArgumentException("Operator not found for expression: " + definition); } firstObject = processStringValue(groups, firstArgument.trim(), placesIndex, QueryParameter.class); secondObject = processStringValue(groups, secondArgument.trim(), placesIndex, QueryParameter.class); operator = operator.trim(); if(firstObject instanceof QueryParameter) { queryParameter = (QueryParameter) firstObject; if(secondObject instanceof QueryParameter) { value = new FieldEvaluator.QueryFieldValue((QueryParameter) secondObject); } else { value = secondObject; } } else if(secondObject instanceof QueryParameter) { queryParameter = (QueryParameter) secondObject; value = firstObject; } else { throw new IllegalArgumentException(""); } if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.DISTINCT))) { evaluator = new Distinct(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.EQUALS))) { evaluator = new Equals(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN))) { evaluator = new GreaterThan(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.GREATER_THAN_OR_EQUALS))) { evaluator = new GreaterThanOrEqual(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.IN))) { evaluator = new In(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.LIKE))) { evaluator = new Like(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.NOT_IN))) { evaluator = new NotIn(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN))) { evaluator = new SmallerThan(queryParameter, value); } else if (operator.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.SMALLER_THAN_OR_EQUALS))) { evaluator = new SmallerThanOrEqual(queryParameter, value); } collection.addEvaluator(evaluator); } else { throw new IllegalArgumentException("Syntax error for expression: " + definition + ", expected {field} {operator} {value}"); } } } private static Object processStringValue(List<String> groups, String stringValue, AtomicInteger placesIndex, Class parameterClass) { Object result = null; if(stringValue.equals(SystemProperties.get(SystemProperties.Query.ReservedWord.REPLACEABLE_VALUE))) { //If the string value is equals than "?" then the value object is an instance of ReplaceableValue. result = new FieldEvaluator.ReplaceableValue(placesIndex.getAndAdd(1)); } else if(stringValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.NULL))) { result = null; } else if(stringValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.TRUE))) { result = true; } else if(stringValue.equalsIgnoreCase(SystemProperties.get(SystemProperties.Query.ReservedWord.FALSE))) { result = false; } else if(stringValue.startsWith(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER))) { if (stringValue.endsWith(SystemProperties.get(SystemProperties.Query.ReservedWord.STRING_DELIMITER))) { //If the string value start and end with "'" then the value can be a string or a date object. stringValue = stringValue.substring(1, stringValue.length() - 1); try { result = SystemProperties.getDateFormat(SystemProperties.Query.DATE_FORMAT).parse(stringValue); } catch (Exception ex) { //The value is not a date result = stringValue; } } else { throw new IllegalArgumentException(""); } } else if(stringValue.startsWith(Strings.REPLACEABLE_GROUP)) { Integer index = Integer.parseInt(stringValue.replace(Strings.REPLACEABLE_GROUP, Strings.EMPTY_STRING)); String group = groups.get(index); if(group.startsWith(SystemProperties.get(SystemProperties.Query.ReservedWord.SELECT))) { result = new FieldEvaluator.QueryValue(Query.compile(groups, index)); } else { //If the string value start with "(" and end with ")" then the value is a collection. Collection<Object> collection = new ArrayList<>(); for (String subStringValue : group.split(SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR))) { collection.add(processStringValue(groups, subStringValue, placesIndex, parameterClass)); } result = collection; } } else if(stringValue.matches(SystemProperties.get(SystemProperties.HCJF_UUID_REGEX))) { result = UUID.fromString(stringValue); } else if(stringValue.matches(SystemProperties.get(SystemProperties.HCJF_NUMBER_REGEX))) { try { result = NumberFormat.getInstance().parse(stringValue); } catch (ParseException e) { throw new IllegalArgumentException(""); } } else { //Default case, only must be a query parameter. String functionName = null; String originalValue = null; String replaceValue = null; String group = null; List<Object> functionParameters = null; Boolean function = false; if(stringValue.contains(Strings.REPLACEABLE_GROUP)) { replaceValue = Strings.getGroupIndex(stringValue); group = groups.get(Integer.parseInt(replaceValue.replace(Strings.REPLACEABLE_GROUP,Strings.EMPTY_STRING))); functionName = stringValue.substring(0, stringValue.indexOf(Strings.REPLACEABLE_GROUP)); originalValue = stringValue.replace(replaceValue, Strings.START_GROUP + group + Strings.END_GROUP); functionParameters = new ArrayList<>(); for(String param : group.split(SystemProperties.get(SystemProperties.Query.ReservedWord.ARGUMENT_SEPARATOR))) { functionParameters.add(processStringValue(groups, param, placesIndex, parameterClass)); } function = true; } else { originalValue = stringValue; } if(parameterClass.equals(QueryParameter.class)) { if(function) { result = new QueryFunction(originalValue, functionName, functionParameters); } else { result = new QueryField(stringValue); } } else if(parameterClass.equals(QueryReturnParameter.class)) { String alias = null; String[] parts = originalValue.split(SystemProperties.get(SystemProperties.Query.AS_REGULAR_EXPRESSION)); if(parts.length == 3) { originalValue = parts[0]; alias = parts[2]; } if(function) { result = new QueryReturnFunction(originalValue, functionName, functionParameters, alias); } else { result = new QueryReturnField(originalValue, alias); } } else if(parameterClass.equals(QueryOrderParameter.class)) { boolean desc = false; if(originalValue.contains(SystemProperties.get(SystemProperties.Query.ReservedWord.DESC))) { originalValue = originalValue.substring(0, originalValue.indexOf(SystemProperties.get(SystemProperties.Query.ReservedWord.DESC))).trim(); desc = true; } if(function) { result = new QueryOrderFunction(originalValue, functionName, functionParameters, desc) ; } else { result = new QueryOrderField(originalValue, desc); } } } return result; } /** * Represents an query id. Wrapper of the UUID class. */ public static final class QueryId { private final UUID id; private QueryId() { this.id = UUID.randomUUID(); } public QueryId(UUID id) { this.id = id; } /** * Get the UUID instance. * @return UUID instance. */ public UUID getId() { return id; } } /** * This class provides an interface to consume a * different collection of naming data to be useful in evaluation * process. */ public interface Consumer<O extends Object> { /** * Get naming information from an instance. * @param instance Data source. * @param queryParameter Query parameter. * @return Return the data storage in the data source indexed * by the parameter name. */ public <R extends Object> R get(O instance, QueryParameter queryParameter); } /** * This private class is the default consume method of the queries. */ private static class IntrospectionConsumer<O extends Object> implements Consumer<O> { /** * Get naming information from an instance. * * @param instance Data source. * @param queryParameter Query parameter. * @return Return the data storage in the data source indexed * by the parameter name. */ @Override public <R extends Object> R get(O instance, QueryParameter queryParameter) { Object result = null; if(queryParameter instanceof QueryField) { String fieldName = ((QueryField)queryParameter).getFieldName(); try { if (instance instanceof JoinableMap) { result = ((JoinableMap) instance).get(fieldName); } else { Introspection.Getter getter = Introspection.getGetters(instance.getClass()).get(fieldName); if (getter != null) { result = getter.get(instance); } else { Log.w(SystemProperties.get(SystemProperties.Query.LOG_TAG), "Order field not found: %s", fieldName); } } } catch (Exception ex) { throw new IllegalArgumentException("Unable to obtain order field value", ex); } } else if(queryParameter instanceof QueryFunction) { throw new UnsupportedOperationException("Function: " + ((QueryFunction)queryParameter).getFunctionName()); } return (R) result; } } /** * This interface must implements a provider to obtain the data collection * for diferents resources. */ public interface DataSource<O extends Object> { /** * This method musr return the data of diferents resources using some query. * @param query Query object. * @return Data collection from the resource. */ public Collection<O> getResourceData(Query query); } /** * Group all the query components. */ public interface QueryComponent {} /** * Represents any kind of resource. */ public static class QueryResource implements Comparable<QueryResource>, QueryComponent { private final String resourceName; public QueryResource(String resourceName) { this.resourceName = resourceName; } /** * Return the resource name. * @return Resource name. */ public String getResourceName() { return resourceName; } @Override public boolean equals(Object obj) { return resourceName.equals(obj); } @Override public int compareTo(QueryResource o) { return resourceName.compareTo(o.getResourceName()); } @Override public String toString() { return getResourceName(); } } public static abstract class QueryParameter implements Comparable<QueryParameter>, QueryComponent { private final String originalValue; public QueryParameter(String originalValue) { this.originalValue = originalValue.trim(); } /** * Return the original representation of the field. * @return Original representation. */ @Override public String toString() { return originalValue; } /** * Compare the original value of the fields. * @param obj Other field. * @return True if the fields are equals. */ @Override public boolean equals(Object obj) { boolean result = false; if(obj instanceof QueryParameter) { result = toString().equals(obj.toString()); } return result; } @Override public int compareTo(QueryParameter o) { return toString().compareTo(o.toString()); } } public static class QueryFunction extends QueryParameter { private final String functionName; private final List<Object> parameters; public QueryFunction(String originalFunction, String functionName, List<Object> parameters) { super(originalFunction); this.functionName = functionName; this.parameters = parameters; } public String getFunctionName() { return functionName; } public List<Object> getParameters() { return parameters; } public Set<QueryResource> getResources() { Set<QueryResource> queryResources = new TreeSet<>(); for(Object parameter : parameters) { if(parameter instanceof QueryField) { queryResources.add(((QueryField)parameter).getResource()); } else if(parameter instanceof QueryFunction) { queryResources.addAll(((QueryFunction)parameter).getResources()); } } return queryResources; } } /** * This class represents any kind of query fields. */ public static class QueryField extends QueryParameter { private QueryResource resource; private String fieldName; private final String index; public QueryField(String field) { super(field); if(field.contains(Strings.CLASS_SEPARATOR)) { resource = new QueryResource(field.substring(0, field.lastIndexOf(Strings.CLASS_SEPARATOR))); this.fieldName = field.substring(field.lastIndexOf(Strings.CLASS_SEPARATOR) + 1).trim(); } else { resource = null; this.fieldName = field.trim(); } if(fieldName.contains(Strings.START_SUB_GROUP)) { fieldName = fieldName.substring(0, field.indexOf(Strings.START_SUB_GROUP)).trim(); index = fieldName.substring(field.indexOf(Strings.START_SUB_GROUP) + 1, field.indexOf(Strings.END_SUB_GROUP)).trim(); } else { index = null; } } protected void setResource(QueryResource resource) { this.resource = resource; } /** * Return the resource associated to the field. * @return Resource name, can be null. */ public QueryResource getResource() { return resource; } /** * Return the field name without associated resource or index. * @return Field name. */ public String getFieldName() { return fieldName; } /** * Return the index associated to the field. * @return Index, can be null. */ public String getIndex() { return index; } } public interface QueryReturnParameter extends QueryComponent { /** * Return the field alias, can be null. * @return Field alias. */ public String getAlias(); } /** * This kind of component represent the fields to be returned into the query. */ public static class QueryReturnField extends QueryField implements QueryReturnParameter { private final String alias; public QueryReturnField(String field) { this(field, null); } public QueryReturnField(String field, String alias) { super(field); this.alias = alias; } /** * Return the field alias, can be null. * @return Field alias. */ public String getAlias() { return alias; } } public static class QueryReturnFunction extends QueryFunction implements QueryReturnParameter { private final String alias; public QueryReturnFunction(String originalFunction, String functionName, List<Object> parameters, String alias) { super(originalFunction, functionName, parameters); this.alias = alias; } /** * Return the field alias, can be null. * @return Field alias. */ public String getAlias() { return alias; } } public interface QueryOrderParameter extends QueryComponent { /** * Return the desc property. * @return Desc property. */ public boolean isDesc(); } /** * This class represents a order field with desc property */ public static class QueryOrderField extends QueryField implements QueryOrderParameter { private final boolean desc; public QueryOrderField(String field, boolean desc) { super(field); this.desc = desc; } /** * Return the desc property. * @return Desc property. */ public boolean isDesc() { return desc; } } public static class QueryOrderFunction extends QueryFunction implements QueryOrderParameter { private final boolean desc; public QueryOrderFunction(String originalFunction, String functionName, List<Object> parameters, boolean desc) { super(originalFunction, functionName, parameters); this.desc = desc; } /** * Return the desc property. * @return Desc property. */ public boolean isDesc() { return desc; } } }
package org.jgroups.protocols; import org.jgroups.Address; import org.jgroups.Event; import org.jgroups.Message; import org.jgroups.View; import org.jgroups.annotations.*; import org.jgroups.stack.Protocol; import org.jgroups.util.Range; import org.jgroups.util.Util; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.atomic.AtomicLong; @MBean(description="Fragments messages larger than fragmentation size into smaller packets") @DeprecatedProperty(names={"overhead"}) public class FRAG2 extends Protocol { private static final String name="FRAG2"; @Property(description="The max number of bytes in a message. Larger messages will be fragmented. Default is 1500 bytes") @ManagedAttribute(description="Fragmentation size", writable=true) int frag_size=1500; /*the fragmentation list contains a fragmentation table per sender *this way it becomes easier to clean up if a sender (member) leaves or crashes */ private final ConcurrentMap<Address,ConcurrentMap<Long,FragEntry>> fragment_list=new ConcurrentHashMap<Address,ConcurrentMap<Long,FragEntry>>(11); /** Used to assign fragmentation-specific sequence IDs (monotonically increasing) */ private int curr_id=1; private final Vector<Address> members=new Vector<Address>(11); @ManagedAttribute(description="Number of sent messages") AtomicLong num_sent_msgs=new AtomicLong(0); @ManagedAttribute(description="Number of received messages") AtomicLong num_received_msgs=new AtomicLong(0); @ManagedAttribute(description="Number of sent fragments") AtomicLong num_sent_frags=new AtomicLong(0); @ManagedAttribute(description="Number of received fragments") AtomicLong num_received_frags=new AtomicLong(0); public final String getName() { return name; } public int getFragSize() {return frag_size;} public void setFragSize(int s) {frag_size=s;} /** @deprecated overhead was removed in 2.6.10 */ public int getOverhead() {return 0;} /** @deprecated overhead was removed in 2.6.10 */ public void setOverhead(int o) {} public long getNumberOfSentMessages() {return num_sent_msgs.get();} public long getNumberOfSentFragments() {return num_sent_frags.get();} public long getNumberOfReceivedMessages() {return num_received_msgs.get();} public long getNumberOfReceivedFragments() {return num_received_frags.get();} synchronized int getNextId() { return curr_id++; } public void init() throws Exception { super.init(); int old_frag_size=frag_size; if(frag_size <=0) throw new Exception("frag_size=" + old_frag_size + ", new frag_size=" + frag_size + ": new frag_size is invalid"); TP transport=getTransport(); if(transport != null && transport.isEnableBundling()) { int max_bundle_size=transport.getMaxBundleSize(); if(frag_size >= max_bundle_size) throw new IllegalArgumentException("frag_size (" + frag_size + ") has to be < TP.max_bundle_size (" + max_bundle_size + ")"); } Map<String,Object> info=new HashMap<String,Object>(1); info.put("frag_size", frag_size); up_prot.up(new Event(Event.CONFIG, info)); down_prot.down(new Event(Event.CONFIG, info)); } public void resetStats() { super.resetStats(); num_sent_msgs.set(0); num_sent_frags.set(0); num_received_frags.set(0); num_received_msgs.set(0); } /** * Fragment a packet if larger than frag_size (add a header). Otherwise just pass down. Only * add a header if fragmentation is needed ! */ public Object down(Event evt) { switch(evt.getType()) { case Event.MSG: Message msg=(Message)evt.getArg(); long size=msg.getLength(); num_sent_msgs.incrementAndGet(); if(size > frag_size) { if(log.isTraceEnabled()) { log.trace(new StringBuilder("message's buffer size is ").append(size) .append(", will fragment ").append("(frag_size=").append(frag_size).append(')')); } fragment(msg); // Fragment and pass down return null; } break; case Event.VIEW_CHANGE: handleViewChange((View)evt.getArg()); break; case Event.CONFIG: Object ret=down_prot.down(evt); if(log.isDebugEnabled()) log.debug("received CONFIG event: " + evt.getArg()); handleConfigEvent((Map<String,Object>)evt.getArg()); return ret; } return down_prot.down(evt); // Pass on to the layer below us } /** * If event is a message, if it is fragmented, re-assemble fragments into big message and pass up * the stack. */ public Object up(Event evt) { switch(evt.getType()) { case Event.MSG: Message msg=(Message)evt.getArg(); FragHeader hdr=(FragHeader)msg.getHeader(name); if(hdr != null) { // needs to be defragmented unfragment(msg, hdr); // Unfragment and possibly pass up return null; } else { num_received_msgs.incrementAndGet(); } break; case Event.VIEW_CHANGE: handleViewChange((View)evt.getArg()); break; case Event.CONFIG: Object ret=up_prot.up(evt); if(log.isDebugEnabled()) log.debug("received CONFIG event: " + evt.getArg()); handleConfigEvent((Map<String,Object>)evt.getArg()); return ret; } return up_prot.up(evt); // Pass up to the layer above us by default } private void handleViewChange(View view) { Vector<Address> new_mbrs=view.getMembers(), left_mbrs; left_mbrs=Util.determineLeftMembers(members, new_mbrs); members.clear(); members.addAll(new_mbrs); for(Address mbr: left_mbrs) { // the new view doesn't contain the sender, it must have left, hence we will clear its fragmentation tables fragment_list.remove(mbr); if(log.isTraceEnabled()) log.trace("[VIEW_CHANGE] removed " + mbr + " from fragmentation table"); } } @ManagedOperation(description="removes all fragments sent by mbr") public void clearFragmentsFor(Address mbr) { if(mbr == null) return; fragment_list.remove(mbr); if(log.isTraceEnabled()) log.trace("removed " + mbr + " from fragmentation table"); } @ManagedOperation(description="Removes all entries from the fragmentation table. " + "Dangerous: this might remove fragments that are still needed to assemble an entire message") public void clearAllFragments() { fragment_list.clear(); } /** Send all fragments as separate messages (with same ID !). Example: <pre> Given the generated ID is 2344, number of fragments=3, message {dst,src,buf} would be fragmented into: [2344,3,0]{dst,src,buf1}, [2344,3,1]{dst,src,buf2} and [2344,3,2]{dst,src,buf3} </pre> */ private void fragment(Message msg) { try { byte[] buffer=msg.getRawBuffer(); List<Range> fragments=Util.computeFragOffsets(msg.getOffset(), msg.getLength(), frag_size); int num_frags=fragments.size(); num_sent_frags.addAndGet(num_frags); if(log.isTraceEnabled()) { Address dest=msg.getDest(); StringBuilder sb=new StringBuilder("fragmenting packet to "); sb.append((dest != null ? dest.toString() : "<all members>")).append(" (size=").append(buffer.length); sb.append(") into ").append(num_frags).append(" fragment(s) [frag_size=").append(frag_size).append(']'); log.trace(sb.toString()); } long id=getNextId(); // used as a seqno for(int i=0; i < fragments.size(); i++) { Range r=fragments.get(i); Message frag_msg=msg.copy(false); // don't copy the buffer, only src, dest and headers. But do copy the headers frag_msg.setBuffer(buffer, (int)r.low, (int)r.high); FragHeader hdr=new FragHeader(id, i, num_frags); frag_msg.putHeader(name, hdr); down_prot.down(new Event(Event.MSG, frag_msg)); } } catch(Exception e) { if(log.isErrorEnabled()) log.error("fragmentation failure", e); } } /** 1. Get all the fragment buffers 2. When all are received -> Assemble them into one big buffer 3. Read headers and byte buffer from big buffer 4. Set headers and buffer in msg 5. Pass msg up the stack */ private void unfragment(Message msg, FragHeader hdr) { Address sender=msg.getSrc(); Message assembled_msg=null; ConcurrentMap<Long,FragEntry> frag_table=fragment_list.get(sender); if(frag_table == null) { frag_table=new ConcurrentHashMap<Long,FragEntry>(); ConcurrentMap<Long,FragEntry> tmp=fragment_list.putIfAbsent(sender, frag_table); if(tmp != null) // value was already present frag_table=tmp; } num_received_frags.incrementAndGet(); FragEntry entry=frag_table.get(hdr.id); if(entry == null) { entry=new FragEntry(hdr.num_frags); FragEntry tmp=frag_table.putIfAbsent(hdr.id, entry); if(tmp != null) entry=tmp; } entry.lock(); try { entry.set(hdr.frag_id, msg); if(entry.isComplete()) { assembled_msg=entry.assembleMessage(); frag_table.remove(hdr.id); } } finally { entry.unlock(); } // assembled_msg=frag_table.add(hdr.id, hdr.frag_id, hdr.num_frags, msg); if(assembled_msg != null) { try { if(log.isTraceEnabled()) log.trace("assembled_msg is " + assembled_msg); assembled_msg.setSrc(sender); // needed ? YES, because fragments have a null src !! num_received_msgs.incrementAndGet(); up_prot.up(new Event(Event.MSG, assembled_msg)); } catch(Exception e) { if(log.isErrorEnabled()) log.error("unfragmentation failed", e); } } } void handleConfigEvent(Map<String,Object> map) { if(map == null) return; if(map.containsKey("frag_size")) { frag_size=((Integer)map.get("frag_size")).intValue(); if(log.isDebugEnabled()) log.debug("setting frag_size=" + frag_size); } } /** * Class represents an entry for a message. Each entry holds an array of byte arrays sorted * once all the byte buffer entries have been filled the fragmentation is considered complete.<br/> * All methods are unsynchronized, use getLock() to obtain a lock for concurrent access. */ private static class FragEntry { // each fragment is a byte buffer final Message fragments[]; //the number of fragments we have received int number_of_frags_recvd=0; private final Lock lock=new ReentrantLock(); /** * Creates a new entry * @param tot_frags the number of fragments to expect for this message */ private FragEntry(int tot_frags) { fragments=new Message[tot_frags]; for(int i=0; i < tot_frags; i++) fragments[i]=null; } /** Use to synchronize on FragEntry */ public void lock() { lock.lock(); } public void unlock() { lock.unlock(); } /** * adds on fragmentation buffer to the message * @param frag_id the number of the fragment being added 0..(tot_num_of_frags - 1) * @param frag the byte buffer containing the data for this fragmentation, should not be null */ public void set(int frag_id, Message frag) { // don't count an already received fragment (should not happen though because the // reliable transmission protocol(s) below should weed out duplicates if(fragments[frag_id] == null) { fragments[frag_id]=frag; number_of_frags_recvd++; } } /** returns true if this fragmentation is complete * ie, all fragmentations have been received for this buffer * */ public boolean isComplete() { /*first make a simple check*/ if(number_of_frags_recvd < fragments.length) { return false; } /*then double check just in case*/ for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) return false; } /*all fragmentations have been received*/ return true; } /** * Assembles all the fragments into one buffer. Takes all Messages, and combines their buffers into one * buffer. * This method does not check if the fragmentation is complete (use {@link #isComplete()} to verify * before calling this method) * @return the complete message in one buffer * */ private Message assembleMessage() { Message retval; byte[] combined_buffer, tmp; int combined_length=0, length, offset; int index=0; for(Message fragment: fragments) { combined_length+=fragment.getLength(); } combined_buffer=new byte[combined_length]; retval=fragments[0].copy(false); for(int i=0; i < fragments.length; i++) { Message fragment=fragments[i]; fragments[i]=null; // help garbage collection a bit tmp=fragment.getRawBuffer(); length=fragment.getLength(); offset=fragment.getOffset(); System.arraycopy(tmp, offset, combined_buffer, index, length); index+=length; } retval.setBuffer(combined_buffer); return retval; } public String toString() { StringBuilder ret=new StringBuilder(); ret.append("[tot_frags=").append(fragments.length).append(", number_of_frags_recvd=").append(number_of_frags_recvd).append(']'); return ret.toString(); } } }
package org.joml; public class RayAabIntersection { private float originX, originY, originZ; private float dirX, dirY, dirZ; /* Needed for ray slope intersection method */ private float c_xy, c_yx, c_zy, c_yz, c_xz, c_zx; private float s_xy, s_yx, s_zy, s_yz, s_xz, s_zx; private byte category; /** * Create a new {@link RayAabIntersection} and initialize it with a ray with origin <tt>(originX, originY, originZ)</tt> * and direction <tt>(dirX, dirY, dirZ)</tt>. * * @param originX * the x coordinate of the origin * @param originY * the y coordinate of the origin * @param originZ * the z coordinate of the origin * @param dirX * the x coordinate of the direction * @param dirY * the y coordinate of the direction * @param dirZ * the z coordinate of the direction */ public RayAabIntersection(float originX, float originY, float originZ, float dirX, float dirY, float dirZ) { set(originX, originY, originZ, dirX, dirY, dirZ); } /** * Update the ray stored by this {@link RayAabIntersection} with the new origin <tt>(originX, originY, originZ)</tt> * and direction <tt>(dirX, dirY, dirZ)</tt>. * * @param originX * the x coordinate of the origin * @param originY * the y coordinate of the origin * @param originZ * the z coordinate of the origin * @param dirX * the x coordinate of the direction * @param dirY * the y coordinate of the direction * @param dirZ * the z coordinate of the direction */ public void set(float originX, float originY, float originZ, float dirX, float dirY, float dirZ) { this.originX = originX; this.originY = originY; this.originZ = originZ; this.dirX = dirX; this.dirY = dirY; this.dirZ = dirZ; precomputeSlope(); } private static int signum(float f) { return (f == 0.0f || Float.isNaN(f)) ? 0 : ((1 - Float.floatToIntBits(f) >>> 31) << 1) - 1; } /** * Precompute the values necessary for the ray slope algorithm. */ private void precomputeSlope() { float invDirX = 1.0f / dirX; float invDirY = 1.0f / dirY; float invDirZ = 1.0f / dirZ; s_yx = dirX * invDirY; s_xy = dirY * invDirX; s_zy = dirY * invDirZ; s_yz = dirZ * invDirY; s_xz = dirZ * invDirX; s_zx = dirX * invDirZ; c_xy = originY - s_xy * originX; c_yx = originX - s_yx * originY; c_zy = originY - s_zy * originZ; c_yz = originZ - s_yz * originY; c_xz = originZ - s_xz * originX; // <- original paper had a bug here. It switched originZ/originX c_zx = originX - s_zx * originZ; // <- original paper had a bug here. It switched originZ/originX int sgnX = signum(dirX); int sgnY = signum(dirY); int sgnZ = signum(dirZ); category = (byte) ((sgnZ+1) << 4 | (sgnY+1) << 2 | (sgnX+1)); } /** * Intersect the ray stored in this {@link RayAabIntersection} with the given axis-aligned box, * given via its minimum corner <tt>(minX, minY, minZ)</tt> and its maximum corner <tt>(maxX, maxY, maxZ)</tt>. * <p> * This implementation uses a tableswitch to dispatch to the correct intersection method. * * @param minX * the x coordinate of the minimum corner * @param minY * the y coordinate of the minimum corner * @param minZ * the z coordinate of the minimum corner * @param maxX * the x coordinate of the maximum corner * @param maxY * the y coordinate of the maximum corner * @param maxZ * the z coordinate of the maximum corner * @return <code>true</code> if the ray intersects with the given axis-aligned box; <code>false</code> otherwise */ public boolean intersect(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { // tableswitch with dense and consecutive cases (will be a simple jump based on the switch argument switch (category) { case 0: // 0b000000: // MMM return MMM(minX, minY, minZ, maxX, maxY, maxZ); case 1: // 0b000001: // OMM return OMM(minX, minY, minZ, maxX, maxY, maxZ); case 2: // 0b000010: // PMM return PMM(minX, minY, minZ, maxX, maxY, maxZ); case 3: // 0b000011: // not used return false; case 4: // 0b000100: // MOM return MOM(minX, minY, minZ, maxX, maxY, maxZ); case 5: // 0b000101: // OOM return OOM(minX, minY, minZ, maxX, maxY); case 6: // 0b000110: // POM return POM(minX, minY, minZ, maxX, maxY, maxZ); case 7: // 0b000111: // not used return false; case 8: // 0b001000: // MPM return MPM(minX, minY, minZ, maxX, maxY, maxZ); case 9: // 0b001001: // OPM return OPM(minX, minY, minZ, maxX, maxY, maxZ); case 10: // 0b001010: // PPM return PPM(minX, minY, minZ, maxX, maxY, maxZ); case 11: // 0b001011: // not used case 12: // 0b001100: // not used case 13: // 0b001101: // not used case 14: // 0b001110: // not used case 15: // 0b001111: // not used return false; case 16: // 0b010000: // MMO return MMO(minX, minY, minZ, maxX, maxY, maxZ); case 17: // 0b010001: // OMO return OMO(minX, minY, minZ, maxX, maxZ); case 18: // 0b010010: // PMO return PMO(minX, minY, minZ, maxX, maxY, maxZ); case 19: // 0b010011: // not used return false; case 20: // 0b010100: // MOO return MOO(minX, minY, minZ, maxY, maxZ); case 21: // 0b010101: // OOO return false; // <- degenerate case case 22: // 0b010110: // POO return POO(minY, minZ, maxX, maxY, maxZ); case 23: // 0b010111: // not used return false; case 24: // 0b011000: // MPO return MPO(minX, minY, minZ, maxX, maxY, maxZ); case 25: // 0b011001: // OPO return OPO(minX, minZ, maxX, maxY, maxZ); case 26: // 0b011010: // PPO return PPO(minX, minY, minZ, maxX, maxY, maxZ); case 27: // 0b011011: // not used case 28: // 0b011100: // not used case 29: // 0b011101: // not used case 30: // 0b011110: // not used case 31: // 0b011111: // not used return false; case 32: // 0b100000: // MMP return MMP(minX, minY, minZ, maxX, maxY, maxZ); case 33: // 0b100001: // OMP return OMP(minX, minY, minZ, maxX, maxY, maxZ); case 34: // 0b100010: // PMP return PMP(minX, minY, minZ, maxX, maxY, maxZ); case 35: // 0b100011: // not used return false; case 36: // 0b100100: // MOP return MOP(minX, minY, minZ, maxX, maxY, maxZ); case 37: // 0b100101: // OOP return OOP(minX, minY, maxX, maxY, maxZ); case 38: // 0b100110: // POP return POP(minX, minY, minZ, maxX, maxY, maxZ); case 39: // 0b100111: // not used return false; case 40: // 0b101000: // MPP return MPP(minX, minY, minZ, maxX, maxY, maxZ); case 41: // 0b101001: // OPP return OPP(minX, minY, minZ, maxX, maxY, maxZ); case 42: // 0b101010: // PPP return PPP(minX, minY, minZ, maxX, maxY, maxZ); default: return false; } } /* Intersection tests for all possible ray direction cases */ private boolean MMM(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originX >= minX && originY >= minY && originZ >= minZ && s_xy * minX - maxY + c_xy <= 0.0f && s_yx * minY - maxX + c_yx <= 0.0f && s_zy * minZ - maxY + c_zy <= 0.0f && s_yz * minY - maxZ + c_yz <= 0.0f && s_xz * minX - maxZ + c_xz <= 0.0f && s_zx * minZ - maxX + c_zx <= 0.0f; } private boolean OMM(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originX >= minX && originX <= maxX && originY >= minY && originZ >= minZ && s_zy * minZ - maxY + c_zy <= 0.0f && s_yz * minY - maxZ + c_yz <= 0.0f; } private boolean PMM(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originX <= maxX && originY >= minY && originZ >= minZ && s_xy * maxX - maxY + c_xy <= 0.0f && s_yx * minY - minX + c_yx >= 0.0f && s_zy * minZ - maxY + c_zy <= 0.0f && s_yz * minY - maxZ + c_yz <= 0.0f && s_xz * maxX - maxZ + c_xz <= 0.0f && s_zx * minZ - minX + c_zx >= 0.0f; } private boolean MOM(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originY >= minY && originY <= maxY && originX >= minX && originZ >= minZ && s_xz * minX - maxZ + c_xz <= 0.0f && s_zx * minZ - maxX + c_zx <= 0.0f; } private boolean OOM(float minX, float minY, float minZ, float maxX, float maxY) { return originZ >= minZ && originX >= minX && originX <= maxX && originY >= minY && originY <= maxY; } private boolean POM(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originY >= minY && originY <= maxY && originX <= maxX && originZ >= minZ && s_xz * maxX - maxZ + c_xz <= 0.0f && s_zx * minZ - minX + c_zx >= 0.0f; } private boolean MPM(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originX >= minX && originY <= maxY && originZ >= minZ && s_xy * minX - minY + c_xy >= 0.0f && s_yx * maxY - maxX + c_yx <= 0.0f && s_zy * minZ - minY + c_zy >= 0.0f && s_yz * maxY - maxZ + c_yz <= 0.0f && s_xz * minX - maxZ + c_xz <= 0.0f && s_zx * minZ - maxX + c_zx <= 0.0f; } private boolean OPM(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originX >= minX && originX <= maxX && originY <= maxY && originZ >= minZ && s_zy * minZ - minY + c_zy >= 0.0f && s_yz * maxY - maxZ + c_yz <= 0.0f; } private boolean PPM(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originX <= maxX && originY <= maxY && originZ >= minZ && s_xy * maxX - minY + c_xy >= 0.0f && s_yx * maxY - minX + c_yx >= 0.0f && s_zy * minZ - minY + c_zy >= 0.0f && s_yz * maxY - maxZ + c_yz <= 0.0f && s_xz * maxX - maxZ + c_xz <= 0.0f && s_zx * minZ - minX + c_zx >= 0.0f; } private boolean MMO(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originZ >= minZ && originZ <= maxZ && originX >= minX && originY >= minY && s_xy * minX - maxY + c_xy <= 0.0f && s_yx * minY - maxX + c_yx <= 0.0f; } private boolean OMO(float minX, float minY, float minZ, float maxX, float maxZ) { return originY >= minY && originX >= minX && originX <= maxX && originZ >= minZ && originZ <= maxZ; } private boolean PMO(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originZ >= minZ && originZ <= maxZ && originX <= maxX && originY >= minY && s_xy * maxX - maxY + c_xy <= 0.0f && s_yx * minY - minX + c_yx >= 0.0f; } private boolean MOO(float minX, float minY, float minZ, float maxY, float maxZ) { return originX >= minX && originY >= minY && originY <= maxY && originZ >= minZ && originZ <= maxZ; } private boolean POO(float minY, float minZ, float maxX, float maxY, float maxZ) { return originX <= maxX && originY >= minY && originY <= maxY && originZ >= minZ && originZ <= maxZ; } private boolean MPO(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originZ >= minZ && originZ <= maxZ && originX >= minX && originY <= maxY && s_xy * minX - minY + c_xy >= 0.0f && s_yx * maxY - maxX + c_yx <= 0.0f; } private boolean OPO(float minX, float minZ, float maxX, float maxY, float maxZ) { return originY <= maxY && originX >= minX && originX <= maxX && originZ >= minZ && originZ <= maxZ; } private boolean PPO(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originZ >= minZ && originZ <= maxZ && originX <= maxX && originY <= maxY && s_xy * maxX - minY + c_xy >= 0.0f && s_yx * maxY - minX + c_yx >= 0.0f; } private boolean MMP(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originX >= minX && originY >= minY && originZ <= maxZ && s_xy * minX - maxY + c_xy <= 0.0f && s_yx * minY - maxX + c_yx <= 0.0f && s_zy * maxZ - maxY + c_zy <= 0.0f && s_yz * minY - minZ + c_yz >= 0.0f && s_xz * minX - minZ + c_xz >= 0.0f && s_zx * maxZ - maxX + c_zx <= 0.0f; } private boolean OMP(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originX >= minX && originX <= maxX && originY >= minY && originZ <= maxZ && s_zy * maxZ - maxY + c_zy <= 0.0f && s_yz * minY - minZ + c_yz >= 0.0f; } private boolean PMP(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originX <= maxX && originY >= minY && originZ <= maxZ && s_xy * maxX - maxY + c_xy <= 0.0f && s_yx * minY - minX + c_yx >= 0.0f && s_zy * maxZ - maxY + c_zy <= 0.0f && s_yz * minY - minZ + c_yz >= 0.0f && s_xz * maxX - minZ + c_xz >= 0.0f && s_zx * maxZ - minX + c_zx >= 0.0f; } private boolean MOP(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originY >= minY && originY <= maxY && originX >= minX && originZ <= maxZ && s_xz * minX - minZ + c_xz >= 0.0f && s_zx * maxZ - maxX + c_zx <= 0.0f; } private boolean OOP(float minX, float minY, float maxX, float maxY, float maxZ) { return originZ <= maxZ && originX >= minX && originX <= maxX && originY >= minY && originY <= maxY; } private boolean POP(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originY >= minY && originY <= maxY && originX <= maxX && originZ <= maxZ && s_xz * maxX - minZ + c_xz >= 0.0f && s_zx * maxZ - minX + c_zx <= 0.0f; } private boolean MPP(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originX >= minX && originY <= maxY && originZ <= maxZ && s_xy * minX - minY + c_xy >= 0.0f && s_yx * maxY - maxX + c_yx <= 0.0f && s_zy * maxZ - minY + c_zy >= 0.0f && s_yz * maxY - minZ + c_yz >= 0.0f && s_xz * minX - minZ + c_xz >= 0.0f && s_zx * maxZ - maxX + c_zx <= 0.0f; } private boolean OPP(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originX >= minX && originX <= maxX && originY <= maxY && originZ <= maxZ && s_zy * maxZ - minY + c_zy < 0.0f && s_yz * maxY - minZ + c_yz < 0.0f; } private boolean PPP(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return originX <= maxX && originY <= maxY && originZ <= maxZ && s_xy * maxX - minY + c_xy >= 0.0f && s_yx * maxY - minX + c_yx >= 0.0f && s_zy * maxZ - minY + c_zy >= 0.0f && s_yz * maxY - minZ + c_yz >= 0.0f && s_xz * maxX - minZ + c_xz >= 0.0f && s_zx * maxZ - minX + c_zx >= 0.0f; } }
/* * $Id: HashQueue.java,v 1.32 2003-04-21 05:37:30 tal Exp $ */ // todo // locking needed on currently running req? what if dequeued by remove() // while it's running. Can't happen? package org.lockss.hasher; import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.security.MessageDigest; import org.lockss.daemon.*; import org.lockss.daemon.status.*; import org.lockss.util.*; import org.lockss.plugin.*; class HashQueue implements Serializable { static final String PREFIX = Configuration.PREFIX + "hasher."; static final String PARAM_PRIORITY = PREFIX + "priority"; static final String PARAM_STEP_BYTES = PREFIX + "stepBytes"; static final String PARAM_NUM_STEPS = PREFIX + "numSteps"; static final String PARAM_COMPLETED_MAX = PREFIX + "historySize"; protected static Logger log = Logger.getLogger("HashQueue"); private LinkedList qlist = new LinkedList(); // the queue // last n completed requests private HistoryList completed = new HistoryList(50); private HashThread hashThread; private BinarySemaphore sem = new BinarySemaphore(); private int hashPriority = -1; private int hashStepBytes = 10000; private int hashNumSteps = 10; private int schedCtr = 0; private int finishCtr = 0; private BigInteger totalBytesHashed = BigInteger.valueOf(0); private long totalTime = 0; HashQueue() { } private synchronized List getQlistSnapshot() { return new ArrayList(qlist); } List getCompletedSnapshot() { synchronized (completed) { return new ArrayList(completed); } } // Return head of queue or null if empty synchronized Request head() { return qlist.isEmpty() ? null : (Request)qlist.getFirst(); } // scan queue, removing and notifying hashes that have finshed or errored // or passed their deadline. void removeCompleted() { List done = findAndRemoveCompleted(); doCallbacks(done); } synchronized List findAndRemoveCompleted() { List done = new ArrayList(); for (ListIterator iter = qlist.listIterator(); iter.hasNext();) { Request req = (Request)iter.next(); if (req.e != null) { removeAndNotify(req, iter, done, "Errored: "); } else if (req.urlsetHasher.finished()) { removeAndNotify(req, iter, done, "Finished: "); } else if (req.deadline.expired()) { req.e = new HashService.Timeout("hash not finished before deadline"); removeAndNotify(req, iter, done, "Expired: "); } } return done; } private void removeAndNotify(Request req, Iterator iter, List done, String msg) { req.finish = ++finishCtr; if (log.isDebug()) { log.debug(msg + ((req.e != null) ? (req.e + ": ") : "") + req); } iter.remove(); req.urlset.storeActualHashDuration(req.timeUsed, req.e); done.add(req); synchronized (completed) { completed.add(req); } } // separated out so callbacks are run outside of synchronized block, // and so can put in another thread if necessary. void doCallbacks(List list) { for (Iterator iter = list.iterator(); iter.hasNext();) { Request req = (Request)iter.next(); try { req.callback.hashingFinished(req.urlset, req.cookie, req.hasher, req.e); } catch (Exception e) { log.error("Hash callback threw", e); } // completed list for status only, don't hold on to caller's objects req.hasher = null; req.callback = null; req.cookie = null; req.urlsetHasher = null; } } // Insert request in queue iff it can finish in time and won't prevent // any that are already queued from finishing in time. synchronized boolean insert(Request req) { long totalDuration = 0; long durationUntilNewReq = -1; int pos = 0; long now = TimeBase.nowMs(); if (log.isDebug()) log.debug("Insert: " + req); for (ListIterator iter = qlist.listIterator(); iter.hasNext();) { Request qreq = (Request)iter.next(); if (req.runBefore(qreq)) { // New req goes here. Remember duration so far, then add new one durationUntilNewReq = totalDuration; totalDuration += req.curEst(); // Now check that all that follow could still finish in time // Requires backing up so will start with one we just looked at iter.previous(); while (iter.hasNext()) { qreq = (Request)iter.next(); if (qreq.overrun()) { // Don't let overrunners prevent others from getting into queue. // (Their curEst() is zero so they wouldn't affect the // totalDuration, but their deadline might precede the // new request's deadline, so might now be unachievable.) break; } totalDuration += qreq.curEst(); if (now + totalDuration > qreq.deadline.getExpirationTime()) { return false; } } } else { pos++; totalDuration += qreq.curEst(); } } // check that new req can finish in time if (durationUntilNewReq < 0) { // new req will be at end durationUntilNewReq = totalDuration; } if ((now + durationUntilNewReq + req.curEst()) > req.deadline.getExpirationTime()) { return false; } req.sched = ++schedCtr; qlist.add(pos, req); return true; } // Resort the queue. Necessary when any request's sort order might have // changed, such as when it becomes overrun. synchronized void reschedule() { Collections.sort(qlist); } boolean scheduleReq(Request req) { if (!insert(req)) { log.debug("Can't schedule hash"); return false; } ensureQRunner(); sem.give(); log.debug("Scheduled hash:" +req); return true; } void init() { registerConfigCallback(); } // Register config callback private void registerConfigCallback() { Configuration.registerConfigurationCallback(new Configuration.Callback() { public void configurationChanged(Configuration newConfig, Configuration oldConfig, Set changedKeys) { setConfig(newConfig, changedKeys); } }); } private void setConfig(Configuration config, Set changedKeys) { hashPriority = config.getInt(PARAM_PRIORITY, Thread.MIN_PRIORITY); hashStepBytes = config.getInt(PARAM_STEP_BYTES, 10000); hashNumSteps = config.getInt(PARAM_NUM_STEPS, 10); int cMax = config.getInt(PARAM_COMPLETED_MAX, 50); if (changedKeys.contains(PARAM_COMPLETED_MAX) ) { synchronized (completed) { completed.setMax(config.getInt(PARAM_COMPLETED_MAX, 50)); } } } // Request - hash queue element. static class Request implements Serializable, Comparable { CachedUrlSet urlset; MessageDigest hasher; Deadline deadline; HashService.Callback callback; Object cookie; CachedUrlSetHasher urlsetHasher; String type; int sched; int finish; long origEst; long timeUsed = 0; long bytesHashed = 0; Exception e; boolean firstOverrun; Request(CachedUrlSet urlset, MessageDigest hasher, Deadline deadline, HashService.Callback callback, Object cookie, CachedUrlSetHasher urlsetHasher, long estimatedDuration, String type) { this.urlset = urlset; this.hasher = hasher; this.deadline = deadline; this.callback = callback; this.cookie = cookie; this.urlsetHasher = urlsetHasher; this.origEst = estimatedDuration; this.type = type; } long curEst() { long t = origEst - timeUsed; return (t > 0 ? t : 0); } boolean finished() { return (e != null) || urlsetHasher.finished(); } boolean overrun() { return timeUsed > origEst; } boolean runBefore(Request other) { return compareTo(other) < 0; } // tk - should this take into account other factors, such as // giving priority to requests with the least time remaining? public int compareTo(Request other) { boolean over1 = overrun(); boolean over2 = other.overrun(); if (over1 && !over2) return 1; if (!over1 && over2) return -1; if (deadline.before(other.deadline)) return -1; if (other.deadline.before(deadline)) return 1; return 0; } public int compareTo(Object o) { return compareTo((Request)o); } static final DateFormat dfDeadline = new SimpleDateFormat("HH:mm:ss"); public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[HQ.Req:"); sb.append(urlset); sb.append(' '); if (cookie instanceof String) { sb.append("\""); sb.append(cookie); sb.append("\""); } sb.append(" "); sb.append(origEst); sb.append("ms by "); sb.append(deadline); // sb.append(dfDeadline.format(deadline.getExpiration())); sb.append("]"); return sb.toString(); } } public void stop() { if (hashThread != null) { log.info("Stopping Q runner"); hashThread.stopQRunner(); hashThread = null; } } // tk add watchdog void ensureQRunner() { if (hashThread == null) { log.info("Starting Q runner"); hashThread = new HashThread("HashQ"); hashThread.start(); } } void runNSteps(Request req, int nsteps, int nbytes, Boolean goOn) { CachedUrlSetHasher ush = req.urlsetHasher; req.firstOverrun = false; Deadline overrunDeadline = null; if (! req.overrun()) { // watch for overrun only if it hasn't overrun yet overrunDeadline = Deadline.in(req.curEst()); } long startTime = TimeBase.nowMs(); long bytesHashed = 0; try { // repeat up to nsteps steps, while goOn is true, // the request we're working on is still at the head of the queue, // and it isn't finished for (int cnt = nsteps; cnt > 0 && goOn.booleanValue() && req == head() && !req.finished(); cnt if (log.isDebug3()) log.debug3("hashStep(" + nbytes + "): " + req); bytesHashed += ush.hashStep(nbytes); // break if it's newly overrun if (!ush.finished() && overrunDeadline != null && overrunDeadline.expired()) { req.firstOverrun = true; if (log.isDebug()) log.debug("Overrun: " + req); break; } } if (!req.finished() && req.deadline.expired()) { if (log.isDebug()) log.debug("Expired: " + req); throw new HashService.Timeout("hash not finished before deadline"); } } catch (Exception e) { // tk - should this catch all Throwable? req.e = e; } long timeDelta = TimeBase.msSince(startTime); req.timeUsed += timeDelta; req.bytesHashed += bytesHashed; totalBytesHashed = totalBytesHashed.add(BigInteger.valueOf(bytesHashed)); totalTime += timeDelta; } // Run up to n steps of the request at the head of the queue, and call // its callback if it's done. // Return true if we did any work, false if no requests on queue. boolean runAndNotify(int nsteps, int nbytes, Boolean goOn) { Request req = head(); if (req == null) { log.debug2("runAndNotify no work"); return false; } runNSteps(req, nsteps, nbytes, goOn); if (req.firstOverrun) { reschedule(); } // need to do this more often than just when one finishes, so will // notice those that expired. Better way than every time? if (true || req.finished()) { removeCompleted(); } return true; } // Hash thread private class HashThread extends Thread { private Boolean goOn = Boolean.FALSE; private HashThread(String name) { super(name); } public void run() { if (hashPriority > 0) { Thread.currentThread().setPriority(hashPriority); } goOn = Boolean.TRUE; try { while (goOn.booleanValue()) { if (!runAndNotify(hashNumSteps, hashStepBytes, goOn)) { sem.take(Deadline.in(Constants.MINUTE)); } // Thread.yield(); } } catch (InterruptedException e) { // no action - expected when stopping } catch (Exception e) { log.error("Unexpected exception caught in hash thread", e); } finally { hashThread = null; } } private void stopQRunner() { goOn = Boolean.FALSE; this.interrupt(); } } StatusAccessor getStatusAccessor() { return new Status(); } private static final List statusSortRules = ListUtil.list(new StatusTable.SortRule("state", true), new StatusTable.SortRule("sort", true)); static final String FOOT_IN = "Order in which requests were made."; static final String FOOT_OVER = "Red indicates overrun."; static final String FOOT_TITLE = "Pending requests are first in table, in the order they will be executed."+ " Completed requests follow, in reverse completion order " + "(most recent first)."; private static final List statusColDescs = ListUtil.list( new ColumnDescriptor("sched", "Req", ColumnDescriptor.TYPE_INT, FOOT_IN), // new ColumnDescriptor("finish", "Out", // ColumnDescriptor.TYPE_INT), new ColumnDescriptor("state", "State", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("au", "Volume", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("cus", "Cached Url Set", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("type", "Type", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("deadline", "Deadline", ColumnDescriptor.TYPE_DATE), new ColumnDescriptor("estimate", "Estimated", ColumnDescriptor.TYPE_TIME_INTERVAL), new ColumnDescriptor("timeused", "Used", ColumnDescriptor.TYPE_TIME_INTERVAL, FOOT_OVER), new ColumnDescriptor("bytesHashed", "Bytes<br>Hashed", ColumnDescriptor.TYPE_INT) ); private class Status implements StatusAccessor { public void populateTable(StatusTable table) { String key = table.getKey(); table.setTitle("Hash Queue"); table.setTitleFootnote(FOOT_TITLE); table.setColumnDescriptors(statusColDescs); table.setDefaultSortRules(statusSortRules); table.setRows(getRows(key)); table.setSummaryInfo(getSummaryInfo(key)); } public boolean requiresKey() { return false; } private List getRows(String key) { List table = new ArrayList(); int ix = 0; for (ListIterator iter = getQlistSnapshot().listIterator(); iter.hasNext();) { table.add(makeRow((Request)iter.next(), false, ix)); } for (ListIterator iter = getCompletedSnapshot().listIterator(); iter.hasNext();) { table.add(makeRow((Request)iter.next(), true, 0)); } return table; } private Map makeRow(Request req, boolean done, int qpos) { Map row = new HashMap(); row.put("sort", new Integer(done ? -req.finish : qpos)); row.put("sched", new Integer(req.sched)); // row.put("finish", new Integer(req.finish)); row.put("state", getState(req, done)); row.put("au", req.urlset.getArchivalUnit().getName()); row.put("cus", req.urlset.getSpec()); row.put("type", req.type); row.put("deadline", req.deadline.getExpiration()); row.put("estimate", new Long(req.origEst)); Object used = new Long(req.timeUsed); if (req.overrun()) { StatusTable.DisplayedValue val = new StatusTable.DisplayedValue(used); val.setColor("red"); used = val; } row.put("timeused", used); row.put("bytesHashed", new Long(req.bytesHashed)); return row; } private Object getState(Request req, boolean done) { if (!done) { return (req == head()) ? REQ_STATE_RUN : REQ_STATE_WAIT; } if (req.e == null) { return REQ_STATE_DONE; } else if (req.e instanceof HashService.Timeout) { return REQ_STATE_TIMEOUT; } else { return REQ_STATE_ERROR; } } private List getSummaryInfo(String key) { List res = new ArrayList(); res.add(new StatusTable.SummaryInfo("Total bytes hashed", ColumnDescriptor.TYPE_INT, totalBytesHashed)); res.add(new StatusTable.SummaryInfo("Total hash time", ColumnDescriptor.TYPE_TIME_INTERVAL, new Long(totalTime))); if (totalTime != 0) { long bpms = totalBytesHashed.divide(BigInteger.valueOf(totalTime)).intValue(); if (bpms < (100 * Constants.SECOND)) { res.add(new StatusTable.SummaryInfo("Bytes/ms", ColumnDescriptor.TYPE_INT, new Long(bpms))); } else { res.add(new StatusTable.SummaryInfo("Bytes/sec", ColumnDescriptor.TYPE_INT, new Long(bpms / Constants.SECOND))); } } return res; } } static class ReqState implements Comparable { String name; int order; ReqState(String name, int order) { this.name = name; this.order = order; } public int compareTo(Object o) { return order - ((ReqState)o).order; } public String toString() { return name; } } static final ReqState REQ_STATE_RUN = new ReqState("Run", 1); static final ReqState REQ_STATE_WAIT = new ReqState("Wait", 2); static final ReqState REQ_STATE_DONE = new ReqState("Done", 3); static final StatusTable.DisplayedValue REQ_STATE_TIMEOUT = new StatusTable.DisplayedValue(new ReqState("Timeout", 3)); static final StatusTable.DisplayedValue REQ_STATE_ERROR = new StatusTable.DisplayedValue(new ReqState("Error", 3)); static { REQ_STATE_TIMEOUT.setColor("red"); REQ_STATE_ERROR.setColor("red"); } }
/* * $Id: AuConfig.java,v 1.5 2003-08-01 15:57:59 tlipkis Exp $ */ package org.lockss.servlet; import javax.servlet.http.*; import javax.servlet.*; import java.io.*; import java.util.*; import java.net.*; import java.text.*; import org.mortbay.html.*; import org.mortbay.tools.*; import org.lockss.util.*; import org.lockss.plugin.*; import org.lockss.daemon.*; import org.lockss.daemon.status.*; /** Create and update AU configuration. */ public class AuConfig extends LockssServlet { static Logger log = Logger.getLogger("AuConfig"); private ConfigManager configMgr; private PluginManager pluginMgr; // Used to insert error messages into the page private String errMsg; private String statusMsg; String action; // action request by form Plugin plug; // current plugin Configuration auConfig; // current config from AU Configuration formConfig; // config read from form Collection defKeys; // plugin's definitional keys Collection allKeys; // all plugin config keys java.util.List editKeys; // non-definitional keys // don't hold onto objects after request finished private void resetLocals() { plug = null; auConfig = null; formConfig = null; defKeys = null; allKeys = null; editKeys = null; } public void init(ServletConfig config) throws ServletException { super.init(config); configMgr = getLockssDaemon().getConfigManager(); pluginMgr = getLockssDaemon().getPluginManager(); } public void lockssHandleRequest() throws IOException { action = req.getParameter("action"); errMsg = null; statusMsg = null; formConfig = null; op: { if (StringUtil.isNullString(action)) { displayAuSummary(); break op; } if (action.equals("Add")) { displayAddAu(); break op; } if (action.equals("EditNew")) { displayEditNew(); break op; } if (action.equals("Create")) { createAu(); break op; } // all other actions require AU. If missing, display summary page String auid = req.getParameter("auid"); ArchivalUnit au = pluginMgr.getAuFromId(auid); if (au == null) { errMsg = "Invalid AuId: " + auid; displayAuSummary(); break op; } if (action.equals("Edit")){ displayEditAu(au); break op; } if (action.equals("Restore")) { displayRestoreAu(au); break op; } if (action.equals("DoRestore")) { updateAu(au); break op; } if (action.equals("Update")) { updateAu(au); break op; } if (action.equals("Unconfigure")) { confirmUnconfigureAu(au); break op; } if (action.equals("Confirm Unconfigure")) { doUnconfigureAu(au); break op; } errMsg = "Unknown action: " + action; displayAuSummary(); } resetLocals(); } private void displayAuSummary() throws IOException { Page page = newPage(); page.add(getErrBlock()); page.add(getExplanationBlock("Add a new volume, or edit an existing one.")); Table tbl = new Table(0, "align=center cellspacing=4 cellpadding=0"); addAddAuRow(tbl); Collection allAUs = pluginMgr.getAllAUs(); if (!allAUs.isEmpty()) { for (Iterator iter = allAUs.iterator(); iter.hasNext(); ) { addAuSummaryRow(tbl, (ArchivalUnit)iter.next()); } } page.add(tbl); endPage(page); } private void addAddAuRow(Table tbl) { Form frm = new Form(srvURL(myServletDescr(), null)); frm.method("POST"); frm.add(new Input(Input.Submit, "action", "Add")); tbl.newRow(); tbl.newCell("align=right valign=center"); tbl.add(frm); tbl.newCell("valign=center"); tbl.add("Add new Volume"); } private void addAuSummaryRow(Table tbl, ArchivalUnit au) { Form frm = new Form(srvURL(myServletDescr(), null)); frm.method("POST"); addAuid(frm, au); Configuration cfg = pluginMgr.getStoredAuConfiguration(au); boolean deleted = cfg.isEmpty(); frm.add(new Input(Input.Submit, "action", deleted ? "Restore": "Edit")); tbl.newRow(); tbl.newCell("align=right valign=center"); tbl.add(frm); tbl.newCell("valign=center"); tbl.add(greyText(au.getName(), deleted)); } private void addAuid(Composite comp, ArchivalUnit au) { comp.add(new Input(Input.Hidden, "auid", au.getAUId())); } private void addPlugId(Composite comp, Plugin plugin) { comp.add(new Input(Input.Hidden, "PluginId", plugin.getPluginId())); } private void fetchAuConfig(ArchivalUnit au) { auConfig = au.getConfiguration(); log.debug("auConfig: " + auConfig); fetchPluginConfig(au.getPlugin()); } private void fetchPluginConfig(Plugin plug) { this.plug = plug; defKeys = plug.getDefiningConfigKeys(); allKeys = plug.getAUConfigProperties(); editKeys = new LinkedList(allKeys); editKeys.removeAll(defKeys); Collections.sort(editKeys); } private void addPropRows(Table tbl, Collection keys, Configuration props, Collection editableKeys) { for (Iterator iter = keys.iterator(); iter.hasNext(); ) { String key = (String)iter.next(); tbl.newRow(); tbl.newCell(); tbl.add(key); tbl.newCell(); String val = props != null ? props.get(key) : null; if (editableKeys != null && editableKeys.contains(key)) { tbl.add(new Input(Input.Text, key, val)); } else { tbl.add(val); } } } private Form createAUEditForm(java.util.List actions, ArchivalUnit au, boolean editable) throws IOException { boolean isNew = au == null; Configuration initVals = formConfig == null ? auConfig : formConfig; if (initVals == null) { initVals = ConfigManager.EMPTY_CONFIGURATION; } Form frm = new Form(srvURL(myServletDescr(), null)); frm.method("POST"); Table tbl = new Table(0, "align=center cellspacing=4 cellpadding=0"); tbl.newRow(); tbl.newCell("colspan=2 align=center"); tbl.add("Volume Definition"); // tbl.add(isNew ? "Defining Properties" : "Fixed Properties"); addPropRows(tbl, defKeys, initVals, (isNew ? (org.apache.commons.collections.CollectionUtils. subtract(defKeys, initVals.keySet())) : null)); tbl.newRow(); tbl.newRow(); tbl.newCell("colspan=2 align=center"); if (editKeys.isEmpty()) { if (!isNew) { tbl.add("No Editable Properties"); } } else { tbl.add("Variable Parameters"); addPropRows(tbl, editKeys, initVals, editKeys); tbl.newRow(); tbl.newCell("colspan=2 align=center"); } if (isNew) { addPlugId(tbl, plug); } else { addAuid(tbl, au); } for (Iterator iter = actions.iterator(); iter.hasNext(); ) { Object act = iter.next(); if (act instanceof String) { tbl.add(new Input(Input.Submit, "action", (String)act)); if (iter.hasNext()) { tbl.add("&nbsp;"); } } else { tbl.add(act); } } frm.add(tbl); return frm; } private void displayEditAu(ArchivalUnit au) throws IOException { Page page = newPage(); fetchAuConfig(au); page.add(getErrBlock()); page.add(getExplanationBlock("Editing Configuration of: " + au.getName())); java.util.List actions = ListUtil.list("Unconfigure"); if (!editKeys.isEmpty()) { actions.add(0, "Update"); } Form frm = createAUEditForm(actions, au, true); page.add(frm); endPage(page); } private void displayRestoreAu(ArchivalUnit au) throws IOException { Page page = newPage(); fetchAuConfig(au); page.add(getErrBlock()); page.add(getExplanationBlock("Restoring Configuration of: " +au.getName())); java.util.List actions = ListUtil.list(new Input(Input.Hidden, "action", "DoRestore"), new Input(Input.Submit, "button", "Restore")); Form frm = createAUEditForm(actions, au, true); page.add(frm); endPage(page); } private void displayAddAu() throws IOException { Page page = newPage(); page.add(getErrBlock()); page.add(getExplanationBlock("Add New Journal Volume")); Form frm = new Form(srvURL(myServletDescr(), null)); frm.method("POST"); frm.add("<center>"); Collection titles = pluginMgr.findAllTitles(); if (!titles.isEmpty()) { frm.add("<br>Choose a title:<br>"); Select sel = new Select("Title", false); sel.add("-no selection-", true, ""); for (Iterator iter = titles.iterator(); iter.hasNext(); ) { String title = (String)iter.next(); sel.add(title, false); } frm.add(sel); frm.add("<br>or"); } SortedMap pMap = new TreeMap(); for (Iterator iter = pluginMgr.getRegisteredPlugins().iterator(); iter.hasNext(); ) { Plugin p = (Plugin)iter.next(); pMap.put(p.getPluginName(), p); } if (!pMap.isEmpty()) { frm.add("<br>Choose a plugin:<br>"); Select sel = new Select("PluginId", false); sel.add("-no selection-", true, ""); for (Iterator iter = pMap.keySet().iterator(); iter.hasNext(); ) { String pName = (String)iter.next(); Plugin p = (Plugin)pMap.get(pName); sel.add(pName, false, p.getPluginId()); } frm.add(sel); frm.add("<br>or"); } frm.add("<br>Enter the class name of a plugin:<br>"); Input in = new Input(Input.Text, "PluginClass"); in.setSize(40); frm.add(in); frm.add("<br><br>"); frm.add(new Input(Input.Hidden, "action", "EditNew")); frm.add(new Input(Input.Submit, "button", "Configure Volume")); page.add(frm); page.add("</center><br>"); endPage(page); } private void displayEditNew() throws IOException { String title = req.getParameter("Title"); if (!StringUtil.isNullString(title)) { Collection c = pluginMgr.getTitlePlugins(title); if (c == null || c.isEmpty()) { errMsg = "Unknown title: " + title; displayAddAu(); return; } // tk - need to deal with > 1 plugin for title Plugin p = (Plugin)c.iterator().next(); formConfig = p.getConfigForTitle(title); fetchPluginConfig(p); } else { String pid = req.getParameter("PluginId"); String pKey; if (!StringUtil.isNullString(pid)) { pKey = pluginMgr.pluginKeyFromId(pid); } else { pid = req.getParameter("PluginClass"); pKey = pluginMgr.pluginKeyFromName(pid); } if (!pluginMgr.ensurePluginLoaded(pKey)) { if (StringUtil.isNullString(pKey)) { errMsg = "You must specify a plugin."; } else { errMsg = "Can't find plugin: " + pid; } displayAddAu(); return; } fetchPluginConfig(pluginMgr.getPlugin(pKey)); } Page page = newPage(); page.add(getErrBlock()); page.add(getExplanationBlock((StringUtil.isNullString(title) ? "Creating new journal volume" : ("Creating new volume of " + title)) + " with plugin: " + plug.getPluginName())); Form frm = createAUEditForm(ListUtil.list("Create"), null, true); page.add(frm); endPage(page); } private void createAu() throws IOException { String pid = req.getParameter("PluginId"); String pKey = pluginMgr.pluginKeyFromId(pid); if (!pluginMgr.ensurePluginLoaded(pKey)) { errMsg = "Can't find plugin: " + pid; displayAddAu(); return; } fetchPluginConfig(pluginMgr.getPlugin(pKey)); formConfig = getAuConfigFromForm(true); try { ArchivalUnit au = pluginMgr.createAndSaveAUConfiguration(plug, formConfig); statusMsg = "AU created."; displayEditAu(au); } catch (ArchivalUnit.ConfigurationException e) { log.error("Error configuring AU", e); errMsg = "Error configuring AU:<br>" + e.getMessage(); displayEditNew(); } catch (IOException e) { log.error("Error saving AU configuration", e); errMsg = "Error saving AU configuration:<br>" + e.getMessage(); displayEditNew(); } } private void updateAu(ArchivalUnit au) throws IOException { fetchAuConfig(au); // Properties p = new Properties(); Configuration formConfig = getAuConfigFromForm(false); if (isChanged(auConfig, formConfig) || isChanged(pluginMgr.getStoredAuConfiguration(au), formConfig)) { try { pluginMgr.setAndSaveAUConfiguration(au, formConfig); statusMsg = "AU configuration saved."; } catch (ArchivalUnit.ConfigurationException e) { log.error("Couldn't reconfigure AU", e); errMsg = e.getMessage(); } catch (IOException e) { log.error("Couldn't save AU configuraton", e); errMsg = "Error saving AU:<br>" + e.getMessage(); displayEditAu(au); } } else { statusMsg = "No changes made."; } displayEditAu(au); } private void confirmUnconfigureAu(ArchivalUnit au) throws IOException { String permFoot = "Permanent deletion occurs only during a reboot," + " when configuration changes are backed up to the configuration floppy."; String unconfigureFoot = "Unconfigure will not take effect until the next daemon restart." + " At that point the volume will be inactive, but its contents" + " will remain in the cache untill the deletion is made permanent" + addFootnote(permFoot) + "."; Page page = newPage(); fetchAuConfig(au); page.add(getErrBlock()); page.add(getExplanationBlock("Are you sure you want to unconfigure" + addFootnote(unconfigureFoot) + ": " + au.getName())); Form frm = createAUEditForm(ListUtil.list("Confirm Unconfigure"), au, false); page.add(frm); endPage(page); } private void doUnconfigureAu(ArchivalUnit au) throws IOException { try { pluginMgr.deleteAUConfiguration(au); statusMsg = "AU configuration removed."; } catch (ArchivalUnit.ConfigurationException e) { log.error("Can't happen", e); errMsg = e.getMessage(); } catch (IOException e) { log.error("Couldn't save AU configuraton", e); errMsg = "Error deleting AU:<br>" + e.getMessage(); } displayAuSummary(); } private void putFormVal(Properties p, String key) { String val = req.getParameter(key); // Must treat empty string as unset param. if (!StringUtil.isNullString(val)) { p.put(key, val); } } boolean isChanged(Configuration oldConfig, Configuration newConfig) { Collection dk = oldConfig.differentKeys(newConfig); boolean changed = false; for (Iterator iter = dk.iterator(); iter.hasNext(); ) { String key = (String)iter.next(); String oldVal = oldConfig.get(key); String newVal = newConfig.get(key); if (!isEqualFormVal(oldVal, newVal)) { changed = true; log.debug("Key " + key + " changed from \"" + oldVal + "\" to \"" + newVal + "\""); } } return changed; } Configuration getAuConfigFromForm(boolean isNew) { Properties p = new Properties(); for (Iterator iter = defKeys.iterator(); iter.hasNext(); ) { String key = (String)iter.next(); if (isNew) { putFormVal(p, key); } else { if (auConfig.get(key) != null) { p.put(key, auConfig.get(key)); } } } for (Iterator iter = editKeys.iterator(); iter.hasNext(); ) { String key = (String)iter.next(); putFormVal(p, key); } return ConfigManager.fromProperties(p); } private boolean isEqualFormVal(String formVal, String oldVal) { return (StringUtil.isNullString(formVal)) ? StringUtil.isNullString(oldVal) : formVal.equals(oldVal); } private Composite getErrBlock() { Composite comp = new Composite(); if (errMsg != null) { comp.add("<center><font color=red>"); comp.add(errMsg); comp.add("</font></center><br>"); } if (statusMsg != null) { comp.add("<center>"); comp.add(statusMsg); comp.add("</center><br>"); } return comp; } protected void endPage(Page page) throws IOException { if (action != null) { page.add("<center>"); page.add(srvLink(myServletDescr(), "Back to Journal Configuration")); page.add("</center>"); } page.add(getFooter()); page.write(resp.getWriter()); } // make me a link in nav table if not on initial journal config page protected boolean linkMeInNav() { return action != null; } }
/* * $Id: RateLimiter.java,v 1.13 2006-09-16 07:33:50 tlipkis Exp $ */ package org.lockss.util; import java.util.*; import org.lockss.config.Configuration; /** * RateLimiter is used to limit the rate at which some class of events * occur. Individual operations on this class are synchronized, so safe to * use from multiple threads. However, in order to ensure the rate isn't * exceeded, multithreaded use requires the pair of calls {@link * #isEventOk()} and {@link #event()}, or the pair {@link * #waitUntilEventOk()} and {@link #event()} to be synchronized as a unit:<pre> synchronized (rateLimiter) { rateLimiter.isEventOk(); rateLimiter.event(); }</pre> */ public class RateLimiter { static Logger log = Logger.getLogger("RateLimiter"); /** A RateLimiter that allows events at an unlimited rate. */ public final static RateLimiter UNLIMITED = new Constant("unlimited"); private int events; // limit on events / interval private long interval; private long time[]; // history of (events) event times, // or null if unlimited private int count = 0; private String rate; /** Create a RateLimiter according to the specified configuration parameters. * @param config the Configuration object * @param currentLimiter optional existing RateLimiter, modified if * necessary * @param maxEventsParam name of the parameter specifying the maximum * number of events per interval * @param intervalParam name of the parameter specifying the length of * the interval * @param maxEvantDefault default maximum number of events per interval, * if config param has no value * @param intervalDefault default interval, if config param has no value * @return a new RateLimiter iff currentLimiter is null, else * currentLimiter, possible reset to a new rate */ public static RateLimiter getConfiguredRateLimiter(Configuration config, RateLimiter currentLimiter, String maxEventsParam, int maxEvantDefault, String intervalParam, long intervalDefault) { int events = config.getInt(maxEventsParam, maxEvantDefault); long interval = config.getTimeInterval(intervalParam, intervalDefault); if (currentLimiter == null) { return new RateLimiter(events, interval); } if (!currentLimiter.isRate(events, interval)) { currentLimiter.setRate(events, interval); } return currentLimiter; } /** Create a RateLimiter according to the specified configuration * parameter, whose value should be a string: * <i>events</i>/<i>time-interval</i>. * @param config the Configuration object * @param currentLimiter optional existing RateLimiter, modified if * necessary * @param param name of the rate string config parameter * @param dfault default rate string * @return a new RateLimiter iff currentLimiter is null, else * currentLimiter, possible reset to a new rate * @throws RuntimeException if the parameter value is either empty or * unparseable and the default string is unparseable */ public static RateLimiter getConfiguredRateLimiter(Configuration config, RateLimiter currentLimiter, String param, String dfault) { String rate = config.get(param, dfault); if (currentLimiter == null) { return makeRateLimiter(rate, dfault); } if (!currentLimiter.isRate(rate)) { currentLimiter.setRate(rate, dfault); } return currentLimiter; } /** Create a RateLimiter according to the rate string: * <i>events</i>/<i>time-interval</i>. * @param rate the rate string * @param dfault default rate string * @return a new RateLimiter * @throws RuntimeException iff the rate string is either empty or * unparseable and the default string is unparseable. */ public static RateLimiter makeRateLimiter(String rate, String dfault) { try { return new RateLimiter(rate); } catch (RuntimeException e) { log.warning("Rate (" + rate + ") illegal, using default (" + dfault + ")"); return new RateLimiter(dfault); } } // helper to parse rate string <events> / <time-interval> private static class Ept { private int events; private long interval; Ept(String rate) { if ("unlimited".equalsIgnoreCase(rate)) { events = 0; interval = 0; } else { List pair = StringUtil.breakAt(rate, '/', 3, false, true); if (pair.size() != 2) { throw new IllegalArgumentException("Rate not n/interval: " + rate); } events = Integer.parseInt((String)pair.get(0)); interval = StringUtil.parseTimeInterval((String)pair.get(1)); } } } /** Create a RateLimiter that limits events to <code>events</code> per * <code>interval</code> milliseconds. * @param events max number of events per interval * @param interval length of interval in milliseconds */ public RateLimiter(int events, long interval) { checkRate(events, interval, false); init(events, interval); } /** Create a RateLimiter that limits events to the specified rate * @param rate the rate string, <i>events</i>/<i>time-interval</i>. */ public RateLimiter(String rate) { Ept ept = new Ept(rate); checkRate(ept.events, ept.interval, true); init(ept.events, ept.interval); this.rate = rate; } private void init(int events, long interval) { this.events = events; this.interval = interval; if (interval != 0) { time = new long[events]; Arrays.fill(time, 0); } else { time = null; } count = 0; } private void checkRate(int events, long interval, boolean allowUnlimited) { if (allowUnlimited && events == 0 && interval == 0) { return; } if (events < 1) { throw new IllegalArgumentException("events: " + events); } if (interval < 1) { throw new IllegalArgumentException("interval: " + interval); } } /** Return the limit as a rate string n/interval */ public String getRate() { if (rate == null) { rate = rateString(); } return rate; } /** Return the limit on the number of events */ public int getLimit() { return events; } /** Return the interval over which events are limited */ public long getInterval() { return interval; } /** Return true if the rate limiter is of specified rate */ public boolean isRate(String rate) { return getRate().equals(rate); } /** Return true if the rate limiter is of specified rate */ public boolean isRate(int events, long interval) { return this.events == events && this.interval == interval; } /** Return true iff the rate limiter imposes no limit */ public boolean isUnlimited() { return time == null; } /** Change the rate */ public synchronized void setRate(String newRate) { if (!isRate(newRate)) { Ept ept = new Ept(newRate); checkRate(ept.events, ept.interval, true); setRate0(ept.events, ept.interval); rate = newRate; } } /** Change the rate */ public synchronized void setRate(String newRate, String dfault) { if (!isRate(newRate)) { Ept ept; try { ept = new Ept(newRate); checkRate(ept.events, ept.interval, true); } catch (RuntimeException e) { log.warning("Configured rate (" + rate + ") illegal, using default (" + dfault + ")"); newRate = dfault; ept = new Ept(newRate); checkRate(ept.events, ept.interval, true); } setRate0(ept.events, ept.interval); rate = newRate; } } /** Change the rate */ public synchronized void setRate(int newEvents, long newInterval) { if (!isRate(newEvents, newInterval)) { checkRate(newEvents, newInterval, false); setRate0(newEvents, newInterval); rate = null; } } private void setRate0(int newEvents, long newInterval) { if (newInterval != this.interval) { if (newInterval == 0 || this.interval == 0) { init(newEvents, newInterval); return; } else { this.interval = newInterval; } } if (events != newEvents) { this.time = resizeEventArray(time, count, newEvents); this.events = newEvents; count = 0; } } /** Return an array of size newEvents with all, or the logically last * newEvents elements from the source array inserted in proper order at * the end. The resulting array assumes that the current pointer will be * reset to zero. This is a purely functional method so it can be easily * tested. It is static to ensure that it's functional. */ static long[] resizeEventArray(long[] arr, int ptr, int newEvents) { int oldEvents = arr.length; long res[] = new long[newEvents]; int p = newEvents; if (ptr != 0) { int alen = ptr < p ? ptr : p; p -= alen; System.arraycopy(arr, ptr - alen, res, p, alen); } int blen = (oldEvents - ptr) < p ? (oldEvents - ptr) : p; p -= blen; System.arraycopy(arr, oldEvents - blen, res, p, blen); if (p > 0) { Arrays.fill(res, 0, p, 0); } return res; } /** Record an occurrence of the event */ public synchronized void event() { if (!isUnlimited()) { time[count] = TimeBase.nowMs(); count = (count + 1) % events; } } /** Return true if an event could occur now without exceeding the limit */ public synchronized boolean isEventOk() { if (isUnlimited()) { return true; } return time[count] == 0 || TimeBase.msSince(time[count]) >= interval; } /** Return the amount of time until the next event is allowed */ public synchronized long timeUntilEventOk() { if (isUnlimited()) { return 0; } long res = TimeBase.msUntil(time[count] + interval); return (res > 0) ? res : 0; } /** Wait until the next event is allowed */ public synchronized boolean waitUntilEventOk() throws InterruptedException { long time = timeUntilEventOk(); if (time <= 0) { return true; } Deadline.in(time).sleep(); return true; } private EDU.oswego.cs.dl.util.concurrent.FIFOSemaphore waitQueue = new EDU.oswego.cs.dl.util.concurrent.FIFOSemaphore(1); /** Wait until event is allowed, signal an event and return. This * version guarantees that threads will wake up in the order they entered * (<i>ie<i>, no thread will wait inordinately long). Calls to this * should <b>not</b> synchronize on the RateLimiter. */ public boolean fifoWaitAndSignalEvent() throws InterruptedException { waitQueue.acquire(); synchronized (this) { boolean res = waitUntilEventOk(); event(); waitQueue.release(); return res; } } public String rateString() { if (isUnlimited()) { return "unlimited"; } return events + "/" + StringUtil.timeIntervalToString(interval); } public String toString() { return "[RL: " + getRate() + "]"; } /** A RateLimiter whose rate cannot be reset */ static class Constant extends RateLimiter { public Constant(int events, long interval) { super(events, interval); } public Constant(String rate) { super(rate); } public void setRate(String newRate) { ill(); } public void setRate(String newRate, String dfault) { ill(); } public void setRate(int newEvents, long newInterval) { ill(); } private void ill() { throw new UnsupportedOperationException("Can't change constant RateLimiter"); } } private static Pool pool = new Pool(); /** Return the {@link RateLimiter.Pool} of shared, named RateLimiters */ public static Pool getPool() { return pool; } /** A pool of named RateLimiters, to facilitate sharing between, * <i>eg</i>, AUs */ public static class Pool { private Map limiterMap; Pool() { limiterMap = new HashMap(); } public synchronized RateLimiter findNamedRateLimiter(Object key, String rate) { return findNamedRateLimiter(key, rate, null); } public synchronized RateLimiter findNamedRateLimiter(Object key, String rate, String dfault) { RateLimiter limiter = (RateLimiter)limiterMap.get(key); if (limiter == null) { limiter = RateLimiter.makeRateLimiter(rate, dfault); limiterMap.put(key, limiter); } else if (!limiter.isRate(rate)) { limiter.setRate(rate, dfault); } return limiter; } public synchronized RateLimiter findNamedRateLimiter(Object key, int events, long interval) { RateLimiter limiter = (RateLimiter)limiterMap.get(key); if (limiter == null) { limiter = new RateLimiter(events, interval); limiterMap.put(key, limiter); } else if (!limiter.isRate(events, interval)) { limiter.setRate(events, interval); } return limiter; } } }
package org.mockito; /** * Allows creating customized argument matchers. * This API was changed in Mockito 2.* in an effort to decouple Mockito from Hamcrest * and reduce the risk of version incompatibility. * <p> * For non-trivial method arguments used in stubbing or verification, you have following options * (in no particular order): * <ul> * <li>refactor the code so that the interactions with collaborators are easier to test with mocks. * Perhaps it is possible to pass a different argument to the method so that mocking is easier? * If stuff is hard to test it usually indicates the design could be better, so do refactor for testability! * </li> * <li>don't match the argument strictly, just use one of the lenient argument matchers like * {@link Mockito#notNull()}. Some times it is better to have a simple test that works than * a complicated test that seem to work. * </li> * <li>implement equals() method in the objects that are used as arguments to mocks. * Mockito naturally uses equals() for argument matching. * Many times, this is option is clean and simple. * </li> * <li>use {@link ArgumentCaptor} to capture the arguments and perform assertions on their state. * Useful when you need to verify the arguments. Captor is not useful if you need argument matching for stubbing. * Many times, this option leads to clean and readable tests with fine-grained validation of arguments. * </li> * <li>use customized argument matchers by implementing {@link ArgumentMatcher} interface * and passing the implementation to the {@link Mockito#argThat} method. * This option is useful if custom matcher is needed for stubbing and can be reused a lot * </li> * <li>use an instance of hamcrest matcher and pass it to * {@link org.mockito.hamcrest.MockitoHamcrest#argThat(org.hamcrest.Matcher)} * Useful if you already have a hamcrest matcher. Reuse and win! * </li> * </ul> * * <p> * Implementations of this interface can be used with {@link Matchers#argThat} method. * Use <code>toString()</code> method for description of the matcher * - it is printed in verification errors. * * <pre class="code"><code class="java"> * class ListOfTwoElements implements ArgumentMatcher&lt;List&gt; { * public boolean matches(Object list) { * return ((List) list).size() == 2; * } * public String toString() { * //printed in verification errors * return "[list of 2 elements]"; * } * } * * List mock = mock(List.class); * * when(mock.addAll(argThat(new ListOfTwoElements))).thenReturn(true); * * mock.addAll(Arrays.asList(&quot;one&quot;, &quot;two&quot;)); * * verify(mock).addAll(argThat(new ListOfTwoElements())); * </code></pre> * * To keep it readable you can extract method, e.g: * * <pre class="code"><code class="java"> * verify(mock).addAll(<b>argThat(new ListOfTwoElements())</b>); * //becomes * verify(mock).addAll(<b>listOfTwoElements()</b>); * </code></pre> * * <p> * Read more about other matchers in javadoc for {@link Matchers} class * * @param <T> type of argument * @since 2.0 */ public interface ArgumentMatcher<T> { /** * Informs if this matcher accepts the given argument. * <p> * The method should <b>never</b> assert if the argument doesn't match. It * should only return false. * <p> * The argument is not using the generic type in order to force explicit casting in the implementation. * This way it is easier to debug when incompatible arguments are passed to the matchers. * You have to trust us on this one. If we used parametrized type then <code>ClassCastException</code> * would be thrown in certain scenarios. * For example: * * <pre class="code"><code class="java"> * //test, method accepts Collection argument and ArgumentMatcher&lt;List&gt; is used * when(mock.useCollection(someListMatcher())).thenDoNothing(); * * //production code, yields confusing ClassCastException * //although Set extends Collection but is not compatible with ArgumentMatcher&lt;List&gt; * mock.useCollection(new HashSet()); * </pre> * * <p> * See the example in the top level javadoc for {@link ArgumentMatcher} * * @param argument * the argument * @return true if this matcher accepts the given argument. */ public boolean matches(Object argument); }
package ornagai.mobile; import com.sun.lwuit.List; import com.sun.lwuit.events.DataChangedListener; import com.sun.lwuit.events.SelectionListener; import com.sun.lwuit.list.ListModel; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.util.Hashtable; import java.util.Stack; import java.util.Vector; import net.sf.jazzlib.ZipEntry; import net.sf.jazzlib.ZipInputStream; import ornagai.mobile.DictionaryRenderer.DictionaryListEntry; /** * * @author Seth N. Hetu */ public class MMDictionary implements ProcessAction, ListModel { //No enums. :( private static final int FMT_TEXT = 0; private static final int FMT_BINARY = 1; //Data - Static private AbstractFile dictFile; //Data - Runtime private boolean doneWithSearchFiles = false; private byte[] wordListData; private int[] wordsInLump; private WeakReference[] lumpDataCache; private int[] currLumpDefinitionSizes; private byte[] lookupTableStaticData; private byte[] lookupTableVariableData; private byte[] currLumpData; private int fileFormat = -1; //Binary data private int numWords; private int numLetters; private int longestWord; private int numLumps; private char[] letterValues; //Curr lump binary data private char[] currLumpLetters; private int currLumpBitsPerLetter; public MMDictionary(AbstractFile dictionaryFile) { this.dictFile = dictionaryFile; } //Load all the things we need to look up a word public void loadLookupTree() { System.gc(); System.out.println("Memory in use before loading: " + (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/1024 + " kb used"); //This is the only function that doesn't need to check for // FMT_TEXT; we know that nothing's been loaded. dictFile.openProcessClose("word_list-zg2009.bin", this); System.gc(); System.out.println("Memory in use after loading word list: " + (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/1024 + " kb used"); //And now, load the lookup tree dictFile.openProcessClose("lookup.bin", this); dictFile.openProcessClose("lookup_vary.bin", this); System.gc(); System.out.println("Memory in use after loading lookup tree: " + (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/1024 + " kb used"); //Now, the model try { initModel(); } catch (IOException ex) { throw new RuntimeException("Error initializing model: " + ex.toString()); } doneWithSearchFiles = true; } //This function reads through our dictionary file and loads // whatever information we are looking for. This is done in a // somewhat implied fashion. public void processFile(InputStream file) { //If we don't have a list of sub-files in the zip, // load that list. At the same time, load the dictionary tree. // Also, optionally, load all data (text format) if (!doneWithSearchFiles) { //What are we loading? if (wordListData==null) { //Binary format fileFormat = FMT_BINARY; //Now, read the contents of the file // NOTE: We need to un-lzma it. try { if (fileFormat==FMT_TEXT) { readTextWordlist(file); } else if (fileFormat==FMT_BINARY) { readBinaryWordlist(file); } } catch (IOException ex) { //Handle... throw new RuntimeException(ex.toString()); } catch (OutOfMemoryError er) { System.out.println((Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/1024 + " kb used"); throw new RuntimeException("Out of memory!"); } } else if (lookupTableStaticData==null) { try { readBinaryLookupTable(file); } catch (IOException ex) { //Handle... throw new RuntimeException(ex.toString()); } catch (OutOfMemoryError er) { System.out.println((Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/1024 + " kb used, " + (Runtime.getRuntime().freeMemory()/1024) + " kb free"); throw new RuntimeException("Out of memory!"); } } else if (lookupTableVariableData==null) { //Read and append try { //System.out.println("New Sub-File"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; for (;;) { int count = file.read(buffer); if (count==-1) break; baos.write(buffer, 0, count); } baos.close(); lookupTableVariableData = baos.toByteArray(); } catch (IOException ex) { //Handle... throw new RuntimeException(ex.toString()); } catch (OutOfMemoryError er) { System.out.println((Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/1024 + " kb used, " + (Runtime.getRuntime().freeMemory()/1024) + " kb free"); throw new RuntimeException("Out of memory!"); } } } } private void readTextWordlist(InputStream zIn) throws IOException { } private void readBinaryLookupTable(InputStream zIn) throws IOException { //Read header byte[] buffer = new byte[1024]; if (zIn.read(buffer, 0, 15)!=15) throw new IOException("Bad binary header length; 15 expected."); int numNodes = getInt(buffer, 0, 3); int numMaxChildren = getInt(buffer, 3, 3); int numMaxMatches = getInt(buffer, 6, 3); int numMaxWordBitID = getInt(buffer, 9, 3); int numMaxNodeBitID = getInt(buffer, 12, 3); //Save bitsPerNodeID = Integer.toBinaryString(numNodes-1).length(); bitsPerNodeBitID = Integer.toBinaryString(numMaxNodeBitID-1).length(); bitsPerNumMaxChildren = Integer.toBinaryString(numMaxChildren-1).length(); bitsPerNumMaxMatches = Integer.toBinaryString(numMaxMatches-1).length(); bitsPerNodeStaticData = bitsPerWordID + bitsPerNodeBitID + bitsPerNumMaxChildren + 2*bitsPerNumMaxMatches; bitsperWordBitID = Integer.toBinaryString(numMaxWordBitID-1).length(); System.out.println("Bits per lookup letter: " + bitsPerTreeLetter); System.out.println("Bits per node ID: " + bitsPerNodeID); System.out.println("Bits per word bit ID: " + bitsperWordBitID); System.out.println("Bits per node static data: " + bitsPerNodeStaticData); //Now, read all words into a byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); int totalCount = 0; for (;;) { int count = zIn.read(buffer); totalCount += count; //System.out.println(" " + (totalCount)/1024 + " kb read"); if (count==-1) break; baos.write(buffer, 0, count); } baos.close(); lookupTableStaticData = baos.toByteArray(); } private void readBinaryWordlist(InputStream zIn) throws IOException { //Read header byte[] buffer = new byte[1024]; if (zIn.read(buffer, 0, 9)!=9) throw new IOException("Bad binary header length; 9 expected."); numWords = getInt(buffer, 0, 3); numLetters = getInt(buffer, 3, 2); longestWord = getInt(buffer, 5, 2); numLumps = getInt(buffer, 7, 2); //Save some data bitsPerLetter = Integer.toBinaryString(numLetters-1).length(); bitsPerWordSize = Integer.toBinaryString(longestWord-1).length(); bitsPerWordID = Integer.toBinaryString(numWords-1).length(); //Temp: write data System.out.println("num words: " + numWords); System.out.println("num letters: " + numLetters); System.out.println("longest word: " + longestWord); System.out.println("num lumps: " + numLumps); //Read data for each lump wordsInLump = new int[numLumps]; lumpDataCache = new WeakReference[numLumps]; int currLump = 0; while (currLump<numLumps) { int remLumps = Math.min(numLumps-currLump, buffer.length/3); if (zIn.read(buffer, 0, remLumps*3)!=remLumps*3) throw new IOException("Error reading header lump data"); for (int i=0; i<remLumps; i++) { wordsInLump[currLump++] = getInt(buffer, i*3, 3); } } //Read value for each letter letterValues = new char[numLetters]; int currLetter = 0; while (currLetter<numLetters) { int remLetters = Math.min(numLetters-currLetter, buffer.length/2); if (zIn.read(buffer, 0, remLetters*2)!=remLetters*2) throw new IOException("Error reading header letter data"); for (int i=0; i<remLetters; i++) { letterValues[currLetter++] = (char)getInt(buffer, i*2, 2); } } //Now, read all words into a byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (;;) { int count = zIn.read(buffer); if (count==-1) break; baos.write(buffer, 0, count); } baos.close(); wordListData = baos.toByteArray(); } private int getInt(byte[] buffer, int offset, int len) { //Something we can handle? switch(len) { case 1: return ((int)buffer[offset])&0xFF; case 2: return ((((int)buffer[offset])&0xFF)<<8) | ((((int)buffer[offset+1])&0xFF)); case 3: return ((((int)buffer[offset])&0xFF)<<16) | ((((int)buffer[offset+1])&0xFF)<<8) | ((((int)buffer[offset+2])&0xFF)); default: throw new IllegalArgumentException("Bad getInt() amount: " + len); } } //Some ListModel implementation details private Vector searchResults = new Vector(); private int searchResultsStartID = 0; //Where to insert it private int searchResultsMatchNodeID = 0; //Match found? //More data: bookkeeping private int totalPrimaryWords; private int selectedIndex; //Used in a predictable way private EventDispatcher selectionListener = new EventDispatcher(); //Sizes - static private int bitsPerNodeID; private int bitsPerNodeBitID; private int bitsPerNumMaxChildren; private int bitsPerNumMaxMatches; private int bitsPerNodeStaticData; private int bitsPerTreeLetter = Integer.toBinaryString('z'-'a').length(); //Sizes - variable private int bitsperWordBitID; //Sizes - dictionary private int bitsPerLetter; private int bitsPerWordSize; private int bitsPerWordID; //Cache private static final int MAX_CACHED_WORDS = 20; private int[] cachedIDs = new int[MAX_CACHED_WORDS]; private DictionaryRenderer.DictionaryListEntry[] cachedVals = new DictionaryRenderer.DictionaryListEntry[MAX_CACHED_WORDS]; private int evictID = 0; //Readers private BitInputStream wordListStr; private BitInputStream lookupTableStaticStr; private BitInputStream lookupTableVariableStr; private BitInputStream currLumpStr; private int currLumpID = -1; private void freeModel() { try { if (wordListStr!=null) wordListStr.close(); if (lookupTableStaticStr!=null) lookupTableStaticStr.close(); if (lookupTableVariableStr!=null) lookupTableVariableStr.close(); } catch (IOException ex) {} //Should never happen //Free space wordListStr = null; lookupTableStaticStr = null; lookupTableVariableStr = null; currLumpStr = null; currLumpID = -1; for (int i=0; i<cachedVals.length; i++) cachedVals[i] = null; //Don't forget to tree the byte[] arrays... but not here. } //Set the temporary list, item ID, and modified size // Returns false if there's nothing to search for public void performSearch(String word) throws IOException { //First: clear our cache //for (int i=0; i<cachedIDs.length; i++) // cachedIDs[i] = -1; //evictID = 0; //Not found entry: DictionaryListEntry notFoundEntry = new DictionaryListEntry("Not found: " + word, -1, true); //Goal: Search down the tree on each letter; put together primary and seccondary matches int resID = 0; try { searchResultsMatchNodeID = 0; searchResultsStartID = 0; searchResults.removeAllElements(); SEARCH_LOOP: for (int letterID=0; letterID<word.length(); letterID++) { //Check all children char letter = Character.toLowerCase(word.charAt(letterID)); int numChildren = readNodeNumChildren(searchResultsMatchNodeID); int prevNodeID = searchResultsMatchNodeID; //Loop through each child for (int currChild=0; currChild<numChildren; currChild++) { //Check the next child char childLetter = readNodeChildKey(searchResultsMatchNodeID, currChild); int childID = readNodeChildValue(searchResultsMatchNodeID, currChild); //Have we found our word? if (letter == childLetter) { searchResultsMatchNodeID = childID; break; } else { //Count int currCount = readNodeTotalReachableChildren(childID); searchResultsStartID += currCount; } } //Are we at the end of the word? Alternatively, did we fail a match? if (letterID==word.length()-1 || searchResultsMatchNodeID==prevNodeID) { if (searchResultsMatchNodeID != prevNodeID) { //Result containers int numPrimary = readNodeNumPrimaryMatches(searchResultsMatchNodeID); DictionaryListEntry[] primaryResults = new DictionaryListEntry[numPrimary]; int numSecondary = readNodeNumSecondaryMatches(searchResultsMatchNodeID); DictionaryListEntry[] secondaryResults = new DictionaryListEntry[numSecondary]; //Get a nifty cache of results System.out.print("primary results: "); for (int i=0; i<numPrimary; i++) { primaryResults[i] = new DictionaryListEntry(readWordString(searchResultsMatchNodeID, i), -2, true); //System.out.print(primaryResults[i].word + (i<numPrimary-1 ? " , " : "")); } System.out.println(); System.out.print("secondary results: "); for (int i=0; i<numSecondary; i++) { secondaryResults[i] = new DictionaryListEntry(readWordSecondaryString(searchResultsMatchNodeID, i), -2, true); //System.out.print(secondaryResults[i].word + (i<numSecondary-1 ? " , " : "")); } System.out.println(); //Now, combine our results into one vector. // If we pass the point where our word should have matched, insert a "not found" message. int nextPrimID = 0; int nextSecID = 0; boolean passedSeekWord = false; while (nextPrimID<numPrimary || nextSecID<numSecondary || !passedSeekWord) { //Get our lineup of potential matches DictionaryListEntry nextPrimaryCandidate = nextPrimID<numPrimary ? primaryResults[nextPrimID] : null; DictionaryListEntry nextSecondaryCandidate = nextSecID<numSecondary ? secondaryResults[nextSecID] : null; //Special case: only the seek word left (implies it didn't match) if (nextPrimaryCandidate==null && nextSecondaryCandidate==null) { resID = searchResults.size(); searchResults.addElement(notFoundEntry); passedSeekWord = true; continue; } //Easy cases: one word is null: DictionaryListEntry nextWord = null; int nextID = 0; //1,2 for prim/sec. 0 for nil if (nextPrimaryCandidate==null) { nextWord = nextSecondaryCandidate; nextID = 2; } else if (nextSecondaryCandidate==null) { nextWord = nextPrimaryCandidate; nextID = 1; } //Slightly harder case: neither word is null: if (nextWord==null) { if (nextPrimaryCandidate.compareTo(nextSecondaryCandidate)<=0) { nextWord = nextPrimaryCandidate; nextID = 1; } else { nextWord = nextSecondaryCandidate; nextID = 2; } } //Is the next match at or past our search word? if (!passedSeekWord) { int search = nextWord.compareTo(word); if (search==0) { passedSeekWord = true; resID = searchResults.size(); } else if (search>0) { nextWord.word = "Not found: " + word; nextWord.id = -1; passedSeekWord = true; nextID = 0; resID = searchResults.size(); } } //Add it searchResults.addElement(nextWord); //Increment if (nextID==1) nextPrimID++; else if (nextID==2) nextSecID++; } //Double-check: /*System.out.print("sorted results: "); for (int i=0; i<searchResults.size(); i++) { System.out.print(searchResults.elementAt(i) + (i<searchResults.size()-1 ? " , " : "")); } System.out.println();*/ } else { //Didn't find any matches, primary or secondary searchResults.addElement(notFoundEntry); searchResultsMatchNodeID = 0; } } } } catch (IOException ex) { //Attempt to recover searchResultsMatchNodeID = 0; searchResultsStartID = 0; searchResults.removeAllElements(); setSelectedIndex(0); } //Now, just set the index this.setSelectedIndex(searchResultsStartID + resID); } public int findWordIDFromEntry(DictionaryListEntry entry) { //We'll need to refactor our search code to return a result set, and then // re-use that in here and in performSearch(). For now, return "not found". return -1; } public String[] getWordTuple(DictionaryListEntry entry) { //Any chance? if (entry.id<0) return null; //Prepare result set String[] result = new String[3]; result[0] = entry.word; //Figure out which lump contains this definition int lumpID = 0; int startLumpOffset = 0; int lumpAdjID = 0; for (;lumpID<wordsInLump.length; lumpID++) { lumpAdjID = entry.id - startLumpOffset; startLumpOffset += wordsInLump[lumpID]; if (startLumpOffset>entry.id) break; if (lumpID==wordsInLump.length-1) return null; } //Is this the ID of the lump that we've cached? If not, read this lump. if (lumpID != currLumpID) { //Set currLumpID = lumpID; //Flush previous data currLumpLetters = null; currLumpDefinitionSizes = null; currLumpData = null; currLumpStr = null; //Try to load from our cache if (lumpDataCache[currLumpID]!=null) currLumpData = (byte[])lumpDataCache[currLumpID].get(); //Reference no longer intact? if (currLumpData==null) { //Save, read, append dictFile.openProcessClose("lump_" + (lumpID+1) + ".bin", new ProcessAction() { public void processFile(InputStream file) { try { //Read static data byte[] buffer = new byte[5]; if (file.read(buffer) != buffer.length) throw new RuntimeException("Error reading lump file: too short?."); currLumpLetters = new char[getInt(buffer, 3, 2)]; currLumpBitsPerLetter = Integer.toBinaryString(currLumpLetters.length-1).length(); //Read "size" values currLumpDefinitionSizes = new int[wordsInLump[currLumpID]]; buffer = new byte[currLumpDefinitionSizes.length*2]; if (file.read(buffer) != buffer.length) throw new RuntimeException("Error reading lump file: too short?."); for (int i=0; i<currLumpDefinitionSizes.length; i++) currLumpDefinitionSizes[i] = getInt(buffer, i*2, 2); //Read "letter" lookup buffer = new byte[currLumpLetters.length*2]; if (file.read(buffer) != buffer.length) throw new RuntimeException("Error reading lump file: too short?."); for (int i=0; i<currLumpLetters.length; i++) currLumpLetters[i] = (char)getInt(buffer, i*2, 2); //Read remaining bitstream ByteArrayOutputStream baos = new ByteArrayOutputStream(); buffer = new byte[1024]; for (;;) { int count = file.read(buffer); if (count==-1) break; baos.write(buffer, 0, count); } baos.close(); currLumpData = baos.toByteArray(); currLumpStr = new BitInputStream(new ByteArrayInputStream(currLumpData)); //Cache lumpDataCache[currLumpID] = new WeakReference(currLumpData); } catch (IOException ex) { //Handle... throw new RuntimeException(ex.toString()); } catch (OutOfMemoryError er) { System.out.println((Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/1024 + " kb used, " + (Runtime.getRuntime().freeMemory()/1024) + " kb free"); throw new RuntimeException("Out of memory!"); } } }); } } //Get the word's bit ID within the lump file. Also get its number of letters int lumpBitID = readWordLumpBitID(lumpAdjID); System.out.println("Reading: " + lumpAdjID); int numLettersInWord = currLumpDefinitionSizes[lumpAdjID]; //Now, read each letter and append it. Look for a tab to break between the POS and the definitoin. StringBuffer sb = new StringBuffer(); boolean foundTab = false; for (int i=0; i<numLettersInWord; i++) { //First time, jump. After that, just advance. int letterID = 0; try { if (i==0) letterID = currLumpStr.readNumberAt(lumpBitID, currLumpBitsPerLetter); else letterID = currLumpStr.readNumber(currLumpBitsPerLetter); } catch (IOException ex) { return null; } //Append char letter = currLumpLetters[letterID]; if (letter!='\t') sb.append(letter); if (letter=='\t' || i==numLettersInWord-1) { if (!foundTab) result[1] = sb.toString(); else result[2] = sb.toString(); sb = new StringBuffer(); if (letter=='\t') foundTab = true; } } //Debug /*System.out.println("Result: "); System.out.println(result[0]); System.out.print(" "); for (int i=0; i<result[0].length(); i++) System.out.print("0x"+Integer.toHexString(result[0].charAt(i)) + " "); System.out.println(); System.out.println(result[1]); System.out.print(" "); for (int i=0; i<result[1].length(); i++) System.out.print("0x"+Integer.toHexString(result[1].charAt(i)) + " "); System.out.println(); System.out.println(result[2]); System.out.print(" "); for (int i=0; i<result[2].length(); i++) System.out.print("0x"+Integer.toHexString(result[2].charAt(i)) + " "); System.out.println();*/ //Valid? if (foundTab) return result; else return null; } private void initModel() throws IOException { //Init our streams wordListStr = new BitInputStream(new ByteArrayInputStream(wordListData)); lookupTableStaticStr = new BitInputStream(new ByteArrayInputStream(lookupTableStaticData)); lookupTableVariableStr = new BitInputStream(new ByteArrayInputStream(lookupTableVariableData)); //Init our cache for (int i=0; i<cachedIDs.length; i++) cachedIDs[i] = -1; //Init our data this.totalPrimaryWords = numWords; } private int readNodeBitID(int nodeID) { //Node IDs are at offset 1, after totalReachable try { return lookupTableStaticStr.readNumberAt(bitsPerNodeStaticData*nodeID + bitsPerWordID, bitsPerNodeBitID); } catch (IOException ex) { return -1; } } private int readNodeTotalReachableChildren(int nodeID) throws IOException { //Word counts are at offset 0 return lookupTableStaticStr.readNumberAt(bitsPerNodeStaticData*nodeID, bitsPerWordID); } private int readNodeNumChildren(int nodeID) throws IOException { //Num children are offset 2, after totalReachable and start-bit return lookupTableStaticStr.readNumberAt(bitsPerNodeStaticData*nodeID + bitsPerWordID + bitsPerNodeBitID, bitsPerNumMaxChildren); } private int readNodeNumPrimaryMatches(int nodeID) throws IOException { //Num primary matches are offset 3, after totalReachable, start-bit, and children return lookupTableStaticStr.readNumberAt(bitsPerNodeStaticData*nodeID + bitsPerWordID + bitsPerNodeBitID + bitsPerNumMaxChildren, bitsPerNumMaxMatches); } private int readNodeNumSecondaryMatches(int nodeID) throws IOException { //Num primary matches are offset 3, after totalReachable, start-bit, children, and primary id return lookupTableStaticStr.readNumberAt(bitsPerNodeStaticData*nodeID + bitsPerWordID + bitsPerNodeBitID + bitsPerNumMaxChildren + bitsPerNumMaxMatches, bitsPerNumMaxMatches); } private char readNodeChildKey(int nodeID, int childID) throws IOException { //Get variable index int nodeBitID = readNodeBitID(nodeID); //Skip letter+node for childID entries nodeBitID += (bitsPerTreeLetter+bitsPerNodeID)*childID; //Read the node value, not the key return (char)(lookupTableVariableStr.readNumberAt(nodeBitID, bitsPerTreeLetter)+'a'); } private int readNodeChildValue(int nodeID, int childID) throws IOException { //Get variable index int nodeBitID = readNodeBitID(nodeID); //Skip letter+node for childID entries nodeBitID += (bitsPerTreeLetter+bitsPerNodeID)*childID; //Read the node value, not the key return lookupTableVariableStr.readNumberAt(nodeBitID+bitsPerTreeLetter, bitsPerNodeID); } private int readNodePrimaryMatch(int nodeID, int primaryID) throws IOException { //Get variable index int nodeBitID = readNodeBitID(nodeID); //Skip letter+node for all child entries int numChildren = readNodeNumChildren(nodeID); nodeBitID += (bitsPerTreeLetter+bitsPerNodeID)*numChildren; //Skip word_bits for each primary before this nodeBitID += bitsperWordBitID * primaryID; //Read the value, return it int res = lookupTableVariableStr.readNumberAt(nodeBitID, bitsperWordBitID); //System.out.println("Reading: " + nodeBitID + " " + bitsperWordBitID + " " + res); return res; } private int readNodeSecondaryMatch(int nodeID, int secondaryID) throws IOException { //Get variable index int nodeBitID = readNodeBitID(nodeID); //Skip letter+node for all child entries int numChildren = readNodeNumChildren(nodeID); nodeBitID += (bitsPerTreeLetter+bitsPerNodeID)*numChildren; //Skip all primary matches int numPrimary = readNodeNumPrimaryMatches(nodeID); nodeBitID += bitsperWordBitID * numPrimary; //Skip word_bits for each secondary before this nodeBitID += bitsperWordBitID * secondaryID; //Read the value, return it int res = lookupTableVariableStr.readNumberAt(nodeBitID, bitsperWordBitID); //System.out.println("Reading: " + nodeBitID + " " + bitsperWordBitID + " " + res); return res; } private String readWordString(int nodeID, int wordPrimaryID) throws IOException { int wordBitID = readNodePrimaryMatch(nodeID, wordPrimaryID); return readWordStringFromBitID(wordBitID); } private String readWordStringFromBitID(int wordBitID) throws IOException { //Read all letters, translate StringBuffer sb = new StringBuffer(); //Number of letters to read int numLetters = wordListStr.readNumberAt(wordBitID, bitsPerWordSize); //Each letter for (;numLetters>0;numLetters int letterID = wordListStr.readNumber(bitsPerLetter); if (letterID>=letterValues.length) return "<error reading string>"; char c = letterValues[letterID]; sb.append(c); } return sb.toString(); } private int readWordLumpBitID(int adjWordID) { //Add up int sum = 0; for (int i=0; i<adjWordID; i++) sum += currLumpDefinitionSizes[i]; //Multiply return sum * currLumpBitsPerLetter; } private String readWordSecondaryString(int nodeID, int wordSecondaryID) throws IOException { int wordBitID = readNodeSecondaryMatch(nodeID, wordSecondaryID); return readWordStringFromBitID(wordBitID); } //Actual list model implementation public int getSize() { return totalPrimaryWords + searchResults.size(); } public Object getItemAt(int listID) { //Valid? if (listID<0 || listID>=getSize()) return null; //Check our search results before checking our cache int adjID = listID - searchResultsStartID; //DictionaryRenderer.DictionaryListEntry res = new DictionaryRenderer.DictionaryListEntry(); if (adjID>=0 && adjID<searchResults.size()) { DictionaryListEntry res = (DictionaryListEntry)searchResults.elementAt(adjID); return res; } else { //Adjust our search results based on the result list if (listID < searchResultsStartID) adjID = listID; else adjID = listID - searchResults.size(); } //Check our cache before getting this item directly. for (int i=0; i<cachedIDs.length; i++) { if (cachedIDs[i] == adjID) { DictionaryListEntry res = cachedVals[i]; //System.out.println("Get item: " + listID + " (cached) : " + res); return res; } } try { //Due to the way words are stored, the fastest way to // find a word's starting ID is to browse from the top of the // node down int nodeID = 0; int primaryWordID = -1; int nodeStartID = 0; //Necessary to start at index zero. for (;primaryWordID==-1;) { //Check all children int numChildren = readNodeNumChildren(nodeID); int totalCount = 0; //Loop through each child for (int currChild=0; currChild<numChildren; currChild++) { //Advance to the next child int childID = readNodeChildValue(nodeID, currChild); int currCount = readNodeTotalReachableChildren(childID); totalCount += currCount; //System.out.println(" Next child has: " + currCount + " total: " + totalCount + " start ID: " + nodeStartID); //Stop here if we know the child is along the right path. if (nodeStartID+totalCount > adjID) { //Set up to advance nodeID = childID; nodeStartID = nodeStartID + totalCount - currCount; //Does this child _actually_ contain the wordID (directly)? int numPrimary = readNodeNumPrimaryMatches(nodeID); //System.out.println(" TAKE: " + numPrimary + " primary"); if (nodeStartID+numPrimary > adjID) primaryWordID = adjID-nodeStartID; else nodeStartID += numPrimary; //Advance break; } else if (currChild==numChildren-1) throw new RuntimeException("No matches from node: " + nodeID + " on list: " + adjID + " total count: " + totalCount); } } //Set up results DictionaryListEntry res = new DictionaryListEntry(readWordString(nodeID, primaryWordID), adjID, false); //Add to our stack cachedIDs[evictID] = adjID; cachedVals[evictID] = res; evictID++; if (evictID >= cachedIDs.length) evictID = 0; return res; } catch (IOException ex) { //System.out.println("Get item: " + listID + " : " + null); return null; } } public int getSelectedIndex() { return selectedIndex; } public void setSelectedIndex(int val) { int oldIndex = selectedIndex; selectedIndex = val; selectionListener.fireSelectionEvent(oldIndex, selectedIndex); } public void addDataChangedListener(DataChangedListener listen) { //Data is changed not through listeners, but by calling explicit functions. // Our list will not auto-refresh, but that's fine for our project. //dataListeners.addElement(listen); } public void removeDataChangedListener(DataChangedListener listen) { //See above //dataListeners.removeElement(listen); } public void addSelectionListener(SelectionListener listen) { selectionListener.addListener(listen); } public void removeSelectionListener(SelectionListener listen) { selectionListener.removeListener(listen); } //Not supported public void addItem(Object arg0) { throw new UnsupportedOperationException("MMDictionary does not support \"addItem()\""); } public void removeItem(int arg0) { throw new UnsupportedOperationException("MMDictionary does not support \"removeItem()\""); } }
package polyglot.ext.jl; /** * Version information for the base compiler. */ public class Version extends polyglot.main.Version { public String name() { return "jl"; } public int major() { return 1; } public int minor() { return 1; } public int patch_level() { return 0; } }
package babel; import io.ExternalTool; import io.Logger; import io.SDFUtil; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import util.ArrayUtil; import util.FileUtil; import util.StringUtil; public class OBWrapper { public static interface Aborter { public boolean abort(); } ExternalTool ext; String babelPath; private Logger logger; private String oBabelPath; public OBWrapper(String babelPath, String oBabelPath, Logger logger) { this.babelPath = babelPath; this.oBabelPath = oBabelPath; this.logger = logger; ext = new ExternalTool(logger); } private HashMap<String, String> version = new HashMap<String, String>(); public String getVersion() { if (!version.containsKey(babelPath)) { try { String v = ext.get("babel", new String[] { babelPath, "-V" }); Pattern pattern = Pattern.compile("^.*([0-9]+\\.[0-9]+\\.[0-9]+).*$"); for (String s : v.split("\n")) { Matcher matcher = pattern.matcher(s); if (matcher.matches()) { version.put(babelPath, matcher.group(1)); break; } } } catch (Exception e) { throw new Error(e); } } return version.get(babelPath); } public String[] computeInchiFromSmiles(String[] smiles) { String inchi[] = new String[smiles.length]; for (int i = 0; i < inchi.length; i++) inchi[i] = ext.get("obinchi", new String[] { oBabelPath, "-:" + smiles[i] + "", "-oinchi" }); return inchi; } public void computeInchiFromSDF(String sdfFile, String outputInchiFile) { System.out.println("computing openbabel inchi, source: " + sdfFile + ", dest: " + outputInchiFile); ext.run("obgen3d", new String[] { babelPath, "-d", "-isdf", sdfFile, "-oinchi", outputInchiFile }); } private boolean[] compute3D(String cacheDir, String type, String content[], boolean isMixture[], String outputSDFile, String title[], Aborter aborter) { if (new File(outputSDFile).exists()) if (!new File(outputSDFile).delete()) throw new Error("could not delete already existing file"); String extendedCacheDir = cacheDir + File.separator + getVersion() + File.separator + type; int cached = 0; int count = 0; boolean valid[] = new boolean[content.length]; for (String mol : content) { String digest = StringUtil.getMD5(mol); String file = extendedCacheDir + File.separator + digest; valid[count] = isMixture == null || !isMixture[count]; if (!valid[count] && new File(file).exists()) new File(file).delete(); if (!new File(file).exists()) { try { FileUtil.createParentFolders(file); File tmp = File.createTempFile(type + "file", type); File out = File.createTempFile("sdffile", "sdf"); BufferedWriter b = new BufferedWriter(new FileWriter(tmp)); b.write(mol + "\n"); b.close(); String gen3d = "--gen3d"; if (isMixture != null && isMixture[count]) { logger.warn("babel does not work for mixtures, using gen2d: " + mol); gen3d = "--gen2d"; } ext.run("obgen3d", new String[] { babelPath, gen3d, "-d", "-i" + type, tmp.getAbsolutePath(), "-osdf", out.getAbsolutePath() }, null, true, null); if (!FileUtil.robustRenameTo(out.getAbsolutePath(), file)) throw new Error("cannot move obresult file"); } catch (IOException e) { throw new Error(e); } } else { cached++; System.out.println("3d result cached: " + file); } if (title == null) { boolean merge = FileUtil.concat(new File(outputSDFile), new File(file), true); if (!merge) throw new Error("could not merge to sdf file"); } else { String sdf[] = FileUtil.readStringFromFile(file).split("\n"); if (sdf[0].length() > 0) throw new Error("already a title " + sdf[0]); sdf[0] = title[count]; FileUtil.writeStringToFile(outputSDFile, ArrayUtil.toString(sdf, "\n", "", "", "") + "\n", true); } count++; if (aborter != null && aborter.abort()) return null; } System.out.println(cached + "/" + content.length + " compounds were precomputed at '" + extendedCacheDir + "', merged obgen3d result to: " + outputSDFile); return valid; } public boolean[] compute3DfromSDF(String cacheDir, String inputSDFile, boolean isMixture[], String outputSDFile, Aborter aborter) { System.out.println("computing openbabel 3d, source: " + inputSDFile + ", dest: " + outputSDFile); return compute3D(cacheDir, "sdf", SDFUtil.readSdf(inputSDFile), isMixture, outputSDFile, null, aborter); } public boolean[] compute3DfromSmiles(String cacheDir, String inputSmilesFile, String outputSDFile, Aborter aborter) { System.out.println("computing openbabel 3d, source: " + inputSmilesFile + ", dest: " + outputSDFile); List<String> content = new ArrayList<String>(); List<Boolean> isMixture = new ArrayList<Boolean>(); List<String> title = new ArrayList<String>(); for (String line : FileUtil.readStringFromFile(inputSmilesFile).split("\n")) { String words[] = line.split("\t"); if (words.length < 1 || words.length > 2) throw new Error(); content.add(words[0]); isMixture.add(content.contains(".")); if (words.length > 1) title.add(words[1]); else title.add(null); } String[] titles = ArrayUtil.toArray(String.class, title); if (ArrayUtil.removeNullValues(titles).size() == 0) titles = null; return compute3D(cacheDir, "smi", ArrayUtil.toArray(content), ArrayUtil.toPrimitiveBooleanArray(isMixture), outputSDFile, titles, aborter); } public boolean[] compute3DfromSmiles(String cacheDir, String smiles[], String outputSDFile, Aborter aborter) { System.out.println("computing openbabel 3d, source is smiles-array, dest: " + outputSDFile); boolean[] isMixture = new boolean[smiles.length]; for (int i = 0; i < isMixture.length; i++) isMixture[i] = smiles[i].contains("."); return compute3D(cacheDir, "smi", smiles, isMixture, outputSDFile, null, aborter); } public List<boolean[]> matchSmarts(List<String> smarts, int numCompounds, String sdfFile, String newFP, String newBabelDataDir) { List<boolean[]> l = new ArrayList<boolean[]>(); for (int i = 0; i < smarts.size(); i++) l.add(new boolean[numCompounds]); File tmp = null; try { tmp = File.createTempFile("sdf" + numCompounds, "OBsmarts"); String cmd[] = { babelPath, "-isdf", sdfFile, "-ofpt", "-xf", newFP, "-xs" }; logger.debug("Running babel: " + ArrayUtil.toString(cmd, " ", "", "")); ext.run("ob-fingerprints", cmd, tmp, true, new String[] { "BABEL_DATADIR=" + newBabelDataDir }); logger.debug("Parsing smarts"); BufferedReader buffy = new BufferedReader(new FileReader(tmp)); String line = null; int compoundIndex = -1; while ((line = buffy.readLine()) != null) { if (line.startsWith(">")) { compoundIndex++; line = line.replaceAll("^>[^\\s]*", "").trim(); } if (line.length() > 0) { // Settings.LOGGER.warn("frags: " + line); boolean minFreq = false; for (String s : line.split("\\t")) { if (s.trim().length() == 0) continue; if (minFreq && s.matches("^\\*[2-4].*")) s = s.substring(2); int smartsIndex = Integer.parseInt(s.split(":")[0]); l.get(smartsIndex)[compoundIndex] = true; minFreq = s.matches(".*>(\\s)*[1-3].*"); } } } } catch (Exception e) { throw new Error("Error while matching smarts with OpenBabel: " + e.getMessage(), e); } finally { tmp.delete(); } return l; } public void main(String args[]) { try { OBWrapper obwrapper = new OBWrapper("/home/martin/software/openbabel-2.3.1/install/bin/babel", "/home/martin/software/openbabel-2.3.1/install/bin/obabel", null); File tmp = File.createTempFile("smiles", "smi"); BufferedWriter b = new BufferedWriter(new FileWriter(tmp)); b.write("c1cccc1\t123\n"); b.write("c1ccnc1\t456\n"); b.close(); obwrapper.compute3DfromSmiles("/tmp/babel3d", tmp.getAbsolutePath(), "/tmp/delme.sdf", null); obwrapper.compute3DfromSDF("/tmp/babel3d", "/tmp/delme.sdf", null, "/tmp/delme.too.sdf", null); } catch (Exception e) { e.printStackTrace(); } } }
package com.axelor.web.service; import java.util.ArrayList; 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 javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import com.axelor.auth.AuthUtils; import com.axelor.common.StringUtils; import com.axelor.db.JPA; import com.axelor.db.JpaSecurity; import com.axelor.db.JpaSecurity.AccessType; import com.axelor.db.mapper.Mapper; import com.axelor.db.mapper.Property; import com.axelor.inject.Beans; import com.axelor.meta.ActionHandler; import com.axelor.meta.MetaStore; import com.axelor.meta.db.MetaJsonRecord; import com.axelor.meta.schema.actions.Action; import com.axelor.meta.schema.views.AbstractView; import com.axelor.meta.schema.views.AbstractWidget; import com.axelor.meta.schema.views.Dashboard; import com.axelor.meta.schema.views.Field; import com.axelor.meta.schema.views.FormInclude; import com.axelor.meta.schema.views.FormView; import com.axelor.meta.schema.views.GridView; import com.axelor.meta.schema.views.Notebook; import com.axelor.meta.schema.views.Panel; import com.axelor.meta.schema.views.PanelField; import com.axelor.meta.schema.views.PanelRelated; import com.axelor.meta.schema.views.PanelTabs; import com.axelor.meta.schema.views.Search; import com.axelor.meta.schema.views.SearchFilters; import com.axelor.meta.schema.views.SimpleContainer; import com.axelor.meta.service.MetaService; import com.axelor.rpc.ActionRequest; import com.axelor.rpc.Request; import com.axelor.rpc.Response; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.google.inject.servlet.RequestScoped; @RequestScoped @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/meta") public class ViewService extends AbstractService { @Inject private MetaService service; @Inject private JpaSecurity security; private Class<?> findClass(String name) { try { return Class.forName(name); } catch (Exception e) { } return null; } @GET @Path("models") @SuppressWarnings("all") public Response models() { final Response response = new Response(); final List<String> all = Lists.newArrayList(); for (Class<?> cls : JPA.models()) { if (security.isPermitted(AccessType.READ, (Class) cls)) { all.add(cls.getName()); } } Collections.sort(all); response.setData(all); response.setTotal(all.size()); response.setStatus(Response.STATUS_SUCCESS); return response; } @GET @Path("fields/{model}") @SuppressWarnings("all") public Response fields(@PathParam("model") String model, @QueryParam("jsonModel") String jsonModel) { final Response response = new Response(); final Map<String, Object> meta = Maps.newHashMap(); final Class<?> modelClass = findClass(model); if (!security.isPermitted(AccessType.READ, (Class) modelClass)) { response.setStatus(Response.STATUS_FAILURE); return response; } final Map<String, Object> jsonFields = Maps.newHashMap(); final List<String> names = Lists.newArrayList(); meta.put("model", model); meta.put("jsonFields", jsonFields); if (StringUtils.isBlank(jsonModel)) { for (Property p : Mapper.of(modelClass).getProperties()) { if (!p.isTransient()) { names.add(p.getName()); } if (p.isJson()) { jsonFields.put(p.getName(), MetaStore.findJsonFields(model, p.getName())); } } meta.putAll(MetaStore.findFields(modelClass, names)); } else if (MetaJsonRecord.class.getName().equals(model)){ names.add("attrs"); meta.putAll(MetaStore.findFields(modelClass, names)); jsonFields.put("attrs", MetaStore.findJsonFields(jsonModel)); } response.setData(meta); response.setStatus(Response.STATUS_SUCCESS); return response; } @GET @Path("views/{model}") public Response views(@PathParam("model") String model) { final MultivaluedMap<String, String> params = getUriInfo().getQueryParameters(true); final Map<String, String> views = Maps.newHashMap(); for (String mode : params.keySet()) { views.put(mode, params.getFirst(mode)); } return service.findViews(findClass(model), views); } private Set<String> findNames(final Set<String> names, final AbstractWidget widget) { List<? extends AbstractWidget> all = null; if (widget instanceof Notebook) { all = ((Notebook) widget).getPages(); } else if (widget instanceof SimpleContainer) { all = ((SimpleContainer) widget).getItems(); } else if (widget instanceof Panel) { all = ((Panel) widget).getItems(); } else if (widget instanceof PanelTabs) { all = ((PanelTabs) widget).getItems(); } else if (widget instanceof FormInclude) { names.addAll(findNames(((FormInclude) widget).getView())); } else if (widget instanceof Field) { names.add(((Field) widget).getName()); if (widget instanceof PanelField) { PanelField field = (PanelField) widget; if (field.getEditor() != null && field.getTarget() == null) { all = field.getEditor().getItems(); } } } else if (widget instanceof PanelRelated) { names.add(((PanelRelated) widget).getName()); } if (all == null) { return names; } for (AbstractWidget item : all) { findNames(names, item); } return names; } public List<String> findNames(final AbstractView view) { Set<String> names = new HashSet<>(); List<AbstractWidget> items = null; if (view instanceof FormView) { items = ((FormView) view).getItems(); } if (view instanceof GridView) { GridView grid = (GridView) view; items = grid.getItems(); if ("sequence".equals(grid.getOrderBy())) { names.add("sequence"); } } if (view instanceof SearchFilters) { items = ((SearchFilters) view).getItems(); } if (items == null || items.isEmpty()) { return new ArrayList<>(names); } for (AbstractWidget widget : items) { findNames(names, widget); } return new ArrayList<>(names); } @GET @Path("view") public Response view( @QueryParam("model") String model, @QueryParam("name") String name, @QueryParam("type") String type) { final Response response = service.findView(model, name, type); final AbstractView view = (AbstractView) response.getData(); final Map<String, Object> data = Maps.newHashMap(); data.put("view", view); if (view instanceof Search && ((Search) view).getSearchForm() != null) { String searchForm = ((Search) view).getSearchForm(); Response searchResponse = service.findView(null, searchForm, "form"); data.put("searchForm", searchResponse.getData()); } final Class<?> modelClass = findClass(model); if (view instanceof AbstractView && modelClass != null) { data.putAll(MetaStore.findFields(modelClass, findNames((AbstractView) view))); } response.setData(data); response.setStatus(Response.STATUS_SUCCESS); return response; } @POST @Path("view") public Response view(Request request) { final Map<String, Object> data = request.getData(); final String name = (String) data.get("name"); final String type = (String) data.get("type"); return view(request.getModel(), name, type); } @POST @Path("view/fields") public Response viewFields(Request request) { final Response response = new Response(); response.setData(MetaStore.findFields(request.getBeanClass(), request.getFields())); return response; } @POST @Path("view/save") public Response save(Request request) { final Map<String, Object> data = request.getData(); final ObjectMapper om = Beans.get(ObjectMapper.class); try { final String type = (String) data.get("type"); final String json = om.writeValueAsString(data); AbstractView view = null; switch(type) { case "dashboard": view = om.readValue(json, Dashboard.class); break; } if (view != null) { return service.saveView(view, AuthUtils.getUser()); } } catch (Exception e) { } return null; } @GET @Path("chart/{name}") public Response chart(@PathParam("name") String name) { final MultivaluedMap<String, String> params = getUriInfo().getQueryParameters(true); final Map<String, Object> context = Maps.newHashMap(); final Request request = new Request(); for(String key : params.keySet()) { List<String> values = params.get(key); if (values.size() == 1) { context.put(key, values.get(0)); } else { context.put(key, values); } } request.setData(context); return service.getChart(name, request); } @POST @Path("chart/{name}") public Response chart(@PathParam("name") String name, Request request) { final Map<String, Object> data = request.getData(); if (data == null || data.get("_domainAction") == null) { return service.getChart(name, request); } ViewService.updateContext((String) data.get("_domainAction"), data); return service.getChart(name, request); } @POST @Path("custom/{name}") public Response dataset(@PathParam("name") String name, Request request) { return service.getDataSet(name, request); } /** * Helper method to update context with re-evaluated domain context for the * given action. * * @param action * the action to re-evaluate * @param domainContext * the context to update * @return updated domainContext */ @SuppressWarnings("all") static Map<String, Object> updateContext(String action, Map<String, Object> domainContext) { if (action == null || domainContext == null) { return domainContext; } final Action act = MetaStore.getAction(action); final String model = (String) domainContext.get("_model"); if (act == null || model == null) { return domainContext; } final ActionRequest actRequest = new ActionRequest(); final Map<String, Object> actData = new HashMap<>(); actData.put("_model", model); actData.put("_domainAction", action); actData.put("_domainContext", domainContext); actRequest.setModel(model); actRequest.setAction(action); actRequest.setData(actData); final ActionHandler actHandler = new ActionHandler(actRequest); final Object res = act.evaluate(actHandler); if (res instanceof Map) { Map<String, Object> ctx = (Map) ((Map) res).get("context"); if (ctx != null) { domainContext.putAll(ctx); } } return domainContext; } }
package com.bagri.common.manage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.bagri.common.security.LocalSubject; import static com.bagri.common.stats.InvocationStatistics.*; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.CompositeType; import javax.management.openmbean.OpenDataException; import javax.management.openmbean.OpenType; import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularData; import javax.management.openmbean.TabularDataSupport; import javax.management.openmbean.TabularType; import javax.management.remote.JMXPrincipal; import javax.security.auth.Subject; import java.lang.management.ManagementFactory; import java.security.AccessControlContext; import java.security.AccessController; import java.security.Principal; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; public class JMXUtils { private static final Logger logger = LoggerFactory.getLogger(JMXUtils.class); public static final String key_type = "type"; public static final String key_name = "name"; public static final String domain = "com.bagri.xdm"; public static final String type_management = "Management"; public static boolean registerMBean(String name, Object mBean) { Hashtable<String, String> keys = getStandardKeys(type_management, name); return registerMBean(domain, keys, mBean); } public static boolean registerMBean(String type, String name, Object mBean) { Hashtable<String, String> keys = getStandardKeys(type, name); return registerMBean(domain, keys, mBean); } public static boolean unregisterMBean(String type, String name) { Hashtable<String, String> keys = getStandardKeys(type, name); return unregisterMBean(domain, keys); } public static Hashtable<String, String> getStandardKeys(String type, String name) { Hashtable<String, String> keys = new Hashtable<String, String>(2); keys.put(key_type, type); keys.put(key_name, name); return keys; } public static boolean registerMBean(Hashtable<String, String> keys, Object mBean) { return registerMBean(domain, keys, mBean); } public static ObjectName getObjectName(String type, String name) throws MalformedObjectNameException { Hashtable<String, String> keys = getStandardKeys(type, name); return new ObjectName(domain, keys); } public static ObjectName getObjectName(Hashtable keys) throws MalformedObjectNameException { return new ObjectName(domain, keys); } public static ObjectName getObjectName(String keys) throws MalformedObjectNameException { return new ObjectName(domain + ":" + keys); } public static boolean registerMBean(String domain, Hashtable<String, String> keys, Object mBean) { ArrayList<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null); MBeanServer defServer = servers.get(0); ObjectName name; try { name = new ObjectName(domain, keys); defServer.registerMBean(mBean, name); return true; } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException ex) { logger.error("register.error: " + ex.getMessage(), ex); } return false; } public static boolean unregisterMBean(Hashtable<String, String> keys) { return unregisterMBean(domain, keys); } public static boolean unregisterMBean(String domain, Hashtable<String, String> keys) { ArrayList<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null); MBeanServer defServer = servers.get(0); ObjectName name; try { name = new ObjectName(domain, keys); defServer.unregisterMBean(name); return true; } catch (MalformedObjectNameException | MBeanRegistrationException | InstanceNotFoundException ex) { logger.error("unregister.error: " + ex.getMessage(), ex); } return false; } public static String getCurrentUser() { AccessControlContext ctx = AccessController.getContext(); Subject subj = Subject.getSubject(ctx); String result = null; if (subj == null) { subj = LocalSubject.getSubject(); } logger.trace("getCurrentUser; subject: {}", subj); if (subj == null) { result = System.getProperty("user.name"); } else { Set<JMXPrincipal> sjp = subj.getPrincipals(JMXPrincipal.class); if (sjp != null && sjp.size() > 0) { result = sjp.iterator().next().getName(); } else { Set<Principal> sp = subj.getPrincipals(); if (sp != null && sp.size() > 0) { result = sp.iterator().next().getName(); } } } if (result == null) { result = "unknown"; } logger.trace("getCurrentUser.exit; returning: {}", result); return result; } public static List<String> queryNames(String wildcard) { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { Set<ObjectName> names = mbs.queryNames(new ObjectName(wildcard), null); List<String> result = new ArrayList<String>(names.size()); for (ObjectName name: names) { result.add(name.toString()); } return result; } catch (MalformedObjectNameException ex) { logger.error("queryNames.error: " + ex.getMessage(), ex); } return Collections.emptyList(); } /** * @param name Statistics name * @param desc Statistics description * @param map Statistics name/value map * @return Composite data */ public static CompositeData mapToComposite(String name, String desc, Map<String, Object> map) { if (map != null && !map.isEmpty()) { try { String[] names = new String[map.size()]; OpenType[] types = new OpenType[map.size()]; int idx = 0; for (Map.Entry<String, Object> e : map.entrySet()) { names[idx] = e.getKey(); types[idx] = getOpenType(e.getValue()); idx++; } CompositeType type = new CompositeType(name, desc, names, names, types); return new CompositeDataSupport(type, map); } catch (OpenDataException ex) { logger.warn("statsToComposite. error: {}", ex.getMessage()); } } return null; } public static TabularData compositeToTabular(String name, String desc, String key, TabularData source, CompositeData data) throws OpenDataException { if (data == null) { return source; } if (source == null) { TabularType type = new TabularType(name, desc, data.getCompositeType(), new String[] {key}); source = new TabularDataSupport(type); } source.put(data); //logger.trace("getStatisticSeries; added row: {}", data); return source; } @SuppressWarnings({ "rawtypes", "unchecked" }) public static TabularData aggregateStats(TabularData source, TabularData target) { // source is not nullable logger.debug("aggregateStats.enter; got source: {}", source); if (source == null) { return target; } TabularData result = new TabularDataSupport(source.getTabularType()); Set<List> keys = (Set<List>) source.keySet(); if (target == null) { //for (List key: keys) { // result.put(source.get(key.toArray())); return source; } else { for (List key: keys) { Object[] index = key.toArray(); CompositeData aggr = aggregateStats(source.get(index), target.get(index)); result.put(aggr); } } logger.debug("aggregateStats.exit; returning: {}", result); return result; } @SuppressWarnings({ "rawtypes", "unchecked" }) public static CompositeData aggregateStats(CompositeData source, CompositeData target) { // source is not nullable Set<String> keys = source.getCompositeType().keySet(); String[] names = keys.toArray(new String[keys.size()]); Object[] srcVals = source.getAll(names); if (target == null) { try { target = new CompositeDataSupport(source.getCompositeType(), names, srcVals); } catch (OpenDataException ex) { logger.warn("aggregateStats. error: {}", ex.getMessage()); return null; } } else { Object[] trgVals = target.getAll(names); trgVals[idx_Failed] = (Integer) srcVals[idx_Failed] + (Integer) trgVals[idx_Failed]; trgVals[idx_First] = ((Comparable) srcVals[idx_First]).compareTo((Comparable) trgVals[idx_First]) < 0 ? srcVals[idx_First] : trgVals[idx_First]; trgVals[idx_Invoked] = (Integer) srcVals[idx_Invoked] + (Integer) trgVals[idx_Invoked]; trgVals[idx_Last] = ((Comparable) srcVals[idx_Last]).compareTo((Comparable) trgVals[idx_Last]) > 0 ? srcVals[idx_Last] : trgVals[idx_Last]; trgVals[idx_Max_Time] = ((Comparable) srcVals[idx_Max_Time]).compareTo((Comparable) trgVals[idx_Max_Time]) > 0 ? srcVals[idx_Max_Time] : trgVals[idx_Max_Time]; trgVals[idx_Method] = srcVals[idx_Method]; trgVals[idx_Min_Time] = ((Comparable) srcVals[idx_Min_Time]).compareTo((Comparable) trgVals[idx_Min_Time]) < 0 ? srcVals[idx_Min_Time] : trgVals[idx_Min_Time]; trgVals[idx_Succeed] = (Integer) srcVals[idx_Succeed] + (Integer) trgVals[idx_Succeed]; trgVals[idx_Sum_Time] = (Long) srcVals[idx_Sum_Time] + (Long) trgVals[idx_Sum_Time]; int cntInvoke = (Integer) trgVals[idx_Invoked]; long tmFirst = ((Date) trgVals[idx_First]).getTime(); long tmLast = ((Date) trgVals[idx_Last]).getTime(); long tmMin = (Long) trgVals[idx_Min_Time]; long tmSum = (Long) trgVals[idx_Sum_Time]; if (cntInvoke > 0) { double dSum = tmSum; trgVals[idx_Avg_Time] = dSum/cntInvoke; double dCnt = cntInvoke*1000; long tmDuration = tmLast - tmFirst + tmMin; //tmAvg; trgVals[idx_Throughput] = dCnt/tmDuration; trgVals[idx_Duration] = tmDuration; } else { trgVals[idx_Avg_Time] = 0.0d; trgVals[idx_Throughput] = 0.0d; trgVals[idx_Duration] = 0L; } try { target = new CompositeDataSupport(source.getCompositeType(), names, trgVals); } catch (OpenDataException ex) { logger.warn("aggregateStats. error: {}", ex.getMessage()); return null; } } return target; } public static CompositeData propsToComposite(String name, String desc, Properties props) { logger.trace("propsToComposite; name: {}; properties: {}", name, props); if (props != null && !props.isEmpty()) { try { String[] names = new String[props.size()]; OpenType[] types = new OpenType[props.size()]; Object[] values = new Object[props.size()]; int idx = 0; for (Map.Entry<Object, Object> e : props.entrySet()) { names[idx] = (String) e.getKey(); types[idx] = getOpenType(e.getValue()); values[idx] = e.getValue(); idx++; } CompositeType type = new CompositeType(name, desc, names, names, types); return new CompositeDataSupport(type, names, values); } catch (/*OpenDataException ex*/ Throwable ex) { logger.warn("propsToComposite. error: {}", ex.getMessage()); } } return null; } /** * @param props Property map * @return Composite data */ public static Map<String, Object> propsFromComposite(CompositeData props) { Map<String, Object> result = new HashMap<String, Object>(props.values().size()); CompositeType type = props.getCompositeType(); for (String name : type.keySet()) { result.put(name, props.get(name)); } return result; } /** * @param props Property map * @return Tabular data */ public static TabularData propsToTabular(Map<String, String> props) { TabularData result = null; try { String typeName = "java.util.Map<java.lang.String, java.lang.String>"; String[] nameValue = new String[]{"name", "value"}; OpenType[] openTypes = new OpenType[]{SimpleType.STRING, SimpleType.STRING}; CompositeType rowType = new CompositeType(typeName, typeName, nameValue, nameValue, openTypes); TabularType tabularType = new TabularType(typeName, typeName, rowType, new String[]{"name"}); result = new TabularDataSupport(tabularType); if (props != null && props.size() > 0) { for (Map.Entry<String, String> prop : props.entrySet()) { result.put(new CompositeDataSupport(rowType, nameValue, new Object[]{prop.getKey(), prop.getValue()})); } } } catch (OpenDataException ex) { logger.error("propsToTabular. error: ", ex); } return result; } /** * @param props Tabular data * @return Property map */ public static Map<String, String> propsFromTabular(TabularData props) { Map<String, String> result = new HashMap<String, String>(props.size()); for (Object prop : props.values()) { CompositeData data = (CompositeData) prop; result.put((String) data.get("name"), (String) data.get("value")); } return result; } /** * @param props Property map * @param compositeType Composite type * @return CompositeData based on type and property Map */ public static CompositeData propsToComposite(Map<String, Object> props, CompositeType compositeType) { CompositeData result = null; try { result = new CompositeDataSupport(compositeType, props); } catch (OpenDataException ex) { logger.error("propsToComposite. error: ", ex); } return result; } /** * @param data Composite data * @return EOD statistics */ public static List<String> compositeToStrings(CompositeData data) { Set<String> keys = data.getCompositeType().keySet(); List<String> result = new ArrayList<String>(keys.size()); for (String key : keys) { result.add(key + ": " + data.get(key)); } return result; } /** * @param props Property map * @return EOD statistics */ public static List<String> propsToStrings(Map<String, Object> props) { List<String> result = new ArrayList<String>(props.size()); for (Map.Entry<String, Object> e : props.entrySet()) { result.add(e.getKey() + ": " + e.getValue()); } return result; } private static OpenType getOpenType(Object value) { if (value == null) { return SimpleType.VOID; } String name = value.getClass().getName(); //if (OpenType.ALLOWED_CLASSNAMES_LIST.contains(name)) { if ("java.lang.Long".equals(name)) { return SimpleType.LONG; } if ("java.lang.Integer".equals(name)) { return SimpleType.INTEGER; } if ("java.lang.String".equals(name)) { return SimpleType.STRING; } if ("java.lang.Double".equals(name)) { return SimpleType.DOUBLE; } if ("java.lang.Float".equals(name)) { return SimpleType.FLOAT; } if ("java.math.BigDecimal".equals(name)) { return SimpleType.BIGDECIMAL; } if ("java.math.BigInteger".equals(name)) { return SimpleType.BIGINTEGER; } if ("java.lang.Boolean".equals(name)) { return SimpleType.BOOLEAN; } if ("java.lang.Byte".equals(name)) { return SimpleType.BYTE; } if ("java.lang.Character".equals(name)) { return SimpleType.CHARACTER; } if ("java.util.Date".equals(name)) { return SimpleType.DATE; } if ("java.lang.Short".equals(name)) { return SimpleType.SHORT; } //"javax.management.ObjectName", //CompositeData.class.getName(), //TabularData.class.getName() return null; // is it allowed ?? } }
package org.perfmon4j.azure; import java.io.IOException; import java.util.ArrayList; import java.util.Base64; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicInteger; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.perfmon4j.IntervalData; import org.perfmon4j.PerfMonData; import org.perfmon4j.PerfMonObservableData; import org.perfmon4j.PerfMonObservableDatum; import org.perfmon4j.SnapShotData; import org.perfmon4j.SystemNameAndGroupsAppender; import org.perfmon4j.util.HttpHelper; import org.perfmon4j.util.HttpHelper.Response; import org.perfmon4j.util.Logger; import org.perfmon4j.util.LoggerFactory; import org.perfmon4j.util.MiscHelper; public class LogAnalyticsAppender extends SystemNameAndGroupsAppender { private static final Logger logger = LoggerFactory.initLogger(LogAnalyticsAppender.class); private static final String API_VERSION = "2016-04-01"; private static final String CONTENT_TYPE = "application/json"; private String customerID = null; private String sharedKey = null; private String azureResourceID = null; private boolean numericOnly = false; private int batchSeconds = 5; // How long to delay before sending a batch of measurements out. private int maxMeasurementsPerBatch = 1000; // Max number of measurements to send per post. private final HttpHelper helper = new HttpHelper(); private final AtomicInteger batchWritersPending = new AtomicInteger(0); private final Object writeQueueLockTokan = new Object(); private final List<QueueElement> writeQueue = new ArrayList<QueueElement>(); private static final Object dedicatedTimerThreadLockTocken = new Object(); private static Timer dedicatedTimerThread = null; // This is a fail safe to prevent failure of writing to Azure to allow measurements // to continue to accumulate and run out of memory. private final int maxWriteQueueSize = Integer.getInteger(LogAnalyticsAppender.class.getName() + ".maxQueueWriteSize" ,1000000).intValue(); public LogAnalyticsAppender(AppenderID id) { super(id, false); this.setExcludeCWDHashFromSystemName(true); } /* package level for testing */ String buildPostURL() { StringBuilder url = new StringBuilder(); url.append("https: .append(getCustomerID()) .append(".ods.opinsights.azure.com/api/logs?api-version=") .append(API_VERSION); return url.toString(); } private String addValueNoQuotes(String key, String value, boolean isLastValue) { return "\"" + MiscHelper.escapeJSONString(key) + "\" : " + value + (isLastValue ? "" : ","); } private String addValue(String key, String value, boolean isLastValue) { return "\"" + MiscHelper.escapeJSONString(key) + "\" : \"" + MiscHelper.escapeJSONString(value) + "\"" + (isLastValue ? "" : ","); } private String addDatumValue(PerfMonObservableDatum<?> datum, boolean isLastValue) { String result = null; String key = datum.getDefaultDisplayName(); if (datum.isNumeric()) { Object complexValue = datum.getComplexObject(); if ((complexValue != null) && (complexValue instanceof Boolean)) { result = addValueNoQuotes(key, (((Boolean)complexValue).booleanValue() ? "true" : "false"), isLastValue); } else { result = addValueNoQuotes(key, datum.toString(), isLastValue); } } else { result = addValue(key, datum.toString(), isLastValue); } return result; } /* package level for testing */ String createSignature(String message) throws IOException { final String signingAlg = "HmacSHA256"; if (sharedKey == null) { throw new IOException("Unable to sign message, sharedKey==null"); } try { Mac mac = Mac.getInstance(signingAlg); SecretKey key = new SecretKeySpec(Base64.getDecoder().decode(sharedKey), signingAlg); mac.init(key); byte[] bytes = mac.doFinal(message.getBytes("UTF-8")); return Base64.getEncoder().encodeToString(bytes); } catch (Exception e) { throw new IOException("Unable to create signature", e); } } /* package level for testing */ String buildStringToSign(int contentLength, String rfc1123DateTime) { StringBuilder result = new StringBuilder(); result .append("POST\n") .append(contentLength) .append("\n") .append(CONTENT_TYPE) .append("\n") .append("x-ms-date:") .append(rfc1123DateTime) .append("\n/api/logs"); return result.toString(); } /* package level for testing */ Map<String, String> buildRequestHeaders(String logType, int contentLength) throws IOException { Map<String, String> result = new HashMap<String, String>(); final String now = MiscHelper.formatTimeAsRFC1123(System.currentTimeMillis()); result.put("Content-Type", CONTENT_TYPE); result.put("Log-Type", logType); result.put("time-generated-field", "timestamp"); result.put("x-ms-date", now); String resID = getAzureResourceID(); if (resID != null) { result.put("x-ms-AzureResourceId", resID); } String stringToSign = buildStringToSign(contentLength, now); String signature = createSignature(stringToSign); result.put("Authorization", "SharedKey " + customerID + ":" + signature); return result; } static String trimPrefixOffCategory(String category) { return category.replaceFirst("^(Interval|Snapshot)\\.", ""); } /* package level for testing */ String buildJSONElement(PerfMonObservableData data) { StringBuilder json = new StringBuilder(); json.append("{"); json.append(addValue("category", trimPrefixOffCategory(data.getDataCategory()), false)); json.append(addValue("systemName", getSystemName(), false)); String[] groups = getGroupsAsArray(); if (groups.length > 0) { json.append(addValue("group", groups[0], false)); } int numDataElements = 0; for(PerfMonObservableDatum<?> datum : data.getObservations()) { if (!datum.getInputValueWasNull() && (!numericOnly || datum.isNumeric())) { numDataElements++; json.append(addDatumValue(datum, false)); } } json.append(addValue("timestamp", MiscHelper.formatTimeAsISO8601(data.getTimestamp()), true)); json.append("}"); return numDataElements > 0 ? json.toString() : null; } private void appendDataLine(QueueElement element) { synchronized (writeQueueLockTokan) { if (writeQueue.size() < maxWriteQueueSize) { writeQueue.add(element); } else { logger.logWarn("LogAnalyticsAppender execeeded maxWriteQueueSize. Measurement is being dropped"); } } if (batchWritersPending.intValue() <= 0) { synchronized (dedicatedTimerThreadLockTocken) { if (dedicatedTimerThread == null) { dedicatedTimerThread = new Timer("PerfMon4J.LogAnalyticsAppenderHttpWriteThread", true); } } dedicatedTimerThread.schedule(new BatchWriter(), getBatchSeconds() * 1000); } } private List<QueueElement> getBatch() { List<QueueElement> result = null; synchronized (writeQueueLockTokan) { if (!writeQueue.isEmpty()) { result = new LinkedList<QueueElement>(); result.addAll(writeQueue); writeQueue.clear(); } } return result; } @Override public void outputData(PerfMonData data) { if (data instanceof PerfMonObservableData) { String json = buildJSONElement((PerfMonObservableData)data); if (json != null) { appendDataLine(new QueueElement(((PerfMonObservableData)data), json)); } else { logger.logWarn("No observable data elements found. Skipping output of data: " + ((PerfMonObservableData)data).getDataCategory()); } } else { logger.logWarn("Unable to write data to Azure. Data class does not implement PerfMonObservableData. " + "Data class = " + data.getClass()); } } public int getBatchSeconds() { return batchSeconds; } public void setBatchSeconds(int batchSeconds) { this.batchSeconds = batchSeconds; } public int getMaxMeasurementsPerBatch() { return maxMeasurementsPerBatch; } public void setMaxMeasurementsPerBatch(int maxMeasurementsPerBatch) { this.maxMeasurementsPerBatch = maxMeasurementsPerBatch; } public HttpHelper getHelper() { return helper; } public void setConnectTimeoutMillis(int connectTimeoutMillis) { helper.setConnectTimeoutMillis(connectTimeoutMillis); } public int getConnectTimeoutMillis() { return helper.getConnectTimeoutMillis(); } public void setReadTimeoutMillis(int readTimeoutMillis) { helper.setReadTimeoutMillis(readTimeoutMillis); } public int getReadTimeoutMillis() { return helper.getReadTimeoutMillis(); } public String getCustomerID() { return customerID; } public void setCustomerID(String customerID) { this.customerID = customerID; } public String getSharedKey() { return sharedKey; } public void setSharedKey(String sharedKey) { this.sharedKey = sharedKey; } public boolean isNumericOnly() { return numericOnly; } public void setNumericOnly(boolean numericOnly) { this.numericOnly = numericOnly; } public String getAzureResourceID() { return azureResourceID; } public void setAzureResourceID(String azureResourceID) { this.azureResourceID = azureResourceID; } static class QueueElement { private static final String INTERVAL_PREFIX = "P4J_Interval"; private static final String MISC_PREFIX = "P4J_Misc"; private static final String SNAPSHOT_PREFIX = "P4J_SnapShot"; private final String key; private final String json; QueueElement(PerfMonObservableData data, String json) { if (data instanceof SnapShotData) { key = snapShotSimpleClassNameToPrefix(data.getClass().getSimpleName()); } else if (data instanceof IntervalData){ key = INTERVAL_PREFIX; } else { key = MISC_PREFIX; } this.json = json; } /** * TEST_ONLY * @param key * @param json */ QueueElement(String key, String json) { this.key = key; this.json = json; } static public Map<String, Deque<String>> sortIntoBatches(List<QueueElement> queue) { Map<String, Deque<String>> result = new HashMap<String, Deque<String>>(); for(QueueElement element : queue) { String key = element.getKey(); Deque<String> batch = result.get(key); if (batch == null) { batch = new LinkedList<String>(); result.put(key, batch); } batch.add(element.getJson()); } return result; } static String snapShotSimpleClassNameToPrefix(String simpleClassName) { String suffix = simpleClassName .replaceAll("\\d+$", "") .replaceAll("(SnapShot)+$", ""); if (suffix.isEmpty()) { return SNAPSHOT_PREFIX; } else { return SNAPSHOT_PREFIX + "_" + suffix; } } public String getKey() { return key; } public String getJson() { return json; } } private class BatchWriter extends TimerTask { BatchWriter() { batchWritersPending.incrementAndGet(); } @Override public void run() { batchWritersPending.decrementAndGet(); List<QueueElement> batches = getBatch(); for (Map.Entry<String, Deque<String>> entry : QueueElement.sortIntoBatches(batches).entrySet()) { String logType = entry.getKey(); Deque<String> batch = entry.getValue(); while (batch != null && !batch.isEmpty()) { int batchSize = 0; StringBuilder postBody = null; for (;batchSize < maxMeasurementsPerBatch && !batch.isEmpty(); batchSize++) { String line = batch.remove(); if (postBody == null) { postBody = new StringBuilder(); postBody.append("["); } else { postBody.append(","); } postBody.append(line); } postBody.append("]"); HttpHelper helper = getHelper(); String postURL = buildPostURL(); String debugOutput = "URL(" + postURL + ") logType(" + logType + ") batchSize(" + batchSize + ")"; try { Map<String, String> headers = buildRequestHeaders(logType, postBody.length()); Response response = helper.doPost(postURL, postBody.toString(), headers); if (!response.isSuccess()) { String message = "Error writing to Azure: " + debugOutput + " - Response: " + response.toString(); logger.logWarn(message); } else if (logger.isDebugEnabled()) { logger.logDebug("Success writing to Azure: " + debugOutput); } } catch (IOException e) { String message = "Exception writing to Azure: " + debugOutput; if (logger.isDebugEnabled()) { logger.logWarn(message, e); } else { message += " Exception(" + e.getClass().getName() + "): " + e.getMessage(); logger.logWarn(message); } } } } } } }
package gov.nih.nci.ncicb.cadsr.common; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class CaDSRUtil { //Key to use for the path to cadsrutil.properties file from system properties protected static String KEY_CADSR_PROPERTIES_PATH = "gov.nih.nci.cadsrutil.properties"; //Key to retrieve the actually default context name protected static final String KEY_DEFAULT_CONTEXT_NAME = "default.context.name"; protected static String defaultContextName; /** * Get the default context name from cadsrutil.properties. Once a valid defaultContextName is read, it's cached. * <br><br> * The property file's path and name should have been set as a System property with key "gov.nih.nci.cadsrutil.properties" <br> * * @return default context name * @throws IOException if unable to find the properties file */ public static String getDefaultContextName() throws IOException { return (defaultContextName == null || defaultContextName.length() == 0) ? CaDSRUtil.getProperty(CaDSRUtil.KEY_DEFAULT_CONTEXT_NAME) : defaultContextName; } /** * Get a property value from the config file: * /local/content/cadsrutil/cadsrutil.properties * @param key * @return * @throws IOException if unable to find the properties file */ protected static String getProperty(String key) throws IOException { String path = System.getProperty(KEY_CADSR_PROPERTIES_PATH); if (path == null || path.length() == 0) throw new IOException("Cadsrutil is unable to get property file path with this key \"" + KEY_CADSR_PROPERTIES_PATH + "\""); Properties properties = loadPropertiesFromFile(path); defaultContextName = properties.getProperty(key); if (defaultContextName == null || defaultContextName.length() == 0) throw new IOException("Unable to find the default context name from file: \"" + path + "\""); return defaultContextName; } protected static Properties loadPropertiesFromFile(String pathname) throws IOException { Properties properties = new Properties(); if (pathname == null || pathname.length() == 0) return properties; FileInputStream in = null; in = new FileInputStream(pathname); if (in != null) { properties.load(in); in.close(); } return properties; } }
package com.dianping.cat.servlet; import java.io.IOException; 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.HttpServletRequest; import org.unidal.lookup.util.StringUtils; import com.dianping.cat.Cat; import com.dianping.cat.message.Metric; public class CdnFilter implements Filter { private static final String DI_LIAN = "DiLian"; private static final String WANG_SU = "WangSu"; private static final String TENG_XUN = "TengXun"; @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { HttpServletRequest httpServletRequest = (HttpServletRequest) request; String vip = queryVip(httpServletRequest); String sourceIp = querySourceIp(httpServletRequest); if (StringUtils.isNotEmpty(sourceIp) && StringUtils.isNotEmpty(vip)) { Metric metric = Cat.getProducer().newMetric("cdn", vip + ":" + sourceIp); metric.setStatus("C"); metric.addData(String.valueOf(1)); } } catch (Exception e) { Cat.logError(e); } chain.doFilter(request, response); } private String querySourceIp(HttpServletRequest request) { return filterXForwardedForIP(request.getHeader("x-forwarded-for")); } private String queryVip(HttpServletRequest request) { String serverName = request.getServerName(); if (serverName != null) { if (serverName.contains("s1.dpfile.com")) { return DI_LIAN; } if (serverName.contains("i1.dpfile.com") || serverName.contains("i3.dpfile.com") || serverName.contains("t2.dpfile.com")) { return DI_LIAN; } if (serverName.contains("s2.dpfile.com")) { return WANG_SU; } if (serverName.contains("i2.dpfile.com") || serverName.contains("t1.dpfile.com") || serverName.contains("t3.dpfile.com")) { return WANG_SU; } if (serverName.contains("s3.dpfile.com")) { return TENG_XUN; } } return null; } private String filterXForwardedForIP(String ip) { if (ip == null || ip.trim().length() == 0) { return null; } else { String[] subIps = ip.split(","); int length = subIps.length; int index = -1; for (int i = 0; i < length; i++) { String subIp = subIps[i]; if (subIp == null || subIp.trim().length() == 0) { continue; } else { subIp = subIp.trim(); if (subIp.startsWith("192.168.") || subIp.startsWith("10.") || "127.0.0.1".equals(subIp)) { continue; } else if (subIp.startsWith("172.")) { String[] iptabs = subIp.split("\\."); int tab2 = Integer.parseInt(iptabs[1]); if (tab2 >= 16 && tab2 <= 31) { continue; } else { index = i; break; } } else { index = i; break; } } } if (index > -1 && index + 1 <= length) { return subIps[index + 1]; } else { return null; } } } @Override public void destroy() { } }
package ru.pravvich.start; import ru.pravvich.models.*; /** * @since Pavel Ravvich * @since 04.11.2016 * @see #add() addition task * @see #updateItem() replace task on new * @see #findByHeader() * @see #findById() * @see #deleteTask() * @see #addCommit() * @see #editionCommit() * @see #viewAllTasks() */ public class StartUI { private Input input; private Tracker tracker = new Tracker(); public StartUI(Input input) { this.input = input; } public void editionCommit() { String oldCommit = input.ask("Enter old commit for edit"); String newCommit = input.ask("Enter new commit"); this.tracker.editionCommit(oldCommit, newCommit); System.out.println(this.tracker.getMessage()); System.out.println("========================================================="); } public void addCommit() { int id = input.askInt("Enter ID task for commit."); String commit = input.ask("Enter commit for this task."); this.tracker.addCommit(this.tracker.findById(id), commit); System.out.println(this.tracker.getMessage()); System.out.println("========================================================="); } // init new task public void add() { String header = this.input.ask("Please enter the task name"); this.tracker.add(new Task(header)); System.out.println(this.tracker.getMessage()); System.out.println("========================================================="); } public void updateItem() { String header = this.input.ask("Enter new name for task."); int id = this.input.askInt("Enter task ID for replace"); Item item = new Item(header, id); this.tracker.updateItem(item); System.out.println(tracker.getMessage()); System.out.println("========================================================="); } public void findById () { int id = this.input.askInt("Enter ID number"); Item item = this.tracker.findById(id); System.out.println(tracker.getMessage() + ": " + item.getHeader()); System.out.println("========================================================="); } public void findByHeader() { String header = this.input.ask("Enter task name for search."); this.tracker.findByHeader(header); System.out.println(tracker.getMessage()); System.out.println("========================================================="); } public void deleteTask() { String header = this.input.ask("Please enter the task name for delete"); int id = this.tracker.findByHeader(header).getId(); Item itemForDelete = this.tracker.findById(id); this.tracker.delete(itemForDelete); System.out.println(tracker.getMessage()); System.out.println("========================================================="); } public void viewAllTasks() { String answer = this.input.ask("View all tasks : view -a" + "\n" + "View all tasks with revers filter : view -f"); if (answer.equals("view -a")) { Item[] print = this.tracker.getPrintArray(); System.out.println(this.tracker.getMessage()); for (Item item : print) { System.out.println(item.getHeader() + " ID: " + item.getId()); } System.out.println("========================================================="); } else if (answer.equals("view -f")) { Item[] print = this.tracker.getArrPrintFilter(); System.out.println(this.tracker.getMessage()); for (Item item : print) { System.out.println(item.getHeader() + " ID: " + item.getId()); } System.out.println("========================================================="); } else { System.out.println("Error: command not found"); System.out.println("========================================================="); } } public static void main(String[] args) { Input input = new ConsoleInput(); StartUI startUI = new StartUI(input); //startUI.add(); //startUI.viewAllTasks(); //startUI.addCommit(); //startUI.editionCommit(); //startUI.updateItem(); //startUI.findById(); //startUI.findByHeader(); //startUI.deleteTask(); //MENU System.out.println("Welcome to task manager!" + "\n" + "Menu: " + " \n" + "1. Add task: n -t" + "\n" + "2. View all tasks: v" + "\n" + "3. Add comment: n -c" + "\n" + "4. Edition comment: e -c" + "\n" + "5. Edition task: e -t" + "\n" + "6. Find bi ID: f -id" + "\n" + "7. Find by header: f -h" + "\n" + "8. Delete task: d -t"); String answer = input.ask("Please select an action:"); if (answer.equals("n -t")) { startUI.add(); } else if (answer.equals("v")) { startUI.viewAllTasks(); } else if (answer.equals("n -c")) { startUI.addCommit(); } else if (answer.equals("e -c")) { startUI.editionCommit(); } else if (answer.equals("e -t")) { startUI.updateItem(); } else if (answer.equals("f -id")) { startUI.findById(); } else if (answer.equals("f -h")) { startUI.findByHeader(); } else if (answer.equals("d -t")) { startUI.deleteTask(); } else { System.out.println("command not found"); } } }
package org.chromium.chrome.browser; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.view.View; import org.chromium.base.CalledByNative; import org.chromium.base.ObserverList; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.ui.toolbar.ToolbarModelSecurityLevel; import org.chromium.content.browser.ContentView; import org.chromium.content.browser.ContentViewClient; import org.chromium.content.browser.ContentViewCore; import org.chromium.content.browser.NavigationClient; import org.chromium.content.browser.NavigationHistory; import org.chromium.content.browser.PageInfo; import org.chromium.content.browser.WebContentsObserverAndroid; import org.chromium.ui.WindowAndroid; import java.util.Iterator; import java.util.concurrent.atomic.AtomicInteger; /** * The basic Java representation of a tab. Contains and manages a {@link ContentView}. * * TabBase provides common functionality for ChromiumTestshell's Tab as well as Chrome on Android's * tab. It's intended to be extended both on Java and C++, with ownership managed by the subclass. * Because of the inner-workings of JNI, the subclass is responsible for constructing the native * subclass which in turn constructs TabAndroid (the native counterpart to TabBase) which in turn * sets the native pointer for TabBase. The same is true for destruction. The Java subclass must be * destroyed which will call into the native subclass and finally lead to the destruction of the * parent classes. */ public abstract class TabBase implements NavigationClient { public static final int INVALID_TAB_ID = -1; /** Used for automatically generating tab ids. */ private static final AtomicInteger sIdCounter = new AtomicInteger(); private int mNativeTabAndroid; /** Unique id of this tab (within its container). */ private final int mId; /** Whether or not this tab is an incognito tab. */ private final boolean mIncognito; /** An Application {@link Context}. Unlike {@link #mContext}, this is the only one that is * publicly exposed to help prevent leaking the {@link Activity}. */ private final Context mApplicationContext; /** The {@link Context} used to create {@link View}s and other Android components. Unlike * {@link #mApplicationContext}, this is not publicly exposed to help prevent leaking the * {@link Activity}. */ private final Context mContext; /** Gives {@link TabBase} a way to interact with the Android window. */ private final WindowAndroid mWindowAndroid; /** The current native page (e.g. chrome-native://newtab), or {@code null} if there is none. */ private NativePage mNativePage; /** The {@link ContentView} showing the current page or {@code null} if the tab is frozen. */ private ContentView mContentView; /** * The {@link ContentViewCore} for the current page, provided for convenience. This always * equals {@link ContentView#getContentViewCore()}, or {@code null} if mContentView is * {@code null}. */ private ContentViewCore mContentViewCore; // Observers and Delegates. private ContentViewClient mContentViewClient; private WebContentsObserverAndroid mWebContentsObserver; private TabBaseChromeWebContentsDelegateAndroid mWebContentsDelegate; private final ObserverList<TabObserver> mObservers = new ObserverList<TabObserver>(); /** * A basic {@link ChromeWebContentsDelegateAndroid} that forwards some calls to the registered * {@link TabObserver}s. Meant to be overridden by subclasses. */ public class TabBaseChromeWebContentsDelegateAndroid extends ChromeWebContentsDelegateAndroid { @Override public void onLoadProgressChanged(int progress) { for (TabObserver observer : mObservers) { observer.onLoadProgressChanged(TabBase.this, progress); } } @Override public void onUpdateUrl(String url) { for (TabObserver observer : mObservers) observer.onUpdateUrl(TabBase.this, url); } @Override public void toggleFullscreenModeForTab(boolean enableFullscreen) { for (TabObserver observer: mObservers) { observer.onToggleFullscreenMode(TabBase.this, enableFullscreen); } } } /** * Creates an instance of a {@link TabBase} with no id. * @param incognito Whether or not this tab is incognito. * @param context An instance of a {@link Context}. * @param window An instance of a {@link WindowAndroid}. */ public TabBase(boolean incognito, Context context, WindowAndroid window) { this(INVALID_TAB_ID, incognito, context, window); } /** * Creates an instance of a {@link TabBase}. * @param id The id this tab should be identified with. * @param incognito Whether or not this tab is incognito. * @param context An instance of a {@link Context}. * @param window An instance of a {@link WindowAndroid}. */ public TabBase(int id, boolean incognito, Context context, WindowAndroid window) { // We need a valid Activity Context to build the ContentView with. assert context == null || context instanceof Activity; mId = generateValidId(id); mIncognito = incognito; // TODO(dtrainor): Only store application context here. mContext = context; mApplicationContext = context != null ? context.getApplicationContext() : null; mWindowAndroid = window; } /** * Adds a {@link TabObserver} to be notified on {@link TabBase} changes. * @param observer The {@link TabObserver} to add. */ public final void addObserver(TabObserver observer) { mObservers.addObserver(observer); } /** * Removes a {@link TabObserver}. * @param observer The {@link TabObserver} to remove. */ public final void removeObserver(TabObserver observer) { mObservers.removeObserver(observer); } /** * @return Whether or not this tab has a previous navigation entry. */ public boolean canGoBack() { return mContentViewCore != null && mContentViewCore.canGoBack(); } /** * @return Whether or not this tab has a navigation entry after the current one. */ public boolean canGoForward() { return mContentViewCore != null && mContentViewCore.canGoForward(); } /** * Goes to the navigation entry before the current one. */ public void goBack() { if (mContentViewCore != null) mContentViewCore.goBack(); } /** * Goes to the navigation entry after the current one. */ public void goForward() { if (mContentViewCore != null) mContentViewCore.goForward(); } @Override public NavigationHistory getDirectedNavigationHistory(boolean isForward, int itemLimit) { if (mContentViewCore != null) { return mContentViewCore.getDirectedNavigationHistory(isForward, itemLimit); } else { return new NavigationHistory(); } } @Override public void goToNavigationIndex(int index) { if (mContentViewCore != null) mContentViewCore.goToNavigationIndex(index); } /** * @return Whether or not the {@link TabBase} is currently showing an interstitial page, such as * a bad HTTPS page. */ public boolean isShowingInterstitialPage() { ContentViewCore contentViewCore = getContentViewCore(); return contentViewCore != null && contentViewCore.isShowingInterstitialPage(); } /** * @return Whether or not the tab has something valid to render. */ public boolean isReady() { return mNativePage != null || (mContentViewCore != null && mContentViewCore.isReady()); } /** * @return The {@link View} displaying the current page in the tab. This might be a * {@link ContentView} but could potentially be any instance of {@link View}. This can * be {@code null}, if the tab is frozen or being initialized or destroyed. */ public View getView() { PageInfo pageInfo = getPageInfo(); return pageInfo != null ? pageInfo.getView() : null; } /** * @return The width of the content of this tab. Can be 0 if there is no content. */ public int getWidth() { View view = getView(); return view != null ? view.getWidth() : 0; } /** * @return The height of the content of this tab. Can be 0 if there is no content. */ public int getHeight() { View view = getView(); return view != null ? view.getHeight() : 0; } /** * @return The application {@link Context} associated with this tab. */ protected Context getApplicationContext() { return mApplicationContext; } /** * Reloads the current page content if it is a {@link ContentView}. */ public void reload() { // TODO(dtrainor): Should we try to rebuild the ContentView if it's frozen? ContentViewCore contentViewCore = getContentViewCore(); if (contentViewCore != null) contentViewCore.reload(); } /** * @return The background color of the tab. */ public int getBackgroundColor() { return getPageInfo() != null ? getPageInfo().getBackgroundColor() : Color.WHITE; } /** * @return The profile associated with this tab. */ public Profile getProfile() { if (mNativeTabAndroid == 0) return null; return nativeGetProfileAndroid(mNativeTabAndroid); } /** * @return The id representing this tab. */ public int getId() { return mId; } /** * @return Whether or not this tab is incognito. */ public boolean isIncognito() { return mIncognito; } /** * @return The {@link ContentView} associated with the current page, or {@code null} if * there is no current page or the current page is displayed using something besides a * {@link ContentView}. */ public ContentView getContentView() { return mNativePage == null ? mContentView : null; } /** * @return The {@link ContentViewCore} associated with the current page, or {@code null} if * there is no current page or the current page is displayed using something besides a * {@link ContentView}. */ public ContentViewCore getContentViewCore() { return mNativePage == null ? mContentViewCore : null; } /** * @return A {@link PageInfo} describing the current page. This is always not {@code null} * except during initialization, destruction, and when the tab is frozen. */ public PageInfo getPageInfo() { return mNativePage != null ? mNativePage : mContentView; } /** * @return The {@link NativePage} associated with the current page, or {@code null} if there is * no current page or the current page is displayed using something besides * {@link NativePage}. */ public NativePage getNativePage() { return mNativePage; } /** * @return Whether or not the {@link TabBase} represents a {@link NativePage}. */ public boolean isNativePage() { return mNativePage != null; } /** * Set whether or not the {@link ContentViewCore} should be using a desktop user agent for the * currently loaded page. * @param useDesktop If {@code true}, use a desktop user agent. Otherwise use a mobile one. * @param reloadOnChange Reload the page if the user agent has changed. */ public void setUseDesktopUserAgent(boolean useDesktop, boolean reloadOnChange) { if (mContentViewCore != null) { mContentViewCore.setUseDesktopUserAgent(useDesktop, reloadOnChange); } } /** * @return Whether or not the {@link ContentViewCore} is using a desktop user agent. */ public boolean getUseDesktopUserAgent() { return mContentViewCore != null && mContentViewCore.getUseDesktopUserAgent(); } /** * @return The current {ToolbarModelSecurityLevel} for the tab. */ public int getSecurityLevel() { if (mNativeTabAndroid == 0) return ToolbarModelSecurityLevel.NONE; return nativeGetSecurityLevel(mNativeTabAndroid); } /** * @return An {@link ObserverList.RewindableIterator} instance that points to all of * the current {@link TabObserver}s on this class. Note that calling * {@link Iterator#remove()} will throw an {@link UnsupportedOperationException}. */ protected ObserverList.RewindableIterator<TabObserver> getTabObservers() { return mObservers.rewindableIterator(); } /** * @return The {@link ContentViewClient} currently bound to any {@link ContentViewCore} * associated with the current page. There can still be a {@link ContentViewClient} * even when there is no {@link ContentViewCore}. */ protected ContentViewClient getContentViewClient() { return mContentViewClient; } /** * @param client The {@link ContentViewClient} to be bound to any current or new * {@link ContentViewCore}s associated with this {@link TabBase}. */ protected void setContentViewClient(ContentViewClient client) { if (mContentViewClient == client) return; ContentViewClient oldClient = mContentViewClient; mContentViewClient = client; if (mContentViewCore == null) return; if (mContentViewClient != null) { mContentViewCore.setContentViewClient(mContentViewClient); } else if (oldClient != null) { // We can't set a null client, but we should clear references to the last one. mContentViewCore.setContentViewClient(new ContentViewClient()); } } /** * Shows the given {@code nativePage} if it's not already showing. * @param nativePage The {@link NativePage} to show. */ protected void showNativePage(NativePage nativePage) { if (mNativePage == nativePage) return; destroyNativePageInternal(); mNativePage = nativePage; for (TabObserver observer : mObservers) observer.onContentChanged(this); } /** * Hides the current {@link NativePage}, if any, and shows the {@link ContentView}. */ protected void showRenderedPage() { if (mNativePage == null) return; destroyNativePageInternal(); for (TabObserver observer : mObservers) observer.onContentChanged(this); } /** * Initializes this {@link TabBase}. */ public void initialize() { } /** * A helper method to initialize a {@link ContentView} without any native WebContents pointer. */ protected final void initContentView() { initContentView(ContentViewUtil.createNativeWebContents(mIncognito)); } /** * Completes the {@link ContentView} specific initialization around a native WebContents * pointer. {@link #getPageInfo()} will still return the {@link NativePage} if there is one. * All initialization that needs to reoccur after a web contents swap should be added here. * <p /> * NOTE: If you attempt to pass a native WebContents that does not have the same incognito * state as this tab this call will fail. * * @param nativeWebContents The native web contents pointer. */ protected void initContentView(int nativeWebContents) { destroyNativePageInternal(); mContentView = ContentView.newInstance(mContext, nativeWebContents, getWindowAndroid()); mContentViewCore = mContentView.getContentViewCore(); mWebContentsDelegate = createWebContentsDelegate(); mWebContentsObserver = createWebContentsObserverAndroid(mContentViewCore); if (mContentViewClient != null) mContentViewCore.setContentViewClient(mContentViewClient); assert mNativeTabAndroid != 0; nativeInitWebContents( mNativeTabAndroid, mId, mIncognito, mContentViewCore, mWebContentsDelegate); } /** * Cleans up all internal state, destroying any {@link NativePage} or {@link ContentView} * currently associated with this {@link TabBase}. Typically, pnce this call is made this * {@link TabBase} should no longer be used as subclasses usually destroy the native component. */ public void destroy() { for (TabObserver observer : mObservers) observer.onDestroyed(this); destroyNativePageInternal(); destroyContentView(true); } private void destroyNativePageInternal() { if (mNativePage == null) return; mNativePage.destroy(); mNativePage = null; } /** * Destroys the current {@link ContentView}. * @param deleteNativeWebContents Whether or not to delete the native WebContents pointer. */ protected final void destroyContentView(boolean deleteNativeWebContents) { if (mContentView == null) return; destroyContentViewInternal(mContentView); if (mContentViewCore != null) mContentViewCore.destroy(); mContentView = null; mContentViewCore = null; mWebContentsDelegate = null; mWebContentsObserver = null; assert mNativeTabAndroid != 0; nativeDestroyWebContents(mNativeTabAndroid, deleteNativeWebContents); } /** * Gives subclasses the chance to clean up some state associated with this {@link ContentView}. * This is because {@link #getContentView()} can return {@code null} if a {@link NativePage} * is showing. * @param contentView The {@link ContentView} that should have associated state cleaned up. */ protected void destroyContentViewInternal(ContentView contentView) { } /** * A helper method to allow subclasses to build their own delegate. * @return An instance of a {@link TabBaseChromeWebContentsDelegateAndroid}. */ protected TabBaseChromeWebContentsDelegateAndroid createWebContentsDelegate() { return new TabBaseChromeWebContentsDelegateAndroid(); } /** * A helper method to allow subclasses to build their own observer. * @param contentViewCore The {@link ContentViewCore} this observer should be built for. * @return An instance of a {@link WebContentsObserverAndroid}. */ protected WebContentsObserverAndroid createWebContentsObserverAndroid( ContentViewCore contentViewCore) { return null; } /** * @return The {@link WindowAndroid} associated with this {@link TabBase}. */ protected WindowAndroid getWindowAndroid() { return mWindowAndroid; } /** * @return The current {@link TabBaseChromeWebContentsDelegateAndroid} instance. */ protected TabBaseChromeWebContentsDelegateAndroid getChromeWebContentsDelegateAndroid() { return mWebContentsDelegate; } /** * Launches all currently blocked popups that were spawned by the content of this tab. */ protected void launchBlockedPopups() { assert mContentViewCore != null; nativeLaunchBlockedPopups(mNativeTabAndroid); } /** * Called when the number of blocked popups has changed. * @param numPopups The current number of blocked popups. */ @CalledByNative protected void onBlockedPopupsStateChanged(int numPopups) { } /** * Called when the favicon of the content this tab represents changes. */ @CalledByNative protected void onFaviconUpdated() { for (TabObserver observer : mObservers) observer.onFaviconUpdated(this); } /** * @return The native pointer representing the native side of this {@link TabBase} object. */ @CalledByNative protected int getNativePtr() { return mNativeTabAndroid; } /** This is currently called when committing a pre-rendered page. */ @CalledByNative private void swapWebContents(final int newWebContents) { destroyContentView(false); initContentView(newWebContents); mContentViewCore.onShow(); mContentViewCore.attachImeAdapter(); for (TabObserver observer : mObservers) observer.onContentChanged(this); } @CalledByNative private void clearNativePtr() { assert mNativeTabAndroid != 0; mNativeTabAndroid = 0; } @CalledByNative private void setNativePtr(int nativePtr) { assert mNativeTabAndroid == 0; mNativeTabAndroid = nativePtr; } /** * Validates {@code id} and increments the internal counter to make sure future ids don't * collide. * @param id The current id. Maybe {@link #INVALID_TAB_ID}. * @return A new id if {@code id} was {@link #INVALID_TAB_ID}, or {@code id}. */ private static int generateValidId(int id) { if (id == INVALID_TAB_ID) id = generateNextId(); incrementIdCounterTo(id + 1); return id; } /** * @return An unused id. */ private static int generateNextId() { return sIdCounter.getAndIncrement(); } /** * Ensures the counter is at least as high as the specified value. The counter should always * point to an unused ID (which will be handed out next time a request comes in). Exposed so * that anything externally loading tabs and ids can set enforce new tabs start at the correct * id. * TODO(aurimas): Investigate reducing the visiblity of this method. * @param id The minimum id we should hand out to the next new tab. */ public static void incrementIdCounterTo(int id) { int diff = id - sIdCounter.get(); if (diff <= 0) return; // It's possible idCounter has been incremented between the get above and the add below // but that's OK, because in the worst case we'll overly increment idCounter. sIdCounter.addAndGet(diff); } private native void nativeInitWebContents(int nativeTabAndroid, int id, boolean incognito, ContentViewCore contentViewCore, ChromeWebContentsDelegateAndroid delegate); private native void nativeDestroyWebContents(int nativeTabAndroid, boolean deleteNative); private native Profile nativeGetProfileAndroid(int nativeTabAndroid); private native void nativeLaunchBlockedPopups(int nativeTabAndroid); private native int nativeGetSecurityLevel(int nativeTabAndroid); }