answer
stringlengths
17
10.2M
package org.springframework.util; import java.io.InputStream; /** * Utility class for class loading, and for diagnostic purposes * to analyze the ClassLoader hierarchy for any object. * @author Rod Johnson * @author Juergen Hoeller * @since 02 April 2001 * @see ClassLoader */ public abstract class ClassLoaderUtils { /** * Load a resource from the class path, first trying the thread context * class loader, then the class loader of the given class. * @param clazz a class to try the class loader of * @param name the resource name * @return an input stream for reading the resource, * or null if not found * @see ClassLoader#getResourceAsStream * @see Class#getResourceAsStream */ public static InputStream getResourceAsStream(Class clazz, String name) { ClassLoader ccl = Thread.currentThread().getContextClassLoader(); InputStream in = null; if (ccl != null) { in = ccl.getResourceAsStream(name); } if (in == null) { in = clazz.getResourceAsStream(name); } return in; } /** * Show the class loader hierarchy for this class. * @param obj object to analyze loader hierarchy for * @param role a description of the role of this class in the application * (e.g., "servlet" or "EJB reference") * @param delim line break * @param tabText text to use to set tabs * @return a String showing the class loader hierarchy for this class */ public static String showClassLoaderHierarchy(Object obj, String role, String delim, String tabText) { String s = "object of " + obj.getClass() + ": role is " + role + delim; return s + showClassLoaderHierarchy(obj.getClass().getClassLoader(), delim, tabText, 0); } /** * Show the class loader hierarchy for this class. * @param cl class loader to analyze hierarchy for * @param delim line break * @param tabText text to use to set tabs * @param indent nesting level (from 0) of this loader; used in pretty printing * @return a String showing the class loader hierarchy for this class */ public static String showClassLoaderHierarchy(ClassLoader cl, String delim, String tabText, int indent) { if (cl == null) { String s = "null classloader " + delim; ClassLoader ctxcl = Thread.currentThread().getContextClassLoader(); s += "Context class loader=" + ctxcl + " hc=" + ctxcl.hashCode(); return s; } String s = ""; //"ClassLoader: "; for (int i = 0; i < indent; i++) s += tabText; s += cl + " hc=" + cl.hashCode() + delim; ClassLoader parent = cl.getParent(); return s + showClassLoaderHierarchy(parent, delim, tabText, indent + 1); } /** * Return a path suitable for use with Class.getResource. Built by taking * the package of the specified class file, converting all dots ('.') to slashes * ('/'), adding a trailing slash, and concatenating the specified resource name * to this. As such, this function may be used to build a path suitable for loading * a resource file that is in the same package as a class file. * @param clazz the Class whose package will be used as the base. * @param resourceName the resource name to append. A leading slash is optional. * @return the built-up resource path * @see java.lang.Class#getResource */ public static String addResourcePathToPackagePath(Class clazz, String resourceName) { if (!resourceName.startsWith("/")) return classPackageAsResourcePath(clazz) + "/" + resourceName; else return classPackageAsResourcePath(clazz) + resourceName; } /** * Given an input class object, returns a string which consists of the class's package * name as a pathname, i.e., a leading '/' is added, and all dots ('.') are replaced by * slashes ('/'). A trailing slash is <b>not</b> added. * @param clazz the input class. A null value will result in "/" being returned. * @return a path which represents the package name, including a leading slash */ public static String classPackageAsResourcePath(Class clazz) { StringBuffer retval = new StringBuffer("/"); if (clazz != null) retval.append(clazz.getPackage().getName().replace('.', '/')); return retval.toString(); } /** * Given a fully qualified name, return a class name: * e.g. com.foo.Bar returns Bar, * com.foo.Bar$Inner returns Bar$Inner. * @param clazz class to find name for * @return the class name without the package prefix. * Will include any enclosing class name, which is also after * the dot. */ public static String classNameWithoutPackagePrefix(Class clazz) { String name = clazz.getName(); int lastDotIndex = name.lastIndexOf("."); // There must be characters after the ., so we don't // need to program defensively for that case return (lastDotIndex == -1) ? name : // default package name.substring(lastDotIndex + 1); } }
package org.fujaba.graphengine; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import org.fujaba.graphengine.graph.Graph; import org.fujaba.graphengine.graph.Node; import org.fujaba.graphengine.pattern.PatternAttribute; import org.fujaba.graphengine.pattern.PatternEdge; import org.fujaba.graphengine.pattern.PatternGraph; import org.fujaba.graphengine.pattern.PatternNode; /** * The PatternEngine contains all logic concerning PatternGraphs. * * @author Philipp Kolodziej */ public class PatternEngine { /** * matches and directly applies a pattern as often as possible * until the optional limit is met, without revisiting graphs, * that were already used (preventing endless cycles). * * @param graph the graph to apply the pattern on * @param pattern the pattern to apply * @param maxCount the maximum number of times the pattern should be applied to the graph * @return the resulting graph */ public static Graph applyPattern(Graph graph, PatternGraph pattern, int maxCount) { // TODO: implement Graph result = graph.clone(); return result; } /** * finds matches for a pattern in a graph. * * @param graph the graph to match the pattern on * @param pattern the pattern to match * @return a list of matches for the pattern in the graph */ public static ArrayList<Match> matchPattern(Graph graph, PatternGraph pattern) { ArrayList<Match> matches = new ArrayList<Match>(); // step 1: for every PatternNode, find all possible Nodes: ArrayList<ArrayList<Node>> couldMatch = new ArrayList<ArrayList<Node>>(); for (int i = 0; i < pattern.getPatternNodes().size(); ++i) { PatternNode patternNode = pattern.getPatternNodes().get(i); if (patternNode.getAction() == "create") { continue; } couldMatch.add(new ArrayList<Node>()); nodes: for (int j = 0; j < graph.getNodes().size(); ++j) { Node node = graph.getNodes().get(j); for (int k = 0; k < patternNode.getPatternAttributes().size(); ++k) { PatternAttribute patternAttribute = patternNode.getPatternAttributes().get(k); if (patternAttribute.getAction() == "create") { continue; } boolean attributeValueMatch = patternAttribute.getValue().equals(node.getAttribute(patternAttribute.getName())); if ((patternAttribute.isNegative() && attributeValueMatch) || (!patternAttribute.isNegative() && !attributeValueMatch)) { continue nodes; } } for (int k = 0; k < patternNode.getPatternEdges().size(); ++k) { PatternEdge patternEdge = patternNode.getPatternEdges().get(k); if (patternEdge.getAction() == "create" || patternEdge.isNegative()) { continue; } if (!node.getEdges().containsKey(patternEdge.getName())) { continue nodes; } } couldMatch.get(i).add(node); } if (couldMatch.get(i).size() < 1) { return matches; } } // step 2: verify the possible matches boolean canTryAnother = false; ArrayList<Integer> currentTry = new ArrayList<Integer>(); for (int i = 0; i < couldMatch.size(); ++i) { currentTry.add(0); } do { canTryAnother = false; HashMap<PatternNode, Node> mapping = new HashMap<PatternNode, Node>(); HashSet<Node> usedNodes = new HashSet<Node>(); boolean duplicateChoice = false; for (int i = 0; i < couldMatch.size(); ++i) { PatternNode patternNode = pattern.getPatternNodes().get(i); Node node = couldMatch.get(i).get(currentTry.get(i)); mapping.put(patternNode, node); if (usedNodes.contains(node)) { duplicateChoice = true; break; } usedNodes.add(node); } if (!duplicateChoice) { boolean fail = false; nodes: for (int i = 0; i < pattern.getPatternNodes().size(); ++i) { PatternNode sourcePatternNode = pattern.getPatternNodes().get(i); for (int j = 0; j < sourcePatternNode.getPatternEdges().size(); ++j) { PatternEdge patternEdge = sourcePatternNode.getPatternEdges().get(j); if (patternEdge.getAction() == "create") { continue; } boolean isThere = mapping.get(sourcePatternNode).getEdges(patternEdge.getName()).contains(mapping.get(patternEdge.getTarget())); if ((patternEdge.isNegative() && isThere) || (!patternEdge.isNegative() && !isThere)) { fail = true; break nodes; } } } if (!fail) { matches.add(new Match(graph, pattern, mapping)); } } for (int i = 0; i < currentTry.size(); ++i) { if (currentTry.get(i) < couldMatch.get(i).size() - 1) { currentTry.set(i, currentTry.get(i) + 1); for (int j = 0; j < i; ++j) { currentTry.set(j, 0); } canTryAnother = true; break; } } } while (canTryAnother); return matches; } /** * applies a pattern to a match, applying all 'create'- and 'delete'-actions specified in the pattern to the graph. * * @param match the match that was previously found * @return the resulting graph */ public static Graph applyMatch(Match match) { for (PatternNode patternNode: match.getPattern().getPatternNodes()) { Node matchedNode; switch (patternNode.getAction()) { case "remove": // remove match.getGraph().removeNode(match.getNodeMatch().get(patternNode)); continue; case "create": // create matchedNode = new Node(); break; default: // match matchedNode = match.getNodeMatch().get(patternNode); } for (PatternAttribute patternAttribute: patternNode.getPatternAttributes()) { switch (patternAttribute.getAction()) { case "remove": // remove matchedNode.removeAttribute(patternAttribute.getName()); break; case "create": // create matchedNode.setAttribute(patternAttribute.getName(), patternAttribute.getValue()); } } for (PatternEdge patternEdge: patternNode.getPatternEdges()) { switch (patternEdge.getAction()) { case "remove": // remove matchedNode.removeEdge(patternEdge.getName(), match.getNodeMatch().get(patternEdge.getTarget())); break; case "create": // create matchedNode.addEdge(patternEdge.getName(), match.getNodeMatch().get(patternEdge.getTarget())); } } } return match.getGraph(); } }
package org.pentaho.ui.xul.swt; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.WeakHashMap; import org.apache.commons.lang.NotImplementedException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.ByteArrayTransfer; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DragSourceListener; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.DropTargetListener; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.dnd.TransferData; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Widget; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulContainer; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.XulDomException; import org.pentaho.ui.xul.XulException; import org.pentaho.ui.xul.containers.XulDeck; import org.pentaho.ui.xul.containers.XulDialog; import org.pentaho.ui.xul.containers.XulRoot; import org.pentaho.ui.xul.dnd.DataTransfer; import org.pentaho.ui.xul.dnd.DropEffectType; import org.pentaho.ui.xul.dnd.DropEvent; import org.pentaho.ui.xul.dom.Document; import org.pentaho.ui.xul.dom.Element; import org.pentaho.ui.xul.impl.AbstractXulComponent; import org.pentaho.ui.xul.util.Orient; public class SwtElement extends AbstractXulComponent { private static final long serialVersionUID = -4407080035694005764L; private static final Log logger = LogFactory.getLog(SwtElement.class); // Per XUL spec, STRETCH is the default align value. private SwtAlign align = SwtAlign.STRETCH; protected Orient orient = Orient.HORIZONTAL; private int flex = 0; protected PropertyChangeSupport changeSupport = new PropertyChangeSupport(this); private boolean disabled; private static Map<String, Object> dndObjects = new WeakHashMap<String, Object>(); private static Map<String, SwtElement> dndSources = new WeakHashMap<String, SwtElement>(); public SwtElement(String tagName) { super(tagName); } @Override public void addChild(Element e) { super.addChild(e); if(e instanceof XulContainer){ AbstractSwtXulContainer container = (AbstractSwtXulContainer) e; if(container.initialized == false){ container.layout(); } } XulComponent comp = (XulComponent) e; Object mo = comp.getManagedObject(); if(mo != null){ if(mo instanceof Control){ if(((Control) mo) != getManagedObject() && getManagedObject() instanceof Composite){ ((Control) mo).setParent((Composite) getManagedObject()); } } else if(mo instanceof Viewer){ if(((Viewer) mo).getControl() != getManagedObject() && getManagedObject() instanceof Composite){ ((Viewer) mo).getControl().setParent((Composite) getManagedObject()); } } } if (initialized) { layout(); ((XulComponent) e).onDomReady(); } } public void addChildAt(Element c, int pos) { super.addChildAt(c, pos); if (initialized) { layout(); } } @Override public void removeChild(Element ele) { super.removeChild(ele); if (ele instanceof XulComponent) { XulComponent comp = (XulComponent)ele; if (comp.getManagedObject() instanceof Widget) { Widget thisWidget = (Widget) comp.getManagedObject(); if (thisWidget != null && !thisWidget.isDisposed()) { thisWidget.dispose(); } } } if (initialized) { layout(); } } public int getFlex() { return flex; } public void setFlex(int flex) { this.flex = flex; } public void setOrient(String orientation) { orient = Orient.valueOf(orientation.toUpperCase()); } public String getOrient() { return orient.toString(); } public Orient getOrientation() { return Orient.valueOf(getOrient()); } @Override public int getPadding() { return (super.getPadding() > -1) ? super.getPadding() : 2; } @Override public int getSpacing() { return (super.getSpacing() > -1) ? super.getSpacing() : 2; } @Override /** * This method attempts to follow the XUL rules * of layouting, using an SWT GridLayout. Any deviations * from the general rules are applied in overrides to this method. */ public void layout() { super.layout(); if (this instanceof XulDeck) { return; } if (!(getManagedObject() instanceof Composite)) { return; } Composite container = (Composite) getManagedObject(); // Total all flex values. // If every child has a flex value, then the GridLayout's columns // should be of equal width. everyChildIsFlexing gives us that boolean. int totalFlex = 0; int thisFlex = 0; boolean everyChildIsFlexing = true; for (Object child : this.getChildNodes()) { thisFlex = ((SwtElement) child).getFlex(); if (thisFlex <= 0) { everyChildIsFlexing = false; } totalFlex += thisFlex; } // By adding the total flex "points" with the number // of child controls, we get a close relative size, using // columns in the GridLayout. switch (orient) { case HORIZONTAL: int columnCount = this.getChildNodes().size() + totalFlex; GridLayout layout = new GridLayout(columnCount, everyChildIsFlexing); if(this.getPadding() > -1){ layout.marginWidth = this.getPadding(); layout.marginHeight = this.getPadding(); } if(this.getSpacing() > -1){ layout.horizontalSpacing = this.getSpacing(); layout.verticalSpacing = this.getSpacing(); } container.setLayout(layout); break; case VERTICAL: layout = new GridLayout(); if(this.getPadding() > -1){ layout.marginWidth = this.getPadding(); layout.marginHeight = this.getPadding(); } if(this.getSpacing() > -1){ layout.horizontalSpacing = this.getSpacing(); layout.verticalSpacing = this.getSpacing(); } container.setLayout(layout); break; } for (Object child : this.getChildNodes()) { SwtElement swtChild = (SwtElement) child; // some children have no object they are managing... skip these kids! Object mo = swtChild.getManagedObject(); if (mo == null || !(mo instanceof Control || mo instanceof Viewer) || swtChild instanceof XulDialog){ continue; } Control c = null; if(mo instanceof Control){ c = (Control) mo; } else if(mo instanceof Viewer){ c = ((Viewer) mo).getControl(); } GridData data = new GridData(); // How many columns or rows should the control span? Use the flex value plus // 1 "point" for the child itself. data.horizontalSpan = orient.equals(Orient.HORIZONTAL) ? swtChild.getFlex() + 1 : 1; data.verticalSpan = orient.equals(Orient.VERTICAL) ? swtChild.getFlex() + 1 : 1; // In XUL, flex defines how the children grab the excess space // in the container - therefore, we need to grab the excess space... switch (orient) { case HORIZONTAL: data.verticalAlignment = SWT.FILL; data.grabExcessVerticalSpace = true; break; case VERTICAL: data.horizontalAlignment = SWT.FILL; data.grabExcessHorizontalSpace = true; break; } if (swtChild.getFlex() > 0) { if(swtChild.getWidth() == 0){ data.grabExcessHorizontalSpace = true; data.horizontalAlignment = SWT.FILL; } if(swtChild.getHeight() == 0){ data.grabExcessVerticalSpace = true; data.verticalAlignment = SWT.FILL; } } if(swtChild.getWidth() > 0){ data.widthHint = swtChild.getWidth(); } if(swtChild.getHeight() > 0){ data.heightHint = swtChild.getHeight(); } // And finally, deal with the align attribute... // Align is the PARENT'S attribute, and affects the // opposite direction of the orientation. if (((XulComponent) swtChild).getAlign() != null) { SwtAlign swtAlign = SwtAlign.valueOf(((XulContainer) swtChild).getAlign().toString()); if (orient.equals(Orient.HORIZONTAL)) { if(swtChild.getHeight() < 0){ data.grabExcessVerticalSpace = true; } } else { //Orient.VERTICAL if(swtChild.getWidth() < 0){ data.grabExcessHorizontalSpace = true; } } } c.setLayoutData(data); } container.layout(true); } @Override /** * Important to understand that when using this method in the * SWT implementation: * * SWT adds new children positionally based on add order. This * means that a child that was added third in a list of 5 can't be * "replaced" to its third position in the dialog, it can only * be added to the end of the child list. * * Major SWT limitation. Replacement can only be used in * a limited number of cases. */ public void replaceChild(XulComponent oldElement, XulComponent newElement) throws XulDomException { super.replaceChild(oldElement, newElement); Widget thisWidget = (Widget) oldElement.getManagedObject(); if (!thisWidget.isDisposed()) { thisWidget.dispose(); } ((Control) newElement.getManagedObject()).setParent((Composite) this.getManagedObject()); layout(); } public void setOnblur(String method) { throw new NotImplementedException(); } public void addPropertyChangeListener(PropertyChangeListener listener) { changeSupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(listener); } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled= disabled; } public void adoptAttributes(XulComponent component) { throw new NotImplementedException(); } public void setMenu(final Menu menu){ //the generic impl... override if you need a more sophisticated handling of the menu if(getManagedObject() instanceof Control){ final Control c = (Control) getManagedObject(); c.addMouseListener(new MouseAdapter(){ @Override public void mouseDown(MouseEvent evt) { Control source = (Control) evt.getSource(); Point pt = source.getDisplay().map(source, null, new Point(evt.x, evt.y)); menu.setLocation(pt.x, pt.y); menu.setVisible(true); } }); } } public void setPopup(Menu menu){ //the generic impl... override if you need a more sophisticated handling of the popupmenu if(getManagedObject() instanceof Control){ ((Control) getManagedObject()).setMenu(menu); } } @Override public void onDomReady() { super.onDomReady(); if(this.context != null){ XulComponent pop = this.getDocument().getElementById(context); if(pop == null){ logger.error("could not find popup menu ("+context+") to add to this component"); } else { setPopup((Menu) pop.getManagedObject()); } } if(this.menu != null){ XulComponent pop = this.getDocument().getElementById(menu); if(pop == null){ logger.error("could not find popup menu ("+context+") to add to this component"); } else { setMenu((Menu) pop.getManagedObject()); } } } @Override public void setVisible(boolean visible) { super.setVisible(visible); if(getManagedObject() instanceof Control){ Control control = (Control) getManagedObject(); Object data = control.getLayoutData(); if(data instanceof GridData){ ((GridData) data).exclude = !visible; } control.setLayoutData(data); control.setVisible(visible); control.getParent().layout(true); } } /** * this class is used internally as a way to keep track of * the xultype, which is currently not exposed in the api but * could be used for grouping of drag and drop groups of widgets. */ private static class XulSwtDndType implements Serializable { private static final long serialVersionUID = 7356053006903234787L; String xultype; Object value; XulSwtDndType(String xultype, Object value, SwtElement xulSource) { this.xultype = xultype; UUID uuid = UUID.randomUUID(); dndObjects.put(uuid.toString(), value); dndSources.put(uuid.toString(), xulSource); this.value = uuid.toString(); } Object getValue() { return dndObjects.get(this.value); } SwtElement getXulSource() { return dndSources.get(this.value); } } /** * this class is used for transferring strings and xul bound objects * between swt xul elements. all elements being transported * are serialized and then deserialized. */ private static class SwtDndTypeTransfer extends ByteArrayTransfer { private static final String TYPENAME = "xul-transfer"; //$NON-NLS-1$ private static final int TYPEID = registerType(TYPENAME); private static SwtDndTypeTransfer _instance = new SwtDndTypeTransfer(); private SwtDndTypeTransfer() {} public static SwtDndTypeTransfer getInstance () { return _instance; } protected String[] getTypeNames(){ return new String[]{TYPENAME}; } protected int[] getTypeIds(){ return new int[] {TYPEID}; } protected boolean validate(Object object) { return object instanceof XulSwtDndType; } public void javaToNative(Object object, TransferData transferData) { if (object == null || !(object instanceof XulSwtDndType[])) return; if (isSupportedType(transferData)) { XulSwtDndType[] myTypes = (XulSwtDndType[]) object; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream writeOut = new ObjectOutputStream(out); writeOut.writeInt(myTypes.length); for (int i = 0; i < myTypes.length; i++) { writeOut.writeObject(myTypes[i]); } byte[] buffer = out.toByteArray(); writeOut.close(); super.javaToNative(buffer, transferData); } catch (IOException e) { e.printStackTrace(); } } } public Object nativeToJava(TransferData transferData){ if (isSupportedType(transferData)) { byte[] buffer = (byte[])super.nativeToJava(transferData); if (buffer == null) { return null; } ObjectInputStream readIn = null; try { readIn = new ObjectInputStream(new ByteArrayInputStream(buffer)); int c = readIn.readInt(); XulSwtDndType[] myData = new XulSwtDndType[c]; for (int i = 0; i < c; i++) { myData[i] = (XulSwtDndType)readIn.readObject(); } readIn.close(); return myData; } catch (Exception ex) { ex.printStackTrace(); return null; } finally { if(readIn != null){ try{ readIn.close(); } catch (IOException ignored){} } } } return null; } } /** * this call enables drag behavior for this element, it must be called by * the component after the managed swt object has been created */ protected void enableDrag(final DropEffectType effect) { //, final String xultype) { DragSource source = new DragSource(getDndObject(), lookupEffect(effect)); Transfer[] types = new Transfer[] {SwtDndTypeTransfer.getInstance()}; source.setTransfer(types); source.addDragListener(new DragSourceListener() { public void dragFinished(DragSourceEvent nativeEvent) { // if (nativeEvent.doit) { // onSwtDragFinished(nativeEvent, lookupXulEffect(nativeEvent.detail)); } public void dragSetData(DragSourceEvent nativeEvent) { if (SwtDndTypeTransfer.getInstance().isSupportedType(nativeEvent.dataType)) { // either strings or bindings, depending on whether elements are set List<Object> obj = getSwtDragData(); XulSwtDndType types[] = new XulSwtDndType[obj.size()]; for (int i = 0; i < obj.size(); i++) { // note, the "xultype" concept is currently disabled and not exposed in the // public API. The idea here was to allow the drag and drop // components to specify their groupings in a single panel. types[i] = new XulSwtDndType("xultype", obj.get(i), SwtElement.this); //$NON-NLS-1$ } nativeEvent.data = types; } } public void dragStart(DragSourceEvent nativeEvent) { DropEvent event = new DropEvent(); DataTransfer dt = new DataTransfer(); event.setDataTransfer(dt); dt.setData(getSwtDragData()); event.setAccepted(true); final String method = getOndrag(); if (method != null) { try{ Document doc = getDocument(); XulRoot window = (XulRoot) doc.getRootElement(); final XulDomContainer con = window.getXulDomContainer(); con.invoke(method, new Object[]{event}); } catch (XulException e){ logger.error("Error calling ondrop event: "+ method,e); //$NON-NLS-1$ } } if (!event.isAccepted()) { nativeEvent.doit = false; } } }); } /** * the native dnd object may not be the managed object, so allow * the child component to define it, defaulting to managed object * * @return dnd object */ protected Control getDndObject() { return (Control)getManagedObject(); } /** * called once the drag is finished * * @param nativeEvent swt event * @param effect drop effect, used to detemine if removing is necessary */ protected void onSwtDragFinished(DropEffectType effect) { throw new UnsupportedOperationException("unsupported element type: " + getClass()); //$NON-NLS-1$ } /** * called to get drag data * * @return list of draggable data, must be serializable */ protected List<Object> getSwtDragData() { throw new UnsupportedOperationException("unsupported element type: " + getClass()); //$NON-NLS-1$ } /** * this call enables drop behavior for this element. * it must be called by the component after the managed swt * object has been created */ protected void enableDrop() { // final String xultype) { DropTarget target = new DropTarget(getDndObject(), DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_DEFAULT); target.setTransfer(new Transfer[] {SwtDndTypeTransfer.getInstance()}); target.addDropListener(new DropTargetListener() { public void dragEnter(DropTargetEvent arg0) { arg0.detail = arg0.operations; } public void dragLeave(DropTargetEvent arg0) {} public void dragOperationChanged(DropTargetEvent arg0) {} public void dragOver(DropTargetEvent event) { onSwtDragOver(event); } public void drop(DropTargetEvent nativeEvent) { DropEvent event = new DropEvent(); DataTransfer dataTransfer = new DataTransfer(); XulSwtDndType types[] = (XulSwtDndType[])nativeEvent.data; SwtElement xulDndSource = null; try { if (types != null) { // && types[0].xultype.equals(xultype)) { List<Object> objs = new ArrayList<Object>(); for (int i = 0; i < types.length; i++) { if (i == 0) { xulDndSource = types[i].getXulSource(); } objs.add(types[i].getValue()); } dataTransfer.setData(objs); dataTransfer.setDropEffect(lookupXulEffect(nativeEvent.detail)); } else { nativeEvent.detail = DND.DROP_NONE; return; } } catch (Exception e) { e.printStackTrace(); } event.setDataTransfer(dataTransfer); event.setAccepted(true); event.setNativeEvent(nativeEvent); resolveDndParentAndIndex(event); final String method = getOndrop(); if (method != null) { try{ Document doc = getDocument(); XulRoot window = (XulRoot) doc.getRootElement(); final XulDomContainer con = window.getXulDomContainer(); con.invoke(method, new Object[]{event}); } catch (XulException e){ logger.error("Error calling ondrop event: "+ method,e); //$NON-NLS-1$ } } if (!event.isAccepted()) { nativeEvent.detail = DND.DROP_NONE; return; } // remove the item from the list if (xulDndSource == null) { throw new RuntimeException("DND Source is null"); } xulDndSource.onSwtDragFinished(lookupXulEffect(nativeEvent.detail)); onSwtDragDropAccepted(event); } public void dropAccept(DropTargetEvent arg0) {} }); } /** * used by child classes on a drop event * to determine the parent and index of the drop. * * Currently only used by SwtTree in hierarchial mode. * * @param event */ protected void resolveDndParentAndIndex(DropEvent event) { // not necessary, but is used by tree and list to specify the parent and index } /** * used by child classes on the drag over event in swt * * @param nativeEvent the native swt event */ protected void onSwtDragOver(DropTargetEvent nativeEvent) { // not necessary, but used by tree and list to control types of DND behavior } /** * this method is called once the drop has been accepted * @param event the drop event */ protected void onSwtDragDropAccepted(DropEvent event) { throw new UnsupportedOperationException("unsupported element type: " + getClass()); //$NON-NLS-1$ } /** * Maps a xul effect to SWT effect * * @param effect xul effect * @return swt effect */ private int lookupEffect(DropEffectType effect) { switch(effect) { case NONE: return DND.DROP_NONE; case MOVE: return DND.DROP_MOVE; case LINK: return DND.DROP_LINK; case COPY: default: return DND.DROP_COPY; } } /** * maps a swt effect to a xul effect * * @param effect swt effect * @return xul effect */ private DropEffectType lookupXulEffect(int effect) { switch(effect) { case DND.DROP_NONE: return DropEffectType.NONE; case DND.DROP_MOVE: return DropEffectType.MOVE; case DND.DROP_LINK: return DropEffectType.LINK; case DND.DROP_COPY: default: return DropEffectType.COPY; } } @Override public void setTooltiptext(String tooltip) { super.setTooltiptext(tooltip); if(getManagedObject() instanceof Control){ ((Control) getManagedObject()).setToolTipText(tooltip); } } }
package de.unitrier.st.soposthistory.tests; import de.unitrier.st.soposthistory.gt.MetricComparison; import de.unitrier.st.soposthistory.gt.MetricComparisonManager; import de.unitrier.st.soposthistory.gt.Statistics; import de.unitrier.st.soposthistory.version.PostVersionList; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import java.util.regex.Matcher; import static de.unitrier.st.soposthistory.util.Util.getClassLogger; import static org.junit.jupiter.api.Assertions.*; @Disabled class DisabledTests { private static Logger logger; private static Path pathToOldMetricComparisons = Paths.get( "testdata", "metrics_comparison", "results_metric_comparison_old.csv" ); static { try { logger = getClassLogger(DisabledTests.class); } catch (IOException e) { e.printStackTrace(); } } @Test void testCompareMetricComparisonManagerWithComparisonFromOldProject() { MetricComparisonManager manager = MetricComparisonManager.create( "TestManager", BlockLifeSpanAndGroundTruthTest.pathToPostIdList, BlockLifeSpanAndGroundTruthTest.pathToPostHistory, BlockLifeSpanAndGroundTruthTest.pathToGroundTruth, true ); List<Integer> postHistoryIds_3758880 = manager.getPostVersionLists().get(3758880).getPostHistoryIds(); List<Integer> postHistoryIds_22037280 = manager.getPostVersionLists().get(22037280).getPostHistoryIds(); manager.compareMetrics(); manager.writeToCSV(BlockLifeSpanAndGroundTruthTest.outputDir); CSVParser csvParser; try { csvParser = CSVParser.parse( pathToOldMetricComparisons.toFile(), StandardCharsets.UTF_8, MetricComparisonManager.csvFormatMetricComparison.withFirstRecordAsHeader() ); csvParser.getHeaderMap(); List<CSVRecord> records = csvParser.getRecords(); for (CSVRecord record : records) { String metric = record.get("metric"); Double threshold = Double.valueOf(record.get("threshold")); // comparison manager computes only thresholds mod 0.10 by now so unequal thresholds will be skipped if ((int) (threshold * 100) % 10 != 0) { continue; } Integer postId = Integer.valueOf(record.get("postid")); Integer postHistoryId = null; Integer truePositivesText = null; Integer trueNegativesText = null; Integer falsePositivesText = null; Integer falseNegativesText = null; Integer truePositivesCode = null; Integer trueNegativesCode = null; Integer falsePositivesCode = null; Integer falseNegativesCode = null; try { postHistoryId = Integer.valueOf(record.get("posthistoryid")); truePositivesText = Integer.valueOf(record.get("#truepositivestext")); trueNegativesText = Integer.valueOf(record.get("#truenegativestext")); falsePositivesText = Integer.valueOf(record.get("#falsepositivestext")); falseNegativesText = Integer.valueOf(record.get("#falsenegativestext")); truePositivesCode = Integer.valueOf(record.get("#truepositivescode")); trueNegativesCode = Integer.valueOf(record.get("#truenegativescode")); falsePositivesCode = Integer.valueOf(record.get("#falsepositivescode")); falseNegativesCode = Integer.valueOf(record.get("#falsenegativescode")); } catch (NumberFormatException ignored) { } MetricComparison tmpMetricComparison = manager.getMetricComparison(postId, metric, threshold); if (postHistoryId == null) { List<Integer> postHistoryIds = null; if (postId == 3758880) { postHistoryIds = postHistoryIds_3758880; } else if (postId == 22037280) { postHistoryIds = postHistoryIds_22037280; } assertNotNull(postHistoryIds); for (Integer tmpPostHistoryId : postHistoryIds) { MetricComparison.MetricResult resultsText = tmpMetricComparison.getResultsText(tmpPostHistoryId); assertNull(resultsText.getTruePositives()); assertNull(resultsText.getFalsePositives()); assertNull(resultsText.getTrueNegatives()); assertNull(resultsText.getFalseNegatives()); MetricComparison.MetricResult resultsCode = tmpMetricComparison.getResultsCode(tmpPostHistoryId); assertNull(resultsCode.getTruePositives()); assertNull(resultsCode.getFalsePositives()); assertNull(resultsCode.getTrueNegatives()); assertNull(resultsCode.getFalseNegatives()); } } else { // TODO: Check true negatives for text and code MetricComparison.MetricResult resultsText = tmpMetricComparison.getResultsText(postHistoryId); assertEquals(truePositivesText, resultsText.getTruePositives()); assertEquals(falsePositivesText, resultsText.getFalsePositives()); assertEquals(falseNegativesText, resultsText.getFalseNegatives()); MetricComparison.MetricResult resultsCode = tmpMetricComparison.getResultsCode(postHistoryId); assertEquals(truePositivesCode, resultsCode.getTruePositives()); assertEquals(falsePositivesCode, resultsCode.getFalsePositives()); assertEquals(falseNegativesCode, resultsCode.getFalseNegatives()); } } } catch (IOException e) { e.printStackTrace(); } } @Test void testSmallSamplesParsable() { testSamples(Statistics.pathsToSmallSamplesFiles); } @Test void testLargeSamplesParsable() { testSamples(Statistics.pathsToLargeSamplesFiles); } private void testSamples(List<Path> paths) { for (Path currentPath : paths) { File[] postHistoryFiles = currentPath.toFile().listFiles( (dir, name) -> name.matches(PostVersionList.fileNamePattern.pattern()) ); assertNotNull(postHistoryFiles); for (File postHistoryFile : postHistoryFiles) { Matcher fileNameMatcher = PostVersionList.fileNamePattern.matcher(postHistoryFile.getName()); if (fileNameMatcher.find()) { int postId = Integer.parseInt(fileNameMatcher.group(1)); // no exception should be thrown for the following two lines PostVersionList postVersionList = PostVersionList.readFromCSV(currentPath, postId, -1); postVersionList.normalizeLinks(); assertTrue(postVersionList.size() > 0); } } } } @Test void comparePossibleMultipleConnectionsWithOldComparisonProject() { // This test case "fails" because the extraction of post blocks has been changed since the creation of the old file. File oldFile = Paths.get(Statistics.pathToMultipleConnectionsDir.toString(), "multiple_possible_connections_old.csv").toFile(); File newFile = Statistics.pathToMultipleConnectionsFile.toFile(); CSVParser csvParserOld, csvParserNew; try { // parse old records csvParserOld = CSVParser.parse( oldFile, StandardCharsets.UTF_8, Statistics.csvFormatMultipleConnections.withFirstRecordAsHeader() .withHeader("postId", "postHistoryId", "localId", "blockTypeId", "possiblePredOrSuccLocalIds", "numberOfPossibleSuccessorsOrPredecessors") ); List<CSVRecord> oldRecords = csvParserOld.getRecords(); List<MultipleConnectionsResultOld> oldResults = new ArrayList<>(oldRecords.size()); for (CSVRecord record : oldRecords) { int postId = Integer.parseInt(record.get("postId")); int postHistoryId = Integer.parseInt(record.get("postHistoryId")); int localId = Integer.parseInt(record.get("localId")); int postBlockTypeId = Integer.parseInt(record.get("blockTypeId")); String possiblePredOrSuccLocalIds = record.get("possiblePredOrSuccLocalIds"); int numberOfPossibleSuccessorsOrPredecessors = Integer.parseInt(record.get("numberOfPossibleSuccessorsOrPredecessors")); oldResults.add(new MultipleConnectionsResultOld(postId, postHistoryId, localId, postBlockTypeId, possiblePredOrSuccLocalIds, numberOfPossibleSuccessorsOrPredecessors)); } // parse new records csvParserNew = CSVParser.parse( newFile, StandardCharsets.UTF_8, Statistics.csvFormatMultipleConnections.withFirstRecordAsHeader() ); List<CSVRecord> newRecords = csvParserNew.getRecords(); List<MultipleConnectionsResultNew> newResults = new ArrayList<>(newRecords.size()); for (CSVRecord record : newRecords) { int postId = Integer.parseInt(record.get("PostId")); int postHistoryId = Integer.parseInt(record.get("PostHistoryId")); int localId = Integer.parseInt(record.get("LocalId")); int postBlockTypeId = Integer.parseInt(record.get("PostBlockTypeId")); int possiblePredecessorsCount = Integer.parseInt(record.get("PossiblePredecessorsCount")); int possibleSuccessorsCount = Integer.parseInt(record.get("PossibleSuccessorsCount")); String possiblePredecessorLocalIds = record.get("PossiblePredecessorLocalIds"); String possibleSuccessorLocalIds = record.get("PossibleSuccessorLocalIds"); newResults.add(new MultipleConnectionsResultNew(postId, postHistoryId, localId, postBlockTypeId, possiblePredecessorsCount, possibleSuccessorsCount, possiblePredecessorLocalIds, possibleSuccessorLocalIds)); } // compare old and new results for (MultipleConnectionsResultNew multipleConnectionsResultNew : newResults) { int newPostId = multipleConnectionsResultNew.postId; int newPostHistoryId = multipleConnectionsResultNew.postHistoryId; int newLocalId = multipleConnectionsResultNew.localId; int newPostBlockTypeId = multipleConnectionsResultNew.postBlockTypeId; int newPossiblePredecessorsCount = multipleConnectionsResultNew.possiblePredecessorsCount; int newPossibleSuccessorsCount = multipleConnectionsResultNew.possibleSuccessorsCount; String newPossiblePredecessorLocalIds = multipleConnectionsResultNew.possiblePredecessorLocalIds; String newPossibleSuccessorLocalIds = multipleConnectionsResultNew.possibleSuccessorLocalIds; for (MultipleConnectionsResultOld multipleConnectionsResultOld : oldResults) { int oldPostId = multipleConnectionsResultOld.postId; int oldPostHistoryId = multipleConnectionsResultOld.postHistoryId; int oldLocalId = multipleConnectionsResultOld.localId; int oldPostBlockTypeId = multipleConnectionsResultOld.postBlockTypeId; int oldNumberOfPossibleSuccessorsOrPredecessors = multipleConnectionsResultOld.numberOfPossibleSuccessorsOrPredecessors; String oldPossiblePredOrSuccLocalIds = multipleConnectionsResultOld.possiblePredOrSuccLocalIds; if (newPostId == oldPostId && newPostHistoryId == oldPostHistoryId && newLocalId == oldLocalId) { assertEquals(newPostBlockTypeId, oldPostBlockTypeId); if (oldPossiblePredOrSuccLocalIds.equals(newPossiblePredecessorLocalIds)) { assertEquals(oldNumberOfPossibleSuccessorsOrPredecessors, newPossiblePredecessorsCount); } else if (oldPossiblePredOrSuccLocalIds.equals(newPossibleSuccessorLocalIds)) { assertEquals(oldNumberOfPossibleSuccessorsOrPredecessors, newPossibleSuccessorsCount); } else { logger.warning("Entry (" + newPostId + "," + newPostHistoryId + "," + newLocalId + ") in new file differs from old file with multiple possible connections."); } break; } } } } catch (IOException e) { e.printStackTrace(); } } private class MultipleConnectionsResultOld { int postId; int postHistoryId; int localId; int postBlockTypeId; String possiblePredOrSuccLocalIds; int numberOfPossibleSuccessorsOrPredecessors; MultipleConnectionsResultOld(int postId, int postHistoryId, int localId, int postBlockTypeId, String possiblePredOrSuccLocalIds, int numberOfPossibleSuccessorsOrPredecessors) { this.postId = postId; this.postHistoryId = postHistoryId; this.localId = localId; this.postBlockTypeId = postBlockTypeId; this.possiblePredOrSuccLocalIds = possiblePredOrSuccLocalIds; this.numberOfPossibleSuccessorsOrPredecessors = numberOfPossibleSuccessorsOrPredecessors; } } private class MultipleConnectionsResultNew { int postId; int postHistoryId; int localId; int postBlockTypeId; int possiblePredecessorsCount; int possibleSuccessorsCount; String possiblePredecessorLocalIds; String possibleSuccessorLocalIds; MultipleConnectionsResultNew(int postId, int postHistoryId, int localId, int postBlockTypeId, int possiblePredecessorsCount, int possibleSuccessorsCount, String possiblePredecessorLocalIds, String possibleSuccessorLocalIds) { this.postId = postId; this.postHistoryId = postHistoryId; this.localId = localId; this.postBlockTypeId = postBlockTypeId; this.possiblePredecessorsCount = possiblePredecessorsCount; this.possibleSuccessorsCount = possibleSuccessorsCount; this.possiblePredecessorLocalIds = possiblePredecessorLocalIds; this.possibleSuccessorLocalIds = possibleSuccessorLocalIds; } } }
package org.gnode.nix.internal; import org.bytedeco.javacpp.Loader; import org.bytedeco.javacpp.Pointer; import org.bytedeco.javacpp.annotation.*; /** * <h1>OptionalUtils</h1> * Low level wrapper to Boost optionals. */ @Properties(value = { @Platform(include = {"<boost/optional.hpp>"}), @Platform(value = "linux"), @Platform(value = "windows")}) public class OptionalUtils { static { Loader.load(); } // Optional Double /** * <h1>OptionalDouble</h1> * Low level <tt>boost::optional&lt;double&gt;</tt> wrapper */ @Name("boost::optional<double>") public static class OptionalDouble extends Pointer { static { Loader.load(); } /** * Get double from the optional. Use this only after calling {@link OptionalDouble#isPresent()}. * * @return double data */ public native @Name("get") double getDouble(); /** * To check if the data is present. * * @return True if data is available, False otherwise. */ public native @Name("is_initialized") @Cast("bool") boolean isPresent(); } // Optional String /** * <h1>OptionalString</h1> * Low level <tt>boost::optional&lt;string&gt;</tt> wrapper */ @Name("boost::optional<std::string>") public static class OptionalString extends Pointer { static { Loader.load(); } /** * Get string from the optional. Use this only after calling {@link OptionalString#isPresent()}. * * @return return string */ public native @Name("get") @StdString String getString(); /** * To check if the data is present. * * @return True if data is available, False otherwise. */ public native @Name("is_initialized") @Cast("bool") boolean isPresent(); } }
package org.icinga.plugin.oracle; import static org.icinga.plugin.oracle.NagiosStatus.CRITICAL; import static org.icinga.plugin.oracle.NagiosStatus.OK; import static org.icinga.plugin.oracle.NagiosStatus.UNKNOWN; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Main class for Nagios checks. * * @author Aparna Chaudhary * @author David Webb */ public class CheckOracle { private static final Logger logger = LoggerFactory.getLogger(CheckOracle.class); boolean debug = false; public static void main(String args[]) { CheckOracle checkOracle = new CheckOracle(); checkOracle.parseOptions(args); } @SuppressWarnings("static-access") private void parseOptions(String[] args) { Options options = null; try { options = new Options(); options.addOption("h", "help", false, "Print help for this application"); options.addOption(OptionBuilder.withDescription("Option to enable debugging [true|false]").withLongOpt("debug") .withType(Boolean.class).hasArg().create('d')); options.addOption("D", false, "Enable output of Nagios performance data"); options.addOption(OptionBuilder.isRequired(true).withDescription("The database hostname to connect to") .withLongOpt("host").withType(String.class).hasArg().create('H')); options.addOption(OptionBuilder.isRequired(true).withDescription("The database listener port").withLongOpt("port") .withType(Number.class).hasArg().create("P")); options.addOption(OptionBuilder.isRequired(true).withDescription("The database instance name") .withLongOpt("instance").withType(String.class).hasArg().create("I")); options.addOption(OptionBuilder.isRequired(true).withDescription("The username you want to login as") .withLongOpt("user").withType(String.class).hasArg().create("u")); options.addOption(OptionBuilder.isRequired(true).withDescription("The password for the user") .withLongOpt("password").withType(String.class).hasArg().create("p")); options.addOption(OptionBuilder.isRequired(true).withDescription("The warning threshold you want to set") .withType(String.class).hasArg().create("W")); options.addOption(OptionBuilder.isRequired(true).withDescription("The critical threshold you want to set") .withType(String.class).hasArg().create("C")); OptionGroup checkOptionGroup = new OptionGroup(); checkOptionGroup.addOption( OptionBuilder.isRequired(false).withDescription("The tablespace to check, pass ALL for all tablespaces") .withLongOpt("tablespace").withType(String.class).hasArg().create("t")); checkOptionGroup.addOption(OptionBuilder.isRequired(false) .withDescription("The username for which session count to check, pass ALL to count all sessions") .withLongOpt("sessions").withType(String.class).hasArg().create("s")); checkOptionGroup.addOption( OptionBuilder.isRequired(false).withDescription("Check that a connection can be made to the database.") .withLongOpt("tns-listener-check").create("tns")); options.addOptionGroup(checkOptionGroup); BasicParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption('h')) { printHelp(options); } if (commandLine.hasOption('d')) { debug = Boolean.valueOf(commandLine.getOptionValue('d')); } String hostname = commandLine.getOptionValue('H'); Integer port = ((Number) commandLine.getParsedOptionValue("P")).intValue(); String instanceName = commandLine.getOptionValue('I'); String username = commandLine.getOptionValue('u'); String password = commandLine.getOptionValue('p'); executeCheck(commandLine, debug, hostname, port, instanceName, username, password); } catch (ParseException e) { printHelp(options); System.exit(UNKNOWN.getCode()); } } /** * Executes the check based on provided options * * @param commandLine * @param debug flag to enable debug logging * @param hostname oracle server host * @param port listener port * @param instanceName instance name * @param username DBA user name * @param password password */ private void executeCheck(CommandLine commandLine, boolean debug, String hostname, Integer port, String instanceName, String username, String password) { Connection conn = null; try { String warning = commandLine.getOptionValue('W'); String crtical = commandLine.getOptionValue('C'); if (commandLine.hasOption("tns")) { try { conn = getConnection(hostname, port, instanceName, username, password); System.out.println(String.format("OK - Connected to %s (%s)", conn.getMetaData().getDatabaseProductName(), conn.getMetaData().getDatabaseProductVersion())); System.exit(OK.getCode()); } catch (SQLException e) { System.out.println("Error: Unable to connect to database - " + e.getMessage()); System.exit(CRITICAL.getCode()); } } else { conn = getConnection(hostname, port, instanceName, username, password); } if (commandLine.hasOption('t')) { String tablespace = commandLine.getOptionValue('t'); if (tablespace.equalsIgnoreCase("ALL")) { CheckTablespaces.performCheck(conn, warning, crtical, debug); } else { CheckTablespace.performCheck(conn, tablespace, warning, crtical, debug); } } else if (commandLine.hasOption('s')) { String userToCheck = commandLine.getOptionValue('s'); if (userToCheck.equalsIgnoreCase("ALL")) { CheckDatabaseSessions.performCheck(conn, warning, crtical, debug); } else { CheckUserSessions.performCheck(conn, userToCheck, warning, crtical, debug); } } else { System.err.println("Error: Invalid option"); System.exit(UNKNOWN.getCode()); } } catch (IllegalArgumentException e) { System.out.println(String.format("UNKNOWN - %s", e.getMessage())); System.exit(UNKNOWN.getCode()); } catch (Exception e) { if (debug) { logger.error("Failed to execute check", e); } System.err.println("Error: Failed to execute check" + e); System.exit(UNKNOWN.getCode()); } finally { try { if (conn != null && !conn.isClosed()) { conn.close(); } } catch (SQLException e) { System.err.println("Error: Failed to close JDBC connection"); System.exit(UNKNOWN.getCode()); } } } /** * Print help text */ public void printHelp(final Options options) { final String commandLineSyntax = "check_oracle"; final HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp(commandLineSyntax, options, true); } /** * Gets a SQL connection based on input parameters * * @param hostname oracle server host * @param port listener port * @param instance instance name * @param username DBA user name * @param password password * @return SQL connection * @throws SQLException thrown when SQL connection cannot be established */ protected Connection getConnection(String hostname, Integer port, String instance, String username, String password) throws SQLException { try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { System.err.println("Error: Failed to load JDBC driver."); System.err.println(e); System.exit(UNKNOWN.getCode()); } if (debug) { logger.debug("Connection URL: " + String.format("jdbc:oracle:thin:@%s:%s:%s", hostname, port, instance)); } String connUrl = String.format("jdbc:oracle:thin:@%s:%s:%s", hostname, port, instance); Connection connection = DriverManager.getConnection(connUrl, username, password); return connection; } }
package org.jboss.test.selenium.actions; import org.jboss.test.selenium.framework.AjaxSelenium; import org.jboss.test.selenium.geometry.Point; import org.jboss.test.selenium.locator.ElementLocator; import org.jboss.test.selenium.waiting.Wait; import org.jboss.test.selenium.waiting.Wait.Waiting; public class Drag { // specifies phase in which is dragging state private int phase; private AjaxSelenium selenium; private ElementLocator itemToDrag; private ElementLocator dropTarget; private int x; private int y; private final int STEPS = 5; private final int FIRST_STEP = 2; private final Waiting wait = Wait.timeout(10); /** * @param selenium * initialized and started Selenium instance * @param itemToDrag * item to drag * @param dropTarget * target of item dragging */ public Drag(AjaxSelenium selenium, ElementLocator itemToDrag, ElementLocator dropTarget) { this.phase = 0; this.selenium = selenium; this.itemToDrag = itemToDrag; this.dropTarget = dropTarget; x = selenium.getElementPositionLeft(dropTarget) - selenium.getElementPositionLeft(itemToDrag); y = selenium.getElementPositionTop(dropTarget) - selenium.getElementPositionTop(itemToDrag); } /** * Starts first phase of dragging. * * Simulate left mouse button pressing and small initial movement. */ public void start() { process(0); } /** * Starts second phase of dragging. * * If there is some unfinished preceding phases, it will be done before this * phase. * * Simulate movement of mouse cursor out of the item that ve want to drag. */ public void mouseOut() { process(1); } /** * Starts third phase of dragging. * * If there is some unfinished preceding phases, it will be done before this * phase. * * Simulate movement of mouse cursor near the target item. */ public void move() { process(2); } /** * Starts fourth phase of dragging. * * If there is some unfinished preceding phases, it will be done before this * phase. */ public void enter() { process(3); } /** * Last phase of dragging. * * If there is some unfinished preceding phases, it will be done before this * phase. * * Drop the item to target. */ public void drop() { process(4); } /** * Holds whole process of dragging serialized to one switch condition. * * If some phase is called by its number, it will be recognized, that is * possible to process this step. * * Internally is used counter 'phase' which will be decreased when passed to * a new phase. Switch condition breaks when will finished in requesting * phase. */ private void process(int request) { if (request < phase) { throw new RuntimeException(); } Point point; switch (phase) { case 0: // START selenium.mouseDown(itemToDrag); point = new Point((x < 0) ? FIRST_STEP : -FIRST_STEP, (y < 0) ? FIRST_STEP : -FIRST_STEP); selenium.mouseMoveAt(itemToDrag, point); if (request < ++phase) break; case 1: // MOUSE OUT selenium.mouseOut(itemToDrag); if (request < ++phase) break; case 2: // MOVE for (int i = 0; i < STEPS; i++) { point = new Point(x * i / STEPS, y * i / STEPS); selenium.mouseMoveAt(itemToDrag, point); wait.waitForTimeout(); } if (request < ++phase) break; case 3: // ENTER point = new Point(x,y); selenium.mouseMoveAt(itemToDrag, point); selenium.mouseOver(dropTarget); if (request < ++phase) break; case 4: // DROP selenium.mouseUp(dropTarget); if (request < ++phase) break; } } }
package org.jfree.chart.servlet; import java.io.File; import java.io.Serializable; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener; /** * Used for deleting charts from the temporary directory when the users session * expires. */ public class ChartDeleter implements HttpSessionBindingListener, Serializable { /** The chart names. */ private List<String> chartNames = new java.util.ArrayList<String>(); /** * Blank constructor. */ public ChartDeleter() { super(); } /** * Add a chart to be deleted when the session expires * * @param filename the name of the chart in the temporary directory to be * deleted. */ public void addChart(String filename) { this.chartNames.add(filename); } /** * Checks to see if a chart is in the list of charts to be deleted * * @param filename the name of the chart in the temporary directory. * * @return A boolean value indicating whether the chart is present in the * list. */ public boolean isChartAvailable(String filename) { return (this.chartNames.contains(filename)); } /** * Binding this object to the session has no additional effects. * * @param event the session bind event. */ @Override public void valueBound(HttpSessionBindingEvent event) { // do nothing } /** * When this object is unbound from the session (including upon session * expiry) the files that have been added to the ArrayList are iterated * and deleted. * * @param event the session unbind event. */ @Override public void valueUnbound(HttpSessionBindingEvent event) { File tempDir = new File(System.getProperty("java.io.tmpdir")); for (String filename : this.chartNames) { File file = new File(tempDir, filename); if (file.exists()) { file.delete(); } } } }
package org.jtrfp.trcl.core; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Set; import org.jtrfp.trcl.coll.CollectionActionDispatcher; import org.springframework.stereotype.Component; @Component public class ControllerInputs { private final HashMap<String,ControllerInput> inputs = new HashMap<String,ControllerInput>(32); private final CollectionActionDispatcher<String> inputNames = new CollectionActionDispatcher<String>(new HashSet<String>()); /** * Obtains an input of the specified name or creates and registers a new one if not available. * @param name * @return * @since Nov 12, 2015 */ public ControllerInput getControllerInput(final String name){ ControllerInput result; if(!inputs.containsKey(name)){ result = new DefaultControllerInput(name); inputs.put(name, result); inputNames.add(name); }else result = inputs.get(name); return result; }//end declareInput(...) public Set<Entry<String,ControllerInput>> getInputs(){ return inputs.entrySet(); } public CollectionActionDispatcher<String> getInputNames(){ return inputNames; } private class DefaultControllerInput implements ControllerInput{ private final String controllerName; private double state = 0; private final PropertyChangeSupport pcs = new PropertyChangeSupport(this); public DefaultControllerInput(String controllerName){ this.controllerName=controllerName; }//end constructor @Override public double getState() throws IllegalStateException { return state; }//end getState() @Override public String getName() { return controllerName; }//end getName() @Override public void setState(double newState) { pcs.firePropertyChange(ControllerInput.STATE, this.state, newState); this.state = newState; }//end setState(...) @Override public void addPropertyChangeListener(PropertyChangeListener l) { pcs.addPropertyChangeListener(l); } @Override public void removePropertyChangeListener(PropertyChangeListener l) { pcs.removePropertyChangeListener(l); } }//end DefaultControllerInput }//end ControllerInputs
package org.phoenixframework.channels; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import okhttp3.*; import okhttp3.ws.WebSocket; import okhttp3.ws.WebSocketCall; import okhttp3.ws.WebSocketListener; import okio.Buffer; import java.io.IOException; import java.util.*; import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level; import java.util.logging.Logger; public class Socket { public class PhoenixWSListener implements WebSocketListener { @Override public void onClose(final int code, final String reason) { try { LOG.log(Level.FINE, "WebSocket onClose {0}/{1}", new Object[]{code, reason}); cancelReconnectTimer(); cancelHeartbeatTimer(); Socket.this.webSocket = null; for (final ISocketCloseCallback callback : socketCloseCallbacks) { callback.onClose(); } } catch (Throwable e2) { handleOnSocketException("onClose", e2); } } @Override public void onFailure(final IOException e, final Response response) { LOG.log(Level.WARNING, "WebSocket connection error", e); try { try { for (final IErrorCallback callback : errorCallbacks) { //TODO if there are multiple errorCallbacks do we really want to trigger //the same channel error callbacks multiple times? triggerChannelError(); callback.onError(e.toString()); } } finally { cancelReconnectTimer(); cancelHeartbeatTimer(); // Assume closed on failure if (Socket.this.webSocket != null) { try { Socket.this.webSocket.close(1001 /*CLOSE_GOING_AWAY*/, "EOF received"); } catch (IOException ioe) { LOG.log(Level.WARNING, "Failed to explicitly close following failure"); } finally { Socket.this.webSocket = null; } } if (reconnectOnFailure) { scheduleReconnectTimer(); } } } catch (Throwable e2) { handleOnSocketException("onFailure", e2); } } @Override public void onMessage(final ResponseBody payload) throws IOException { LOG.log(Level.FINE, "Envelope received: {0}", payload); try { if (payload.contentType() == WebSocket.TEXT) { final Envelope envelope = objectMapper.readValue(payload.byteStream(), Envelope.class); synchronized (channels) { for (final Channel channel : channels) { if (channel.isMember(envelope.getTopic())) { channel.trigger(envelope.getEvent(), envelope); } } } for (final IMessageCallback callback : messageCallbacks) { callback.onMessage(envelope); } } } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to read message payload", e); } catch (ConcurrentModificationException e) { LOG.log(Level.SEVERE, "ConcurrentModificationException!", e); } catch (Throwable e2) { handleOnSocketException("onMessage", e2); } finally { payload.close(); } } @Override public void onOpen(final WebSocket webSocket, final Response response) { try { LOG.log(Level.FINE, "WebSocket onOpen: {0}", webSocket); Socket.this.webSocket = webSocket; cancelReconnectTimer(); startHeartbeatTimer(); for (final ISocketOpenCallback callback : socketOpenCallbacks) { callback.onOpen(); } Socket.this.flushSendBuffer(); } catch (Throwable e2) { handleOnSocketException("onOpen", e2); } } @Override public void onPong(final Buffer payload) { LOG.log(Level.INFO, "PONG received: {0}", payload); } } private static final Logger LOG = Logger.getLogger(Socket.class.getName()); public static final int RECONNECT_INTERVAL_MS = 5000; private static final int DEFAULT_HEARTBEAT_INTERVAL = 7000; private final List<Channel> channels = new ArrayList<>(); private String endpointUri = null; private final Set<IErrorCallback> errorCallbacks = Collections .newSetFromMap(new HashMap<IErrorCallback, Boolean>()); private final int heartbeatInterval; private TimerTask heartbeatTimerTask = null; private final OkHttpClient httpClient = new OkHttpClient(); private final Set<IMessageCallback> messageCallbacks = Collections .newSetFromMap(new HashMap<IMessageCallback, Boolean>()); private final ObjectMapper objectMapper = new ObjectMapper(); private boolean reconnectOnFailure = true; private TimerTask reconnectTimerTask = null; private int refNo = 1; private final LinkedBlockingQueue<RequestBody> sendBuffer = new LinkedBlockingQueue<>(); private final Set<ISocketCloseCallback> socketCloseCallbacks = Collections .newSetFromMap(new HashMap<ISocketCloseCallback, Boolean>()); private final Set<ISocketOpenCallback> socketOpenCallbacks = Collections .newSetFromMap(new HashMap<ISocketOpenCallback, Boolean>()); private OnSocketThrowExceptionListener onSocketThrowExceptionListener; private Timer timer = null; private WebSocket webSocket = null; /** * Annotated WS Endpoint. Private member to prevent confusion with "onConn*" registration * methods. */ private final PhoenixWSListener wsListener = new PhoenixWSListener(); public Socket(final String endpointUri) throws IOException { this(endpointUri, DEFAULT_HEARTBEAT_INTERVAL); } public Socket(final String endpointUri, final int heartbeatIntervalInMs) { LOG.log(Level.FINE, "PhoenixSocket({0})", endpointUri); this.endpointUri = endpointUri; this.heartbeatInterval = heartbeatIntervalInMs; this.timer = new Timer("Reconnect Timer for " + endpointUri); } /** * Retrieve a channel instance for the specified topic * * @param topic The channel topic * @param payload The message payload * @return A Channel instance to be used for sending and receiving events for the topic */ public Channel chan(final String topic, final JsonNode payload) { LOG.log(Level.FINE, "chan: {0}, {1}", new Object[]{topic, payload}); final Channel channel = new Channel(topic, payload, Socket.this); synchronized (channels) { channels.add(channel); } return channel; } public void connect() throws IOException { LOG.log(Level.FINE, "connect"); disconnect(); final String httpUrl = this.endpointUri.replaceFirst("^ws:", "http:") .replaceFirst("^wss:", "https:"); final Request request = new Request.Builder().url(httpUrl).build(); final WebSocketCall wsCall = WebSocketCall.create(httpClient, request); wsCall.enqueue(wsListener); } public void disconnect() throws IOException { cancelReconnectTimer(); cancelHeartbeatTimer(); LOG.log(Level.FINE, "disconnect"); if (webSocket != null) { webSocket.close(1001 /*CLOSE_GOING_AWAY*/, "Disconnected by client"); } } /** * @return true if the socket connection is connected */ public boolean isConnected() { return webSocket != null; } /** * Register a callback for SocketEvent.ERROR events * * @param callback The callback to receive CLOSE events * @return This Socket instance */ public Socket onClose(final ISocketCloseCallback callback) { this.socketCloseCallbacks.add(callback); return this; } /** * Register a callback for SocketEvent.ERROR events * * @param callback The callback to receive ERROR events * @return This Socket instance */ public Socket onError(final IErrorCallback callback) { this.errorCallbacks.add(callback); return this; } /** * Register a callback for SocketEvent.MESSAGE events * * @param callback The callback to receive MESSAGE events * @return This Socket instance */ public Socket onMessage(final IMessageCallback callback) { this.messageCallbacks.add(callback); return this; } /** * Register a callback for SocketEvent.OPEN events * * @param callback The callback to receive OPEN events * @return This Socket instance */ public Socket onOpen(final ISocketOpenCallback callback) { cancelReconnectTimer(); this.socketOpenCallbacks.add(callback); return this; } /** * Sends a message envelope on this socket * * @param envelope The message envelope * @return This socket instance * @throws IOException Thrown if the message cannot be sent */ public Socket push(final Envelope envelope) throws IOException { try { LOG.log(Level.FINE, "Pushing envelope: {0}", envelope); final ObjectNode node = objectMapper.createObjectNode(); node.put("topic", envelope.getTopic()); node.put("event", envelope.getEvent()); node.put("ref", envelope.getRef()); node.set("payload", envelope.getPayload() == null ? objectMapper.createObjectNode() : envelope.getPayload()); final String json = objectMapper.writeValueAsString(node); LOG.log(Level.FINE, "Sending JSON: {0}", json); RequestBody body = RequestBody.create(WebSocket.TEXT, json); if (this.isConnected()) { try { webSocket.sendMessage(body); } catch (IllegalStateException e) { LOG.log(Level.SEVERE, "Attempted to send push when socket is not open", e); } } else { this.sendBuffer.add(body); } } catch (Throwable e) { handleOnSocketException("push", e); } return this; } /** * Should the socket attempt to reconnect if websocket.onFailure is called. * * @param reconnectOnFailure reconnect value */ public void reconectOnFailure(final boolean reconnectOnFailure) { this.reconnectOnFailure = reconnectOnFailure; } /** * Removes the specified channel if it is known to the socket * * @param channel The channel to be removed */ public void remove(final Channel channel) { synchronized (channels) { for (final Iterator chanIter = channels.iterator(); chanIter.hasNext(); ) { if (chanIter.next() == channel) { chanIter.remove(); break; } } } } public void removeAllChannels() { synchronized (channels) { channels.clear(); } } /** * All previously uncaught exceptions are now caught quietly without causing the android app to crash. * <p> * However, although the app has been stopped from crashing, it does not imply the app is functioning as intended. Set the following listener to track the reasons for the issue so that if a fix is found, it can be applied later. * * @param listener */ public void setOnSocketThrowExceptionListener(OnSocketThrowExceptionListener listener) { onSocketThrowExceptionListener = listener; } @Override public String toString() { return "PhoenixSocket{" + "endpointUri='" + endpointUri + '\'' + ", channels=" + channels + ", refNo=" + refNo + ", webSocket=" + webSocket + '}'; } synchronized String makeRef() { int val = refNo++; if (refNo == Integer.MAX_VALUE) { refNo = 0; } return Integer.toString(val); } private void cancelHeartbeatTimer() { if (Socket.this.heartbeatTimerTask != null) { Socket.this.heartbeatTimerTask.cancel(); } } private void cancelReconnectTimer() { if (Socket.this.reconnectTimerTask != null) { Socket.this.reconnectTimerTask.cancel(); } } private void flushSendBuffer() { while (this.isConnected() && !this.sendBuffer.isEmpty()) { final RequestBody body = this.sendBuffer.remove(); try { this.webSocket.sendMessage(body); } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to send payload {0}", body); } } } /** * Sets up and schedules a timer task to make repeated reconnect attempts at configured * intervals */ private void scheduleReconnectTimer() { cancelReconnectTimer(); cancelHeartbeatTimer(); Socket.this.reconnectTimerTask = new TimerTask() { @Override public void run() { LOG.log(Level.FINE, "reconnectTimerTask run"); try { Socket.this.connect(); } catch (Exception e) { LOG.log(Level.SEVERE, "Failed to reconnect to " + Socket.this.wsListener, e); } } }; timer.schedule(Socket.this.reconnectTimerTask, RECONNECT_INTERVAL_MS); } private void startHeartbeatTimer() { cancelHeartbeatTimer(); Socket.this.heartbeatTimerTask = new TimerTask() { @Override public void run() { LOG.log(Level.FINE, "heartbeatTimerTask run"); if (Socket.this.isConnected()) { try { Envelope envelope = new Envelope("phoenix", "heartbeat", new ObjectNode(JsonNodeFactory.instance), Socket.this.makeRef()); Socket.this.push(envelope); } catch (Exception e) { LOG.log(Level.SEVERE, "Failed to send heartbeat", e); } } } }; timer.schedule(Socket.this.heartbeatTimerTask, Socket.this.heartbeatInterval, Socket.this.heartbeatInterval); } private void triggerChannelError() { for (final Channel channel : channels) { channel.trigger(ChannelEvent.ERROR.getPhxEvent(), null); } } static String replyEventName(final String ref) { return "chan_reply_" + ref; } private void handleOnSocketException(String method, Throwable e) { LOG.log(Level.SEVERE, "Something went terribly wrong! Catching all throwables", e); if (onSocketThrowExceptionListener != null) { onSocketThrowExceptionListener.onThrowException(e); } } public interface OnSocketThrowExceptionListener { void onThrowException(Throwable e); } }
package peergos.server.tests.simulation; import peergos.server.Main; import peergos.server.storage.IpfsWrapper; import peergos.server.tests.UserTests; import peergos.server.util.Args; import peergos.server.util.Logging; import peergos.server.util.PeergosNetworkUtils; import peergos.shared.Crypto; import peergos.shared.NetworkAccess; import peergos.shared.user.UserContext; import peergos.shared.user.fs.cryptree.CryptreeNode; import peergos.shared.util.Pair; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; import static peergos.server.tests.UserTests.buildArgs; /** * Run some I/O and then check the file-system is as expected. */ public class Simulator implements Runnable { private class SimulationRecord { private final List<Simulation> simuations = new ArrayList<>(); private final List<Long> timestamps = new ArrayList<>(); public void add(Simulation simulation) { long now = System.currentTimeMillis(); timestamps.add(now); simuations.add(simulation); } } private static final Logger LOG = Logging.LOG(); private static final int MIN_FILE_LENGTH = 256; private static final int MAX_FILE_LENGTH = Integer.MAX_VALUE; enum Simulation {READ, WRITE, MKDIR, RM} private final int opCount; private final Random random; private final Supplier<Simulation> getNextSimulation; private final long meanFileLength; private final SimulationRecord simulationRecord = new SimulationRecord(); private final FileSystem referenceFileSystem, testFileSystem; private final Map<Path, List<String>> simulatedDirectoryToFiles = new HashMap<>(); long fileNameCounter; private String getNextName() { return "" + fileNameCounter++; } private Path getRandomExistingFile() { Path dir = getRandomExistingDirectory(); List<String> fileNames = simulatedDirectoryToFiles.get(dir); if (fileNames.isEmpty()) return getRandomExistingFile(); int pos = random.nextInt(fileNames.size()); String fileName = fileNames.get(pos); return dir.resolve(fileName); } private Path getRandomExistingDirectory() { List<Path> directories = new ArrayList<>(simulatedDirectoryToFiles.keySet()); try { int pos = random.nextInt(directories.size()); return directories.get(pos); } catch (Exception ex) { System.out.println(); throw ex; } } private void rm() { Path path = getRandomExistingFile(); simulatedDirectoryToFiles.get(path.getParent()).remove(path.getFileName().toString()); testFileSystem.delete(path); referenceFileSystem.delete(path); } private Path mkdir() { String dirBaseName = getNextName(); Path path = getRandomExistingDirectory().resolve(dirBaseName); simulatedDirectoryToFiles.putIfAbsent(path, new ArrayList<>()); LOG.info("mkdir-ing "+ path); testFileSystem.mkdir(path); referenceFileSystem.mkdir(path); return path; } private Path getAvailableFilePath() { return getRandomExistingDirectory().resolve(getNextName()); } private int getNextFileLength() { double pos = random.nextGaussian(); int targetLength = (int) (pos * meanFileLength); return Math.min(MAX_FILE_LENGTH, Math.max(targetLength, MIN_FILE_LENGTH)); } private byte[] getNextFileContents() { byte[] bytes = new byte[getNextFileLength()]; random.nextBytes(bytes); return bytes; } public Simulator(int opCount, Random random, Supplier<Simulation> getNextSimulation, long meanFileLength, FileSystem referenceFileSystem, FileSystem testFileSystem) { if (! referenceFileSystem.user().equals(testFileSystem.user())) throw new IllegalStateException("Users must be the same"); simulatedDirectoryToFiles.put(Paths.get("/"+ referenceFileSystem.user()), new ArrayList<>()); this.opCount = opCount; this.random = random; this.getNextSimulation = getNextSimulation; this.meanFileLength = meanFileLength; this.referenceFileSystem = referenceFileSystem; this.testFileSystem = testFileSystem; } private boolean read(Path path) { LOG.info("Reading path " + path); byte[] refBytes = referenceFileSystem.read(path); byte[] testBytes = testFileSystem.read(path); return Arrays.equals(refBytes, testBytes); } private void write() { Path path = getAvailableFilePath(); byte[] fileContents = getNextFileContents(); Path dirName = path.getParent(); String fileName = path.getFileName().toString(); simulatedDirectoryToFiles.get(dirName).add(fileName); LOG.info("Writing path " + path.resolve(fileName) + " with length " + fileContents.length); testFileSystem.write(path, fileContents); referenceFileSystem.write(path, fileContents); } private void init() { //seed file-system with a directory and a file run(Simulation.MKDIR); run(Simulation.WRITE); } private void run(Simulation simulation) { switch (simulation) { case READ: read(getRandomExistingFile()); break; case WRITE: write(); break; case MKDIR: mkdir(); break; case RM: rm(); break; default: throw new IllegalStateException("Unexpected simulation " + simulation); } simulationRecord.add(simulation); } public void run() { LOG.info("Running file-system IO-simulation"); init(); for (int iOp = 2; iOp < opCount; iOp++) { Simulation simulation = getNextSimulation.get(); run(simulation); } LOG.info("Running file-system verification"); boolean isVerified = verify(); LOG.info("System verified = "+ isVerified); } private boolean verify() { Set<Path> expectedFiles = simulatedDirectoryToFiles.entrySet().stream() .flatMap(e -> e.getValue().stream() .map(file -> e.getKey().resolve(file))) .collect(Collectors.toSet()); boolean isVerified = true; for (FileSystem fs : Arrays.asList(testFileSystem, referenceFileSystem)) { Set<Path> paths = new HashSet<>(); fs.walk(paths::add); Set<Path> expectedFilesAndFolders = new HashSet<>(expectedFiles); expectedFilesAndFolders.addAll(simulatedDirectoryToFiles.keySet()); // extras? Set<Path> extras = new HashSet<>(paths); extras.removeAll(expectedFilesAndFolders); for (Path extra : extras) { LOG.info("filesystem " + fs + " has an extra path " + extra); isVerified = false; } // missing? expectedFilesAndFolders.removeAll(paths); for (Path missing : expectedFilesAndFolders) { LOG.info("filesystem " + fs + " is missing the path " + missing); isVerified = false; } } // contents for (Path path : expectedFiles) { try { byte[] testData = testFileSystem.read(path); byte[] refData = referenceFileSystem.read(path); if (!Arrays.equals(testData, refData)) { LOG.info("Path " + path + " has different contents between the file-systems"); isVerified = false; } } catch (Exception ex) { LOG.info("Failed to read path + " + path); isVerified = false; } } return isVerified; } public static void main(String[] a) throws Exception { Crypto crypto = Crypto.initJava(); Args args = buildArgs() .with("useIPFS", "true") .with("peergos.password", "testpassword") .with("pki.keygen.password", "testpkipassword") .with("pki.keyfile.password", "testpassword") .with(IpfsWrapper.IPFS_BOOTSTRAP_NODES, ""); // no bootstrapping Main.PKI_INIT.main(args); NetworkAccess networkAccess = NetworkAccess.buildJava(new URL("http://localhost:" + args.getInt("port"))).get(); LOG.info("***NETWORK READY***"); UserContext userContext = PeergosNetworkUtils.ensureSignedUp("some-user", "some password", networkAccess, crypto); PeergosFileSystemImpl peergosFileSystem = new PeergosFileSystemImpl(userContext); Path root = Files.createTempDirectory("test_filesystem"); NativeFileSystemImpl nativeFileSystem = new NativeFileSystemImpl(root, "some-user"); int opCount = 100; Map<Simulation, Double> probabilities = Stream.of( new Pair<>(Simulation.READ, 0.05), new Pair<>(Simulation.WRITE, 0.75), new Pair<>(Simulation.RM, 0.15), new Pair<>(Simulation.MKDIR, 0.05) ).collect( Collectors.toMap(e -> e.left, e-> e.right)); final Random random = new Random(1); Supplier<Simulation> getNextSimulation = () -> { double acc = 0; double p = random.nextDouble(); for (Map.Entry<Simulation, Double> e : probabilities.entrySet()) { Simulation simulation = e.getKey(); Double prob = e.getValue(); acc += prob; if (p < acc) return simulation; } throw new IllegalStateException(); }; //hard-mode CryptreeNode.setMaxChildLinkPerBlob(10); int meanFileLength = 256; Simulator simulator = new Simulator(opCount, random, getNextSimulation, meanFileLength, nativeFileSystem, peergosFileSystem); try { simulator.run(); } catch (Throwable t) { LOG.log(Level.SEVERE, t, () -> "So long"); } finally { System.exit(0); } } }
package org.plumelib.util; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Comparator; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.NonNull; /** * Deterministic versions of {@code java.lang.Class} methods, which return arrays in sorted order. */ public class ClassDeterministic { /** Do not call; this class is a collection of methods and does not represent anything. */ private ClassDeterministic() { throw new Error("do not instantiate"); } /** * Like {@link Class#getAnnotations()}, but returns the methods in deterministic order. * * @param c the Class whose annotations to return * @return the class's annotations */ public static Annotation[] getAnnotations(Class<?> c) { Annotation[] result = c.getAnnotations(); Arrays.sort(result, annotationComparator); return result; } /** * Like {@link Class#getDeclaredAnnotations()}, but returns the methods in deterministic order. * * @param c the Class whose declared annotations to return * @return the class's declared annotations */ public static Annotation[] getDeclaredAnnotations(Class<?> c) { Annotation[] result = c.getDeclaredAnnotations(); Arrays.sort(result, annotationComparator); return result; } /** * Like {@link Class#getClasses()}, but returns the classes in deterministic order. * * @param c the Class whose member classes to return * @return the class's member classes */ public static Class<?>[] getClasses(Class<?> c) { Class<?>[] result = c.getClasses(); Arrays.sort(result, classComparator); return result; } /** * Like {@link Class#getDeclaredClasses()}, but returns the classes in deterministic order. * * @param c the Class whose declared member classes to return * @return the class's declared member classes */ public static Class<?>[] getDeclaredClasses(Class<?> c) { Class<?>[] result = c.getDeclaredClasses(); Arrays.sort(result, classComparator); return result; } /** * Like {@link Class#getEnumConstants()}, but returns the methods in deterministic order. * * @param <T> the class's type parameter * @param c the Class whose enum constants to return * @return the class's enum constants */ public static <T> T @Nullable [] getEnumConstants(Class<T> c) { @NonNull T[] result = c.getEnumConstants(); if (result == null) { return null; } Arrays.sort(result, toStringComparator); return result; } /** * Like {@link Class#getConstructors()}, but returns the methods in deterministic order. * * @param c the Class whose constructors to return * @return the class's constructors */ public static Constructor<?>[] getConstructors(Class<?> c) { Constructor<?>[] result = c.getConstructors(); Arrays.sort(result, constructorComparator); return result; } /** * Like {@link Class#getDeclaredConstructors()}, but returns the methods in deterministic order. * * @param c the Class whose declared constructors to return * @return the class's declared constructors */ public static Constructor<?>[] getDeclaredConstructors(Class<?> c) { Constructor<?>[] result = c.getDeclaredConstructors(); Arrays.sort(result, constructorComparator); return result; } /** * Like {@link Class#getFields()}, but returns the methods in deterministic order. * * @param c the Class whose fields to return * @return the class's fields */ public static Field[] getFields(Class<?> c) { Field[] result = c.getFields(); Arrays.sort(result, fieldComparator); return result; } /** * Like {@link Class#getDeclaredFields()}, but returns the methods in deterministic order. * * @param c the Class whose declared fields to return * @return the class's declared fields */ public static Field[] getDeclaredFields(Class<?> c) { Field[] result = c.getDeclaredFields(); Arrays.sort(result, fieldComparator); return result; } /** * Like {@link Class#getMethods()}, but returns the methods in deterministic order. * * @param c the Class whose methods to return * @return the class's methods */ public static Method[] getMethods(Class<?> c) { Method[] result = c.getMethods(); Arrays.sort(result, methodComparator); return result; } /** * Like {@link Class#getDeclaredMethods()}, but returns the methods in deterministic order. * * @param c the Class whose declared methods to return * @return the class's declared methods */ public static Method[] getDeclaredMethods(Class<?> c) { Method[] result = c.getDeclaredMethods(); Arrays.sort(result, methodComparator); return result; } /// Helper routines // /** // * Creates a sorted list from an array of elements using the given classComparator. // * // * @param array the array of elements to be sorted // * @param comparator the classComparator over the element type // * @param <T> the element type // * @return the sorted list of elements of the given array // */ // private <T> List<T> toSortedList(T[] array, Comparator<T> comparator) { // List<T> list = new ArrayList<>(); // Collections.addAll(list, array); // Collections.sort(list, comparator); // return list; /** Compares Annotation objects by type name. */ static AnnotationComparator annotationComparator = new AnnotationComparator(); /** Compares Annotation objects by type name. */ private static class AnnotationComparator implements Comparator<Annotation> { @Override public int compare(Annotation a1, Annotation a2) { return classComparator.compare(a1.annotationType(), a2.annotationType()); } } /** Compares Class objects by fully-qualified name. */ static ClassComparator classComparator = new ClassComparator(); /** Compares Class objects by fully-qualified name. */ private static class ClassComparator implements Comparator<Class<?>> { @Override public int compare(Class<?> c1, Class<?> c2) { return c1.getName().compareTo(c2.getName()); } } /** * Compares Method objects by signature: compares name, number of parameters, parameter type * names, declaring class, and return type (which is necessary to distinguish bridge methods). */ static MethodComparator methodComparator = new MethodComparator(); /** * Compares Method objects by signature: compares name, number of parameters, parameter type * names, declaring class, and return type (which is necessary to distinguish bridge methods). */ private static class MethodComparator implements Comparator<Method> { @Override public int compare(Method m1, Method m2) { int result; result = m1.getName().compareTo(m2.getName()); if (result != 0) { return result; } Class<?>[] ptypes1 = m1.getParameterTypes(); Class<?>[] ptypes2 = m2.getParameterTypes(); result = ptypes1.length - ptypes2.length; if (result != 0) { return result; } assert ptypes1.length == ptypes2.length : "@AssumeAssertion(index): difference of lengths is 0; https://github.com/kelloggm/checker-framework/issues/231"; for (int i = 0; i < ptypes1.length; i++) { result = classComparator.compare(ptypes1[i], ptypes2[i]); if (result != 0) { return result; } } // Consider the declaring class last. This minimizes differences in order when overriding // relationships in a library have changed. result = classComparator.compare(m1.getDeclaringClass(), m2.getDeclaringClass()); if (result != 0) { return result; } // Two methods in a classfile can have the same name and argument types // if one is a bridge method. Distinguish them by their return type. result = classComparator.compare(m1.getReturnType(), m2.getReturnType()); if (result != 0) { return result; } return result; } } /** * Compares Constructor objects by signature: compares name, number of parameters, and parameter * type names. */ static ConstructorComparator constructorComparator = new ConstructorComparator(); /** * Compares Constructor objects by signature: compares name, number of parameters, and parameter * type names. */ private static class ConstructorComparator implements Comparator<Constructor<?>> { @Override public int compare(Constructor<?> c1, Constructor<?> c2) { int result = classComparator.compare(c1.getDeclaringClass(), c2.getDeclaringClass()); if (result != 0) { return result; } Class<?>[] ptypes1 = c1.getParameterTypes(); Class<?>[] ptypes2 = c2.getParameterTypes(); result = ptypes1.length - ptypes2.length; if (result != 0) { return result; } assert ptypes1.length == ptypes2.length : "@AssumeAssertion(index): difference of lengths is 0; https://github.com/kelloggm/checker-framework/issues/231"; for (int i = 0; i < ptypes1.length; i++) { result = classComparator.compare(ptypes1[i], ptypes2[i]); if (result != 0) { return result; } } return result; } } /** Compares Field objects by name. */ static FieldComparator fieldComparator = new FieldComparator(); /** Compares Field objects by name. */ private static class FieldComparator implements Comparator<Field> { @Override public int compare(Field f1, Field f2) { int result = classComparator.compare(f1.getDeclaringClass(), f2.getDeclaringClass()); if (result != 0) { return result; } return f1.getName().compareTo(f2.getName()); } } /** Compares objects by the result of toString(). */ static ToStringComparator toStringComparator = new ToStringComparator(); /** Compares objects by the result of toString(). */ private static class ToStringComparator implements Comparator<Object> { @Override public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } } }
package org.scijava.platform; import java.io.IOException; import java.net.URL; import java.util.List; import org.scijava.app.App; import org.scijava.app.AppService; import org.scijava.command.CommandService; import org.scijava.event.EventService; import org.scijava.plugin.SingletonService; import org.scijava.service.SciJavaService; /** * Interface for service that handles platform-specific deployment issues. A * "platform" can be an operating system, CPU architecture, or version of Java. * * @author Curtis Rueden */ public interface PlatformService extends SingletonService<Platform>, SciJavaService { EventService getEventService(); CommandService getCommandService(); /** Gets the platform handlers applicable to this platform. */ List<Platform> getTargetPlatforms(); /** * Opens a URL in a platform-dependent way. Typically the URL is opened in an * external web browser instance, but the behavior is ultimately defined by * the available platform handler implementations. */ void open(URL url) throws IOException; /** * Executes a native program and waits for it to return. * * @return the exit code of the execution. */ int exec(String... args) throws IOException; /** * Informs the active platform handlers of a UI's newly created application * menu structure. Each active platform handler may choose to do something * platform-specific with the menus. * * @param menus The UI's newly created menu structure * @return true iff the menus should not be added to the UI as normal because * a platform handler did something platform-specific with them * instead. */ boolean registerAppMenus(Object menus); // -- Deprecated methods -- /** @deprecated Use {@link AppService} and {@link App} instead. */ @Deprecated AppEventService getAppEventService(); }
package org.scribe.builder.api; import org.scribe.extractors.AccessTokenExtractor; import org.scribe.extractors.JsonTokenExtractor; import org.scribe.model.OAuthConfig; import org.scribe.model.Verb; import org.scribe.oauth.LinkedIn20ServiceImpl; import org.scribe.oauth.OAuthService; import org.scribe.utils.OAuthEncoder; import org.scribe.utils.Preconditions; public class LinkedInApi20 extends DefaultApi20 { private static final String AUTHORIZE_URL = "https: private static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=%s"; @Override public Verb getAccessTokenVerb() { return Verb.GET; } @Override public String getAccessTokenEndpoint() { return "https: } @Override public String getAuthorizationUrl(final OAuthConfig config) { Preconditions.checkValidUrl(config.getCallback(), "Must provide a valid url as callback. LinkedIn does not support OOB"); if (config.hasScope()) { return String.format( SCOPED_AUTHORIZE_URL, config.getApiKey(), OAuthEncoder.encode(config.getCallback()), OAuthEncoder.encode(config.getScope())); } else { return String.format(AUTHORIZE_URL, config.getApiKey(), OAuthEncoder.encode(config.getCallback())); } } @Override public AccessTokenExtractor getAccessTokenExtractor() { return new JsonTokenExtractor(); } @Override public OAuthService createService(final OAuthConfig config) { return new LinkedIn20ServiceImpl(this, config); } }
package pl.datamatica.traccar.api.fcm; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.NamingException; import javax.persistence.EntityManager; import org.apache.http.client.methods.CloseableHttpResponse; import pl.datamatica.traccar.api.Context; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import pl.datamatica.traccar.api.Application; import pl.datamatica.traccar.model.NotificationStatus; import pl.datamatica.traccar.model.User; import pl.datamatica.traccar.model.UserSession; public abstract class Daemon { private final Runnable runnable; protected Daemon() { runnable = new Runnable() { @Override public void run() { EntityManager em = Context.getInstance().createEntityManager(); try { em.getTransaction().begin(); doWork(em); em.getTransaction().commit(); } catch(Exception e) { Logger.getLogger(Daemon.class.getName()) .log(Level.SEVERE, null, e); } finally { em.close(); } } }; } public abstract void start(ScheduledExecutorService scheduler); protected void start(ScheduledExecutorService scheduler, long delay, long period){ scheduler.scheduleAtFixedRate(runnable, delay, period, TimeUnit.MINUTES); } protected abstract void doWork(EntityManager em); protected void sendToFcm(EntityManager em, FcmNotificationDto dto) { Gson gson = Context.getInstance().getGson(); String message = gson.toJson(dto); String result = sendToFcm(message); boolean success = false; if(result != null) { try { JsonParser parser = new JsonParser(); JsonObject o = parser.parse(result).getAsJsonObject(); success = o.get("success").getAsInt() == 1; if(!success) Logger.getLogger(Daemon.class.getName()) .log(Level.INFO, o.getAsJsonArray("results").toString()); } catch(Exception e) { // Probably incorrect fcm scret -> incorrect response JSON Logger.getLogger(Daemon.class.getName()).log(Level.INFO, e.getLocalizedMessage()); } } NotificationStatus ns = new NotificationStatus(dto.getTo(), dto.getKind(), success); em.persist(ns); } private String sendToFcm(String body) { CloseableHttpClient client = HttpClients.createDefault(); HttpPost request = new HttpPost("https://fcm.googleapis.com/fcm/send"); CloseableHttpResponse response = null; try { request.addHeader("Authorization", "key=" + Application.getConfigRecord("java:/fcm_secret")); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(body)); response = client.execute(request); if(response.getStatusLine().getStatusCode() != 200) return EntityUtils.toString(response.getEntity()); return EntityUtils.toString(response.getEntity()); } catch (NamingException ne) { // probably config file doesn't have fcm secret Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, null, ne); return null; } catch (Exception ex) { Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, null, ex); return null; } finally { try { if(response != null) response.close(); client.close(); } catch (IOException ex) { Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, null, ex); } } } public void clearInactiveSessions(EntityManager em, User user) { Set<String> activeSessions = new HashSet<>(em .createNativeQuery("SELECT sessionId from JettySessions") .getResultList()); List<UserSession> validSessions = new ArrayList<>(); for(UserSession s : user.getSessions()) { if(activeSessions.contains(s.getSessionId())) validSessions.add(s); } user.setSessions(validSessions); } }
package redis.clients.jedis; import java.util.List; import java.util.regex.Pattern; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.PooledObjectFactory; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.util.Hashing; import redis.clients.util.Pool; public class ShardedJedisPool extends Pool<ShardedJedis> { public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, List<JedisShardInfo> shards) { this(poolConfig, shards, Hashing.MURMUR_HASH); } public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, List<JedisShardInfo> shards, Hashing algo) { this(poolConfig, shards, algo, null); } public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, List<JedisShardInfo> shards, Pattern keyTagPattern) { this(poolConfig, shards, Hashing.MURMUR_HASH, keyTagPattern); } public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) { super(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern)); } public void returnBrokenResource(final ShardedJedis resource) { returnBrokenResourceObject(resource); } /** * PoolableObjectFactory custom impl. */ private static class ShardedJedisFactory implements PooledObjectFactory<ShardedJedis> { private List<JedisShardInfo> shards; private Hashing algo; private Pattern keyTagPattern; public ShardedJedisFactory(List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) { this.shards = shards; this.algo = algo; this.keyTagPattern = keyTagPattern; } @Override public PooledObject<ShardedJedis> makeObject() throws Exception { ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern); return new DefaultPooledObject<ShardedJedis>(jedis); } @Override public void destroyObject(PooledObject<ShardedJedis> pooledShardedJedis) throws Exception { final ShardedJedis shardedJedis = pooledShardedJedis.getObject(); for (Jedis jedis : shardedJedis.getAllShards()) { try { try { jedis.quit(); } catch (Exception e) { } jedis.disconnect(); } catch (Exception e) { } } } @Override public boolean validateObject( PooledObject<ShardedJedis> pooledShardedJedis) { try { ShardedJedis jedis = pooledShardedJedis.getObject(); for (Jedis shard : jedis.getAllShards()) { if (!shard.ping().equals("PONG")) { return false; } } return true; } catch (Exception ex) { return false; } } @Override public void activateObject(PooledObject<ShardedJedis> p) throws Exception { } @Override public void passivateObject(PooledObject<ShardedJedis> p) throws Exception { } } }
package rtk.dimension; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.MobEffects; import net.minecraft.potion.PotionEffect; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.ITeleporter; import rtk.common.CMath; public class TeleporterExitDarkVoid implements ITeleporter { @Override public void placeEntity(World world, Entity entity, float yaw) { EntityPlayer player = (EntityPlayer) entity; if (player != null) player.addPotionEffect(new PotionEffect(MobEffects.NAUSEA, 240)); int x = MathHelper.floor(entity.posX); int z = MathHelper.floor(entity.posZ); BlockPos pos = new BlockPos(x, 0, z); BlockPos bedRockHole = findBedrockHole(world, pos); if (bedRockHole == null) return; BlockPos spawnPos = findSpawnLocationByHole(world, bedRockHole); if (spawnPos == null) return; entity.motionX = 0; entity.motionY = 0; entity.motionZ = 0; entity.setPosition(spawnPos.getX() + 0.5, spawnPos.getY() + 1, spawnPos.getZ() + 0.5); } public BlockPos findBedrockHole(World world, BlockPos pos) { int radius = 16; BlockPos result = null; for (BlockPos p: CMath.cuboid( pos.add(-radius,0, -radius), pos.add(radius, 0, radius) )) { if (world.isAirBlock(p)) { result = p; break; } } if (result == null) return null; // Move away from edges to center in 3x3 hole. for (EnumFacing dir: EnumFacing.HORIZONTALS) if (!world.isAirBlock(result.offset(dir))) result = result.offset(dir, -1); return result; } public BlockPos findSpawnLocationByHole(World world, BlockPos pos) { int radius = 2; int height = 6; for (BlockPos p: CMath.cuboid( pos.add(-radius,0, -radius), pos.add(radius, height, radius) )) { if (world.isSideSolid(p, EnumFacing.UP) && world.isAirBlock(p.up(1)) && world.isAirBlock(p.up(2))) return p; } return null; } }
package scrum.server.project; import ilarkesto.base.Str; import ilarkesto.base.time.Date; import ilarkesto.base.time.DateAndTime; import ilarkesto.core.logging.Log; import ilarkesto.velocity.ContextBuilder; import ilarkesto.velocity.Velocity; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import scrum.client.wiki.HtmlContext; import scrum.client.wiki.WikiModel; import scrum.client.wiki.WikiParser; import scrum.server.collaboration.Wikipage; import scrum.server.issues.Issue; import scrum.server.pr.BlogEntry; public class HomepageUpdater { private static Log log = Log.get(HomepageUpdater.class); private Project project; private MyHtmlContext htmlContext; private File templateDir; private File outputDir; private Velocity velocity; private HomepageUpdater(Project project, String templatePath, String outputPath) { super(); assert project != null; this.project = project; this.templateDir = new File(templatePath); this.outputDir = new File(outputPath); htmlContext = new MyHtmlContext(project); velocity = new Velocity(templateDir); } private void processDefaultTemplates() { ContextBuilder context = new ContextBuilder(); fillProject(context.putSubContext("project")); fillWiki(context.putSubContext("wiki")); fillBlog(context.putSubContext("blog")); fillSprintBacklog(context.putSubContext("sprintBacklog")); fillProductBacklog(context.putSubContext("productBacklog")); fillIssues(context); File[] templateFiles = templateDir.listFiles(); if (templateFiles == null) return; for (File templateFile : templateFiles) { String templateName = templateFile.getName(); if (!templateName.endsWith(".vm")) continue; if (templateName.equals(Velocity.LIB_TEMPLATE_NAME)) continue; if (templateName.startsWith("iss.")) continue; String outputFileName = Str.removeSuffix(templateName, ".vm"); velocity.processTemplate(templateName, new File(outputDir.getPath() + "/" + outputFileName), context); } } private void processIssueTemplates() { List<Issue> issues = new ArrayList<Issue>(project.getUrgentIssues()); for (Issue issue : issues) { ContextBuilder context = new ContextBuilder(); fillIssue(context.putSubContext("issue"), issue); String reference = issue.getReference(); processEntityTemplate(context, reference); } } private void processStoryTemplates() { List<Requirement> requirements = new ArrayList<Requirement>(project.getRequirements()); for (Requirement requirement : requirements) { if (requirement.isClosed()) continue; ContextBuilder context = new ContextBuilder(); fillStory(context.putSubContext("story"), requirement); processEntityTemplate(context, requirement.getReference()); } } private void processEntityTemplate(ContextBuilder context, String reference) { String prefix = reference.substring(0, 3); File[] templateFiles = templateDir.listFiles(); if (templateFiles == null) return; for (File templateFile : templateFiles) { String templateName = templateFile.getName(); if (!templateName.endsWith(".vm")) continue; if (!templateName.startsWith(prefix + ".")) continue; String outputFileName = Str.removeSuffix(templateName, ".vm"); outputFileName = Str.removePrefix(outputFileName, prefix + "."); outputFileName = reference + "." + outputFileName; velocity.processTemplate(templateName, new File(outputDir.getPath() + "/" + outputFileName), context); } } private void fillIssues(ContextBuilder context) { List<Issue> issues = new ArrayList<Issue>(project.getUrgentIssues()); for (Issue issue : issues) { fillIssue(context.addSubContext("bugs"), issue); } } private void fillIssue(ContextBuilder context, Issue issue) { context.put("reference", issue.getReference()); context.put("label", issue.getLabel()); context.put("description", wiki2html(issue.getDescription(), htmlContext)); context.put("statement", wiki2html(issue.getStatement(), htmlContext)); } private void fillBlog(ContextBuilder context) { List<BlogEntry> entries = new ArrayList<BlogEntry>(project.getBlogEntrys()); Collections.sort(entries); for (BlogEntry entry : entries) { if (!entry.isPublished()) continue; fillBlogEntry(context.addSubContext("entries"), entry); } } private void fillBlogEntry(ContextBuilder context, BlogEntry entry) { context.put("reference", entry.getReference()); context.put("title", entry.getTitle()); context.put("text", wiki2html(entry.getText(), htmlContext)); context.put("plainText", wiki2text(entry.getText())); DateAndTime date = entry.getDateAndTime(); context.put("date", date.toString(Date.FORMAT_LONGMONTH_DAY_YEAR)); context.put("rssDate", date.toString(DateAndTime.FORMAT_RFC822)); } private void fillSprintBacklog(ContextBuilder context) { List<Requirement> requirements = new ArrayList<Requirement>(project.getCurrentSprint().getRequirements()); Collections.sort(requirements, project.getRequirementsOrderComparator()); for (Requirement requirement : requirements) { fillStory(context.addSubContext("stories"), requirement); } } private void fillProductBacklog(ContextBuilder context) { List<Requirement> requirements = new ArrayList<Requirement>(project.getRequirements()); Collections.sort(requirements, project.getRequirementsOrderComparator()); for (Requirement requirement : requirements) { if (requirement.isClosed() || requirement.isInCurrentSprint()) continue; fillStory(context.addSubContext("stories"), requirement); } } private void fillStory(ContextBuilder context, Requirement requirement) { context.put("reference", requirement.getReference()); context.put("label", requirement.getLabel()); context.put("description", wiki2html(requirement.getDescription(), htmlContext)); } private void fillWiki(ContextBuilder context) { for (Wikipage page : project.getWikipages()) { context.put(page.getName(), wiki2html(page.getText(), htmlContext)); } } private void fillProject(ContextBuilder context) { context.put("label", project.getLabel()); context.put("shortDescription", project.getShortDescription()); context.put("description", wiki2html(project.getDescription(), htmlContext)); context.put("longDescription", wiki2html(project.getLongDescription(), htmlContext)); } public static void updateHomepage(String templatePath, String outputPath, Project project) { HomepageUpdater updater = new HomepageUpdater(project, templatePath, outputPath); synchronized (project) { updater.processDefaultTemplates(); updater.processIssueTemplates(); updater.processStoryTemplates(); } } public static void updateHomepage(Project project) { File homepageDir = project.getHomepageDirFile(); if (homepageDir == null || !homepageDir.exists()) { log.warn("Updating project homepage failed. Homepage directory does not exist:", homepageDir); return; } File velocityDir = new File(homepageDir.getPath() + "/velocity"); if (velocityDir.exists()) updateHomepage(velocityDir.getPath(), homepageDir.getPath(), project); } public static String wiki2html(String wikitext, HtmlContext context) { if (Str.isBlanc(wikitext)) return ""; WikiParser wikiParser = new WikiParser(wikitext); WikiModel model = wikiParser.parse(); return model.toHtml(context); } public static String wiki2text(String wikitext) { if (Str.isBlanc(wikitext)) return ""; return wikitext; } private static class MyHtmlContext implements HtmlContext { private Project project; public MyHtmlContext(Project project) { super(); this.project = project; } @Override public String getDownloadUrlByReference(String reference) { return reference; } @Override public String getEntityLabelByReference(String reference) { return reference; } } }
package seedu.jimi.model; import java.time.DayOfWeek; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.logging.Logger; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; import seedu.jimi.commons.core.LogsCenter; import seedu.jimi.commons.core.UnmodifiableObservableList; import seedu.jimi.commons.util.StringUtil; import seedu.jimi.model.datetime.DateTime; import seedu.jimi.model.event.Event; import seedu.jimi.model.task.DeadlineTask; import seedu.jimi.model.task.FloatingTask; import seedu.jimi.model.task.ReadOnlyTask; /** * Represents a manager for filtered lists used in the UI component. * Respective UI components should already be listeners to each of the lists in {@code listMap}. */ public class FilteredListManager { private static final Logger logger = LogsCenter.getLogger(FilteredListManager.class); // @@author A0140133B public enum ListId { DAY_AHEAD_0, DAY_AHEAD_1, DAY_AHEAD_2, DAY_AHEAD_3, DAY_AHEAD_4, DAY_AHEAD_5, DAY_AHEAD_6, FLOATING_TASKS, COMPLETED, INCOMPLETE, TASKS_AGENDA, EVENTS_AGENDA } private final HashMap<ListId, FilteredList<ReadOnlyTask>> listMap = new HashMap<ListId, FilteredList<ReadOnlyTask>>(); private final HashMap<ListId, SortedList<ReadOnlyTask>> sortedListMap = new HashMap<ListId, SortedList<ReadOnlyTask>>(); private final HashMap<ListId, Expression> defaultExpressions = new HashMap<ListId, Expression>(); public FilteredListManager(TaskBook taskBook) { initDefaultExpressions(); initFilteredLists(taskBook); initSortedLists(); } /* * 1. Initializing each list with taskBook's own internal list. * 2. Setting default filters for each list. * * Adds in CompletedQualifiers when initializing agenda lists. */ private void initFilteredLists(TaskBook taskBook) { for (ListId id : ListId.values()) { listMap.put(id, new FilteredList<ReadOnlyTask>(taskBook.getTasks())); if(id.equals(ListId.TASKS_AGENDA)) { listMap.get(id).setPredicate(new PredicateExpression(new TaskQualifier(true), new CompletedQualifier(false))::satisfies); } else if(id.equals(ListId.EVENTS_AGENDA)) { listMap.get(id).setPredicate(new PredicateExpression(new EventQualifier(true), new CompletedQualifier(false))::satisfies); } else { listMap.get(id).setPredicate(defaultExpressions.get(id)::satisfies); } } } /** * @@author A0138915X * * Wraps all the filteredLists with sortedLists. */ private void initSortedLists() { for(ListId id : ListId.values()) { SortedList<ReadOnlyTask> sortedList = new SortedList<ReadOnlyTask>(listMap.get(id)); sortedList.setComparator(new Comparator<ReadOnlyTask>() { @Override public int compare(ReadOnlyTask arg0, ReadOnlyTask arg1) { if(arg0 instanceof Event) { if(arg1 instanceof Event) { return ((Event) arg0).getStart().compareTo(((Event) arg1).getStart()); } else { //return -2, lowest natural ordering return -2; } } else if(arg0 instanceof DeadlineTask) { if(arg1 instanceof DeadlineTask) { return ((DeadlineTask) arg0).getDeadline().compareTo(((DeadlineTask) arg1).getDeadline()); } else { //return -1, 2nd lowest natural ordering return -1; } } else { //compare names of floating tasks return arg0.getName().fullName.compareToIgnoreCase(arg1.getName().fullName); } } }); sortedListMap.put(id, sortedList); } } //@@author // @@author A0140133B /** * Initializes default expressions used by all the filtered lists in {@code listMap}. */ private void initDefaultExpressions() { // Expression matches if it's an incomplete floating task. defaultExpressions.put(ListId.FLOATING_TASKS, new PredicateExpression(new FloatingTaskQualifier(true), new CompletedQualifier(false))); // Expression matches if it's a completed non-event. defaultExpressions.put(ListId.COMPLETED, new PredicateExpression(new EventQualifier(false), new CompletedQualifier(true))); // Expression matches if it's an incomplete non-event. defaultExpressions.put(ListId.INCOMPLETE, new PredicateExpression(new EventQualifier(false), new CompletedQualifier(false))); // Expressions match if they match the current relative day and are incomplete. defaultExpressions.put(ListId.DAY_AHEAD_0, new PredicateExpression(new WeekQualifier(ListId.DAY_AHEAD_0), new CompletedQualifier(false))); defaultExpressions.put(ListId.DAY_AHEAD_1, new PredicateExpression(new WeekQualifier(ListId.DAY_AHEAD_1), new CompletedQualifier(false))); defaultExpressions.put(ListId.DAY_AHEAD_2, new PredicateExpression(new WeekQualifier(ListId.DAY_AHEAD_2), new CompletedQualifier(false))); defaultExpressions.put(ListId.DAY_AHEAD_3, new PredicateExpression(new WeekQualifier(ListId.DAY_AHEAD_3), new CompletedQualifier(false))); defaultExpressions.put(ListId.DAY_AHEAD_4, new PredicateExpression(new WeekQualifier(ListId.DAY_AHEAD_4), new CompletedQualifier(false))); defaultExpressions.put(ListId.DAY_AHEAD_5, new PredicateExpression(new WeekQualifier(ListId.DAY_AHEAD_5), new CompletedQualifier(false))); defaultExpressions.put(ListId.DAY_AHEAD_6, new PredicateExpression(new WeekQualifier(ListId.DAY_AHEAD_6), new CompletedQualifier(false))); // Expression matches if it's a task. defaultExpressions.put(ListId.TASKS_AGENDA, new PredicateExpression(new TaskQualifier(true))); // Expression matches if it's an event. defaultExpressions.put(ListId.EVENTS_AGENDA, new PredicateExpression(new EventQualifier(true))); } //@@author public UnmodifiableObservableList<ReadOnlyTask> getSortedFilteredList(ListId id) { return new UnmodifiableObservableList<ReadOnlyTask>(sortedListMap.get(id)); } /** Updates filters of all filtered lists to default specified in {@code defaultExpressions} */ public void updateFilteredListsToNormalListing() { for (ListId id : ListId.values()) { if (id.equals(ListId.TASKS_AGENDA)) { listMap.get(id).setPredicate( new PredicateExpression(new TaskQualifier(true), new CompletedQualifier(false))::satisfies); } else if (id.equals(ListId.EVENTS_AGENDA)) { listMap.get(id).setPredicate( new PredicateExpression(new EventQualifier(true), new CompletedQualifier(false))::satisfies); } else { listMap.get(id).setPredicate(defaultExpressions.get(id)::satisfies); } } } /** Updates filtered list identified by {@code id} with keyword filter along with its default filter. */ public void updateFilteredList(ListId id, Set<String> keywords) { updateFilteredList(id, defaultExpressions.get(id), new PredicateExpression(new NameQualifier(keywords))); } // @@author A0138915X public void updateFilteredList(ListId id, DateTime fromDate, DateTime toDate) { if (toDate == null) { updateFilteredList(id, defaultExpressions.get(id), new PredicateExpression(new DateQualifier(fromDate))); } else { updateFilteredList(id, defaultExpressions.get(id), new PredicateExpression(new DateQualifier(fromDate, toDate))); } } public void updateFilteredList(ListId id, Set<String> keywords, DateTime fromDate, DateTime toDate) { if (toDate == null) { updateFilteredList(id, defaultExpressions.get(id), new PredicateExpression(new NameQualifier(keywords), new CompletedQualifier(false), new DateQualifier(fromDate))); } else { updateFilteredList(id, defaultExpressions.get(id), new PredicateExpression(new NameQualifier(keywords), new CompletedQualifier(false), new DateQualifier(fromDate, toDate))); } } //@@author // @@author A0140133B /** * Updates filtered list identified by {@code id} with the filter in {@code other}, along with the original * default filter of list identified by {@code id}. */ public void updateFilteredList(ListId id, ListId other) { updateFilteredList(id, defaultExpressions.get(id), defaultExpressions.get(other)); } /** * Updates filtered list identified by {@code id} with a filter that matches all filters in {@code expressions}. */ private void updateFilteredList(ListId id, Expression... expressions) { listMap.get(id).setPredicate(t -> Arrays.stream(expressions).allMatch(e -> e.satisfies(t))); } // @@author interface Expression { boolean satisfies(ReadOnlyTask task); String toString(); } // @@author A0140133B /** * Represents a predicate expression that allows for multiple {@code Qualifier} instances. * * For this PredicateExpression to satisfy, all qualifiers must pass. */ private class PredicateExpression implements Expression { private final List<Qualifier> qualifiers; PredicateExpression(Qualifier... qualifiers) { this.qualifiers = Arrays.asList(qualifiers); } @Override public boolean satisfies(ReadOnlyTask task) { return qualifiers.stream().allMatch(q -> q.run(task)); } @Override public String toString() { return qualifiers.toString(); } } // @@author interface Qualifier { boolean run(ReadOnlyTask task); String toString(); } private class NameQualifier implements Qualifier { private Set<String> nameKeyWords; public NameQualifier(Set<String> nameKeyWords) { this.nameKeyWords = nameKeyWords; } @Override public boolean run(ReadOnlyTask task) { return nameKeyWords.stream() .filter(keyword -> StringUtil.containsIgnoreCase(task.getName().fullName, keyword)) .findAny() .isPresent(); } @Override public String toString() { return "name=" + String.join(", ", nameKeyWords); } } /** * Checks for tasks/events that fall within a specific date or a range of dates. * @author zexuan * */ //@@author A0138915X private class DateQualifier implements Qualifier { DateTime startDate; DateTime endDate; public DateQualifier(DateTime specificDate) { this.startDate = specificDate; } public DateQualifier(DateTime fromDate, DateTime toDate) { this.startDate = fromDate; this.endDate = toDate; } @Override public boolean run(ReadOnlyTask task) { logger.info(this.startDate.toString()); if(endDate == null && startDate != null) { //if searching for a specific date if(task instanceof Event) { return ((Event) task).getStart().getDifferenceInDays(startDate) >= 0 && ((Event) task).getEnd().getDifferenceInDays(startDate) <= 0; } else if(task instanceof DeadlineTask) { return ((DeadlineTask) task).getDeadline().getDifferenceInDays(startDate) == 0; } } else if(endDate != null) { //if searching for a range of dates if(task instanceof Event) { Event e = (Event) task; return DateTime.isOverLapping(startDate, endDate, e.getStart(), e.getEnd()); } else if(task instanceof DeadlineTask) { return ((DeadlineTask) task).getDeadline().between(startDate, endDate); } } return false; //if floating task } } /** * Qualifier to check if task/event is overdue w.r.t. current time. * @author zexuan * */ private class OverdueQualifier implements Qualifier { @Override public boolean run(ReadOnlyTask task) { if(task instanceof Event) { //needed? } else if(task instanceof DeadlineTask) { return LocalDateTime.now().compareTo(((DeadlineTask) task).getDeadline().getLocalDateTime()) >= 0; } return false; } } //@@author private class WeekQualifier implements Qualifier { private final ListId id; WeekQualifier(ListId i) { id = i; } @Override public boolean run(ReadOnlyTask task) { DayOfWeek currentDay = new DateTime().getLocalDateTime().getDayOfWeek(); DayOfWeek dayOfWeek = null; // dynamically set the day that each list corresponds to switch (id) { case DAY_AHEAD_0 : dayOfWeek = currentDay; break; case DAY_AHEAD_1 : dayOfWeek = currentDay.plus(1); break; case DAY_AHEAD_2 : dayOfWeek = currentDay.plus(2); break; case DAY_AHEAD_3 : dayOfWeek = currentDay.plus(3); break; case DAY_AHEAD_4 : dayOfWeek = currentDay.plus(4); break; case DAY_AHEAD_5 : dayOfWeek = currentDay.plus(5); break; case DAY_AHEAD_6 : dayOfWeek = currentDay.plus(6); break; default : break; } if (task instanceof DeadlineTask) { return isTaskSameWeekDate((DeadlineTask) task, dayOfWeek); } else if (task instanceof Event) { return isEventSameWeekDate((Event) task, dayOfWeek); } else { return false; } } /** * Checks if the task is at most 1 week ahead of current time. */ private boolean isTaskSameWeekDate(DeadlineTask task, DayOfWeek day) { long daysDifference = new DateTime().getDifferenceInDays(task.getDeadline()); if (daysDifference >= 0) { return task.getDeadline().getLocalDateTime().getDayOfWeek().getValue() == day.getValue(); // check if day of the week } return false; } /** * Checks if the event is at most 1 week ahead of current time or is * occuring now. */ private boolean isEventSameWeekDate(Event event, DayOfWeek day) { long daysDifference = new DateTime().getDifferenceInDays(event.getStart()); // checks if event is not within only at most a week ahead if (!(daysDifference >= 0 && daysDifference <= 7)) { return false; } int eventStartDay = event.getStart().getLocalDateTime().getDayOfWeek().getValue(); DateTime eventEndDate = event.getEnd(); Optional<DateTime> ed = Optional.ofNullable(eventEndDate); logger.info("Checking event: " + day + " " + daysDifference); if (ed.isPresent()) { Integer eventEndDay = ed.get().getLocalDateTime().getDayOfWeek().getValue(); Optional<Integer> endDay = Optional.ofNullable(eventEndDay); return day.getValue() >= eventStartDay && day.getValue() <= endDay.orElse(0); } else { return day.getValue() == eventStartDay; } } } private class CompletedQualifier implements Qualifier { boolean isCheckCompleted; public CompletedQualifier(boolean isCheckCompleted) { this.isCheckCompleted = isCheckCompleted; } @Override public boolean run(ReadOnlyTask task) { return isCheckCompleted == task.isCompleted(); } } // @@author A0138915X /** * Predicate for filtering events from the internal list. * * @param isMatchingForEvent If true, matches events. Else matches anything that's not an event. */ private class EventQualifier implements Qualifier { private final boolean isMatchingForEvent; public EventQualifier(boolean isMatchingForEvent) { this.isMatchingForEvent = isMatchingForEvent; } @Override public boolean run(ReadOnlyTask task) { return isMatchingForEvent == task instanceof Event; } } /** * Predicate for filtering floatingTasks from the internal list. * @param isMatchingForFloating If true, matches floating tasks. Else matches anything that's not a floating task. */ private class FloatingTaskQualifier implements Qualifier { private final boolean isMatchingForFloating; public FloatingTaskQualifier(boolean isMatchingForFloating) { this.isMatchingForFloating = isMatchingForFloating; } @Override public boolean run(ReadOnlyTask task) { return isMatchingForFloating == !(task instanceof Event || task instanceof DeadlineTask); } } /** * Predicate for filtering tasks from the internal list. * @param isCheckCompleted If true, matches tasks. Else matches anything that's not a task. */ private class TaskQualifier implements Qualifier { private final boolean isMatchingForTask; public TaskQualifier(boolean isMatchingForTask) { this.isMatchingForTask = isMatchingForTask; } @Override public boolean run(ReadOnlyTask task) { return isMatchingForTask == task instanceof FloatingTask; } } // @@author }
package seedu.malitio.storage; import com.google.common.eventbus.Subscribe; import seedu.malitio.commons.core.ComponentManager; import seedu.malitio.commons.core.LogsCenter; import seedu.malitio.commons.events.model.MalitioChangedEvent; import seedu.malitio.commons.events.storage.DataSavingExceptionEvent; import seedu.malitio.commons.events.storage.DataStorageFileChangedEvent; import seedu.malitio.commons.exceptions.DataConversionException; import seedu.malitio.commons.util.FileUtil; import seedu.malitio.model.ReadOnlyMalitio; import seedu.malitio.model.UserPrefs; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.Optional; import java.util.logging.Logger; /** * Manages storage of Malitio data in local storage. */ public class StorageManager extends ComponentManager implements Storage { private static final Logger logger = LogsCenter.getLogger(StorageManager.class); private MalitioStorage malitioStorage; private UserPrefsStorage userPrefsStorage; public StorageManager(MalitioStorage malitioStorage, UserPrefsStorage userPrefsStorage) { super(); this.malitioStorage = malitioStorage; this.userPrefsStorage = userPrefsStorage; } public StorageManager(String malitioFilePath, String userPrefsFilePath) { this(new XmlMalitioStorage(malitioFilePath), new JsonUserPrefsStorage(userPrefsFilePath)); } @Override public Optional<UserPrefs> readUserPrefs() throws DataConversionException, IOException { return userPrefsStorage.readUserPrefs(); } @Override public void saveUserPrefs(UserPrefs userPrefs) throws IOException { userPrefsStorage.saveUserPrefs(userPrefs); } @Override public String getMalitioFilePath() { return malitioStorage.getMalitioFilePath(); } @Override public Optional<ReadOnlyMalitio> readMalitio() throws DataConversionException, IOException { return readMalitio(malitioStorage.getMalitioFilePath()); } @Override public Optional<ReadOnlyMalitio> readMalitio(String filePath) throws DataConversionException, IOException { logger.fine("Attempting to read data from file: " + filePath); return malitioStorage.readMalitio(filePath); } @Override public void saveMalitio(ReadOnlyMalitio malitio) throws IOException { saveMalitio(malitio, malitioStorage.getMalitioFilePath()); } @Override public void saveMalitio(ReadOnlyMalitio malitio, String filePath) throws IOException { logger.fine("Attempting to write to data file: " + filePath); malitioStorage.saveMalitio(malitio, filePath); } @Override @Subscribe public void handleMalitioChangedEvent(MalitioChangedEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event, "Local data changed, saving to file")); try { saveMalitio(event.data, malitioStorage.getMalitioFilePath()); } catch (IOException e) { raise(new DataSavingExceptionEvent(e)); } } /** * Stores the current data file in the new directory and deletes the old data file. * @param event * @throws DataConversionException * @throws IOException */ //@@author a0126633j @Subscribe public void handleDataStorageFileChangedEvent(DataStorageFileChangedEvent event) throws DataConversionException, IOException { String oldDataFilePath = malitioStorage.getMalitioFilePath(); Optional<ReadOnlyMalitio> dataToBeTransferred = malitioStorage.readMalitio(); malitioStorage = new XmlMalitioStorage(event.dataFilePath); if(FileUtil.twoFilePathsAreEqual(oldDataFilePath, this.malitioStorage.getMalitioFilePath())) { return; } logger.info(LogsCenter.getEventHandlingLogMessage(event, "Data storage file path changed, updating..")); try { logger.info(LogsCenter.getEventHandlingLogMessage(event, "Old data file is being deleted.")); FileUtil.deleteFile(oldDataFilePath); } catch (IOException e) { logger.info(LogsCenter.getEventHandlingLogMessage(event, "Failed to delete old data file.")); } } }
package tigase.server.gateways; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.logging.Logger; import net.sf.jml.Email; import net.sf.jml.MsnContact; import net.sf.jml.MsnList; import net.sf.jml.MsnContactList; import net.sf.jml.MsnGroup; import net.sf.jml.MsnMessenger; import net.sf.jml.MsnOwner; import net.sf.jml.MsnSwitchboard; import net.sf.jml.MsnUserStatus; import net.sf.jml.MsnProtocol; import net.sf.jml.event.MsnContactListListener; import net.sf.jml.event.MsnMessageListener; import net.sf.jml.event.MsnMessengerListener; import net.sf.jml.impl.MsnMessengerFactory; import net.sf.jml.message.MsnControlMessage; import net.sf.jml.message.MsnDatacastMessage; import net.sf.jml.message.MsnInstantMessage; import net.sf.jml.message.MsnSystemMessage; import net.sf.jml.message.MsnUnknownMessage; import tigase.server.Packet; import tigase.util.JIDUtils; import tigase.xml.Element; import tigase.xml.XMLUtils; /** * Describe class MsnConnection here. * * * Created: Mon Nov 12 11:42:01 2007 * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class MsnConnection implements MsnContactListListener, GatewayConnection, MsnMessengerListener, MsnMessageListener { /** * Private logger for class instancess. */ private static Logger log = Logger.getLogger("tigase.server.gateways.MsnConnection"); private String username = null; private String password = null; private MsnMessenger messenger = null; private GatewayListener listener = null; private Set<String> xmpp_jids = new HashSet<String>(); private String active_jid = null; private String gatewayDomain = null; // Implementation of tigase.server.gateways.GatewayConnection public void setLogin(String username, String password) { this.username = username; this.password = password; log.finest("Username, password set: (" + username + "," + password + ")"); } public void setGatewayDomain(String domain) { this.gatewayDomain = domain; log.finest("gatewayDomain set: " + domain); } public void addJid(String jid) { xmpp_jids.add(jid); active_jid = jid; log.finest("JID added: " + jid); } public void removeJid(String jid) { xmpp_jids.remove(jid); log.finest("JID removed: " + jid); } public void setGatewayListener(GatewayListener listener) { this.listener = listener; } public void init() throws GatewayException { messenger = MsnMessengerFactory.createMsnMessenger(username, password); messenger.addMessageListener(this); messenger.addMessengerListener(this); messenger.addContactListListener(this); //messenger.setSupportedProtocol(new MsnProtocol[] {MsnProtocol.MSNP11}); //MsnOwner owner = messenger.getOwner(); //owner.setNotifyMeWhenSomeoneAddedMe(true); //owner.setOnlyNotifyAllowList(true); //owner.setInitStatus(MsnUserStatus.ONLINE); } public void login() { messenger.login(); } public void logout() { messenger.logout(); } public void sendMessage(Packet packet) { String address = JIDUtils.getNodeNick(packet.getElemTo()).replace("%", "@"); active_jid = packet.getElemFrom(); if (packet.getElemName().equals("message")) { log.finest("Sending message: " + packet.toString()); String body = XMLUtils.unescape(packet.getElemCData("/message/body")); messenger.sendText(Email.parseStr(address), body); } else { log.finest("Ignoring unknown packet: " + packet.toString()); } } // Implementation of net.sf.jml.event.MsnMessageListener /** * Describe <code>instantMessageReceived</code> method here. * * @param msnSwitchboard a <code>MsnSwitchboard</code> value * @param msnInstantMessage a <code>MsnInstantMessage</code> value * @param msnContact a <code>MsnContact</code> value */ public void instantMessageReceived(final MsnSwitchboard msnSwitchboard, final MsnInstantMessage msnInstantMessage, final MsnContact msnContact) { String to = active_jid; String from = listener.formatJID(msnContact.getEmail().getEmailAddress()); String content = XMLUtils.escape(msnInstantMessage.getContent()); Element message = new Element("message", new String[] {"from", "to", "type"}, new String[] {from, to, "chat"}); Element body = new Element("body", content); message.addChild(body); Packet packet = new Packet(message); log.finest("Received instant message: " + packet.toString()); listener.packetReceived(packet); } /** * Describe <code>controlMessageReceived</code> method here. * * @param msnSwitchboard a <code>MsnSwitchboard</code> value * @param msnControlMessage a <code>MsnControlMessage</code> value * @param msnContact a <code>MsnContact</code> value */ public void controlMessageReceived(final MsnSwitchboard msnSwitchboard, final MsnControlMessage msnControlMessage, final MsnContact msnContact) { String to = active_jid; String from = listener.formatJID(msnContact.getEmail().getEmailAddress()); Element message = new Element("message", new String[] {"from", "to", "type"}, new String[] {from, to, "chat"}); Element composing = new Element("composing"); composing.setXMLNS("http://jabber.org/protocol/chatstates"); message.addChild(composing); Packet packet = new Packet(message); log.finest("Received control message: " + packet.toString()); listener.packetReceived(packet); } /** * Describe <code>systemMessageReceived</code> method here. * * @param msnMessenger a <code>MsnMessenger</code> value * @param msnSystemMessage a <code>MsnSystemMessage</code> value */ public void systemMessageReceived(final MsnMessenger msnMessenger, final MsnSystemMessage msnSystemMessage) { // Do nothing.... // String to = active_jid; // String from = gatewayDomain; // String content = msnSystemMessage.getContent() == null ? "" // : XMLUtils.escape(msnSystemMessage.getContent()); // Element message = new Element("message", // new String[] {"from", "to", "type"}, // new String[] {from, to, "chat"}); // Element body = new Element("body", content); // message.addChild(body); // Packet packet = new Packet(message); // log.finest("Received system message: " + packet.toString()); // listener.packetReceived(packet); } /** * Describe <code>datacastMessageReceived</code> method here. * * @param msnSwitchboard a <code>MsnSwitchboard</code> value * @param msnDatacastMessage a <code>MsnDatacastMessage</code> value * @param msnContact a <code>MsnContact</code> value */ public void datacastMessageReceived(final MsnSwitchboard msnSwitchboard, final MsnDatacastMessage msnDatacastMessage, final MsnContact msnContact) { // Ignore for now, I don't know yet how to handle it. } /** * Describe <code>unknownMessageReceived</code> method here. * * @param msnSwitchboard a <code>MsnSwitchboard</code> value * @param msnUnknownMessage a <code>MsnUnknownMessage</code> value * @param msnContact a <code>MsnContact</code> value */ public void unknownMessageReceived(final MsnSwitchboard msnSwitchboard, final MsnUnknownMessage msnUnknownMessage, final MsnContact msnContact) { // Ignore for now, I don't know yet how to handle it. } // Implementation of net.sf.jml.event.MsnMessengerListener /** * Describe <code>logout</code> method here. * * @param msnMessenger a <code>MsnMessenger</code> value */ public void logout(final MsnMessenger msnMessenger) { List<RosterItem> roster = getRoster(msnMessenger, MsnUserStatus.OFFLINE); listener.logout(active_jid); listener.userRoster(active_jid, roster); log.finest(active_jid + " logout called."); } /** * Describe <code>loginCompleted</code> method here. * * @param msnMessenger a <code>MsnMessenger</code> value */ public void loginCompleted(final MsnMessenger msnMessenger) { listener.loginCompleted(active_jid); log.finest(active_jid + " logout completed."); MsnOwner owner = msnMessenger.getOwner(); log.fine("Owner initstatus: " + owner.getInitStatus().getDisplayStatus()); log.fine("Owner isNotifyMeWhenSomeoneAddedMe: " + owner.isNotifyMeWhenSomeoneAddedMe()); log.fine("Owner isOnlyNotifyAllowList: " + owner.isOnlyNotifyAllowList()); owner.setNotifyMeWhenSomeoneAddedMe(true); // owner.setOnlyNotifyAllowList(false); owner.setInitStatus(MsnUserStatus.ONLINE); owner.setStatus(MsnUserStatus.ONLINE); } /** * Describe <code>exceptionCaught</code> method here. * * @param msnMessenger a <code>MsnMessenger</code> value * @param throwable a <code>Throwable</code> value */ public void exceptionCaught(final MsnMessenger msnMessenger, final Throwable throwable) { listener.gatewayException(active_jid, throwable); } // Implementation of net.sf.jml.event.MsnContactListListener /** * Describe <code>contactListSyncCompleted</code> method here. * * @param msnMessenger a <code>MsnMessenger</code> value */ public void contactListSyncCompleted(final MsnMessenger msnMessenger) { log.finest(active_jid + " contactListSyncCompleted completed."); // MsnContact[] list = msnMessenger.getContactList().getContacts(); // if (list != null) { // Queue<Packet> buddy_presences = new LinkedList<Packet>(); // String to = active_jid; // String from = gatewayDomain; // Element iq = new Element("iq", // new String[] {"from", "to", "type", "id"}, // new String[] {from, to, "set", "1r"}); // Element query = new Element("query"); // query.setXMLNS("jabber:iq:roster"); // iq.addChild(query); // for (MsnContact contact: list) { // Element item = new Element("item"); // String jid = XMLUtils.escape(contact.getId().replace("@", "%") // + "@" + gatewayDomain); // item.setAttribute("jid", jid); // item.setAttribute("subscription", "both"); // item.setAttribute("name", XMLUtils.escape(contact.getFriendlyName())); // MsnGroup[] groups = contact.getBelongGroups(); // if (groups != null && groups.length > 0) { // for (MsnGroup group: groups) { // Element grel = new Element("group"); // grel.setCData(group.getGroupName()); // item.addChild(grel); // query.addChild(item); // Element presence = new Element("presence", // new String[] {"from", "to"}, new String[] {jid, to}); // if (contact.getStatus() == MsnUserStatus.OFFLINE ) { // presence.setAttribute("type", "unavailable"); // } else { // presence.addChild(new Element("show", // contact.getStatus().getDisplayStatus())); // buddy_presences.offer(new Packet(presence)); // Packet roster = new Packet(iq); // log.finest("Sending out the roster: " + roster.toString()); // listener.packetReceived(roster); // Packet pack = null; // while ((pack = buddy_presences.poll()) != null) { // log.finest("Sending out the buddy presence: " + pack.toString()); // listener.packetReceived(pack); } private List<RosterItem> getRoster(final MsnMessenger msnMessenger, final MsnUserStatus presetStatus) { MsnContact[] list = msnMessenger.getContactList().getContacts(); List<RosterItem> roster = new ArrayList<RosterItem>(); if (list != null) { for (MsnContact contact: list) { if (contact.isInList(MsnList.AL)) { MsnGroup[] c_groups = contact.getBelongGroups(); if (c_groups != null && c_groups.length > 0) { for (MsnGroup c_grp: c_groups) { log.fine("Contact " + contact.getEmail().getEmailAddress() + " group: " + c_grp.getGroupName()); } } else { log.fine("Contact " + contact.getEmail().getEmailAddress() + " is not in any group"); } MsnContactList c_list = contact.getContactList(); RosterItem item = new RosterItem(contact.getEmail().getEmailAddress()); item.setName(contact.getFriendlyName()); item.setSubscription("both"); MsnUserStatus status = presetStatus != null ? presetStatus : contact.getStatus(); if (status == MsnUserStatus.OFFLINE ) { item.setStatus(new UserStatus("unavailable", null)); } else { item.setStatus(new UserStatus(null, status.getDisplayStatus().toLowerCase())); } MsnGroup[] groups = contact.getBelongGroups(); if (groups != null && groups.length > 0) { List<String> grps = new ArrayList<String>(); for (MsnGroup group: groups) { grps.add(group.getGroupName()); } item.setGroups(grps); } log.finest("Contact AL received: " + contact.getEmail().getEmailAddress() + ", status: " + status.getDisplayStatus()); roster.add(item); } if (contact.isInList(MsnList.AL)) { log.fine("Contact " + contact.getEmail().getEmailAddress() + " is on AL list."); } if (contact.isInList(MsnList.BL)) { log.fine("Contact " + contact.getEmail().getEmailAddress() + " is on BL list."); } if (contact.isInList(MsnList.FL)) { log.fine("Contact " + contact.getEmail().getEmailAddress() + " is on FL list."); } if (contact.isInList(MsnList.PL)) { log.fine("Contact " + contact.getEmail().getEmailAddress() + " is on PL list."); } if (contact.isInList(MsnList.RL)) { log.fine("Contact " + contact.getEmail().getEmailAddress() + " is on RL list."); } } } return roster; } /** * Describe <code>contactListInitCompleted</code> method here. * * @param msnMessenger a <code>MsnMessenger</code> value */ public void contactListInitCompleted(final MsnMessenger msnMessenger) { log.finest(active_jid + " contactListInitCompleted completed."); listener.userRoster(active_jid, getRoster(msnMessenger, null)); } /** * Describe <code>contactStatusChanged</code> method here. * * @param msnMessenger a <code>MsnMessenger</code> value * @param msnContact a <code>MsnContact</code> value */ public void contactStatusChanged(final MsnMessenger msnMessenger, final MsnContact msnContact) { log.finest(active_jid + " contactStatusChanged completed."); // String to = active_jid; // String jid = // XMLUtils.escape(msnContact.getEmail().getEmailAddress().replace("@", "%") // + "@" + gatewayDomain); // Element presence = new Element("presence", // new String[] {"from", "to"}, new String[] {jid, to}); // if (msnContact.getStatus() == MsnUserStatus.OFFLINE ) { // presence.setAttribute("type", "unavailable"); // } else { // presence.addChild(new Element("show", // msnContact.getStatus().getDisplayStatus().toLowerCase())); // Packet packet = new Packet(presence); // log.finest("Sending out buddy presence: " + packet.toString()); if (msnContact.isInList(MsnList.AL)) { RosterItem item = new RosterItem(msnContact.getEmail().getEmailAddress()); item.setName(msnContact.getFriendlyName()); item.setSubscription("both"); if (msnContact.getStatus() == MsnUserStatus.OFFLINE ) { item.setStatus(new UserStatus("unavailable", null)); } else { item.setStatus(new UserStatus(null, msnContact.getStatus().getDisplayStatus().toLowerCase())); } MsnGroup[] groups = msnContact.getBelongGroups(); if (groups != null && groups.length > 0) { List<String> grps = new ArrayList<String>(); for (MsnGroup group: groups) { grps.add(group.getGroupName()); } item.setGroups(grps); } listener.updateStatus(active_jid, item); } if (msnContact.isInList(MsnList.AL)) { log.fine("Contact " + msnContact.getEmail().getEmailAddress() + " is on AL list."); } if (msnContact.isInList(MsnList.BL)) { log.fine("Contact " + msnContact.getEmail().getEmailAddress() + " is on BL list."); } if (msnContact.isInList(MsnList.FL)) { log.fine("Contact " + msnContact.getEmail().getEmailAddress() + " is on FL list."); } if (msnContact.isInList(MsnList.PL)) { log.fine("Contact " + msnContact.getEmail().getEmailAddress() + " is on PL list."); } if (msnContact.isInList(MsnList.RL)) { log.fine("Contact " + msnContact.getEmail().getEmailAddress() + " is on RL list."); } } /** * Describe <code>ownerStatusChanged</code> method here. * * @param msnMessenger a <code>MsnMessenger</code> value */ public void ownerStatusChanged(final MsnMessenger msnMessenger) { log.finest(active_jid + " ownerStatusChanged completed."); } /** * Describe <code>contactAddedMe</code> method here. * * @param msnMessenger a <code>MsnMessenger</code> value * @param msnContact a <code>MsnContact</code> value */ public void contactAddedMe(final MsnMessenger msnMessenger, final MsnContact msnContact) { String to = active_jid; String from = listener.formatJID(msnContact.getEmail().getEmailAddress()); Element presence = new Element("presence", new String[] {"from", "to", "type"}, new String[] {from, to, "subscribe"}); Packet packet = new Packet(presence); log.finest("Received subscription presence: " + packet.toString()); listener.packetReceived(packet); presence = new Element("presence", new String[] {"from", "to", "type"}, new String[] {from, to, "subscribed"}); packet = new Packet(presence); log.finest("Received subscription presence: " + packet.toString()); listener.packetReceived(packet); log.finest(active_jid + " contactAddedMe completed."); } /** * Describe <code>contactRemovedMe</code> method here. * * @param msnMessenger a <code>MsnMessenger</code> value * @param msnContact a <code>MsnContact</code> value */ public void contactRemovedMe(final MsnMessenger msnMessenger, final MsnContact msnContact) { String to = active_jid; String from = listener.formatJID(msnContact.getEmail().getEmailAddress()); Element presence = new Element("presence", new String[] {"from", "to", "type"}, new String[] {from, to, "unsubscribe"}); Packet packet = new Packet(presence); log.finest("Received subscription presence: " + packet.toString()); listener.packetReceived(packet); presence = new Element("presence", new String[] {"from", "to", "type"}, new String[] {from, to, "unsubscribed"}); packet = new Packet(presence); log.finest("Received subscription presence: " + packet.toString()); listener.packetReceived(packet); log.finest(active_jid + " contactRemovedMe completed."); } /** * Describe <code>contactAddCompleted</code> method here. * * @param msnMessenger a <code>MsnMessenger</code> value * @param msnContact a <code>MsnContact</code> value */ public void contactAddCompleted(final MsnMessenger msnMessenger, final MsnContact msnContact) { RosterItem item = new RosterItem(msnContact.getEmail().getEmailAddress()); item.setName(msnContact.getFriendlyName()); item.setSubscription("both"); if (msnContact.getStatus() == MsnUserStatus.OFFLINE ) { item.setStatus(new UserStatus("unavailable", null)); } else { item.setStatus(new UserStatus(null, msnContact.getStatus().getDisplayStatus().toLowerCase())); } MsnGroup[] groups = msnContact.getBelongGroups(); if (groups != null && groups.length > 0) { List<String> grps = new ArrayList<String>(); for (MsnGroup group: groups) { grps.add(group.getGroupName()); } item.setGroups(grps); } listener.updateStatus(active_jid, item); log.finest(active_jid + " contactAddCompleted completed."); } /** * Describe <code>contactRemoveCompleted</code> method here. * * @param msnMessenger a <code>MsnMessenger</code> value * @param msnContact a <code>MsnContact</code> value */ public void contactRemoveCompleted(final MsnMessenger msnMessenger, final MsnContact msnContact) { log.finest(active_jid + " contactRemoveCompleted completed: " + msnContact.getEmail().getEmailAddress()); } /** * Describe <code>groupAddCompleted</code> method here. * * @param msnMessenger a <code>MsnMessenger</code> value * @param msnGroup a <code>MsnGroup</code> value */ public void groupAddCompleted(final MsnMessenger msnMessenger, final MsnGroup msnGroup) { log.finest(active_jid + " groupAddCompleted completed."); } /** * Describe <code>groupRemoveCompleted</code> method here. * * @param msnMessenger a <code>MsnMessenger</code> value * @param msnGroup a <code>MsnGroup</code> value */ public void groupRemoveCompleted(final MsnMessenger msnMessenger, final MsnGroup msnGroup) { log.finest(active_jid + " groupRemoveCompleted completed."); } public void addBuddy(String id, String nick) throws GatewayException { messenger.addFriend(Email.parseStr(id), nick); messenger.unblockFriend(Email.parseStr(id)); log.finest(active_jid + " addBuddy completed: " + id); } public void removeBuddy(String id) throws GatewayException { messenger.removeFriend(Email.parseStr(id), false); log.finest(active_jid + " removeBuddy completed: " + id); } public String getType() { return "msn"; } public String getName() { return "MSN Gateway"; } public String getPromptMessage() { return "Please enter the Windows Live Messenger address of the person " + "you would like to contact."; } }
package levels; import item.Item; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import javax.imageio.ImageIO; import thingsthatmove.Enemy; import thingsthatmove.GameObject; import thingsthatmove.Player; import thingsthatmove.Projectile; public class Room { private ArrayList<Enemy> enemies = new ArrayList<Enemy>(); private ArrayList<Rectangle> hitboxes = new ArrayList<Rectangle>(); private ArrayList<Item> items = new ArrayList<Item>(); private ArrayList<GameObject> roomObjects = new ArrayList<GameObject>(); private Thread moveEnemies; private Player player; private Image background, hud; private Image northClosedDoor, southClosedDoor, eastClosedDoor, westClosedDoor; private Image northOpenDoor, southOpenDoor, eastOpenDoor, westOpenDoor; private Room north, east, south, west; private boolean northOpen, southOpen, eastOpen, westOpen; private boolean atNorthDoor, atSouthDoor, atEastDoor, atWestDoor; private boolean inRoom; // The room bounds private final int LOWER_X_BOUND = 90; private final int UPPER_X_BOUND = 960; private final int LOWER_Y_BOUND = 200; private final int UPPER_Y_BOUND = 672; private final int NORTH_DOOR_X = 450; private final int NORTH_DOOR_Y = 335; private final int SOUTH_DOOR_X = 450; private final int SOUTH_DOOR_Y = 681; private final int EAST_DOOR_X = 926; private final int EAST_DOOR_Y = 420; private final int WEST_DOOR_X = 140; private final int WEST_DOOR_Y = 420; public Room(ArrayList<Enemy> e, ArrayList<Item> i, ArrayList<GameObject> go, Player p, Room north, Room east, Room south, Room west) { this.enemies = e; this.items = i; this.roomObjects = go; this.player = p; this.north = north; this.east = east; this.south = south; this.west = west; try { hud = ImageIO.read(getClass().getResource("/images/hud.png")); background = ImageIO.read(getClass().getResource("/images/emptyroomSCALED.png")); //Closed doors northClosedDoor = ImageIO.read(getClass().getResourceAsStream("/images/doors/closeddoornorth.png")); southClosedDoor = ImageIO.read(getClass().getResourceAsStream("/images/doors/closeddoorsouth.png")); eastClosedDoor = ImageIO.read(getClass().getResourceAsStream("/images/doors/closeddooreast.png")); westClosedDoor = ImageIO.read(getClass().getResourceAsStream("/images/doors/closeddoorwest.png")); //Open doors northOpenDoor = ImageIO.read(getClass().getResourceAsStream("/images/doors/opendoornorth.png")); southOpenDoor = ImageIO.read(getClass().getResourceAsStream("/images/doors/opendoorsouth.png")); eastOpenDoor = ImageIO.read(getClass().getResourceAsStream("/images/doors/opendooreast.png")); westOpenDoor = ImageIO.read(getClass().getResourceAsStream("/images/doors/opendoorwest.png")); } catch (IOException ioe) { ioe.printStackTrace(); } atNorthDoor = false; atSouthDoor = false; atEastDoor = false; atWestDoor = false; } public Room(ArrayList<Enemy> e, ArrayList<Item> i, ArrayList<GameObject> go, Player p) { this(e, i, go, p, null, null, null, null); } public Room(Room north, Room east, Room south, Room west) { this(null, null, null, null, north, east, south, west); } public boolean isNorthOpen() { return northOpen; } public boolean isSouthOpen() { return southOpen; } public boolean isEastOpen() { return eastOpen; } public boolean isWestOpen() { return westOpen; } public void updateDoorStatus() { // Keep all doors closed if there are enemies if (hasEnemies()) { northOpen = false; southOpen = false; eastOpen = false; westOpen = false; } // No enemies, open all doors else { northOpen = true; southOpen = true; eastOpen = true; westOpen = true; } } public void update() { updateHitboxes(); updateDoorStatus(); checkIfPlayerAtDoor(); checkProjectileCollision(); } /** * Checks collisions between all the projectiles and the enemies in this room */ private void checkProjectileCollision() { ArrayList<Projectile> projectiles = player.getAllPlayerProjectiles(); for(Projectile p : projectiles) { for(Enemy e : enemies) { if (p.getHitBox().intersects(e.getHitBox())) { e.takeDamage(p.getDamage()); p.killProjectile(); } } } } /** * Checks if a player is at one of the doors and sets booleans if it is */ private void checkIfPlayerAtDoor() { //Check if player is at a door double x = player.getX(); double y = player.getY(); //North door if (north != null && x > 412 && x < 518 && y < 250) { atNorthDoor = true; } else if (south != null && x > 412 && x < 518 && y > 565) { atSouthDoor = true; } else if (east != null && x > 845 && y > 392 && y < 498) { atEastDoor = true; } else if (west != null && x < 210 && y > 392 && y < 498) { atWestDoor = true; } } public boolean isPlayerAtNorthDoor() { if (atNorthDoor && player.isMovingNorth()) return true; return false; } public boolean isPlayerAtSouthDoor() { if (atSouthDoor && player.isMovingSouth()) return true; return false; } public boolean isPlayerAtEastDoor() { if (atEastDoor && player.isMovingEast()) return true; return false; } public boolean isPlayerAtWestDoor() { if (atWestDoor && player.isMovingWest()) return true; return false; } public void resetAllDoors() { atNorthDoor = false; atSouthDoor = false; atEastDoor = false; atWestDoor = false; } public Player getPlayer() { return player; } public void setPlayer(Player p) { this.player = p; } public void removePlayer() { this.player = null; } public boolean hasPlayer() { if (player == null) return false; return true; } public ArrayList<Enemy> getEnemies() { return enemies; } public void addEnemies(ArrayList<Enemy> e) { enemies = e; } public void removeEnemies() { enemies = null; } public boolean hasEnemies() { if (enemies == null) return false; return true; } public ArrayList<Item> getItems() { return items; } public void addItems(ArrayList<Item> i) { items = i; } public void removeItems() { items = null; } public boolean hasItems() { if (items == null) return false; return true; } public ArrayList<GameObject> getRoomObjects() { return roomObjects; } public void addRoomObjects(ArrayList<GameObject> go) { roomObjects = go; } public void removeRoomObjects() { roomObjects = null; } public boolean hasRoomObjects() { if (roomObjects == null) return false; return true; } public boolean setNorth(Room r) { if (north != null) return false; north = r; return true; } public boolean setSouth(Room r) { if (south != null) return false; south = r; return true; } public boolean setWest(Room r) { if (west != null) return false; west = r; return true; } public boolean setEast(Room r) { if (east != null) return false; east = r; return true; } public Room getNorth() { return north; } public Room getSouth() { return south; } public Room getWest() { return west; } public Room getEast() { return east; } public boolean isFull() { if (north != null && south != null && west != null && east != null) return true; return false; } public void startRoom() { updateHitboxes(); resetAllDoors(); inRoom = true; System.out.println("STARTING ROOM"); moveEnemies = new Thread(new EnemyMovementThread()); moveEnemies.start(); } public void endRoom() { System.out.println("ENDING ROOM"); inRoom = false; //Clear all projectiles player.clearProjectiles(); } public void updateHitboxes() { // Remove all current hitboxes hitboxes.clear(); // Add all enemy hitboxes for (Enemy e : enemies) hitboxes.add(e.getHitBox()); // Add all item hitboxes for (Item i : items) hitboxes.add(i.getHitBox()); } public boolean enemyCollision(int enemyIndex, Rectangle enemyHitbox) { for (int i = 0; i < enemyIndex; i++) { updateHitboxes(); if (enemyHitbox.intersects(hitboxes.get(i))) return true; } for (int j = enemyIndex + 1; j < hitboxes.size(); j++) { //updateHitboxes(); System.out.println("HITBOX SIZE " + hitboxes.size() + " CURRENT INDEX " + j); if (enemyHitbox.intersects(hitboxes.get(j))) return true; } return false; } public void draw(Graphics g) { g.drawImage(hud, 0, 0, null); g.drawImage(background, 0, 198, null); g.setColor(Color.RED); g.drawRect(130, 325, 780, 250); g.setColor(Color.BLACK); drawDoors(g); for (Enemy currentEnemy : enemies) { Rectangle r = currentEnemy.getHitBox(); g.drawImage(currentEnemy.getImage(), (int)currentEnemy.getX(), (int)currentEnemy.getY(), null); g.drawRect((int)r.getX(), (int)r.getY(), (int)r.getWidth(), (int)r.getHeight()); } for (Item currentItem : items) { g.drawImage(currentItem.getImage(), (int)currentItem.getX(), (int)currentItem.getY(), null); } for (GameObject currentRoomObject : roomObjects) { g.drawImage(currentRoomObject.getImage(), (int)currentRoomObject.getX(), (int)currentRoomObject.getY(), null); } } /** * Draws the doors of the room to the given graphics * * @param g the graphics to draw to */ private void drawDoors(Graphics g) { //Draw doors if (north != null) { if (northOpen) g.drawImage(northOpenDoor, NORTH_DOOR_X, NORTH_DOOR_Y - 100, null); else g.drawImage(northClosedDoor, NORTH_DOOR_X, NORTH_DOOR_Y - 100, null); } if (south != null) { if (southOpen) g.drawImage(southOpenDoor, SOUTH_DOOR_X, SOUTH_DOOR_Y, null); else g.drawImage(southClosedDoor, SOUTH_DOOR_X, SOUTH_DOOR_Y, null); } if (east != null) { if (eastOpen) g.drawImage(eastOpenDoor, EAST_DOOR_X, EAST_DOOR_Y, null); else g.drawImage(eastClosedDoor, EAST_DOOR_X, EAST_DOOR_Y, null); } if (west != null) { if (westOpen) g.drawImage(westOpenDoor, WEST_DOOR_X - 100, WEST_DOOR_Y, null); else g.drawImage(westClosedDoor, WEST_DOOR_X - 100, WEST_DOOR_Y, null); } } private class EnemyMovementThread implements Runnable { public void run() { while (inRoom) { for (int n = 0; n < enemies.size(); n++) { // Each enemy can go four directions (N,E,S,W) // Enemies decide on which direction to take on a random basis // Enemies want to (more likely) to continue moving in a direction, until they hit another game object // After hitting another game object they will decide another direction on a random basis // When enemies are within aggro-range follow players // Enemies cannot overlap other game objects Enemy currentEnemy = enemies.get(n); if (!currentEnemy.isAlive()) enemies.remove(n); // Only move moveable enemies else if (currentEnemy.canMove()) { int direction; Random r = new Random(); // No initial direction if (currentEnemy.getDirection() == ' ') currentEnemy.setRandomDirection(); // Already moving in a direction else { // Set a 5% chance to change direction if (r.nextInt(100) >= 95) currentEnemy.setRandomDirection(); } // Keep track of old coordinates int oldX = (int)currentEnemy.getX(); int oldY = (int)currentEnemy.getY(); // Enemy is of the aggresive type if (currentEnemy.isAngry()) { int enemyWidth = (int) currentEnemy.getSize().getWidth(); int enemyHeight = (int) currentEnemy.getSize().getHeight(); // Make an aggro rectangle for range // Aggro range is in a 5 * enemy width by 5 * enemy height box with the enemy in the centre Rectangle aggroBox = new Rectangle(oldX - enemyWidth * 2, oldY - enemyHeight * 2, enemyWidth * 5, enemyHeight * 5); // Player is within aggro range if (aggroBox.intersects(player.getHitBox())) { // Change direction to run at the player AGGRESIVELY if (player.getX() == currentEnemy.getX()) { if (player.getY() > currentEnemy.getY()) currentEnemy.setDirection('S'); else currentEnemy.setDirection('N'); } else if (player.getX() > currentEnemy.getX()) currentEnemy.setDirection('E'); else currentEnemy.setDirection('W'); } } // Move the enemy in its direction currentEnemy.moveInDirection(); // There is a collision with another ENEMY or ITEM (not player) so move back and change direction if (enemyCollision(n, currentEnemy.getHitBox())) { currentEnemy.move(oldX, oldY); currentEnemy.setRandomDirection(); currentEnemy.moveInDirection(); // Still collision if (enemyCollision(n, currentEnemy.getHitBox())) { currentEnemy.move(oldX, oldY); currentEnemy.setRandomDirection(); currentEnemy.moveInDirection(); // Still collision if (enemyCollision(n, currentEnemy.getHitBox())) currentEnemy.move(oldX, oldY); } } } } try { Thread.sleep(20); } catch (Exception exc) { } } } } }
package uk.ac.edukapp.servlets; import uk.ac.edukapp.model.*; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.Namespace; import org.jdom.input.SAXBuilder; /** * Servlet implementation class RegisterServlet */ public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; private Log log; private static final File FILE_UPLOAD_TEMP_DIRECTORY = new File( System.getProperty("java.io.tmpdir")); private int intMaxFileUploadSize = 25 * 1024 * 1024;// 25 mb is more than // enough /** * @see HttpServlet#HttpServlet() */ public UploadServlet() { super(); log = LogFactory.getLog(UploadServlet.class); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(request)) {// file attached // =>widget invoke // wookie/widgets // rest service DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // Set factory constraints diskFileItemFactory.setSizeThreshold(intMaxFileUploadSize); diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY); // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload( diskFileItemFactory); try { // Get the multipart items as a list List<FileItem> listFileItems = (List<FileItem>) servletFileUpload .parseRequest(request); // Create a list to hold all of the parts List<org.apache.commons.httpclient.methods.multipart.Part> listParts = new ArrayList<org.apache.commons.httpclient.methods.multipart.Part>(); // Iterate the multipart items list for (FileItem fileItemCurrent : listFileItems) { // If the current item is a form field, then create a string // part if (fileItemCurrent.isFormField()) { StringPart stringPart = new StringPart( fileItemCurrent.getFieldName(), // The field // name fileItemCurrent.getString() // The field value ); log.info("request string part:" + fileItemCurrent.getFieldName() + ":" + fileItemCurrent.getString()); // Add the part to the list listParts.add(stringPart); } else { // The item is a file upload, so we create a FilePart FilePart filePart = new FilePart( fileItemCurrent.getFieldName(), // The field // name new ByteArrayPartSource( fileItemCurrent.getName(), // The // uploaded // file name fileItemCurrent.get() // The uploaded // file contents )); // Add the part to the list listParts.add(filePart); } } PostMethod postMethod = new PostMethod( "http://widgets.open.ac.uk:8080/wookie/widgets"); MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts .toArray(new org.apache.commons.httpclient.methods.multipart.Part[] {}), postMethod.getParams()); postMethod.setRequestEntity(multipartRequestEntity); HttpClient client = new HttpClient(); // add the basic http authentication credentials Credentials defaultcreds = new UsernamePasswordCredentials( "java", "java"); client.getState().setCredentials( new AuthScope("widgets.open.ac.uk", 8080, AuthScope.ANY_REALM), defaultcreds); int status = client.executeMethod(postMethod); System.out.println("returns status:" + status); log.info("post execution return status:" + status); byte[] responseBody = postMethod.getResponseBody(); System.out.println("RESPONSE follows"); System.out.println(new String(responseBody)); log.info("RESPONSE follows"); log.info(new String(responseBody)); InputStream istream = postMethod.getResponseBodyAsStream(); // if (status == HttpStatus.SC_OK) { // // HTTP 200 succesful upload // // widget updated // } else if (status == HttpStatus.SC_CREATED) { // // HTTP 201 succesful upload // // - new widget created if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED) { SAXBuilder builder = new SAXBuilder(); Document document = (Document) builder.build(istream); Element rootNode = document.getRootElement(); Namespace XML_NS = Namespace.getNamespace("", "http: String widget_id = rootNode.getAttributeValue("id"); String version = rootNode.getAttributeValue("version"); String recomended_height = rootNode .getAttributeValue("height"); String recomended_width = rootNode .getAttributeValue("width"); String name = rootNode.getChildText("name", XML_NS); String icon = rootNode.getChildText("icon", XML_NS); String description = rootNode.getChildText("description", XML_NS); String author = rootNode.getChildText("author", XML_NS); System.out.println("\n\nname:" + name + "\n\n"); log.info("\n\nname:" + name + "\n\n"); EntityManagerFactory factory = Persistence .createEntityManagerFactory("edukapp"); EntityManager em = factory.createEntityManager(); Widgetprofile widgetprofile = null; try { em.getTransaction().begin(); widgetprofile = new Widgetprofile(); widgetprofile.setName(name); byte zero = 0; widgetprofile.setW3cOrOs(zero); widgetprofile.setWidId(widget_id); em.persist(widgetprofile); WidgetDescription wd = new WidgetDescription(); wd.setDescription(description); wd.setWid_id(widgetprofile.getId()); em.persist(wd); log.info("Widget created with id:" + widgetprofile.getId()); } catch (Exception e) { e.printStackTrace(); // em.getTransaction().rollback(); doForward(request, response, "/upload.jsp?error=1"); } em.getTransaction().commit(); em.close(); factory.close(); if (widgetprofile != null) { doForward(request, response, "/widget.jsp?id=" + widgetprofile.getId()); } else { doForward(request, response, "/upload.jsp?error=2"); } } else { // any other HTTP status than 200/201 doForward(request, response, "/upload.jsp?error=3"); } } catch (HttpException hte) { log.error("Fatal protocol violation: " + hte.getMessage()); hte.printStackTrace(); doForward(request, response, "/upload.jsp?error=4"); } catch (IOException ioe) { log.error("Fatal transport error: " + ioe.getMessage()); ioe.printStackTrace(); doForward(request, response, "/upload.jsp?error=5"); } catch (FileUploadException fue) { fue.printStackTrace(); doForward(request, response, "/upload.jsp?error=6"); } catch (JDOMException jdomex) { jdomex.printStackTrace(); doForward(request, response, "/upload.jsp?error=7"); } catch (Exception e) { e.printStackTrace(); doForward(request, response, "/upload.jsp?error=9"); } } else { // get parameters String uploadurl = null; String gadgetName = null; uploadurl = request.getParameter("uploadurl"); gadgetName = request.getParameter("gadget-name"); EntityManagerFactory factory = Persistence .createEntityManagerFactory("edukapp"); EntityManager em = factory.createEntityManager(); Widgetprofile gadget = null; try { em.getTransaction().begin(); gadget = new Widgetprofile(); gadget.setName(gadgetName); byte one = 1; gadget.setW3cOrOs(one); gadget.setWidId(uploadurl); em.persist(gadget); log.info("Gadget created with id:" + gadget.getId()); } catch (Exception e) { e.printStackTrace(); // em.getTransaction().rollback(); doForward(request, response, "/upload.jsp?error=1"); } em.getTransaction().commit(); em.close(); factory.close(); if (gadget != null) { doForward(request, response, "/widget.jsp?id=" + gadget.getId()); } else { doForward(request, response, "/upload.jsp?error=1"); } } } private void doForward(HttpServletRequest request, HttpServletResponse response, String jsp) throws ServletException, IOException { /* * if we redirect using the dispatcher then the url in address bar does * not update */ // RequestDispatcher dispatcher = getServletContext() // .getRequestDispatcher(jsp); // dispatcher.forward(request, response); response.sendRedirect(jsp); } }
package net.finmath.functions; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.ArrayRealVector; import org.apache.commons.math3.linear.DecompositionSolver; import org.apache.commons.math3.linear.EigenDecomposition; import org.apache.commons.math3.linear.LUDecomposition; import org.apache.commons.math3.linear.QRDecomposition; import org.apache.commons.math3.linear.SingularValueDecomposition; import cern.colt.matrix.impl.DenseDoubleMatrix2D; /** * This class implements some methods from linear algebra (e.g. solution of a linear equation, PCA). * * It is basically a functional wrapper using either the Colt library or Apache commons math. * * I am currently preferring to use Colt, due to better performance in some situations, however it allows * to easily switch some parts to Apache commons math (this is the motivation for this class). * * @author Christian Fries * @version 1.5 */ public class LinearAlgebra { /** * Find a solution of the linear equation A x = b where * <ul> * <li>A is an n x m - matrix given as double[n][m]</li> * <li>b is an m - vector given as double[m],</li> * <li>x is an n - vector given as double[n],</li> * </ul> * * @param A The matrix (left hand side of the linear equation). * @param b The vector (right hand of the linear equation). * @return A solution x to A x = b. */ public static double[] solveLinearEquation(double[][] A, double[] b) { /* * We still use Colt, because in some situation Colt appears to be faster by a factor * of 2 to 5. Sometimes even more. * SVD is very slow. * For jblas use: * return org.jblas.Solve.solve(new org.jblas.DoubleMatrix(A), new org.jblas.DoubleMatrix(b)).data; */ boolean isSolveLinearEquationUseColt = true; if(isSolveLinearEquationUseColt) { // We use the linear algebra package from cern. cern.colt.matrix.linalg.Algebra linearAlgebra = new cern.colt.matrix.linalg.Algebra(); double[] x = linearAlgebra.solve(new DenseDoubleMatrix2D(A), linearAlgebra.transpose(new DenseDoubleMatrix2D(new double[][] { b }))).viewColumn(0).toArray(); return x; } else { Array2DRowRealMatrix matrix = new Array2DRowRealMatrix(A); DecompositionSolver solver; if(matrix.getColumnDimension() == matrix.getRowDimension()) { solver = new LUDecomposition(matrix).getSolver(); } else { solver = new QRDecomposition(new Array2DRowRealMatrix(A)).getSolver(); } // Using SVD // solver = new SingularValueDecomposition(new Array2DRowRealMatrix(A)).getSolver(); double[] x = solver.solve(new Array2DRowRealMatrix(b)).getColumn(0); return x; } } /** * Returns the inverse of a given matrix. * * @param matrix A matrix given as double[n][n]. * @return The inverse of the given matrix. */ public static double[][] invert(double[][] matrix) { // Use LU from common math LUDecomposition lu = new LUDecomposition(new Array2DRowRealMatrix(matrix)); double[][] matrixInverse = lu.getSolver().getInverse().getData(); return matrixInverse; } /** * Find a solution of the linear equation A x = b where * <ul> * <li>A is an symmetric n x n - matrix given as double[n][n]</li> * <li>b is an n - vector given as double[n],</li> * <li>x is an n - vector given as double[n],</li> * </ul> * * @param matrix The matrix A (left hand side of the linear equation). * @param vector The vector b (right hand of the linear equation). * @return A solution x to A x = b. */ public static double[] solveLinearEquationSymmetric(double[][] matrix, double[] vector) { return solveLinearEquation(matrix, vector); // We use the linear algebra package apache commons math // DecompositionSolver solver = new LUDecomposition(new Array2DRowRealMatrix(matrix, false)).getSolver(); // DecompositionSolver solver = new CholeskyDecomposition(new Array2DRowRealMatrix(matrix, false)).getSolver(); // return solver.solve(new ArrayRealVector(vector)).toArray(); } /** * Find a solution of the linear equation A x = b in the least square sense where * <ul> * <li>A is an n x m - matrix given as double[n][m]</li> * <li>b is an m - vector given as double[m],</li> * <li>x is an n - vector given as double[n],</li> * </ul> * * @param matrix The matrix A (left hand side of the linear equation). * @param vector The vector b (right hand of the linear equation). * @return A solution x to A x = b. */ public static double[] solveLinearEquationLeastSquare(double[][] matrix, double[] vector) { // We use the linear algebra package apache commons math DecompositionSolver solver = new SingularValueDecomposition(new Array2DRowRealMatrix(matrix, false)).getSolver(); return solver.solve(new ArrayRealVector(vector)).toArray(); } /** * Returns the matrix of the n Eigenvectors corresponding to the first n largest Eigenvalues of a correlation matrix. * These Eigenvectors can also be interpreted as "principal components" (i.e., the method implements the PCA). * * @param correlationMatrix The given correlation matrix. * @param numberOfFactors The requested number of factors (eigenvectors). * @return Matrix of n Eigenvectors (columns) (matrix is given as double[n][numberOfFactors], where n is the number of rows of the correlationMatrix. */ public static double[][] getFactorMatrix(double[][] correlationMatrix, int numberOfFactors) { return getFactorMatrixUsingCommonsMath(correlationMatrix, numberOfFactors); } /** * Returns a correlation matrix which has rank &lt; n and for which the first n factors agree with the factors of correlationMatrix. * * @param correlationMatrix The given correlation matrix. * @param numberOfFactors The requested number of factors (Eigenvectors). * @return Factor reduced correlation matrix. */ public static double[][] factorReduction(double[][] correlationMatrix, int numberOfFactors) { return factorReductionUsingCommonsMath(correlationMatrix, numberOfFactors); } /** * Returns the matrix of the n Eigenvectors corresponding to the first n largest Eigenvalues of a correlation matrix. * These eigenvectors can also be interpreted as "principal components" (i.e., the method implements the PCA). * * @param correlationMatrix The given correlation matrix. * @param numberOfFactors The requested number of factors (Eigenvectors). * @return Matrix of n Eigenvectors (columns) (matrix is given as double[n][numberOfFactors], where n is the number of rows of the correlationMatrix. */ private static double[][] getFactorMatrixUsingCommonsMath(double[][] correlationMatrix, int numberOfFactors) { /* * Factor reduction */ // Create an eigen vector decomposition of the correlation matrix EigenDecomposition eigenDecomp = new EigenDecomposition(new Array2DRowRealMatrix(correlationMatrix, false)); double[] eigenValues = eigenDecomp.getRealEigenvalues(); double[][] eigenVectorMatrix = eigenDecomp.getV().getData(); class EigenValueIndex implements Comparable<EigenValueIndex> { private int index; Double value; public EigenValueIndex(int index, double value) { this.index = index; this.value = value; } @Override public int compareTo(EigenValueIndex o) { return o.value.compareTo(value); } }; List<EigenValueIndex> eigenValueIndices = new ArrayList<EigenValueIndex>(); for(int i=0; i<eigenValues.length; i++) eigenValueIndices.add(i,new EigenValueIndex(i,eigenValues[i])); Collections.sort(eigenValueIndices); // Extract factors corresponding to the largest eigenvalues double[][] factorMatrix = new double[eigenValues.length][numberOfFactors]; for (int factor = 0; factor < numberOfFactors; factor++) { int eigenVectorIndex = (int) eigenValueIndices.get(factor).index; double eigenValue = eigenValues[eigenVectorIndex]; double signChange = eigenVectorMatrix[0][eigenVectorIndex] > 0.0 ? 1.0 : -1.0; // Convention: Have first entry of eigenvector positive. This is to make results more consistent. double eigenVectorNormSquared = 0.0; for (int row = 0; row < eigenValues.length; row++) { eigenVectorNormSquared += eigenVectorMatrix[row][eigenVectorIndex] * eigenVectorMatrix[row][eigenVectorIndex]; } eigenValue = Math.max(eigenValue,0.0); for (int row = 0; row < eigenValues.length; row++) { factorMatrix[row][factor] = signChange * Math.sqrt(eigenValue/eigenVectorNormSquared) * eigenVectorMatrix[row][eigenVectorIndex]; } } return factorMatrix; } /** * Returns a correlation matrix which has rank &lt; n and for which the first n factors agree with the factors of correlationMatrix. * * @param correlationMatrix The given correlation matrix. * @param numberOfFactors The requested number of factors (Eigenvectors). * @return Factor reduced correlation matrix. */ public static double[][] factorReductionUsingCommonsMath(double[][] correlationMatrix, int numberOfFactors) { // Extract factors corresponding to the largest eigenvalues double[][] factorMatrix = getFactorMatrix(correlationMatrix, numberOfFactors); // Renormalize rows for (int row = 0; row < correlationMatrix.length; row++) { double sumSquared = 0; for (int factor = 0; factor < numberOfFactors; factor++) sumSquared += factorMatrix[row][factor] * factorMatrix[row][factor]; if(sumSquared != 0) { for (int factor = 0; factor < numberOfFactors; factor++) factorMatrix[row][factor] = factorMatrix[row][factor] / Math.sqrt(sumSquared); } else { // This is a rare case: The factor reduction of a completely decorrelated system to 1 factor for (int factor = 0; factor < numberOfFactors; factor++) factorMatrix[row][factor] = 1.0; } } // Orthogonalized again double[][] reducedCorrelationMatrix = (new Array2DRowRealMatrix(factorMatrix).multiply(new Array2DRowRealMatrix(factorMatrix).transpose())).getData(); return getFactorMatrix(reducedCorrelationMatrix, numberOfFactors); } }
package org.bouncycastle.openssl; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.cms.ContentInfo; import org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.pkcs.RSAPublicKey; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.DSAParameter; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.cert.X509AttributeCertificateHolder; import org.bouncycastle.cert.X509CRLHolder; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.io.pem.PemHeader; import org.bouncycastle.util.io.pem.PemObject; import org.bouncycastle.util.io.pem.PemObjectParser; import org.bouncycastle.util.io.pem.PemReader; /** * Class for parsing OpenSSL PEM encoded streams containing * X509 certificates, PKCS8 encoded keys and PKCS7 objects. * <p> * In the case of PKCS7 objects the reader will return a CMS ContentInfo object. Public keys will be returned as * well formed SubjectPublicKeyInfo objects, private keys will be returned as well formed PrivateKeyInfo objects. In the * case of a private key a PEMKeyPair will normally be returned if the encoding contains both the private and public * key definition. CRLs, Certificates, PKCS#10 requests, and Attribute Certificates will generate the appropriate BC holder class. * </p> */ public class PEMParser extends PemReader { private final Map parsers = new HashMap(); /** * Create a new PEMReader * * @param reader the Reader */ public PEMParser( Reader reader) { super(reader); parsers.put("CERTIFICATE REQUEST", new PKCS10CertificationRequestParser()); parsers.put("NEW CERTIFICATE REQUEST", new PKCS10CertificationRequestParser()); parsers.put("CERTIFICATE", new X509CertificateParser()); parsers.put("TRUSTED CERTIFICATE", new X509CertificateParser()); parsers.put("X509 CERTIFICATE", new X509CertificateParser()); parsers.put("X509 CRL", new X509CRLParser()); parsers.put("PKCS7", new PKCS7Parser()); parsers.put("ATTRIBUTE CERTIFICATE", new X509AttributeCertificateParser()); parsers.put("EC PARAMETERS", new ECCurveParamsParser()); parsers.put("PUBLIC KEY", new PublicKeyParser()); parsers.put("RSA PUBLIC KEY", new RSAPublicKeyParser()); parsers.put("RSA PRIVATE KEY", new KeyPairParser(new RSAKeyPairParser())); parsers.put("DSA PRIVATE KEY", new KeyPairParser(new DSAKeyPairParser())); parsers.put("EC PRIVATE KEY", new KeyPairParser(new ECDSAKeyPairParser())); parsers.put("ENCRYPTED PRIVATE KEY", new EncryptedPrivateKeyParser()); parsers.put("PRIVATE KEY", new PrivateKeyParser()); } public Object readObject() throws IOException { PemObject obj = readPemObject(); if (obj != null) { String type = obj.getType(); if (parsers.containsKey(type)) { return ((PemObjectParser)parsers.get(type)).parseObject(obj); } else { throw new IOException("unrecognised object: " + type); } } return null; } private class KeyPairParser implements PemObjectParser { private final PEMKeyPairParser pemKeyPairParser; public KeyPairParser(PEMKeyPairParser pemKeyPairParser) { this.pemKeyPairParser = pemKeyPairParser; } /** * Read a Key Pair */ public Object parseObject( PemObject obj) throws IOException { boolean isEncrypted = false; String dekInfo = null; List headers = obj.getHeaders(); for (Iterator it = headers.iterator(); it.hasNext();) { PemHeader hdr = (PemHeader)it.next(); if (hdr.getName().equals("Proc-Type") && hdr.getValue().equals("4,ENCRYPTED")) { isEncrypted = true; } else if (hdr.getName().equals("DEK-Info")) { dekInfo = hdr.getValue(); } } // extract the key byte[] keyBytes = obj.getContent(); try { if (isEncrypted) { StringTokenizer tknz = new StringTokenizer(dekInfo, ","); String dekAlgName = tknz.nextToken(); byte[] iv = Hex.decode(tknz.nextToken()); return new PEMEncryptedKeyPair(dekAlgName, iv, keyBytes, pemKeyPairParser); } return pemKeyPairParser.parse(keyBytes); } catch (IOException e) { if (isEncrypted) { throw new PEMException("exception decoding - please check password and data.", e); } else { throw new PEMException(e.getMessage(), e); } } catch (IllegalArgumentException e) { if (isEncrypted) { throw new PEMException("exception decoding - please check password and data.", e); } else { throw new PEMException(e.getMessage(), e); } } } } private class DSAKeyPairParser implements PEMKeyPairParser { public PEMKeyPair parse(byte[] encoding) throws IOException { try { ASN1Sequence seq = ASN1Sequence.getInstance(encoding); if (seq.size() != 6) { throw new PEMException("malformed sequence in DSA private key"); } // ASN1Integer v = (ASN1Integer)seq.getObjectAt(0); ASN1Integer p = ASN1Integer.getInstance(seq.getObjectAt(1)); ASN1Integer q = ASN1Integer.getInstance(seq.getObjectAt(2)); ASN1Integer g = ASN1Integer.getInstance(seq.getObjectAt(3)); ASN1Integer y = ASN1Integer.getInstance(seq.getObjectAt(4)); ASN1Integer x = ASN1Integer.getInstance(seq.getObjectAt(5)); return new PEMKeyPair( new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(p.getValue(), q.getValue(), g.getValue())), y), new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(p.getValue(), q.getValue(), g.getValue())), x)); } catch (IOException e) { throw e; } catch (Exception e) { throw new PEMException( "problem creating DSA private key: " + e.toString(), e); } } } private class ECDSAKeyPairParser implements PEMKeyPairParser { public PEMKeyPair parse(byte[] encoding) throws IOException { try { ASN1Sequence seq = ASN1Sequence.getInstance(encoding); org.bouncycastle.asn1.sec.ECPrivateKey pKey = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(seq); AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, pKey.getParameters()); PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey); SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo(algId, pKey.getPublicKey().getBytes()); return new PEMKeyPair(pubInfo, privInfo); } catch (IOException e) { throw e; } catch (Exception e) { throw new PEMException( "problem creating EC private key: " + e.toString(), e); } } } private class RSAKeyPairParser implements PEMKeyPairParser { public PEMKeyPair parse(byte[] encoding) throws IOException { try { ASN1Sequence seq = ASN1Sequence.getInstance(encoding); if (seq.size() != 9) { throw new PEMException("malformed sequence in RSA private key"); } org.bouncycastle.asn1.pkcs.RSAPrivateKey keyStruct = org.bouncycastle.asn1.pkcs.RSAPrivateKey.getInstance(seq); RSAPublicKey pubSpec = new RSAPublicKey( keyStruct.getModulus(), keyStruct.getPublicExponent()); AlgorithmIdentifier algId = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE); return new PEMKeyPair(new SubjectPublicKeyInfo(algId, pubSpec), new PrivateKeyInfo(algId, keyStruct)); } catch (IOException e) { throw e; } catch (Exception e) { throw new PEMException( "problem creating RSA private key: " + e.toString(), e); } } } private class PublicKeyParser implements PemObjectParser { public PublicKeyParser() { } public Object parseObject(PemObject obj) throws IOException { return SubjectPublicKeyInfo.getInstance(obj.getContent()); } } private class RSAPublicKeyParser implements PemObjectParser { public RSAPublicKeyParser() { } public Object parseObject(PemObject obj) throws IOException { try { RSAPublicKey rsaPubStructure = RSAPublicKey.getInstance(obj.getContent()); return new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), rsaPubStructure); } catch (IOException e) { throw e; } catch (Exception e) { throw new PEMException("problem extracting key: " + e.toString(), e); } } } private class X509CertificateParser implements PemObjectParser { /** * Reads in a X509Certificate. * * @return the X509Certificate * @throws java.io.IOException if an I/O error occured */ public Object parseObject(PemObject obj) throws IOException { try { return new X509CertificateHolder(obj.getContent()); } catch (Exception e) { throw new PEMException("problem parsing cert: " + e.toString(), e); } } } private class X509CRLParser implements PemObjectParser { /** * Reads in a X509CRL. * * @return the X509Certificate * @throws java.io.IOException if an I/O error occured */ public Object parseObject(PemObject obj) throws IOException { try { return new X509CRLHolder(obj.getContent()); } catch (Exception e) { throw new PEMException("problem parsing cert: " + e.toString(), e); } } } private class PKCS10CertificationRequestParser implements PemObjectParser { /** * Reads in a PKCS10 certification request. * * @return the certificate request. * @throws java.io.IOException if an I/O error occured */ public Object parseObject(PemObject obj) throws IOException { try { return new PKCS10CertificationRequest(obj.getContent()); } catch (Exception e) { throw new PEMException("problem parsing certrequest: " + e.toString(), e); } } } private class PKCS7Parser implements PemObjectParser { /** * Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS * API. * * @return the X509Certificate * @throws java.io.IOException if an I/O error occured */ public Object parseObject(PemObject obj) throws IOException { try { ASN1InputStream aIn = new ASN1InputStream(obj.getContent()); return ContentInfo.getInstance(aIn.readObject()); } catch (Exception e) { throw new PEMException("problem parsing PKCS7 object: " + e.toString(), e); } } } private class X509AttributeCertificateParser implements PemObjectParser { public Object parseObject(PemObject obj) throws IOException { return new X509AttributeCertificateHolder(obj.getContent()); } } private class ECCurveParamsParser implements PemObjectParser { public Object parseObject(PemObject obj) throws IOException { try { Object param = ASN1Primitive.fromByteArray(obj.getContent()); if (param instanceof ASN1ObjectIdentifier) { return ASN1Primitive.fromByteArray(obj.getContent()); } else if (param instanceof ASN1Sequence) { return X9ECParameters.getInstance(param); } else { return null; // implicitly CA } } catch (IOException e) { throw e; } catch (Exception e) { throw new PEMException("exception extracting EC named curve: " + e.toString()); } } } private class EncryptedPrivateKeyParser implements PemObjectParser { public EncryptedPrivateKeyParser() { } /** * Reads in an EncryptedPrivateKeyInfo * * @return the X509Certificate * @throws java.io.IOException if an I/O error occured */ public Object parseObject(PemObject obj) throws IOException { try { return new PKCS8EncryptedPrivateKeyInfo(EncryptedPrivateKeyInfo.getInstance(obj.getContent())); } catch (Exception e) { throw new PEMException("problem parsing ENCRYPTED PRIVATE KEY: " + e.toString(), e); } } } private class PrivateKeyParser implements PemObjectParser { public PrivateKeyParser() { } public Object parseObject(PemObject obj) throws IOException { try { return PrivateKeyInfo.getInstance(obj.getContent()); } catch (Exception e) { throw new PEMException("problem parsing PRIVATE KEY: " + e.toString(), e); } } } }
package rhomobile.mapview; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import com.rho.RhoClassFactory; import com.rho.RhoConf; import com.rho.RhoEmptyLogger; import com.rho.RhoLogger; import com.rho.net.IHttpConnection; import net.rim.device.api.math.Fixed32; import net.rim.device.api.system.Bitmap; import net.rim.device.api.system.EncodedImage; import net.rim.device.api.ui.Field; import net.rim.device.api.ui.Graphics; import net.rim.device.api.util.Comparator; import net.rim.device.api.util.SimpleSortingVector; public class ESRIMapField extends Field implements RhoMapField { private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() : new RhoLogger("ESRIMapField"); private static final int TILE_SIZE = 256; private static final int MIN_ZOOM = 0; private static final int MAX_ZOOM = 19; private static final int CACHE_UPDATE_INTERVAL = 500; // Maximum size of image cache (number of images stored locally) private static final int MAX_IMAGE_CACHE_SIZE = 32; // Mode of decoding EncodedImage to bitmap private static final int DECODE_MODE = EncodedImage.DECODE_NATIVE | EncodedImage.DECODE_NO_DITHER | EncodedImage.DECODE_READONLY | EncodedImage.DECODE_ALPHA; // Constants required to coordinates calculations private static final long MIN_LATITUDE = degreesToPixelsY(90, MAX_ZOOM); private static final long MAX_LATITUDE = degreesToPixelsY(-90, MAX_ZOOM); private static final long MAX_LONGITUDE = degreesToPixelsX(180, MAX_ZOOM); // DON'T CHANGE THIS CONSTANT!!! // This is maximum absolute value of sine ( == sin(85*PI/180) ) allowed by Merkator projection private static final double MAX_SIN = 0.99627207622; private static final double PI = Math.PI; private Hashtable mMapUrls = new Hashtable(); private String mMapType; // Coordinates of center in pixels of maximum zoom level private long mLatitude = degreesToPixelsY(0, MAX_ZOOM); private long mLongitude = degreesToPixelsX(0, MAX_ZOOM); private int mZoom = 0; private int mWidth; private int mHeight; private static class ByCoordinatesComparator implements Comparator { public int compare (Object o1, Object o2) { CachedImage img1 = (CachedImage)o1; CachedImage img2 = (CachedImage)o2; if (img1.latitude < img2.latitude) return -1; if (img1.latitude > img2.latitude) return 1; if (img1.longitude < img2.longitude) return 1; if (img1.longitude > img2.longitude) return -1; if (img1.zoom < img2.zoom) return -1; if (img1.zoom > img2.zoom) return 1; return 0; } } private static class ByAccessTimeComparator implements Comparator { public int compare (Object o1, Object o2) { long l1 = ((CachedImage)o1).lastUsed; long l2 = ((CachedImage)o2).lastUsed; return l1 < l2 ? 1 : l1 > l2 ? -1 : 0; } }; private class CachedImage { public EncodedImage image; public Bitmap bitmap; public long latitude; public long longitude; public int zoom; public String key; public long lastUsed; public CachedImage(EncodedImage img, long lat, long lon, int z) { image = img; bitmap = null; latitude = lat; longitude = lon; zoom = z; key = makeCacheKey(latitude, longitude, zoom); lastUsed = System.currentTimeMillis(); } }; private class ImageCache { private Hashtable hash; private SimpleSortingVector cvec; private SimpleSortingVector tvec; public ImageCache() { reinit(); } private void reinit() { hash = new Hashtable(); cvec = new SimpleSortingVector(); cvec.setSortComparator(new ByCoordinatesComparator()); cvec.setSort(true); tvec = new SimpleSortingVector(); tvec.setSortComparator(new ByAccessTimeComparator()); tvec.setSort(true); } public ImageCache clone() { ImageCache cloned = new ImageCache(); for (Enumeration e = hash.elements(); e.hasMoreElements();) cloned.put((CachedImage)e.nextElement()); return cloned; } public Enumeration sortedByCoordinates() { return cvec.elements(); } public CachedImage get(String key) { return (CachedImage)hash.get(key); } public void put(CachedImage img) { put(img, true); } private void put(CachedImage img, boolean doCheck) { hash.put(img.key, img); cvec.addElement(img); tvec.addElement(img); if (doCheck) check(); } private void check() { if (hash.size() < MAX_IMAGE_CACHE_SIZE) return; SimpleSortingVector vec = tvec; reinit(); Enumeration e = vec.elements(); while (e.hasMoreElements()) { CachedImage img = (CachedImage)e.nextElement(); put(img, false); } } }; private ImageCache mImgCache = new ImageCache(); private static abstract class MapCommand { public abstract String type(); public abstract String description(); } private static class MapFetchCommand extends MapCommand { public String baseUrl; public int zoom; public long latitude; public long longitude; public MapFetchCommand(String baseUrl, int zoom, long latitude, long longitude) { this.baseUrl = baseUrl; this.zoom = zoom; this.latitude = latitude; this.longitude = longitude; } private String makeDescription() { return "" + zoom + "/" + latitude + "/" + longitude; } public String type() { return "fetch"; } public String description() { return "fetch:" + makeDescription(); } }; private class MapThread extends Thread { private static final int BLOCK_SIZE = 1024; private Vector commands = new Vector(); private boolean active = true; public void process(MapCommand cmd) { synchronized (commands) { commands.addElement(cmd); commands.notify(); } } public void stop() { active = false; interrupt(); } public void run() { try { while (active) { MapCommand cmd = null; synchronized (commands) { if (commands.isEmpty()) { try { commands.wait(); } catch (InterruptedException e) { // Nothing } continue; } int last = commands.size() - 1; cmd = (MapCommand)commands.elementAt(last); commands.removeElementAt(last); if (cmd == null) continue; } try { if (cmd instanceof MapFetchCommand) processCommand((MapFetchCommand)cmd); else LOG.INFO("Received unknown command: " + cmd.type() + ", ignore it"); } catch (Exception e) { LOG.ERROR("Processing of map command failed", e); } } } catch (Exception e) { LOG.ERROR("Fatal error in map thread", e); } finally { LOG.INFO("Map thread exit"); } } private byte[] fetchData(String url) throws IOException { IHttpConnection conn = RhoClassFactory.getNetworkAccess().connect(url,false); conn.setRequestMethod("GET"); //conn.setRequestProperty("User-Agent", "Blackberry"); //conn.setRequestProperty("Accept", "*/*"); InputStream is = conn.openInputStream(); int code = conn.getResponseCode(); if (code/100 != 2) throw new IOException("ESRI map server respond with " + code + " " + conn.getResponseMessage()); int size = conn.getHeaderFieldInt("Content-Length", 0); byte[] data = new byte[size]; if (size == 0) size = 1073741824; // 1Gb :) byte[] buf = new byte[BLOCK_SIZE]; for (int offset = 0; offset < size;) { int n = is.read(buf, 0, BLOCK_SIZE); if (n <= 0) break; if (offset + n > data.length) { byte[] newData = new byte[offset + n]; System.arraycopy(data, 0, newData, 0, data.length); data = newData; } System.arraycopy(buf, 0, data, offset, n); offset += n; } return data; } private void processCommand(MapFetchCommand cmd) throws IOException { LOG.TRACE("Processing map fetch command (thread #" + hashCode() + "): " + cmd.description()); long ts = toMaxZoom(TILE_SIZE, cmd.zoom); int row = (int)(cmd.latitude/ts); int column = (int)(cmd.longitude/ts); StringBuffer url = new StringBuffer(); url.append(cmd.baseUrl); url.append("/MapServer/tile/"); url.append(cmd.zoom); url.append('/'); url.append(row); url.append('/'); url.append(column); String finalUrl = url.toString(); byte[] data = fetchData(finalUrl); EncodedImage img = EncodedImage.createEncodedImage(data, 0, data.length); img.setDecodeMode(DECODE_MODE); long lat = row*ts + ts/2; long lon = column*ts + ts/2; LOG.TRACE("Map request done, draw just received image: zoom=" + cmd.zoom + ", lat=" + lat + ", lon=" + lon); CachedImage cachedImage = new CachedImage(img, lat, lon, cmd.zoom); // Put image to the cache and trigger redraw synchronized (ESRIMapField.this) { mImgCache.put(cachedImage); } redraw(); } }; private MapThread mMapThread = new MapThread(); private class CacheUpdate extends Thread { private boolean active = true; public void stop() throws InterruptedException { active = false; join(); } public void run() { LOG.TRACE("Cache update thread started"); while (active) { try { Thread.sleep(CACHE_UPDATE_INTERVAL); } catch (InterruptedException e) { // Ignore } // ", mLongitude=" + mLongitude + ", mZoom=" + mZoom); long ts = toMaxZoom(TILE_SIZE, mZoom); //LOG.TRACE("Tile size on the maximum zoom level: " + ts); long h = toMaxZoom(mHeight, mZoom); //LOG.TRACE("Height of the screen on the maximum zoom level: " + h); long w = toMaxZoom(mWidth, mZoom); //LOG.TRACE("Width of the screen on the maximum zoom level: " + w); long totalTiles = MapTools.math_pow2(mZoom); //LOG.TRACE("Total tiles count on zoom level " + mZoom + ": " + totalTiles); long tlLat = mLatitude - h/2; if (tlLat < 0) tlLat = 0; long tlLon = mLongitude - w/2; if (tlLon < 0) tlLon = 0; //LOG.TRACE("tlLat=" + tlLat + ", tlLon=" + tlLon); for (long lat = (tlLat/ts)*ts, latLim = Math.min(tlLat + h + ts, ts*totalTiles); lat < latLim; lat += ts) { for (long lon = (tlLon/ts)*ts, lonLim = Math.min(tlLon + w + ts, ts*totalTiles); lon < lonLim; lon += ts) { String key = makeCacheKey(lat, lon, mZoom); MapFetchCommand cmd = null; synchronized (ESRIMapField.this) { CachedImage img = mImgCache.get(key); if (img == null) { //LOG.TRACE("lat=" + lat + ", lon=" + lon + "; key=" + key); String baseUrl = (String)mMapUrls.get(mMapType); cmd = new MapFetchCommand(baseUrl, mZoom, lat, lon); CachedImage dummy = new CachedImage(null, lat, lon, mZoom); mImgCache.put(dummy); } } if (cmd != null) mMapThread.process(cmd); } } } LOG.TRACE("Cache update thread stopped"); } }; private CacheUpdate mCacheUpdate = new CacheUpdate(); public ESRIMapField() { String url = RhoConf.getInstance().getString("esri_map_url_roadmap"); if (url == null || url.length() == 0) url = "http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/"; mMapUrls.put("roadmap", url); url = RhoConf.getInstance().getString("esri_map_url_satellite"); if (url == null || url.length() == 0) url = "http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/"; mMapUrls.put("satellite", url); mMapType = "roadmap"; LOG.TRACE("ESRIMapField ctor: mLatitude=" + mLatitude + ", mLongitude=" + mLongitude); mMapThread.start(); mCacheUpdate.start(); } public void close() { mMapThread.stop(); try { mCacheUpdate.stop(); } catch (InterruptedException e) { LOG.ERROR("Stopping of cache update thread was interrupted", e); } } public void redraw() { invalidate(); } protected void paint(Graphics graphics) { // Draw background for (int i = 1, lim = 2*Math.max(mWidth, mHeight); i < lim; i += 5) { graphics.drawLine(0, i, i, 0); } ImageCache imgCache; synchronized (this) { imgCache = mImgCache.clone(); } // Draw map tiles Enumeration e = imgCache.sortedByCoordinates(); while (e.hasMoreElements()) { // Draw map CachedImage img = (CachedImage)e.nextElement(); if (img.image == null) continue; paintImage(graphics, img); } } private void paintImage(Graphics graphics, CachedImage img) { // Skip images with zoom level which differ from the current zoom level if (img.zoom != mZoom) return; long left = -toCurrentZoom(mLongitude - img.longitude, mZoom); long top = -toCurrentZoom(mLatitude - img.latitude, mZoom); if (img.zoom != mZoom) { double x = MapTools.math_pow2d(img.zoom - mZoom); int factor = Fixed32.tenThouToFP((int)(x*10000)); img.image = img.image.scaleImage32(factor, factor); img.bitmap = null; } int imgWidth = img.image.getScaledWidth(); int imgHeight = img.image.getScaledHeight(); left += (mWidth - imgWidth)/2; top += (mHeight - imgHeight)/2; int w = mWidth - (int)left; int h = mHeight - (int)top; int maxW = mWidth + TILE_SIZE; int maxH = mHeight + TILE_SIZE; if (w < 0 || h < 0 || w > maxW || h > maxH) { // Image will not be displayed, free its bitmap and skip it img.bitmap = null; return; } if (img.bitmap == null) img.bitmap = img.image.getBitmap(); graphics.drawBitmap((int)left, (int)top, w, h, img.bitmap, 0, 0); } protected void layout(int w, int h) { mWidth = Math.min(mWidth, w); mHeight = Math.min(mHeight, h); setExtent(mWidth, mHeight); } public int calculateZoom(double latDelta, double lonDelta) { int zoom1 = calcZoom(latDelta, mWidth); int zoom2 = calcZoom(lonDelta, mHeight); return zoom1 < zoom2 ? zoom1 : zoom2; } public Field getBBField() { return this; } public double getCenterLatitude() { return pixelsToDegreesY(mLatitude, MAX_ZOOM); } public double getCenterLongitude() { return pixelsToDegreesX(mLongitude, MAX_ZOOM); } private void validateCoordinates() { if (mLatitude < MIN_LATITUDE) mLatitude = MIN_LATITUDE; if (mLatitude > MAX_LATITUDE) mLatitude = MAX_LATITUDE; } public void moveTo(double lat, double lon) { mLatitude = degreesToPixelsY(lat, MAX_ZOOM); mLongitude = degreesToPixelsX(lon, MAX_ZOOM); validateCoordinates(); //LOG.TRACE("moveTo(" + lat + ", " + lon + "): mLatitude=" + mLatitude + ", mLongitude=" + mLongitude); } public void move(int dx, int dy) { mLatitude += toMaxZoom(dy, mZoom); mLongitude += toMaxZoom(dx, mZoom); validateCoordinates(); //LOG.TRACE("move(" + dx + ", " + dy + "): mLatitude=" + mLatitude + ", mLongitude=" + mLongitude); } public void setMapType(String type) { mMapType = type; //LOG.TRACE("setMapType: " + mMapType); } public void setPreferredSize(int width, int height) { mWidth = width; mHeight = height; } public int getPreferredWidth() { return mWidth; } public int getPreferredHeight() { return mHeight; } public void setZoom(int zoom) { mZoom = zoom; if (mZoom < MIN_ZOOM) mZoom = MIN_ZOOM; if (mZoom > MAX_ZOOM) mZoom = MAX_ZOOM; LOG.TRACE("setZoom: " + mZoom); } public int getMaxZoom() { return MAX_ZOOM; } public int getMinZoom() { return MIN_ZOOM; } public int getZoom() { return mZoom; } private static int calcZoom(double degrees, int pixels) { double angleRatio = degrees*TILE_SIZE/pixels; double twoInZoomExp = 360/angleRatio; int zoom = (int)MapTools.math_log2(twoInZoomExp); return zoom; } private static long toMaxZoom(long n, int zoom) { if (n == 0) return 0; long pow = MapTools.math_pow2(MAX_ZOOM - zoom); return n*pow; } private static long toCurrentZoom(long coord, int zoom) { if (coord == 0) return 0; long pow = MapTools.math_pow2(MAX_ZOOM - zoom); return coord/pow; } private static long degreesToPixelsX(double n, int z) { while (n < -180.0) n += 360.0; while (n > 180.0) n -= 360.0; double angleRatio = 360d/MapTools.math_pow2(z); double val = (n + 180)*TILE_SIZE/angleRatio; return (long)val; } private static long degreesToPixelsY(double n, int z) { // Merkator projection double sin_phi = MapTools.math_sin(n*PI/180); // MAX_SIN - maximum value of sine allowed by Merkator projection // (~85.0 degrees of north latitude) if (sin_phi < -MAX_SIN) sin_phi = -MAX_SIN; if (sin_phi > MAX_SIN) sin_phi = MAX_SIN; double ath = MapTools.math_atanh(sin_phi); double val = TILE_SIZE * MapTools.math_pow2(z) * (1 - ath/PI)/2; return (long)val; } private static double pixelsToDegreesX(long n, int z) { while (n < 0) n += MAX_LONGITUDE; while (n > MAX_LONGITUDE) n -= MAX_LONGITUDE; double angleRatio = 360d/MapTools.math_pow2(z); double val = n*angleRatio/TILE_SIZE - 180.0; return val; } private static double pixelsToDegreesY(long n, int z) { // Revert calculation of Merkator projection double ath = PI - 2*PI*n/(TILE_SIZE*MapTools.math_pow2(z)); double th = MapTools.math_tanh(ath); double val = 180*MapTools.math_asin(th)/PI; return val; } private String makeCacheKey(long lat, long lon, int z) { while (lon < 0) lon += MAX_LONGITUDE; while (lon > MAX_LONGITUDE) lon -= MAX_LONGITUDE; long ts = toMaxZoom(TILE_SIZE, z); long x = lon/ts; long y = lat/ts; StringBuffer buf = new StringBuffer(); buf.append(z); buf.append(';'); buf.append(x); buf.append(';'); buf.append(y); String key = buf.toString(); return key; } public long toScreenCoordinateX(double n) { long v = degreesToPixelsX(n, mZoom); long center = toCurrentZoom(mLongitude, mZoom); long begin = center - mWidth/2; return v - begin; } public long toScreenCoordinateY(double n) { long v = degreesToPixelsY(n, mZoom); long center = toCurrentZoom(mLatitude, mZoom); long begin = center - mHeight/2; return v - begin; } }
package dr.app.beauti.treespanel; import dr.app.beauti.BeautiFrame; import dr.app.beauti.util.PanelUtils; import dr.app.beauti.options.*; import dr.app.tools.TemporalRooting; import dr.evolution.alignment.Patterns; import dr.evolution.datatype.PloidyType; import dr.evolution.distance.DistanceMatrix; import dr.evolution.distance.F84DistanceMatrix; import dr.evolution.tree.NeighborJoiningTree; import dr.evolution.tree.Tree; import dr.evolution.tree.UPGMATree; import org.virion.jam.panels.OptionsPanel; import javax.swing.*; import javax.swing.plaf.BorderUIResource; import java.awt.*; import java.awt.event.*; /** * @author Andrew Rambaut * @author Alexei Drummond * @author Walter Xie * @version $Id: PriorsPanel.java,v 1.9 2006/09/05 13:29:34 rambaut Exp $ */ public class PartitionTreeModelPanel extends OptionsPanel { private static final long serialVersionUID = 8096349200725353543L; private JComboBox ploidyTypeCombo = new JComboBox(PloidyType.values()); private JComboBox startingTreeCombo = new JComboBox(StartingTreeType.values()); private JComboBox userTreeCombo = new JComboBox(); // private BeautiFrame frame = null; private BeautiOptions options = null; private boolean settingOptions = false; private final PartitionTreeModel partitionTreeModel; public PartitionTreeModelPanel(PartitionTreeModel partitionTreeModel, BeautiOptions options) { super(12, 18); this.partitionTreeModel = partitionTreeModel; this.options = options; PanelUtils.setupComponent(ploidyTypeCombo); ploidyTypeCombo.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent ev) { // setupPanel(); } } ); PanelUtils.setupComponent(startingTreeCombo); startingTreeCombo.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent ev) { setupPanel(); } } ); PanelUtils.setupComponent(userTreeCombo); userTreeCombo.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent ev) { fireUserTreeChanged(); } } ); setupPanel(); } private void fireUserTreeChanged() { partitionTreeModel.setUserStartingTree(getSelectedUserTree(options)); } private void setupPanel() { removeAll(); if ((options.shareSameTreePrior && options.activedSameTreePrior != null && options.activedSameTreePrior.getNodeHeightPrior().equals(TreePrior.EXTENDED_SKYLINE)) || (!options.shareSameTreePrior && partitionTreeModel != null && partitionTreeModel.getPartitionTreePrior().getNodeHeightPrior().equals(TreePrior.EXTENDED_SKYLINE)) || options.isSpeciesAnalysis()) { addComponentWithLabel("Ploidy Type:", ploidyTypeCombo); } addComponentWithLabel("Starting Tree:", startingTreeCombo); if (startingTreeCombo.getSelectedItem() == StartingTreeType.USER) { addComponentWithLabel("Select Tree:", userTreeCombo); } userTreeCombo.removeAllItems(); if (options.userTrees.size() == 0) { userTreeCombo.addItem("no trees loaded"); userTreeCombo.setEnabled(false); } else { for (Tree tree : options.userTrees) { userTreeCombo.addItem(tree.getId()); } userTreeCombo.setEnabled(true); } // generateTreeAction.setEnabled(options != null && options.dataPartitions.size() > 0); validate(); repaint(); } public void setOptions() { if (partitionTreeModel == null) { return; } settingOptions = true; if ((options.shareSameTreePrior && options.activedSameTreePrior != null && options.activedSameTreePrior.getNodeHeightPrior().equals(TreePrior.EXTENDED_SKYLINE)) || (!options.shareSameTreePrior && partitionTreeModel != null && partitionTreeModel.getPartitionTreePrior().getNodeHeightPrior().equals(TreePrior.EXTENDED_SKYLINE)) || options.isSpeciesAnalysis()) { ploidyTypeCombo.setSelectedItem(partitionTreeModel.getPloidyType()); } startingTreeCombo.setSelectedItem(partitionTreeModel.getStartingTreeType()); if (partitionTreeModel.getUserStartingTree() != null) { userTreeCombo.setSelectedItem(partitionTreeModel.getUserStartingTree().getId()); } setupPanel(); settingOptions = false; validate(); repaint(); } public void getOptions(BeautiOptions options) { if (settingOptions) return; if ((options.shareSameTreePrior && options.activedSameTreePrior != null && options.activedSameTreePrior.getNodeHeightPrior().equals(TreePrior.EXTENDED_SKYLINE)) || (!options.shareSameTreePrior && partitionTreeModel != null && partitionTreeModel.getPartitionTreePrior().getNodeHeightPrior().equals(TreePrior.EXTENDED_SKYLINE)) || options.isSpeciesAnalysis()) { partitionTreeModel.setPloidyType( (PloidyType) ploidyTypeCombo.getSelectedItem()); } partitionTreeModel.setStartingTreeType( (StartingTreeType) startingTreeCombo.getSelectedItem()); partitionTreeModel.setUserStartingTree(getSelectedUserTree(options)); } private Tree getSelectedUserTree(BeautiOptions options) { String treeId = (String) userTreeCombo.getSelectedItem(); for (Tree tree : options.userTrees) { if (tree.getId().equals(treeId)) { return tree; } } return null; } }
package edu.washington.escience.myriad.operator; import java.io.Serializable; import java.util.Arrays; import edu.washington.escience.myriad.DbException; import edu.washington.escience.myriad.Schema; import edu.washington.escience.myriad.TupleBatch; /** * Abstract class for implementing operators. * * @author slxu * * Currently, the operator api design requires that each single operator instance should be executed within a * single thread. * * No multi-thread synchronization is considered. * */ public abstract class Operator implements Serializable { /** Required for Java serialization. */ private static final long serialVersionUID = 1L; /** * A single buffer for temporally holding a TupleBatch for pull. * */ private TupleBatch outputBuffer = null; /** * A bit denoting whether the operator is open (initialized). * */ private boolean open = false; /** * EOS. Initially set it as true; * */ private boolean eos = true; private boolean eoi = true; /** * Closes this iterator. * * @throws DbException if any errors occur */ public final void close() throws DbException { // Ensures that a future call to next() will fail outputBuffer = null; open = false; setEOS(true); setEOI(true); cleanup(); final Operator[] children = getChildren(); if (children != null) { for (final Operator child : children) { if (child != null) { child.close(); } } } } /** * Check if EOS is meet. * * This method is non-blocking. * * @return if the Operator is EOS * * */ public final boolean eos() { return eos; } public final boolean eoi() { return eoi; } /** * Returns the next output TupleBatch, or null if EOS is meet. * * This method is blocking. * * * @return the next output TupleBatch, or null if EOS * * @throws DbException if any processing error occurs * */ protected abstract TupleBatch fetchNext() throws DbException; /** * @return return the children Operators of this operator. If there is only one child, return an array of only one * element. For join operators, the order of the children is not important. But they should be consistent * among multiple calls. */ public abstract Operator[] getChildren(); public final TupleBatch next() throws DbException { if (!open) { throw new IllegalStateException("Operator not yet open"); } if (eos() || eoi()) { return null; } TupleBatch result = null; if (outputBuffer != null) { result = outputBuffer; } else { result = fetchNext(); } outputBuffer = null; while (result != null && result.numTuples() <= 0) { result = fetchNext(); } if (result == null) { // now we have three possibilities when result == null: EOS, EOI, or just a null. // returns a null won't cause a problem so far, since a producer will keep calling fetchNext() until EOS // call checkEOSAndEOI to set self EOS and EOI, if applicable checkEOSAndEOI(); } return result; } public void checkEOSAndEOI() { // this is the implementation for ordinary operators, e.g. join, project. // some operators have their own logics, e.g. LeafOperator, IDBInput. // so they should override this function Operator[] children = getChildren(); boolean[] childrenEOI = getChildrenEOI(); boolean allEOS = true; int count = 0; for (int i = 0; i < children.length; ++i) { if (children[i].eos()) { childrenEOI[i] = true; } else if (children[i].eoi()) { childrenEOI[i] = true; allEOS = false; } if (childrenEOI[i]) { count++; } } if (count == children.length) { if (allEOS) { setEOS(true); } else { setEOI(true); } for (Operator child : children) { child.setEOI(false); } cleanChildrenEOI(); } } /** * Check if currently there's any TupleBatch available for pull. * * This method is non-blocking. * * @throws DbException if any problem * * @return if currently there's output for pulling. * * */ public final boolean nextReady() throws DbException { if (!open) { throw new DbException("Operator not yet open"); } if (eos()) { throw new DbException("Operator already eos"); } if (outputBuffer == null) { outputBuffer = fetchNextReady(); while (outputBuffer != null && outputBuffer.numTuples() <= 0) { // XXX while or not while? For a single thread operator, while sounds more efficient generally outputBuffer = fetchNextReady(); } } return outputBuffer != null; } /** * open the operator and do initializations. * * @throws DbException if any error occurs * */ public final void open() throws DbException { // open the children first if (open) { // XXX Do some error handling to multi-open? throw new DbException("Operator already open."); } final Operator[] children = getChildren(); if (children != null) { for (final Operator child : children) { if (child != null) { child.open(); } } } setEOS(false); setEOI(false); // do my initialization init(); open = true; } /** * Explicitly set EOS for this operator. * * Only call this method if the operator is a leaf operator. * * */ public final void setEOS(boolean x) { eos = x; } public final void setEOI(boolean x) { eoi = x; } public boolean isOpen() { return open; } /** * Do the initialization of this operator. * * @throws DbException if any error occurs * */ protected abstract void init() throws DbException; /** * Do the clean up, release resources. * * @throws DbException if any error occurs * */ protected abstract void cleanup() throws DbException; /** * Generate next output TupleBatch if possible. Return null immediately if currently no output can be generated. * * Do not block the execution thread in this method, including sleep, wait on locks, etc. * * @throws DbException if any error occurs * * @return next ready output TupleBatch. null if either EOS or no output TupleBatch can be generated currently. * */ protected abstract TupleBatch fetchNextReady() throws DbException; /** * @return return the Schema of the output tuples of this operator. * */ public abstract Schema getSchema(); /** * Returns the next output TupleBatch, or null if EOS is meet. * * This method is blocking. * * * @return the next output TupleBatch, or null if EOS Set the children(child) of this operator. If the operator has * only one child, children[0] should be used. If the operator is a join, children[0] and children[1] should * be used. * * * @param children the Operators which are to be set as the children(child) of this operator */ // have we ever used this function? public abstract void setChildren(Operator[] children); public boolean[] childrenEOI = null; public boolean[] getChildrenEOI() { if (childrenEOI == null) { // getChildren() == null indicates a leaf operator, which has its own checkEOSAndEOI() childrenEOI = new boolean[getChildren().length]; } return childrenEOI; } public void cleanChildrenEOI() { Arrays.fill(childrenEOI, false); } }
package org.springframework.util; import java.lang.reflect.Method; import java.text.NumberFormat; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.util.visitor.ReflectiveVisitorSupport; import org.springframework.util.visitor.Visitor; /** * Visitor that encapsulates value string styling algorithms. * * @author Keith Donald */ public class DefaultObjectStyler implements Visitor, ObjectStyler { private ReflectiveVisitorSupport visitorSupport = new ReflectiveVisitorSupport(); private static final String EMPTY = "[empty]"; private static final String NULL = "[null]"; /** * Styles the string form of this object using the reflective visitor * pattern. The reflective help removes the need to define a vistable class * for each type of styled valued. * * @param o * The object to be styled. * @return The styled string. */ public String style(Object o) { return (String)visitorSupport.invokeVisit(this, o); } String visit(String value) { return ('\'' + value + '\''); } String visit(Number value) { return NumberFormat.getInstance().format(value); } String visit(Class clazz) { return ClassUtils.getShortName(clazz); } String visit(Method method) { return method.getName() + "@" + ClassUtils.getShortName(method.getDeclaringClass()); } String visit(Map value) { StringBuffer buffer = new StringBuffer(value.size() * 8 + 16); buffer.append("map["); for (Iterator i = value.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry)i.next(); buffer.append(style(entry)); if (i.hasNext()) { buffer.append(',').append(' '); } } if (value.isEmpty()) { buffer.append(EMPTY); } buffer.append("]"); return buffer.toString(); } String visit(Map.Entry value) { return style(value.getKey()) + " -> " + style(value.getValue()); } String visit(Collection value) { StringBuffer buffer = new StringBuffer(value.size() * 8 + 16); buffer.append(getTypeString(value) + "["); for (Iterator i = value.iterator(); i.hasNext();) { buffer.append(style(i.next())); if (i.hasNext()) { buffer.append(',').append(' '); } } if (value.isEmpty()) { buffer.append(EMPTY); } buffer.append("]"); return buffer.toString(); } private String getTypeString(Collection value) { if (value instanceof List) { return "list"; } else if (value instanceof Set) { return "set"; } else { return "collection"; } } String visit(Object value) { if (value.getClass().isArray()) { return styleArray(getObjectArray(value)); } else { return String.valueOf(value); } } String visitNull() { return NULL; } private String styleArray(Object[] array) { StringBuffer buffer = new StringBuffer(array.length * 8 + 16); buffer.append("array<" + StringUtils.delete(ClassUtils.getShortName(array.getClass()), ";") + ">["); for (int i = 0; i < array.length - 1; i++) { buffer.append(style(array[i])); buffer.append(',').append(' '); } if (array.length > 0) { buffer.append(style(array[array.length - 1])); } else { buffer.append(EMPTY); } buffer.append("]"); return buffer.toString(); } private Object[] getObjectArray(Object value) { if (value.getClass().getComponentType().isPrimitive()) { return ArrayUtils.toObjectArrayFromPrimitive(value); } else { return (Object[])value; } } }
package sculture.lucene; import edu.smu.tspell.wordnet.NounSynset; import edu.smu.tspell.wordnet.Synset; import edu.smu.tspell.wordnet.SynsetType; import edu.smu.tspell.wordnet.WordNetDatabase; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.*; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class SearchEngine { static Directory index; static SynonymAnalyzer analyzer; static WordNetDatabase database; private static final float ID_BOOST = 0; private static final float TITLE_BOOST = 1f; private static final float CONTENT_BOOST = 0.75f; private static final float TAG_BOOST = 1.2f; private static final float HYPONYM_BOOST = 0.1f; private static final float HYPERNYM_BOOST = 0.005f; public static void initialize() { String u = SearchEngine.class.getClassLoader().getResource("WordNet-3.0").getPath(); System.setProperty("wordnet.database.dir", u + File.separator + "dict"); database = WordNetDatabase.getFileInstance(); analyzer = new SynonymAnalyzer(); try { index = FSDirectory.open(new File("index").toPath()); } catch (IOException e) { e.printStackTrace(); } System.gc(); } public static void addDoc(long id, String title, String content, String tags) { if (database == null) initialize(); IndexWriterConfig config = new IndexWriterConfig(analyzer); IndexWriter w; try { w = new IndexWriter(index, config); Document doc = new Document(); TextField id_field = new TextField("id", id + "", Field.Store.YES); id_field.setBoost(ID_BOOST); TextField title_field = new TextField("title", title, Field.Store.YES); title_field.setBoost(TITLE_BOOST); TextField content_field = new TextField("content", content, Field.Store.YES); content_field.setBoost(CONTENT_BOOST); TextField tags_field = new TextField("tags", tags, Field.Store.YES); tags_field.setBoost(TAG_BOOST); doc.add(id_field); doc.add(title_field); doc.add(content_field); doc.add(tags_field); w.addDocument(doc); w.close(); } catch (IOException e) { e.printStackTrace(); } } public static void removeDoc(long id) { if (database == null) initialize(); IndexWriterConfig config = new IndexWriterConfig(analyzer); IndexWriter w; try { w = new IndexWriter(index, config); Query q = new QueryParser("id", analyzer).parse(id + ""); w.deleteDocuments(q); w.close(); } catch (IOException | ParseException e) { e.printStackTrace(); } } public static List<Long> search(String search_term, int page, int size) { if (database == null) initialize(); String wordnet = ""; String[] searches = search_term.split(" "); NounSynset nounSynset; NounSynset[] hyponyms; NounSynset[] hypernyms; Synset[] synsets; for (String s : searches) { synsets = database.getSynsets(s, SynsetType.NOUN); for (Synset synset : synsets) { nounSynset = (NounSynset) (synset); hyponyms = nounSynset.getHyponyms(); hypernyms = nounSynset.getHypernyms(); System.out.println(hypernyms.length); System.out.println(hyponyms.length); for (NounSynset n : hypernyms) { wordnet = "\"" + n.getWordForms()[0] + "\"^" + HYPERNYM_BOOST + " "; } for (NounSynset n : hyponyms) { wordnet = "\"" + n.getWordForms()[0] + "\"^" + HYPONYM_BOOST + " "; } } } System.gc(); List<Long> story_ids = new ArrayList<>(); MultiFieldQueryParser parser = new MultiFieldQueryParser(new String[]{"id", "title", "content", "tags"}, analyzer); Query query; try { int endIndex = page * size; System.out.println(search_term + " " + wordnet); query = parser.parse(search_term + " " + wordnet); IndexReader reader = DirectoryReader.open(index); IndexSearcher searcher = new IndexSearcher(reader); TopScoreDocCollector collector = TopScoreDocCollector.create(endIndex + 1); searcher.search(query, collector); ScoreDoc[] hits = collector.topDocs((page - 1) * size, size).scoreDocs; Document d; for (ScoreDoc hit : hits) { d = searcher.doc(hit.doc); story_ids.add(Long.valueOf(d.get("id"))); } } catch (ParseException | IOException e) { e.printStackTrace(); } System.gc(); return story_ids; } public static void removeAll() { if (database == null) initialize(); IndexWriterConfig config = new IndexWriterConfig(analyzer); IndexWriter w; try { w = new IndexWriter(index, config); w.deleteAll(); w.close(); } catch (IOException e) { e.printStackTrace(); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.jme3.gde.android; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectInformation; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.NotifyDescriptor.Message; import org.openide.filesystems.FileChooserBuilder; import org.openide.filesystems.FileLock; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.Exceptions; import org.openide.util.NbPreferences; import org.openide.util.Utilities; import org.openide.xml.XMLUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * * @author normenhansen */ public class AndroidSdkTool { /** * Starts the Android target configuration utility. */ public static void startAndroidTool() { startAndroidTool(false); } public static void startAndroidTool(boolean modal) { final String path = getAndroidToolPath(); if (path == null) { return; } Thread thread = new Thread(new Runnable() { @Override public void run() { String[] command = new String[]{path}; ProcessBuilder builder = new ProcessBuilder(command); try { Process proc = builder.start(); OutputReader outReader = new OutputReader(proc.getInputStream()); OutputReader errReader = new OutputReader(proc.getErrorStream()); outReader.start(); errReader.start(); proc.waitFor(); } catch (InterruptedException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } }); if (modal) { thread.run(); } else { thread.start(); } } /** * Returns a FileObject for the android SDK folder, null if none is specified * @return */ public static FileObject getSdkFolder() { String path = getSdkPath(); if (path == null) { return null; } FileObject fileObj = FileUtil.toFileObject(new File(path)); if (fileObj == null) { return null; } return fileObj; } /** * Returns a String with the path to the SDK or null if none is specified. * @return */ public static String getSdkPath() { String path = NbPreferences.forModule(AndroidSdkTool.class).get("sdk_path", null); if (path == null) { FileChooserBuilder builder = new FileChooserBuilder(AndroidSdkTool.class); builder.setTitle("Please select Android SDK Folder"); builder.setDirectoriesOnly(true); File file = builder.showOpenDialog(); if (file != null) { FileObject folder = FileUtil.toFileObject(file); if (folder.getFileObject("tools") == null) { Message msg = new NotifyDescriptor.Message( "Not a valid SDK folder!", NotifyDescriptor.ERROR_MESSAGE); DialogDisplayer.getDefault().notifyLater(msg); } else { String name = file.getPath(); NbPreferences.forModule(AndroidSdkTool.class).put("sdk_path", name); return name; } } } else { return path; } return null; } /** * Returns a string with the path to the android tool, specific for platform (.exe for windows) * @return */ public static String getAndroidToolPath() { FileObject executable = null; FileObject folder = getSdkFolder(); if (folder == null) { return null; } if (Utilities.isWindows()) { executable = folder.getFileObject("tools/android.bat"); } else { executable = folder.getFileObject("tools/android"); } if (executable != null) { return FileUtil.toFile(executable).getPath(); } else { return null; } } /** * Gets a list of android targets registered in the SDK * @return */ public static List<AndroidTarget> getTargetList() { ArrayList<AndroidTarget> list = new ArrayList<AndroidTarget>(); final String path = getAndroidToolPath(); if (path == null) { return list; } String[] command = new String[]{path, "list", "targets"}; ProcessBuilder builder = new ProcessBuilder(command); try { Process proc = builder.start(); ListReader outReader = new ListReader(proc.getInputStream(), list); OutputReader errReader = new OutputReader(proc.getErrorStream()); outReader.start(); errReader.start(); proc.waitFor(); } catch (InterruptedException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } return list; } //TODO: check mainJmeClass public static void checkProject(Project project, String target, String name, String activity, String packag, String mainJmeClass) { final String path = getAndroidToolPath(); if (path == null) { return; } FileObject folder = project.getProjectDirectory().getFileObject("mobile"); if (folder == null) { try { folder = project.getProjectDirectory().createFolder("mobile"); createProject(project, target, name, activity, packag, mainJmeClass); } catch (IOException ex) { Exceptions.printStackTrace(ex); return; } } else { updateProject(project, target, name); } } public static void createProject(Project project, String target, String name, String activity, String packag, String mainJmeClass) { final String path = getAndroidToolPath(); if (path == null) { return; } FileObject folder = project.getProjectDirectory().getFileObject("mobile"); if (folder == null) { try { folder = project.getProjectDirectory().createFolder("mobile"); } catch (IOException ex) { Exceptions.printStackTrace(ex); return; } } String[] command = new String[]{path, "create", "project", "--target", target, "--name", name, "--path", FileUtil.toFile(folder).getPath(), "--activity", activity, "--package", packag}; ProcessBuilder builder = new ProcessBuilder(command); FileLock lock = null; try { Process proc = builder.start(); OutputReader outReader = new OutputReader(proc.getInputStream()); OutputReader errReader = new OutputReader(proc.getErrorStream()); outReader.start(); errReader.start(); proc.waitFor(); String mainActName = "mobile/src/" + packag.replaceAll("\\.", "/") + "/MainActivity.java"; FileObject mainAct = project.getProjectDirectory().getFileObject(mainActName); if (mainAct != null) { lock = mainAct.lock(); OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(mainAct.getOutputStream(lock))); out.write(mainActivityString(mainJmeClass, packag)); out.close(); lock.releaseLock(); } else { throw new IOException("Cannot find " + mainActName); } } catch (InterruptedException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { if (lock != null) { lock.releaseLock(); } Exceptions.printStackTrace(ex); } updateAndroidManifest(project); updateAndroidApplicationName(project, name); } public static void updateProject(Project project, String target, String name) { final String path = getAndroidToolPath(); if (path == null) { return; } FileObject folder = project.getProjectDirectory().getFileObject("mobile"); if (folder == null) { return; } String[] command = new String[]{path, "update", "project", "--target", target, "--name", name, "--path", FileUtil.toFile(folder).getPath()}; ProcessBuilder builder = new ProcessBuilder(command); try { Process proc = builder.start(); OutputReader outReader = new OutputReader(proc.getInputStream()); OutputReader errReader = new OutputReader(proc.getErrorStream()); outReader.start(); errReader.start(); proc.waitFor(); } catch (InterruptedException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } updateAndroidApplicationName(project, name); } private static void updateAndroidManifest(Project project) { FileObject manifest = project.getProjectDirectory().getFileObject("mobile/AndroidManifest.xml"); if (manifest == null) { return; } InputStream in = null; FileLock lock = null; OutputStream out = null; try { in = manifest.getInputStream(); Document configuration = XMLUtil.parse(new InputSource(in), false, false, null, null); in.close(); in = null; boolean changed = false; Element sdkElement = XmlHelper.findChildElement(configuration.getDocumentElement(), "uses-sdk"); if (sdkElement == null) { sdkElement = configuration.createElement("uses-sdk"); configuration.getDocumentElement().appendChild(sdkElement); changed = true; } if (!"8".equals(sdkElement.getAttribute("android:minSdkVersion"))) { sdkElement.setAttribute("android:minSdkVersion", "8"); changed = true; } Element screensElement = XmlHelper.findChildElement(configuration.getDocumentElement(), "supports-screens"); if (screensElement == null) { screensElement = configuration.createElement("supports-screens"); screensElement.setAttribute("android:anyDensity", "true"); // screensElement.setAttribute("android:xlargeScreens", "true"); screensElement.setAttribute("android:largeScreens", "true"); screensElement.setAttribute("android:smallScreens", "true"); screensElement.setAttribute("android:normalScreens", "true"); configuration.getDocumentElement().appendChild(screensElement); changed = true; } if (changed) { lock = manifest.lock(); out = manifest.getOutputStream(lock); XMLUtil.write(configuration, out, "UTF-8"); out.close(); out = null; lock.releaseLock(); lock = null; } } catch (SAXException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } finally { if (lock != null) { lock.releaseLock(); } try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ex1) { Exceptions.printStackTrace(ex1); } } } private static void updateAndroidApplicationName(Project project, String name) { FileObject manifest = project.getProjectDirectory().getFileObject("mobile/res/values/strings.xml"); if (manifest == null) { return; } InputStream in = null; FileLock lock = null; OutputStream out = null; try { in = manifest.getInputStream(); Document configuration = XMLUtil.parse(new InputSource(in), false, false, null, null); in.close(); in = null; Element sdkElement = XmlHelper.findChildElementWithAttribute(configuration.getDocumentElement(), "string", "name", "app_name"); if (sdkElement == null) { sdkElement = configuration.createElement("string"); sdkElement.setAttribute("name", "app_name"); configuration.getDocumentElement().appendChild(sdkElement); } if (!sdkElement.getTextContent().trim().equals(name)) { sdkElement.setTextContent(name); lock = manifest.lock(); out = manifest.getOutputStream(lock); XMLUtil.write(configuration, out, "UTF-8"); out.close(); out = null; lock.releaseLock(); lock = null; } } catch (SAXException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } finally { if (lock != null) { lock.releaseLock(); } try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ex1) { Exceptions.printStackTrace(ex1); } } } private static String mainActivityString(String mainClass, String packag) { String str = "package " + packag + ";\n" + " \n" + "import com.jme3.app.AndroidHarness;\n" + "import android.content.pm.ActivityInfo;\n" + "import com.jme3.system.android.AndroidConfigChooser.ConfigType;\n" + " \n" + "public class MainActivity extends AndroidHarness{\n" + " \n" + " /*\n" + " * Note that you can ignore the errors displayed in this file,\n" + " * the android project will build regardless.\n" + " * Install the 'Android' plugin under Tools->Plugins->Available Plugins\n" + " * to get error checks and code completion for the Android project files.\n" + " */\n" + " \n" + " public MainActivity(){\n" + " // Set the application class to run\n" + " appClass = \"" + mainClass + "\";\n" + " // Try ConfigType.FASTEST; or ConfigType.LEGACY if you have problems\n" + " eglConfigType = ConfigType.BEST;\n" + " // Exit Dialog title & message\n" + " exitDialogTitle = \"Exit?\";\n" + " exitDialogMessage = \"Press Yes\";\n" + " // Enable verbose logging\n" + " eglConfigVerboseLogging = false;\n" + " // Choose screen orientation\n" + " screenOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;\n" + " // Invert the MouseEvents X (default = true)\n" + " mouseEventsInvertX = true;\n" + " // Invert the MouseEvents Y (default = true)\n" + " mouseEventsInvertY = true;\n" + " }\n" + " \n" + "}\n"; return str; } public static class AndroidTarget { private int id; private String name; private String title; private String platform; private int apiLevel; private int revision; private String skins; public AndroidTarget() { } public AndroidTarget(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPlatform() { return platform; } public void setPlatform(String platform) { this.platform = platform; } public int getApiLevel() { return apiLevel; } public void setApiLevel(int apiLevel) { this.apiLevel = apiLevel; } public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public String getSkins() { return skins; } public void setSkins(String skins) { this.skins = skins; } @Override public String toString() { return getTitle(); } @Override public boolean equals(Object obj) { if (obj instanceof String && getName() != null) { return getName().equals(obj); } else { return super.equals(obj); } } } }
package com.wonderpush.sdk; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.os.Build; import android.telephony.TelephonyManager; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TimeZone; import java.util.TreeSet; public class InstallationManager { static final String TAG = WonderPush.TAG; /** * How long to wait for no other call to {@link #putInstallationCustomProperties(JSONObject)} * before writing changes to the server. */ protected static final long CACHED_INSTALLATION_CUSTOM_PROPERTIES_MIN_DELAY = 5 * 1000; /** * How long to wait for another call to {@link #putInstallationCustomProperties(JSONObject)} at maximum, * if there are no pause of {@link #CACHED_INSTALLATION_CUSTOM_PROPERTIES_MIN_DELAY} time between calls. */ protected static final long CACHED_INSTALLATION_CUSTOM_PROPERTIES_MAX_DELAY = 20 * 1000; public static JSONObject getInstallationCustomProperties() { try { JSONObject sync = JSONSyncInstallation.forCurrentUser().getSdkState(); JSONObject custom = sync == null ? null : sync.optJSONObject("custom"); if (custom == null) return new JSONObject(); Iterator<String> it = custom.keys(); while (it.hasNext()) { String key = it.next(); if (key.indexOf('_') < 0) { it.remove(); } } return custom; } catch (JSONException ex) { Log.e(WonderPush.TAG, "Failed to read installation custom properties", ex); return new JSONObject(); } } public static synchronized void putInstallationCustomProperties(JSONObject customProperties) { try { customProperties = JSONUtil.deepCopy(customProperties); Iterator<String> it = customProperties.keys(); while (it.hasNext()) { String key = it.next(); if (key.indexOf('_') < 0) { Log.w(WonderPush.TAG, "Dropping installation property with no prefix: " + key); it.remove(); } } JSONObject diff = new JSONObject(); diff.put("custom", customProperties); JSONSyncInstallation.forCurrentUser().put(diff); } catch (JSONException ex) { Log.e(WonderPush.TAG, "Failed to put installation custom properties " + customProperties, ex); } } public static synchronized void setProperty(String field, Object value) { if (field == null) return; value = JSONUtil.wrap(value); try { JSONObject diff = new JSONObject(); diff.put(field, value); putInstallationCustomProperties(diff); } catch (JSONException ex) { Log.e(WonderPush.TAG, "Failed to setProperty(" + field + ", " + value + ")", ex); } } public static synchronized void unsetProperty(String field) { if (field == null) return; try { JSONObject diff = new JSONObject(); diff.put(field, JSONObject.NULL); putInstallationCustomProperties(diff); } catch (JSONException ex) { Log.e(WonderPush.TAG, "Failed to unsetProperty(" + field + ")", ex); } } public static synchronized void addProperty(String field, Object value) { value = JSONUtil.wrap(value); if (field == null || value == null || value == JSONObject.NULL) return; // The contract is to actually append new values only, not shuffle or deduplicate everything, // hence the array and the set. List<Object> values = new ArrayList<>(getPropertyValues(field)); Set<Object> set = new HashSet<>(values); JSONArray inputs = value instanceof JSONArray ? (JSONArray) value : new JSONArray().put(value); for (int i = 0, e = inputs.length(); i < e; ++i) { try { Object input = inputs.get(i); if (input == null || input == JSONObject.NULL) continue; if (set.contains(input)) continue; values.add(input); set.add(input); } catch (JSONException ex) { Log.e(WonderPush.TAG, "Unexpected exception in addProperty", ex); } } setProperty(field, values); } public static synchronized void removeProperty(String field, Object value) { value = JSONUtil.wrap(value); if (field == null || value == null) return; // Note: We accept removing JSONObject.NULL // The contract is to actually remove every listed values (all duplicated appearances), not shuffle or deduplicate everything else List<Object> values = getPropertyValues(field); JSONArray inputs = null; try { inputs = new JSONArray((value instanceof JSONArray ? (JSONArray) value : new JSONArray().put(value)).toString()); } catch (JSONException ex) { Log.e(WonderPush.TAG, "Unexpected exception in removeProperty", ex); return; } Set<Object> set = new HashSet<>(JSONUtil.JSONArrayToList(inputs, Object.class, true)); if (set.isEmpty()) return; JSONArray newValues = new JSONArray(); for (Object item : values) { if (item == null) continue; if (set.contains(item)) continue; newValues.put(item); } setProperty(field, newValues); } public static synchronized Object getPropertyValue(String field) { if (field == null) return JSONObject.NULL; JSONObject properties = getInstallationCustomProperties(); Object value = properties.opt(field); while (value instanceof JSONArray) { // Note, the documentation says *never* a JSONArray, so we use a while instead of an if to sure of that value = ((JSONArray) value).length() > 0 ? ((JSONArray) value).opt(0) : null; } if (value == null) value = JSONObject.NULL; return value; } public static synchronized List<Object> getPropertyValues(String field) { if (field == null) return Collections.emptyList(); JSONObject properties = getInstallationCustomProperties(); Object value = properties.opt(field); if (value == null || value == JSONObject.NULL) { return Collections.emptyList(); } else if (value instanceof JSONArray) { return JSONUtil.JSONArrayToList((JSONArray) value, Object.class, true); } else { return Collections.singletonList(value); } } public static synchronized void addTag(String... tag) { Set<String> tags = new TreeSet<>(getTags()); // use a sorted implementation to avoid useless diffs for (String aTag : tag) { if (aTag != null && !aTag.isEmpty()) { tags.add(aTag); } else { Log.w(TAG, "Dropping invalid tag " + aTag); } } try { JSONObject diff = new JSONObject(); JSONObject custom = new JSONObject(); diff.put("custom", custom); custom.putOpt("tags", new JSONArray(tags)); JSONSyncInstallation.forCurrentUser().put(diff); } catch (JSONException ex) { Log.e(TAG, "Failed to addTag", ex); } } public static synchronized void removeTag(String... tag) { Set<String> tags = new TreeSet<>(getTags()); // use a sorted implementation to avoid useless diffs tags.removeAll(Arrays.asList(tag)); try { JSONObject diff = new JSONObject(); JSONObject custom = new JSONObject(); diff.put("custom", custom); custom.putOpt("tags", new JSONArray(tags)); JSONSyncInstallation.forCurrentUser().put(diff); } catch (JSONException ex) { Log.e(TAG, "Failed to addTag", ex); } } public static synchronized void removeAllTags() { try { JSONObject diff = new JSONObject(); JSONObject custom = new JSONObject(); diff.put("custom", custom); custom.putOpt("tags", JSONObject.NULL); JSONSyncInstallation.forCurrentUser().put(diff); } catch (JSONException ex) { Log.e(TAG, "Failed to removeAllTags", ex); } } public static synchronized Set<String> getTags() { JSONObject custom; try { JSONObject sync = JSONSyncInstallation.forCurrentUser().getSdkState(); custom = sync != null ? sync.optJSONObject("custom") : null; if (custom == null) custom = new JSONObject(); } catch (JSONException ex) { Log.e(WonderPush.TAG, "Failed to read installation custom properties", ex); custom = new JSONObject(); } JSONArray tags = custom.optJSONArray("tags"); if (tags == null) { tags = new JSONArray(); // Recover from a potential scalar string value String val = JSONUtil.optString(custom, "tags"); if (val != null) { tags.put(val); } } TreeSet<String> rtn = new TreeSet<>(); // use a sorted implementation to avoid useless diffs later on for (int i = 0, l = tags.length(); i < l; ++i) { try { Object val = tags.get(i); if (val instanceof String && !((String) val).isEmpty()) { rtn.add((String) val); } } catch (JSONException ex) { Log.e(TAG, "Failed to get tags at position " + i + " from " + tags, ex); } } return rtn; } public static synchronized boolean hasTag(String tag) { if (tag == null) return false; return getTags().contains(tag); } protected static void updateInstallationCoreProperties(final Context context) { WonderPush.safeDefer(new Runnable() { @Override public void run() { JSONObject diff = new JSONObject(); try { JSONObject application = new JSONObject(); application.put("version", getApplicationVersion()); application.put("sdkVersion", getSDKVersion()); application.put("integrator", WonderPush.getIntegrator() == null ? JSONObject.NULL : WonderPush.getIntegrator()); diff.put("application", application); JSONObject device = new JSONObject(); device.put("id", WonderPush.getDeviceId()); device.put("platform", "Android"); device.put("osVersion", getOsVersion()); device.put("brand", getDeviceBrand()); device.put("model", getDeviceModel()); device.put("screenWidth", getScreenWidth()); device.put("screenHeight", getScreenHeight()); device.put("screenDensity", getScreenDensity()); JSONObject configuration = new JSONObject(); configuration.put("timeZone", getUserTimezone()); configuration.put("timeOffset", getUserTimeOffset()); configuration.put("carrier", getCarrierName()); configuration.put("locale", getLocaleString()); configuration.put("country", getLocaleCountry()); configuration.put("currency", getLocaleCurrency()); device.put("configuration", configuration); diff.put("device", device); JSONSyncInstallation.forCurrentUser().put(diff); } catch (JSONException ex) { Log.e(TAG, "Unexpected error while updating installation core properties", ex); } catch (Exception ex) { Log.e(TAG, "Unexpected error while updating installation core properties", ex); } } }, 0); } protected static String getApplicationVersion() { String versionName = null; try { PackageInfo packageInfo = WonderPush.getApplicationContext().getPackageManager().getPackageInfo(WonderPush.getApplicationContext().getPackageName(), 0); versionName = packageInfo.versionName; } catch (PackageManager.NameNotFoundException e) { WonderPush.logDebug("Could not retreive version name"); } return versionName; } protected static String getOsVersion() { return "" + android.os.Build.VERSION.SDK_INT; } protected static String getUserTimezone() { return WonderPush.getTimeZone(); } protected static long getUserTimeOffset() { String timeZone = WonderPush.getTimeZone(); TimeZone tz = TimeZone.getTimeZone(timeZone); return tz.getOffset(TimeSync.getTime()); } protected static String getCarrierName() { TelephonyManager telephonyManager = ((TelephonyManager) WonderPush.getApplicationContext() .getSystemService(Context.TELEPHONY_SERVICE)); return telephonyManager.getNetworkOperatorName(); } protected static String getLocaleString() { return WonderPush.getLocale(); } protected static String getLocaleCountry() { return WonderPush.getCountry(); } protected static String getLocaleCurrency() { return WonderPush.getCurrency(); } protected static String getSDKVersion() { return WonderPush.SDK_VERSION; } /** * Gets the model of this android device. */ protected static String getDeviceModel() { return Build.MODEL; } protected static String getDeviceBrand() { return Build.MANUFACTURER; } protected static int getScreenDensity() { return Resources.getSystem().getConfiguration().densityDpi; } protected static int getScreenWidth() { return Resources.getSystem().getDisplayMetrics().widthPixels; } protected static int getScreenHeight() { return Resources.getSystem().getDisplayMetrics().heightPixels; } }
package org.cyanogenmod.launcher.home.api.cards; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import org.cyanogenmod.launcher.home.api.provider.CmHomeContract; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Date; import java.util.List; public class DataCard extends PublishableCard { private static final String TAG = "DataCard"; private static final CmHomeContract.ICmHomeContract sContract = new CmHomeContract.DataCard(); private String mInternalId; private String mReasonText; private Date mContentCreatedDate; private Date mCreatedDate; private Date mLastModifiedDate; private Uri mContentSourceImageUri; private Uri mAvatarImageUri; private String mTitle; private String mSmallText; private String mBodyText; private Intent mCardClickIntent; private String mAction1Text; private Intent mAction1Intent; private String mAction2Text; private Intent mAction2Intent; private Priority mPriority = Priority.MID; public enum Priority { HIGH(0), MID(1), LOW(2); private final int mValue; private Priority(int value) { mValue = value; } public int getValue() { return mValue; } public static Priority getModeForValue(int value) { switch (value) { case 0: return HIGH; case 1: return MID; case 2: return LOW; default: return MID; } } } private List<DataCardImage> mImages = new ArrayList<DataCardImage>(); private DataCard() { super(sContract); } public DataCard(String title, Date contentCreatedDate) { super(sContract); setTitle(title); setContentCreatedDate(contentCreatedDate); } public void addDataCardImage(Uri uri) { DataCardImage image = new DataCardImage(getId(), uri); mImages.add(image); } public void setInternalId(String internalId) { mInternalId = internalId; } public String getInternalId() { return mInternalId; } private void setCreatedDate(Date date) { mCreatedDate = date; } private void setLastModifiedDate(Date date) { mLastModifiedDate = date; } public void addDataCardImage(DataCardImage image) { mImages.add(image); } public void clearImages() { mImages.clear(); } public void removeDataCardImage(DataCardImage image) { mImages.remove(image); } public Date getCreatedDate() { return mCreatedDate; } public String getReasonText() { return mReasonText; } public void setReasonText(String reason) { this.mReasonText = reason; } public Date getContentCreatedDate() { return mContentCreatedDate; } public void setContentCreatedDate(Date contentCreatedDate) { this.mContentCreatedDate = contentCreatedDate; } public Date getLastModifiedDate() { return mLastModifiedDate; } public Uri getContentSourceImageUri() { return mContentSourceImageUri; } public void setContentSourceImageUri(Uri contentSourceImageUri) { this.mContentSourceImageUri = contentSourceImageUri; } public Uri getAvatarImageUri() { return mAvatarImageUri; } public void setAvatarImageUri(Uri avatarImageUri) { this.mAvatarImageUri = avatarImageUri; } public String getTitle() { return mTitle; } public void setTitle(String title) { this.mTitle = title; } public String getSmallText() { return mSmallText; } public void setSmallText(String smallText) { this.mSmallText = smallText; } public String getBodyText() { return mBodyText; } public void setBodyText(String bodyText) { this.mBodyText = bodyText; } public Intent getCardClickIntent() { return mCardClickIntent; } public void setCardClickIntent(Intent cardClickIntent) { mCardClickIntent = cardClickIntent; } public String getAction1Text() { return mAction1Text; } public void setAction1Text(String action1Text) { this.mAction1Text = action1Text; } public Intent getAction1Intent() { return mAction1Intent; } public void setAction1Intent(Intent action1Intent) { this.mAction1Intent = action1Intent; } public String getAction2Text() { return mAction2Text; } public void setAction2Text(String action2Text) { this.mAction2Text = action2Text; } public Intent getAction2Intent() { return mAction2Intent; } public void setAction2Intent(Intent action2Intent) { this.mAction2Intent = action2Intent; } public Priority getPriority() { return mPriority; } private int getPriorityAsInt() { return mPriority.getValue(); } private void setPriority(int value) { mPriority = Priority.getModeForValue(value); } public void setPriority(Priority priority) { this.mPriority = priority; } @Override public boolean publish(Context context) { boolean updated = super.publish(context); if (!updated) { // Initialize the created date and modified date to now. mCreatedDate = new Date(); mLastModifiedDate = new Date(); } for (DataCardImage image : mImages) { image.publish(context); } return updated; } /** * Updates an existing row in the ContentProvider that represents this card. * This will update every column at once. * @param context A Context object to retrieve the ContentResolver * @return true if the update successfully updates a row, false otherwise. */ protected boolean update(Context context) { boolean updated = super.update(context); if (updated) { // Update all associated images as well for (DataCardImage image : mImages) { image.publish(context); } } return updated; } /** * Removes this DataCard from the feed, so that it is no longer visible to the user. * @param context The context of the publishing application. * @return True if the card was successfully unpublished, false otherwise. */ @Override public boolean unpublish(Context context) { boolean deleted = super.unpublish(context); if (deleted) { // Delete all associated images as well for (DataCardImage image : mImages) { image.unpublish(context); } } return deleted; } @Override protected ContentValues getContentValues() { ContentValues values = new ContentValues(); values.put(CmHomeContract.DataCard.INTERNAL_ID_COL, getInternalId()); values.put(CmHomeContract.DataCard.REASON_COL, getReasonText()); if (getContentCreatedDate() != null) { values.put(CmHomeContract.DataCard.DATE_CONTENT_CREATED_COL, getContentCreatedDate().getTime()); } if (getContentSourceImageUri() != null) { values.put(CmHomeContract.DataCard.CONTENT_SOURCE_IMAGE_URI_COL, getContentSourceImageUri().toString()); } if (getAvatarImageUri() != null) { values.put(CmHomeContract.DataCard.AVATAR_IMAGE_URI_COL, getAvatarImageUri().toString()); } values.put(CmHomeContract.DataCard.TITLE_TEXT_COL, getTitle()); values.put(CmHomeContract.DataCard.SMALL_TEXT_COL, getSmallText()); values.put(CmHomeContract.DataCard.BODY_TEXT_COL, getBodyText()); values.put(CmHomeContract.DataCard.ACTION_1_TEXT_COL, getAction1Text()); if (getAction1Intent() != null) { values.put(CmHomeContract.DataCard.ACTION_1_URI_COL, getAction1Intent().toUri(Intent.URI_INTENT_SCHEME).toString()); } values.put(CmHomeContract.DataCard.ACTION_2_TEXT_COL, getAction2Text()); if (getAction2Intent() != null) { values.put(CmHomeContract.DataCard.ACTION_2_URI_COL, getAction2Intent().toUri(Intent.URI_INTENT_SCHEME).toString()); } values.put(CmHomeContract.DataCard.PRIORITY_COL, getPriorityAsInt()); if (getCardClickIntent() != null) { values.put(CmHomeContract.DataCard.CARD_CLICK_URI_COL, getCardClickIntent().toUri(Intent.URI_INTENT_SCHEME).toString()); } return values; } public static List<DataCard> getAllPublishedDataCards(Context context) { return getAllPublishedDataCards(context, CmHomeContract.DataCard.CONTENT_URI, CmHomeContract.DataCardImage.CONTENT_URI); } public static DataCard createFromCurrentCursorRow(Cursor cursor, String authority) { DataCard card = createFromCurrentCursorRow(cursor); card.setAuthority(authority); return card; } public static DataCard createFromCurrentCursorRow(Cursor cursor) { DataCard dataCard = new DataCard(); dataCard.setId(cursor.getInt(cursor.getColumnIndex(CmHomeContract.DataCard._ID))); dataCard.setInternalId(cursor.getString(cursor.getColumnIndex(CmHomeContract.DataCard .INTERNAL_ID_COL))); long createdTime = cursor.getLong(cursor.getColumnIndex(CmHomeContract.DataCard .DATE_CREATED_COL)); dataCard.setCreatedDate(new Date(createdTime)); long modifiedTime = cursor.getLong(cursor.getColumnIndex(CmHomeContract.DataCard .LAST_MODIFIED_COL)); dataCard.setLastModifiedDate(new Date(modifiedTime)); long contentCreatedTime = cursor.getLong( cursor.getColumnIndex(CmHomeContract.DataCard.DATE_CONTENT_CREATED_COL)); dataCard.setContentCreatedDate(new Date(contentCreatedTime)); dataCard.setReasonText(cursor.getString(cursor.getColumnIndex(CmHomeContract.DataCard .REASON_COL))); String contentSourceUriString = cursor.getString(cursor.getColumnIndex( CmHomeContract.DataCard.CONTENT_SOURCE_IMAGE_URI_COL)); if (!TextUtils.isEmpty(contentSourceUriString)) { dataCard.setContentSourceImageUri(Uri.parse(contentSourceUriString)); } String avatarImageUriString = cursor.getString(cursor.getColumnIndex( CmHomeContract.DataCard.AVATAR_IMAGE_URI_COL)); if (!TextUtils.isEmpty(avatarImageUriString)) { dataCard.setAvatarImageUri(Uri.parse(avatarImageUriString)); } dataCard.setTitle(cursor.getString( cursor.getColumnIndex(CmHomeContract.DataCard.TITLE_TEXT_COL))); dataCard.setSmallText( cursor.getString(cursor.getColumnIndex( CmHomeContract.DataCard.SMALL_TEXT_COL))); dataCard.setBodyText(cursor.getString( cursor.getColumnIndex(CmHomeContract.DataCard.BODY_TEXT_COL))); dataCard.setAction1Text( cursor.getString(cursor.getColumnIndex( CmHomeContract.DataCard.ACTION_1_TEXT_COL))); String clickActionUriString = cursor.getString( cursor.getColumnIndex(CmHomeContract.DataCard.CARD_CLICK_URI_COL)); if (!TextUtils.isEmpty(clickActionUriString)) { try { Intent cardClickIntent = Intent.parseUri(clickActionUriString, Intent.URI_INTENT_SCHEME); dataCard.setCardClickIntent(cardClickIntent); } catch (URISyntaxException e) { Log.e(TAG, "Unable to parse uri to Intent: " + clickActionUriString); } } String action1UriString = cursor.getString( cursor.getColumnIndex(CmHomeContract.DataCard.ACTION_1_URI_COL)); if (!TextUtils.isEmpty(action1UriString)) { try { dataCard.setAction1Intent(Intent.parseUri(action1UriString, Intent.URI_INTENT_SCHEME)); } catch (URISyntaxException e) { Log.e(TAG, "Unable to parse uri to Intent: " + action1UriString); } } dataCard.setAction2Text(cursor.getString( cursor.getColumnIndex(CmHomeContract.DataCard.ACTION_2_TEXT_COL))); String action2UriString = cursor.getString( cursor.getColumnIndex(CmHomeContract.DataCard.ACTION_2_URI_COL)); if (!TextUtils.isEmpty(action2UriString)) { try { dataCard.setAction2Intent(Intent.parseUri(action2UriString, Intent.URI_INTENT_SCHEME)); } catch (URISyntaxException e) { Log.e(TAG, "Unable to parse uri to Intent: " + action2UriString); } } int priority = cursor.getInt(cursor.getColumnIndex(CmHomeContract.DataCard .PRIORITY_COL)); dataCard.setPriority(priority); return dataCard; } public static List<DataCard> getAllPublishedDataCards(Context context, Uri dataCardContentUri, Uri dataCardImageContentUri) { ContentResolver contentResolver = context.getContentResolver(); List<DataCard> allCards = new ArrayList<DataCard>(); Cursor cursor = null; try { cursor = contentResolver.query(dataCardContentUri, CmHomeContract.DataCard.PROJECTION_ALL, null, null, CmHomeContract.DataCard.DATE_CREATED_COL); // Catching all Exceptions, since we can't be sure what the extension will do. } catch (Exception e) { Log.e(TAG, "Error querying for DataCards, ContentProvider threw an exception for uri:" + " " + dataCardContentUri, e); } if (cursor != null) { while (cursor.moveToNext()) { DataCard dataCard = createFromCurrentCursorRow(cursor, dataCardContentUri.getAuthority()); allCards.add(dataCard); } cursor.close(); } // Retrieve all DataCardImages for each DataCard. // Doing this in a separate loop since each iteration // will also be querying the ContentProvider. for (DataCard card : allCards) { List<DataCardImage> images = DataCardImage .getPublishedDataCardImagesForDataCardId(context, dataCardImageContentUri, card.getId()); for (DataCardImage image : images) { card.addDataCardImage(image); } } return allCards; } }
package gov.nih.nci.cadsr.cdecurate.tool.tags; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; /** * This JSP tag library class is for action Menu * @author hveerla * */ public class ObjMenuTag extends MenuTag { public int doEndTag() throws JspException { getSessionAttributes(); HttpSession session = pageContext.getSession(); int rowsChecked = 0; if (vCheckList!=null){ rowsChecked = vCheckList.size(); } JspWriter objMenu = this.pageContext.getOut(); if (selACType != null) { try { objMenu.println("<table style = \"border-collapse: collapse; background-color: #d8d8df\">"); objMenu.println("<tr><td colspan=\"2\"><p style=\"margin: 0px 0px 5px 0px; color: red\"><span id=\"selCnt\">" + rowsChecked + "</span> Record(s) Selected</p></td><td align=\"right\" valign=\"top\"><span style=\"border: 1px solid black; padding: 0.5px 1px 0.5px 1px;cursor:default;\">x</span></td></tr>"); objMenu.println("<tr style = \"background-color:#4876FF\"><td class=\"cell\" align=\"center\"><input type=\"checkbox\" onclick=\"this.checked=false;\"></td><td class=\"cell\" align=\"center\"><b><font color = \"#FFFFFF\">Action</b></td><td class=\"cell\" align=\"center\"><input type=\"checkbox\" checked onclick=\"this.checked=true;\"></td></tr>"); if ((selACType).equals("DataElement")) { objMenu.println(displayEdit() + displayView() + displayDesignate() + displayViewDetiails() + displayGetAssociatedDEC() + displayGetAssociatedVD() + displayUploadDoc() + displayMonitor() + displayUnMonitor() + displayNewUsingExisting() + displayNewVersion() + displayShowAll() + displayHideAll() + displayAppend()); } if ((selACType).equals("DataElementConcept")) { objMenu.println(displayEdit() + displayView() + displayGetAssociatedDE() + displayUploadDoc() + displayMonitor() + displayUnMonitor() + displayNewUsingExisting() + displayNewVersion() + displayShowAll() + displayHideAll() + displayAppend()); } if ((selACType).equals("ValueDomain")) { objMenu.println(displayEdit() + displayView() + displayGetAssociatedDE() + displayUploadDoc() + displayMonitor() + displayUnMonitor() + displayNewUsingExisting() + displayNewVersion() + displayShowAll() + displayHideAll() + displayAppend()); } if ((selACType).equals("ConceptualDomain")) { objMenu.println(displayGetAssociatedDE() + displayGetAssociatedDEC() + displayGetAssociatedVD() + displayShowAll() + displayHideAll()); } if ((selACType).equals("PermissibleValue")) { objMenu.println(displayGetAssociatedDE() + displayGetAssociatedVD() + displayShowAll() + displayHideAll()); } if ((selACType).equals("ClassSchemeItems")){ objMenu.println(displayGetAssociatedDE() + displayGetAssociatedDEC() + displayGetAssociatedVD() + displayShowAll() + displayHideAll()); } if ((selACType).equals("ValueMeaning")) { objMenu.println(generateTR("edit","edit","performUncheckedCkBoxAction('edit')","","","Edit") + displayView() + displayGetAssociatedDE() + displayGetAssociatedVD() + displayShowAll() + displayHideAll()); } if ((selACType).equals("ConceptClass")) { objMenu.println(displayGetAssociatedDE() + displayGetAssociatedDEC() + displayGetAssociatedVD() + displayShowAll() + displayHideAll()); } if ((selACType).equals("ObjectClass")){ objMenu.println(displayGetAssociatedDEC() + displayShowAll() + displayHideAll()); } if ((selACType).equals("Property")) { objMenu.println(displayGetAssociatedDEC() + displayShowAll() + displayHideAll()); } objMenu.println(generateTR("","","","16_show_rows","ShowSelectedRowss()","Show Selected Rows")); objMenu.println(generateTR("","","","select_all","SelectAllCheckBox()","Select All")); objMenu.println(generateTR("","","","unselect_all","UnSelectAllCheckBox()","Unselect All")); objMenu.println("</table></div>"); } catch (IOException e) { e.printStackTrace(); } } return EVAL_PAGE; } public String generateTR(String id, String imageSingle, String jsMethodSingle, String imageMultiple, String jsMethodMultiple, String value){ HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); String image_single = null; String image_multiple = null; String tdTag1 = null; String tdTag2 = null; if (imageSingle != null && !(imageSingle == "" )) image_single = "<img src=\""+ request.getContextPath() +"/images/"+imageSingle+".gif\" border=\"0\">"; else image_single = " if (imageMultiple != null && !(imageMultiple == "" )) image_multiple = "<img src=\""+ request.getContextPath() +"/images/"+imageMultiple+".gif\" border=\"0\">"; else image_multiple = " if (image_single == " tdTag1 = "<td class=\"cell\" align = \"center\" style = \"cursor:default\">"+image_single+"</td>"; }else{ tdTag1 = "<td class=\"cell\" align = \"center\" onmouseover=\"menuItemFocus(this);\" onmouseout=\"menuItemNormal(this);\" onclick=\"javascript:" + jsMethodSingle + ";\">"+image_single+"</td>"; } if (image_multiple == " tdTag2 = "<td class=\"cell\" align = \"center\" style = \"cursor:default\">"+image_multiple+"</td>" ; }else{ tdTag2 = "<td class=\"cell\" align = \"center\" onmouseover=\"menuItemFocus(this);\" onmouseout=\"menuItemNormal(this);\" onclick=\"javascript:" + jsMethodMultiple + ";\">"+image_multiple+"</td>"; } String tag ="<tr>" + tdTag1 +"<td class=\"cell\" align = \"left\">"+ value +"</td>" + tdTag2 +"</tr>"; return tag; } public String displayEdit(){ String tag = generateTR("edit","edit_16","performUncheckedCkBoxAction('edit')","block_edit_new","performAction('blockEdit')","Edit"); return tag; } public String displayView(){ String tag = generateTR("view","16_preview","viewAC()","","","View"); return tag; } public String displayDesignate(){ String tag = generateTR("","16_designate","performUncheckedCkBoxAction('designate')","16_designate_multi","performAction('designate')","Designate"); return tag; } public String displayViewDetiails(){ String tag = generateTR("details","cde-book-16","GetDetails()","","","View Details"); return tag; } public String displayGetAssociatedDE(){ String tag = generateTR("associatedDE","16_associated","getAssocDEs()","","","Get Associated DE"); return tag; } public String displayGetAssociatedDEC(){ String tag = generateTR("associatedDEC","16_associated","getAssocDECs()","","","Get Associated DEC"); return tag; } public String displayGetAssociatedVD(){ String tag = generateTR("associatedVD","16_associated","getAssocVDs()","","","Get Associated VD"); return tag; } public String displayUploadDoc(){ String tag = generateTR("uploadDoc","16_uploading","performUncheckedCkBoxAction('uploadDoc')","","","Upload Document(s)"); return tag; } public String displayMonitor(){ String tag = generateTR("","monitor","performUncheckedCkBoxAction('monitor')","monitor_multi","performAction('monitor')","Monitor"); return tag; } public String displayUnMonitor(){ String tag = generateTR("","unmonitor","performUncheckedCkBoxAction('unmonitor')","unmonitor_multi","performAction('unmonitor')","Unmonitor"); return tag; } public String displayNewUsingExisting(){ String tag = generateTR("newUE","16_new_use_existing","createNew('newUsingExisting')","","","New Using Existing"); return tag; } public String displayNewVersion(){ String tag = generateTR("newVersion","16_new_version","createNew('newVersion')","","","New Version"); return tag; } public String displayShowAll(){ String tag = generateTR("","","","plus_12","hideShowAllDef(true)","Show All Definitions"); return tag; } public String displayHideAll(){ String tag = generateTR("","","","minus_12","hideShowAllDef(false)","Hide All Definitions"); return tag; } public String displayAppend(){ String tag = generateTR("","","","16_append","performAction('append')","Append"); return tag; } }
package gov.nih.nci.calab.dto.administration; /** * This class includes all properties of an aliquot that need to be viewed and * saved. * * @author pansu * */ /* CVS $Id: AliquotBean.java,v 1.4 2006-04-04 15:31:29 pansu Exp $ */ public class AliquotBean { private String aliquotId; private ContainerBean container; private String howCreated; private String creator; private String creationDate; private SampleBean sample; public AliquotBean() { container=new ContainerBean(); sample=new SampleBean(); } public AliquotBean(String aliquotId, ContainerBean container, String howCreated, String creator, String creationDate) { // TODO Auto-generated constructor stub this.aliquotId = aliquotId; this.container = container; this.howCreated = howCreated; this.creator=creator; this.creationDate=creationDate; } public AliquotBean(String aliquotId, ContainerBean container, String howCreated, String creator, String creationDate, SampleBean sample) { // TODO Auto-generated constructor stub this(aliquotId, container, howCreated, creator, creationDate); this.sample=sample; } public String getAliquotId() { return aliquotId; } public void setAliquotId(String aliquotId) { this.aliquotId = aliquotId; } public ContainerBean getContainer() { return container; } public void setContainer(ContainerBean container) { this.container = container; } public String getHowCreated() { return howCreated; } public void setHowCreated(String howCreated) { this.howCreated = howCreated; } public String getCreationDate() { return creationDate; } public void setCreationDate(String creationDate) { this.creationDate = creationDate; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public SampleBean getSample() { return sample; } public void setSample(SampleBean sample) { this.sample = sample; } }
package gov.nih.nci.calab.ui.core; import java.io.File; import java.io.FileInputStream; import gov.nih.nci.calab.dto.characterization.CharacterizationBean; import gov.nih.nci.calab.dto.characterization.CharacterizationFileBean; import gov.nih.nci.calab.exception.InvalidSessionException; import gov.nih.nci.calab.exception.NoAccessException; import gov.nih.nci.calab.service.util.CalabConstants; import gov.nih.nci.calab.service.util.PropertyReader; import gov.nih.nci.calab.ui.submit.NanoparticleSizeAction; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import org.apache.struts.validator.DynaValidatorForm; public abstract class AbstractDispatchAction extends DispatchAction { private static Logger logger = Logger.getLogger(AbstractDispatchAction.class); public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; // response.setHeader("Cache-Control", "no-cache"); if (isCancelled(request)) return mapping.findForward("cancel"); // TODO fill in the common operations */ if (!loginRequired() || loginRequired() && isUserLoggedIn(request)) { if (loginRequired()) { String dispatch = request.getParameter("dispatch"); // check whether user have access to the class boolean accessStatus = canUserExecute(request.getSession()); //if dispatch is view or accessStatus is true don't throw exception if (!dispatch.equals("view") && !accessStatus) { throw new NoAccessException( "You don't have access to class: " + this.getClass().getName()); } } forward = super.execute(mapping, form, request, response); } else { throw new InvalidSessionException(); } return forward; } /** * * @param request * @return whether the user is successfully logged in. */ private boolean isUserLoggedIn(HttpServletRequest request) { boolean isLoggedIn = false; if (request.getSession().getAttribute("user") != null) { isLoggedIn = true; } return isLoggedIn; } public abstract boolean loginRequired(); /** * Check whether the current user in the session can perform the action * * @param session * @return * @throws Exception */ public boolean canUserExecute(HttpSession session) throws Exception { return InitSessionSetup.getInstance().canUserExecuteClass(session, this.getClass()); } /** * Update multiple children on the same form * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward updateManufacturers(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; HttpSession session = request.getSession(); CharacterizationBean sizeChar=(CharacterizationBean) theForm.get("achar"); if (sizeChar.getInstrument() != null) { String type = sizeChar.getInstrument().getType(); session.setAttribute("selectedInstrumentType", type); InitSessionSetup.getInstance().setManufacturerPerType(session, sizeChar.getInstrument().getType()); } return mapping.getInputForward(); } /** * Download action to handle download characterization file * @param * @return */ public ActionForward download (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String fileId=request.getParameter("fileId"); String rootPath = PropertyReader.getProperty(CalabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); if (rootPath.charAt(rootPath.length()-1) == File.separatorChar) rootPath = rootPath.substring(0, rootPath.length()-1); CharacterizationFileBean fileBean = (CharacterizationFileBean) request.getSession().getAttribute("characterizationFile" + fileId); String filename = rootPath + fileBean.getPath(); File dFile = new File(filename); if (dFile.exists()) { response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename=" + fileBean.getName()); response.setHeader("Cache-Control", "no-cache"); java.io.InputStream in = new FileInputStream (dFile); java.io.OutputStream out = response.getOutputStream(); byte[] bytes = new byte[32768]; int numRead = 0; while ((numRead = in.read(bytes)) > 0) { out.write(bytes, 0, numRead); } out.close(); } else { throw new Exception ("ERROR: file not found."); } return null; } }
package gov.nih.nci.calab.ui.workflow; /** * This class prepares aliquot IDs to be used in the Use Aliquot input form. * * @author pansu */ /* CVS $Id: LoadAliquotsAction.java,v 1.3 2006-03-08 22:09:12 pansu Exp $ */ import gov.nih.nci.calab.service.workflow.UseAliquotService; import gov.nih.nci.calab.ui.core.AbstractBaseAction; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.validator.DynaValidatorForm; public class LoadAliquotsAction extends AbstractBaseAction { private static Logger logger=Logger.getLogger(LoadAliquotsAction.class); public ActionForward executeTask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward=null; HttpSession session=request.getSession(); try { /**@todo fill in details for getting aliquot IDs */ // tmp codes to be replaced. DynaValidatorForm loadAliquotsForm = (DynaValidatorForm) form; String runId=(String)loadAliquotsForm.get("runId"); UseAliquotService service=new UseAliquotService(); List<String> allAliquotIds=service.getAliquots(); session.setAttribute("allAliquotIds", allAliquotIds); session.setAttribute("runId", runId); // end of tmp codes forward=mapping.findForward("success"); } catch(Exception e) { logger.error("Caught exception when loading in aliquot IDs.", e); /**@todo fill in details for error handling */ forward=mapping.findForward("failure"); } return forward; } public boolean loginRequired() { //temporarily set to false until login module is working return false; //return true; } }
package gov.nih.nci.rembrandt.web.ajax; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import gov.nih.nci.caintegrator.application.lists.ListManager; import gov.nih.nci.caintegrator.application.lists.ListSubType; import gov.nih.nci.caintegrator.application.lists.ListType; import gov.nih.nci.caintegrator.application.lists.UserList; import gov.nih.nci.caintegrator.application.lists.UserListBean; import gov.nih.nci.caintegrator.application.lists.UserListBeanHelper; import gov.nih.nci.caintegrator.application.lists.ajax.CommonListFunctions; //import gov.nih.nci.ispy.util.ispyConstants; import gov.nih.nci.rembrandt.queryservice.validation.DataValidator; import gov.nih.nci.rembrandt.web.helper.RembrandtListValidator; import gov.nih.nci.rembrandt.dto.lookup.AllGeneAliasLookup; import gov.nih.nci.rembrandt.dto.lookup.LookupManager; import javax.naming.OperationNotSupportedException; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import uk.ltd.getahead.dwr.ExecutionContext; public class DynamicListHelper { /** * Basically a wrapper for app-commons/application/lists/ajax/CommonListFunctions * except this specifically sets the ListValidator for this context and passes it off * to the CommonListFunctions * */ public DynamicListHelper() {} /* public static String getPatientListAsList() { return CommonListFunctions.getListAsList(ListType.PatientDID); } public static String getGeneListAsList() { return CommonListFunctions.getListAsList(ListType.GeneSymbol); } */ public static String getGenericListAsList(String listType) { return CommonListFunctions.getListAsList(ListType.valueOf(listType)); } public static String createGenericList(String listType, List<String> list, String name) throws OperationNotSupportedException { try { //the list name SamplesFromClinicalReport is used internally by the system, force users to NOT use this name if(name.equalsIgnoreCase("SamplesFromClinicalReport")) { name += "_1"; } String[] tps = CommonListFunctions.parseListType(listType); //tps[0] = ListType //tps[1] = ListSubType (if not null) ListType lt = ListType.valueOf(tps[0]); if(tps.length > 1 && tps[1] != null){ //create a list out of [1] ArrayList<ListSubType> lst = new ArrayList(); lst.add(ListSubType.valueOf(tps[1])); return CommonListFunctions.createGenericList(lt, lst, list, name, new RembrandtListValidator(ListSubType.valueOf(tps[1]), ListType.valueOf(tps[0]), list)); } else if(tps.length >0 && tps[0] != null) { //no subtype, only a primary type - typically a PatientDID then return CommonListFunctions.createGenericList(lt, list, name, new RembrandtListValidator(ListSubType.Custom, ListType.valueOf(tps[0]), list)); } else { //no type or subtype, not good, force to clinical in catch //return CommonListFunctions.createGenericList(lt, list, name, new RembrandtListValidator()); throw new Exception(); } } catch(Exception e) { //try as a patient list as default, will fail validation if its not accepted return CommonListFunctions.createGenericList(ListType.PatientDID, list, name, new RembrandtListValidator(ListType.PatientDID, list)); } } /* public static String createPatientList(String[] list, String name){ return CommonListFunctions.createGenericList(ListType.PatientDID, list, name, new RembrandtListValidator()); } */ /* public static String createGeneList(String[] list, String name){ return CommonListFunctions.createGenericList(ListType.Gene, list, name, new RembrandtListValidator()); } */ public static String exportListasTxt(String name, HttpSession session){ return CommonListFunctions.exportListasTxt(name, session); } public static String getAllLists() { //create a list of allowable types ArrayList listTypesList = new ArrayList(); for(ListType l : ListType.values()) { listTypesList.add(l.toString()); } //call CommonListFunctions.getAllLists(listTypesList); return "(" + CommonListFunctions.getAllLists(listTypesList) + ")"; } public static String getGenericList(String listType) { //just want one type ArrayList<String> listTypesList = new ArrayList(); listTypesList.add(listType); return CommonListFunctions.getAllLists(listTypesList); } public static String getPathwayGeneSymbols(String pathwayName) { List<String> geneSymbols = LookupManager.getPathwayGeneSymbols(pathwayName); JSONArray symbols = new JSONArray(); for(String symbol : geneSymbols) { symbols.add(symbol); } return "(" + symbols.toString() + ")"; } /* public static String getPathwayGeneSymbols() { List<String> geneSymbols = LookupManager.getPathwayGeneSymbols(); JSONArray symbols = new JSONArray(); for(String symbol : geneSymbols) { symbols.add(symbol); } //call CommonListFunctions.getAllLists(listTypesList); return "(" + symbols.toString() + ")"; } */ /* public static String getAllPatientLists() { return CommonListFunctions.getAllLists(ListType.PatientDID.toString()); } */ /* public static String getAllGeneLists() { return CommonListFunctions.getAllLists(ListType.GeneSymbol.toString()); } */ public static String uniteLists(String[] sLists, String groupName, String groupType, String action) { return CommonListFunctions.uniteLists(sLists, groupName, groupType, action); } public static String getRBTFeatures() { String jfeats = ""; //get the features from the external props String feats = System.getProperty("rembrandt.feedback.features"); List<String> f = Arrays.asList(feats.split(",")); JSONArray fs = new JSONArray(); for(String s : f) { s = s.trim(); fs.add(s); } if(fs.size()>0){ jfeats = fs.toString(); } return jfeats; } public static String getGeneAliases(String gene) { JSONArray aliases = new JSONArray(); try { if(!DataValidator.isGeneSymbolFound(gene)){ AllGeneAliasLookup[] allGeneAlias = DataValidator.searchGeneKeyWord(gene); // if there are aliases , set the array to be displayed in the form and return the showAlias warning if(allGeneAlias != null){ for(int i =0; i < allGeneAlias.length ; i++){ JSONObject a = new JSONObject(); AllGeneAliasLookup alias = allGeneAlias[i]; a.put("alias", (alias.getAlias() !=null) ? alias.getAlias() : "N/A"); a.put("symbol", (alias.getApprovedSymbol()!=null)?alias.getApprovedSymbol() : "N/A"); a.put("name", (alias.getApprovedName()!=null) ? alias.getApprovedName() : "N/A"); //alias.getAlias()+"\t"+alias.getApprovedSymbol()+"\t"+alias.getApprovedName() aliases.add(a); } } else { aliases.add("invalid"); } } else { aliases.add("valid"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return aliases.toString(); } }
// $Id: PlaceController.java,v 1.7 2002/02/14 00:00:45 mdb Exp $ package com.threerings.crowd.client; import java.awt.event.ActionEvent; import java.util.ArrayList; import com.samskivert.swing.Controller; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.util.CrowdContext; /** * Controls the user interface that is used to display a place. When the * client moves to a new place, the appropriate place controller is * constructed and requested to create and display the appopriate user * interface for that place. */ public abstract class PlaceController extends Controller { /** * Initializes this place controller with a reference to the context * that they can use to access client services and to the * configuration record for this place. The controller should create * as much of its user interface that it can without having access to * the place object because this will be invoked in parallel with the * fetching of the place object. When the place object is obtained, * the controller will be notified and it can then finish the user * interface configuration and put the user interface into operation. * * @param ctx the client context. * @param config the place configuration for this place. */ public void init (CrowdContext ctx, PlaceConfig config) { // keep these around _ctx = ctx; _config = config; // create our user interface _view = createPlaceView(); // initialize our delegates applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { delegate.init(_ctx, _config); } }); // let the derived classes do any initialization stuff didInit(); } /** * Derived classes can override this and perform any * initialization-time processing they might need. They should of * course be sure to call <code>super.didInit()</code>. */ protected void didInit () { } /** * Returns a reference to the place view associated with this * controller. This is only valid after a call has been made to {@link * #init}. */ public PlaceView getPlaceView () { return _view; } /** * Creates the user interface that will be used to display this place. * The view instance returned will later be configured with the place * object, once it becomes available. */ protected abstract PlaceView createPlaceView (); /** * This is called by the location director once the place object has * been fetched. The place controller will dispatch the place object * to the user interface hierarchy via {@link * PlaceViewUtil#dispatchWillEnterPlace}. Derived classes can override * this and perform any other starting up that they need to do */ public void willEnterPlace (final PlaceObject plobj) { if (_view != null ) { // let the UI hierarchy know that we've got our place PlaceViewUtil.dispatchWillEnterPlace(_view, plobj); // and display the user interface _ctx.setPlaceView(_view); } // let our delegates know what's up applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { delegate.willEnterPlace(plobj); } }); } /** * This is called by the location director when we are leaving this * place and need to clean up after ourselves and shutdown. Derived * classes should override this method (being sure to call * <code>super.didLeavePlace</code>) and perform any necessary * cleanup. */ public void didLeavePlace (final PlaceObject plobj) { // let the UI hierarchy know that we're outta here if (_view != null ) { PlaceViewUtil.dispatchDidLeavePlace(_view, plobj); } // let our delegates know what's up applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { delegate.didLeavePlace(plobj); } }); } /** * Handles basic place controller action events. Derived classes * should be sure to call <code>super.handleAction</code> for events * they don't specifically handle. */ public boolean handleAction (final ActionEvent action) { final boolean[] handled = new boolean[1]; // let our delegates have a crack at the action applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { // we take advantage of short-circuiting here handled[0] = handled[0] || delegate.handleAction(action); } }); return handled[0]; } /** * Adds the supplied delegate to the list for this controller. */ protected void addDelegate (PlaceControllerDelegate delegate) { if (_delegates == null) { _delegates = new ArrayList(); } _delegates.add(delegate); } /** * Used to call methods in delegates. */ protected static interface DelegateOp { public void apply (PlaceControllerDelegate delegate); } /** * Applies the supplied operation to the registered delegates. */ protected void applyToDelegates (DelegateOp op) { if (_delegates != null) { int dcount = _delegates.size(); for (int i = 0; i < dcount; i++) { op.apply((PlaceControllerDelegate)_delegates.get(i)); } } } /** A reference to the active client context. */ protected CrowdContext _ctx; /** A reference to our place configuration. */ protected PlaceConfig _config; /** A reference to the place object for which we're controlling a user * interface. */ protected PlaceObject _plobj; /** A reference to the root user interface component. */ protected PlaceView _view; /** A list of the delegates in use by this controller. */ protected ArrayList _delegates; }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.puzzle.data; import com.samskivert.util.StringUtil; import com.threerings.util.RandomUtil; import com.threerings.puzzle.Log; /** * Does something extraordinary. */ public class TeamPuzzleObject extends PuzzleObject { // AUTO-GENERATED: FIELDS START /** The field name of the <code>teams</code> field. */ public static final String TEAMS = "teams"; /** The field name of the <code>targets</code> field. */ public static final String TARGETS = "targets"; /** The field name of the <code>winningTeam</code> field. */ public static final String WINNING_TEAM = "winningTeam"; // AUTO-GENERATED: FIELDS END /** The team index assigned to each player index. */ public int[] teams; /** The index of the player targeted by each player. */ public short[] targets; /** The team index of the winning teams, or <code>-1</code> if the game * is not yet over. */ public byte winningTeam; /** * Returns the number of active players in the given team. */ public int getTeamActivePlayerCount (int teamid) { int count = 0; for (int ii = 0; ii < players.length; ii++) { if (teams[ii] == teamid && isActivePlayer(ii)) { count++; } } return count; } /** * Returns a random valid target player for the given player, or * <code>-1</code> if there are no valid target players. */ public int getRandomValidTarget (int pidx) { // if there's no valid target player, pull the ripcord int vcount = getValidTargetCount(pidx); if (vcount < 1) { if (isInPlay()) { Log.info("No valid targets [game=" + which() + ", pidx=" + pidx + ", status=" + StringUtil.toString(playerStatus) + ", teams=" + StringUtil.toString(teams) + "]."); } return -1; } // choose a random valid player and skip to their index int tpidx = 0, tcount = RandomUtil.getInt(vcount); do { // if this is a valid target and tcount is zero, stop; note // that we rely on the short-circuit to only decrement tcount // when we're on a valid target if (isRandomValidTarget(pidx, tpidx) && (tcount return tpidx; } tpidx++; } while (tpidx < players.length); // we should never get here, but it's best to be robust Log.warning("Failed to find valid target [game=" + which() + ", pidx=" + pidx + ", vcount=" + vcount + ", status=" + StringUtil.toString(playerStatus) + ", teams=" + StringUtil.toString(teams) + "]."); return -1; } /** * Returns the number of valid target players for the given player. */ public int getValidTargetCount (int pidx) { int count = 0; for (int ii = 0; ii < players.length; ii++) { if (isRandomValidTarget(pidx, ii)) { count++; } } return count; } /** * Returns whether one player may target another player. * * @param pidx the player index of the player attempting to change * their target player. * @param tpidx the player index of the player being targeted. */ public boolean isValidTarget (int pidx, int tpidx) { return (tpidx >= 0 && tpidx < players.length && pidx != tpidx && isActivePlayer(tpidx) && teams[pidx] != teams[tpidx]); } /** * Returns whether one player may target another player on random * reassignment. * * @param pidx the player index of the player attempting to change * their target player. * @param tpidx the player index of the player being targeted. */ protected boolean isRandomValidTarget (int pidx, int tpidx) { return isValidTarget(pidx, tpidx); } // AUTO-GENERATED: METHODS START /** * Requests that the <code>teams</code> field be set to the * specified value. The local value will be updated immediately and an * event will be propagated through the system to notify all listeners * that the attribute did change. Proxied copies of this object (on * clients) will apply the value change when they received the * attribute changed notification. */ public void setTeams (int[] value) { int[] ovalue = this.teams; requestAttributeChange( TEAMS, value, ovalue); this.teams = (value == null) ? null : (int[])value.clone(); } /** * Requests that the <code>index</code>th element of * <code>teams</code> field be set to the specified value. * The local value will be updated immediately and an event will be * propagated through the system to notify all listeners that the * attribute did change. Proxied copies of this object (on clients) * will apply the value change when they received the attribute * changed notification. */ public void setTeamsAt (int value, int index) { int ovalue = this.teams[index]; requestElementUpdate( TEAMS, index, new Integer(value), new Integer(ovalue)); this.teams[index] = value; } /** * Requests that the <code>targets</code> field be set to the * specified value. The local value will be updated immediately and an * event will be propagated through the system to notify all listeners * that the attribute did change. Proxied copies of this object (on * clients) will apply the value change when they received the * attribute changed notification. */ public void setTargets (short[] value) { short[] ovalue = this.targets; requestAttributeChange( TARGETS, value, ovalue); this.targets = (value == null) ? null : (short[])value.clone(); } /** * Requests that the <code>index</code>th element of * <code>targets</code> field be set to the specified value. * The local value will be updated immediately and an event will be * propagated through the system to notify all listeners that the * attribute did change. Proxied copies of this object (on clients) * will apply the value change when they received the attribute * changed notification. */ public void setTargetsAt (short value, int index) { short ovalue = this.targets[index]; requestElementUpdate( TARGETS, index, new Short(value), new Short(ovalue)); this.targets[index] = value; } /** * Requests that the <code>winningTeam</code> field be set to the * specified value. The local value will be updated immediately and an * event will be propagated through the system to notify all listeners * that the attribute did change. Proxied copies of this object (on * clients) will apply the value change when they received the * attribute changed notification. */ public void setWinningTeam (byte value) { byte ovalue = this.winningTeam; requestAttributeChange( WINNING_TEAM, new Byte(value), new Byte(ovalue)); this.winningTeam = value; } // AUTO-GENERATED: METHODS END }
package fr.paris.lutece.portal.service.init; /** * this class provides informations about application version */ public final class AppInfo { /** Defines the current version of the application */ private static final String APP_VERSION = "3.1.4"; /** * Creates a new AppInfo object. */ private AppInfo( ) { } /** * Returns the current version of the application * @return APP_VERSION The current version of the application */ public static String getVersion( ) { return APP_VERSION; } }
package fr.paris.lutece.portal.service.init; /** * this class provides informations about application version */ public final class AppInfo { /** Defines the current version of the application */ private static final String APP_VERSION = "7.0.2"; static final String LUTECE_BANNER_VERSION = "\n _ _ _ _____ ___ ___ ___ ____\n" + "| | | | | | |_ _| | __| / __| | __| |__ |\n" + "| |__ | |_| | | | | _| | (__ | _| / / \n" + "|____| \\___/ |_| |___| \\___| |___| /_/ "; static final String LUTECE_BANNER_SERVER = "\n _ _ _ _____ ___ ___ ___ ___ ___ ___ __ __ ___ ___ \n" + "| | | | | | |_ _| | __| / __| | __| / __| | __| | _ \\ \\ \\ / / | __| | _ \\\n" + "| |__ | |_| | | | | _| | (__ | _| \\__ \\ | _| | / \\ V / | _| | /\n" + "|____| \\___/ |_| |___| \\___| |___| |___/ |___| |_|_\\ \\_/ |___| |_|_\\"; /** * Creates a new AppInfo object. */ private AppInfo( ) { } /** * Returns the current version of the application * * @return APP_VERSION The current version of the application */ public static String getVersion( ) { return APP_VERSION; } }
package net.kaleidos.hibernate.usertype; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.commons.lang.ObjectUtils; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.usertype.UserType; import org.postgresql.util.PGobject; import java.io.Serializable; import java.lang.reflect.Type; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.HashMap; import java.util.Map; public class JsonMapType implements UserType { public static int SQLTYPE = 90021; private final Type userType = Map.class; private final Gson gson = new GsonBuilder().serializeNulls().create(); @Override public int[] sqlTypes() { return new int[]{SQLTYPE}; } @Override public Class<?> returnedClass() { return userType.getClass(); } @Override public boolean equals(Object x, Object y) throws HibernateException { return ObjectUtils.equals(x, y); } @Override public int hashCode(Object x) throws HibernateException { return x == null ? 0 : x.hashCode(); } @Override public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException { String jsonString = ((PGobject)rs.getObject(names[0])).getValue(); return gson.fromJson(jsonString, userType); } @Override public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException { if (value == null) { st.setNull(index, Types.OTHER); } else { st.setObject(index, gson.toJson(value, userType), Types.OTHER); } } @SuppressWarnings({"rawtypes", "unchecked"}) @Override public Object deepCopy(Object value) throws HibernateException { if (value == null) { return null; } Map m = (Map) value; return new HashMap(m); } @Override public boolean isMutable() { return true; } @Override public Serializable disassemble(Object value) throws HibernateException { return gson.toJson(value, userType); } @Override public Object assemble(Serializable cached, Object owner) throws HibernateException { return gson.fromJson((String) cached, userType); } @Override public Object replace(Object original, Object target, Object owner) throws HibernateException { return original; } }
package nl.b3p.viewer.admin.stripes; import java.util.*; import javax.annotation.security.RolesAllowed; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.controller.LifecycleStage; import net.sourceforge.stripes.validation.Validate; import net.sourceforge.stripes.validation.ValidateNestedProperties; import nl.b3p.viewer.config.app.*; import nl.b3p.viewer.config.security.Group; import nl.b3p.viewer.config.services.*; import org.stripesstuff.stripersist.Stripersist; /** * * @author Jytte Schaeffer */ @UrlBinding("/action/layer") @StrictBinding @RolesAllowed({Group.ADMIN,Group.REGISTRY_ADMIN}) public class LayerActionBean implements ActionBean { private static final String JSP = "/WEB-INF/jsp/services/layer.jsp"; private ActionBeanContext context; @Validate @ValidateNestedProperties({ @Validate(field = "titleAlias", label="Naam"), @Validate(field = "legendImageUrl", label="Legenda") }) private Layer layer; @Validate private String parentId; private List<Group> allGroups; private SortedSet<String> applicationsUsedIn = new TreeSet(); @Validate private List<String> groupsRead = new ArrayList<String>(); @Validate private List<String> groupsWrite = new ArrayList<String>(); @Validate private Map<String, String> details = new HashMap<String, String>(); @Validate private SimpleFeatureType simpleFeatureType; @Validate private Long featureSourceId; private List featureSources; //<editor-fold defaultstate="collapsed" desc="getters & setters"> public ActionBeanContext getContext() { return context; } public void setContext(ActionBeanContext context) { this.context = context; } public Map<String, String> getDetails() { return details; } public void setDetails(Map<String, String> details) { this.details = details; } public Layer getLayer() { return layer; } public void setLayer(Layer layer) { this.layer = layer; } public List<Group> getAllGroups() { return allGroups; } public void setAllGroups(List<Group> allGroups) { this.allGroups = allGroups; } public List<String> getGroupsRead() { return groupsRead; } public void setGroupsRead(List<String> groupsRead) { this.groupsRead = groupsRead; } public List<String> getGroupsWrite() { return groupsWrite; } public void setGroupsWrite(List<String> groupsWrite) { this.groupsWrite = groupsWrite; } public SortedSet<String> getApplicationsUsedIn() { return applicationsUsedIn; } public void setApplicationsUsedIn(SortedSet<String> applicationsUsedIn) { this.applicationsUsedIn = applicationsUsedIn; } public SimpleFeatureType getSimpleFeatureType() { return simpleFeatureType; } public void setSimpleFeatureType(SimpleFeatureType simpleFeatureType) { this.simpleFeatureType = simpleFeatureType; } public Long getFeatureSourceId() { return featureSourceId; } public void setFeatureSourceId(Long featureSourceId) { this.featureSourceId = featureSourceId; } public List getFeatureSources() { return featureSources; } public void setFeatureSources(List featureSources) { this.featureSources = featureSources; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } //</editor-fold> @Before(stages = LifecycleStage.BindingAndValidation) @SuppressWarnings("unchecked") public void load() { allGroups = Stripersist.getEntityManager().createQuery("from Group").getResultList(); featureSources = Stripersist.getEntityManager().createQuery("from FeatureSource").getResultList(); } @DefaultHandler public Resolution edit() { if (layer != null) { details = layer.getDetails(); groupsRead.addAll(layer.getReaders()); groupsWrite.addAll(layer.getWriters()); if (layer.getFeatureType() != null) { simpleFeatureType = layer.getFeatureType(); featureSourceId = simpleFeatureType.getFeatureSource().getId(); } findApplicationsUsedIn(); } return new ForwardResolution(JSP); } private void findApplicationsUsedIn() { GeoService service = layer.getService(); String layerName = layer.getName(); List<ApplicationLayer> applicationLayers = Stripersist.getEntityManager().createQuery("from ApplicationLayer where service = :service" + " and layerName = :layerName").setParameter("service", service).setParameter("layerName", layerName).getResultList(); for (Iterator it = applicationLayers.iterator(); it.hasNext();) { ApplicationLayer appLayer = (ApplicationLayer) it.next(); /* * The parent level of the applicationLayer is needed to find out in * which application the Layer is used. This solution is not good * when there are many levels. */ List<Level> levels = Stripersist.getEntityManager().createQuery("from Level").getResultList(); for (Iterator iter = levels.iterator(); iter.hasNext();) { Level level = (Level) iter.next(); if (level != null && level.getLayers().contains(appLayer)) { applicationsUsedIn.addAll(getApplicationNames(level)); } } } } private Set<String> getApplicationNames(Level level) { Set<String> names = new HashSet(); for(Application app: level.findApplications()) { names.add(app.getNameWithVersion()); } return names; } public Resolution save() { layer.getDetails().clear(); layer.getDetails().putAll(details); layer.getReaders().clear(); for (String groupName : groupsRead) { layer.getReaders().add(groupName); } layer.getWriters().clear(); for (String groupName : groupsWrite) { layer.getWriters().add(groupName); } if (simpleFeatureType != null) { layer.setFeatureType(simpleFeatureType); } Stripersist.getEntityManager().persist(layer); layer.getService().authorizationsModified(); Stripersist.getEntityManager().getTransaction().commit(); getContext().getMessages().add(new SimpleMessage("De kaartlaag is opgeslagen")); return new ForwardResolution(JSP); } }
package org.apache.velocity.servlet; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.OutputStreamWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.Properties; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.Template; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.RuntimeSingleton; import org.apache.velocity.io.VelocityWriter; import org.apache.velocity.util.SimplePool; import org.apache.velocity.context.Context; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.MethodInvocationException; /** * Base class which simplifies the use of Velocity with Servlets. * Extend this class, implement the <code>handleRequest()</code> method, * and add your data to the context. Then call * <code>getTemplate("myTemplate.wm")</code>. * * This class puts some things into the context object that you should * be aware of: * <pre> * "req" - The HttpServletRequest object * "res" - The HttpServletResponse object * </pre> * * There are other methods you can override to access, alter or control * any part of the request processing chain. Please see the javadocs for * more information on : * <ul> * <li> loadConfiguration() : for setting up the Velocity runtime * <li> createContext() : for creating and loading the Context * <li> setContentType() : for changing the content type on a request * by request basis * <li> handleRequest() : you <b>must</b> implement this * <li> mergeTemplate() : the template rendering process * <li> requestCleanup() : post rendering resource or other cleanup * <li> error() : error handling * </ul> * <br> * If you put a contentType object into the context within either your * serlvet or within your template, then that will be used to override * the default content type specified in the properties file. * * "contentType" - The value for the Content-Type: header * * @author Dave Bryson * @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a> * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> * @author <a href="kjohnson@transparent.com">Kent Johnson</a> * @author <a href="dlr@finemaltcoding.com">Daniel Rall</a> * $Id: VelocityServlet.java,v 1.53 2003/10/23 16:13:28 dlr Exp $ */ public abstract class VelocityServlet extends HttpServlet { /** * The context key for the HTTP request object. */ public static final String REQUEST = "req"; /** * The context key for the HTTP response object. */ public static final String RESPONSE = "res"; /** * The HTTP content type context key. */ public static final String CONTENT_TYPE = "default.contentType"; /** * The default content type for the response */ public static final String DEFAULT_CONTENT_TYPE = "text/html"; /** * Encoding for the output stream */ public static final String DEFAULT_OUTPUT_ENCODING = "ISO-8859-1"; /** * The default content type, itself defaulting to {@link * #DEFAULT_CONTENT_TYPE} if not configured. */ private static String defaultContentType; /** * This is the string that is looked for when getInitParameter is * called (<code>org.apache.velocity.properties</code>). */ protected static final String INIT_PROPS_KEY = "org.apache.velocity.properties"; /** * Use of this properties key has been deprecated, and will be * removed in Velocity version 1.5. */ private static final String OLD_INIT_PROPS_KEY = "properties"; /** * Cache of writers */ private static SimplePool writerPool = new SimplePool(40); /** * Performs initialization of this servlet. Called by the servlet * container on loading. * * @param config The servlet configuration to apply. * * @exception ServletException */ public void init( ServletConfig config ) throws ServletException { super.init( config ); /* * do whatever we have to do to init Velocity */ initVelocity( config ); /* * Now that Velocity is initialized, cache some config. */ defaultContentType = RuntimeSingleton.getString(CONTENT_TYPE, DEFAULT_CONTENT_TYPE); } /** * Initializes the Velocity runtime, first calling * loadConfiguration(ServletConvig) to get a * java.util.Properties of configuration information * and then calling Velocity.init(). Override this * to do anything to the environment before the * initialization of the singelton takes place, or to * initialize the singleton in other ways. */ protected void initVelocity( ServletConfig config ) throws ServletException { try { /* * call the overridable method to allow the * derived classes a shot at altering the configuration * before initializing Runtime */ Properties props = loadConfiguration( config ); Velocity.init( props ); } catch( Exception e ) { throw new ServletException("Error initializing Velocity: " + e, e); } } /** * Loads the configuration information and returns that * information as a Properties, which will be used to * initialize the Velocity runtime. * <br><br> * Currently, this method gets the initialization parameter * VelocityServlet.INIT_PROPS_KEY, which should be a file containing * the configuration information. * <br><br> * To configure your Servlet Spec 2.2 compliant servlet runner to pass * this to you, put the following in your WEB-INF/web.xml file * <br> * <pre> * &lt;servlet&gt; * &lt;servlet-name&gt; YourServlet &lt/servlet-name&gt; * &lt;servlet-class&gt; your.package.YourServlet &lt;/servlet-class&gt; * &lt;init-param&gt; * &lt;param-name&gt; org.apache.velocity.properties &lt;/param-name&gt; * &lt;param-value&gt; velocity.properties &lt;/param-value&gt; * &lt;/init-param&gt; * &lt;/servlet&gt; * </pre> * * Alternately, if you wish to configure an entire context in this * fashion, you may use the following: * <br> * <pre> * &lt;context-param&gt; * &lt;param-name&gt; org.apache.velocity.properties &lt;/param-name&gt; * &lt;param-value&gt; velocity.properties &lt;/param-value&gt; * &lt;description&gt; Path to Velocity configuration &lt;/description&gt; * &lt;/context-param&gt; * </pre> * * Derived classes may do the same, or take advantage of this code to do the loading for them via : * <pre> * Properties p = super.loadConfiguration( config ); * </pre> * and then add or modify the configuration values from the file. * <br> * * @param config ServletConfig passed to the servlets init() function * Can be used to access the real path via ServletContext (hint) * @return java.util.Properties loaded with configuration values to be used * to initialize the Velocity runtime. * @throws FileNotFoundException if a specified file is not found. * @throws IOException I/O problem accessing the specified file, if specified. * @deprecated Use VelocityViewServlet from the Velocity Tools * library instead. */ protected Properties loadConfiguration(ServletConfig config) throws IOException, FileNotFoundException { // This is a little overly complex because of legacy support // for the initialization properties key "properties". // References to OLD_INIT_PROPS_KEY should be removed at // Velocity version 1.5. String propsFile = config.getInitParameter(INIT_PROPS_KEY); if (propsFile == null || propsFile.length() == 0) { ServletContext sc = config.getServletContext(); propsFile = config.getInitParameter(OLD_INIT_PROPS_KEY); if (propsFile == null || propsFile.length() == 0) { propsFile = sc.getInitParameter(INIT_PROPS_KEY); if (propsFile == null || propsFile.length() == 0) { propsFile = sc.getInitParameter(OLD_INIT_PROPS_KEY); if (propsFile != null && propsFile.length() > 0) { sc.log("Use of the properties initialization " + "parameter '" + OLD_INIT_PROPS_KEY + "' has " + "been deprecated by '" + INIT_PROPS_KEY + '\''); } } } else { sc.log("Use of the properties initialization parameter '" + OLD_INIT_PROPS_KEY + "' has been deprecated by '" + INIT_PROPS_KEY + '\''); } } /* * This will attempt to find the location of the properties * file from the relative path to the WAR archive (ie: * docroot). Since JServ returns null for getRealPath() * because it was never implemented correctly, then we know we * will not have an issue with using it this way. I don't know * if this will break other servlet engines, but it probably * shouldn't since WAR files are the future anyways. */ Properties p = new Properties(); if ( propsFile != null ) { String realPath = getServletContext().getRealPath(propsFile); if ( realPath != null ) { propsFile = realPath; } p.load( new FileInputStream(propsFile) ); } return p; } /** * Handles HTTP <code>GET</code> requests by calling {@link * #doRequest()}. */ public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doRequest(request, response); } /** * Handles HTTP <code>POST</code> requests by calling {@link * #doRequest()}. */ public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doRequest(request, response); } /** * Handles all requests (by default). * * @param request HttpServletRequest object containing client request * @param response HttpServletResponse object for the response */ protected void doRequest(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { Context context = null; try { /* * first, get a context */ context = createContext( request, response ); /* * set the content type */ setContentType( request, response ); /* * let someone handle the request */ Template template = handleRequest( request, response, context ); /* * bail if we can't find the template */ if ( template == null ) { return; } /* * now merge it */ mergeTemplate( template, context, response ); } catch (Exception e) { /* * call the error handler to let the derived class * do something useful with this failure. */ error( request, response, e); } finally { /* * call cleanup routine to let a derived class do some cleanup */ requestCleanup( request, response, context ); } } protected void requestCleanup( HttpServletRequest request, HttpServletResponse response, Context context ) { return; } protected void mergeTemplate( Template template, Context context, HttpServletResponse response ) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException, UnsupportedEncodingException, Exception { ServletOutputStream output = response.getOutputStream(); VelocityWriter vw = null; // ASSUMPTION: response.setContentType() has been called. String encoding = response.getCharacterEncoding(); try { vw = (VelocityWriter) writerPool.get(); if (vw == null) { vw = new VelocityWriter(new OutputStreamWriter(output, encoding), 4 * 1024, true); } else { vw.recycle(new OutputStreamWriter(output, encoding)); } template.merge(context, vw); } finally { try { if (vw != null) { /* * flush and put back into the pool * don't close to allow us to play * nicely with others. */ vw.flush(); /* * Clear the VelocityWriter's reference to its * internal OutputStreamWriter to allow the latter * to be GC'd while vw is pooled. */ vw.recycle(null); writerPool.put(vw); } } catch (Exception e) { // do nothing } } } /** * Sets the content type of the response, defaulting to {@link * #defaultContentType} if not overriden. Delegates to {@link * #chooseCharacterEncoding(HttpServletRequest)} to select the * appropriate character encoding. * * @param request The servlet request from the client. * @param response The servlet reponse to the client. */ protected void setContentType(HttpServletRequest request, HttpServletResponse response) { String contentType = defaultContentType; int index = contentType.lastIndexOf(';') + 1; if (index <= 0 || (index < contentType.length() && contentType.indexOf("charset", index) == -1)) { // Append the character encoding which we'd like to use. String encoding = chooseCharacterEncoding(request); //RuntimeSingleton.debug("Chose output encoding of '" + // encoding + '\''); if (!DEFAULT_OUTPUT_ENCODING.equalsIgnoreCase(encoding)) { contentType += "; charset=" + encoding; } } response.setContentType(contentType); //RuntimeSingleton.debug("Response Content-Type set to '" + // contentType + '\''); } /** * Chooses the output character encoding to be used as the value * for the "charset=" portion of the HTTP Content-Type header (and * thus returned by <code>response.getCharacterEncoding()</code>). * Called by {@link #setContentType(HttpServletRequest, * HttpServletResponse)} if an encoding isn't already specified by * Content-Type. By default, chooses the value of * RuntimeSingleton's <code>output.encoding</code> property. * * @param request The servlet request from the client. */ protected String chooseCharacterEncoding(HttpServletRequest request) { return RuntimeSingleton.getString(RuntimeConstants.OUTPUT_ENCODING, DEFAULT_OUTPUT_ENCODING); } /** * Returns a context suitable to pass to the handleRequest() method * <br><br> * Default implementation will create a VelocityContext object, * put the HttpServletRequest and HttpServletResponse * into the context accessable via the keys VelocityServlet.REQUEST and * VelocityServlet.RESPONSE, respectively. * * @param request servlet request from client * @param response servlet reponse to client * * @return context */ protected Context createContext(HttpServletRequest request, HttpServletResponse response ) { /* * create a new context */ VelocityContext context = new VelocityContext(); /* * put the request/response objects into the context * wrap the HttpServletRequest to solve the introspection * problems */ context.put( REQUEST, request ); context.put( RESPONSE, response ); return context; } /** * Retrieves the requested template. * * @param name The file name of the template to retrieve relative to the * template root. * @return The requested template. * @throws ResourceNotFoundException if template not found * from any available source. * @throws ParseErrorException if template cannot be parsed due * to syntax (or other) error. * @throws Exception if an error occurs in template initialization */ public Template getTemplate( String name ) throws ResourceNotFoundException, ParseErrorException, Exception { return RuntimeSingleton.getTemplate(name); } /** * Retrieves the requested template with the specified * character encoding. * * @param name The file name of the template to retrieve relative to the * template root. * @param encoding the character encoding of the template * * @return The requested template. * @throws ResourceNotFoundException if template not found * from any available source. * @throws ParseErrorException if template cannot be parsed due * to syntax (or other) error. * @throws Exception if an error occurs in template initialization * * @since Velocity v1.1 */ public Template getTemplate( String name, String encoding ) throws ResourceNotFoundException, ParseErrorException, Exception { return RuntimeSingleton.getTemplate( name, encoding ); } /** * Implement this method to add your application data to the context, * calling the <code>getTemplate()</code> method to produce your return * value. * <br><br> * In the event of a problem, you may handle the request directly * and return <code>null</code> or throw a more meaningful exception * for the error handler to catch. * * @param request servlet request from client * @param response servlet reponse * @param ctx The context to add your data to. * @return The template to merge with your context or null, indicating * that you handled the processing. * * @since Velocity v1.1 */ protected Template handleRequest( HttpServletRequest request, HttpServletResponse response, Context ctx ) throws Exception { /* * invoke handleRequest */ Template t = handleRequest( ctx ); /* * if it returns null, this is the 'old' deprecated * way, and we want to mimic the behavior for a little * while anyway */ if (t == null) { throw new Exception ("handleRequest(Context) returned null - no template selected!" ); } return t; } /** * Implement this method to add your application data to the context, * calling the <code>getTemplate()</code> method to produce your return * value. * <br><br> * In the event of a problem, you may simple return <code>null</code> * or throw a more meaningful exception. * * @deprecated Use * {@link #handleRequest( HttpServletRequest request, * HttpServletResponse response, Context ctx )} * * @param ctx The context to add your data to. * @return The template to merge with your context. */ protected Template handleRequest( Context ctx ) throws Exception { throw new Exception ("You must override VelocityServlet.handleRequest( Context) " + " or VelocityServlet.handleRequest( HttpServletRequest, " + " HttpServletResponse, Context)" ); } /** * Invoked when there is an error thrown in any part of doRequest() processing. * <br><br> * Default will send a simple HTML response indicating there was a problem. * * @param request original HttpServletRequest from servlet container. * @param response HttpServletResponse object from servlet container. * @param cause Exception that was thrown by some other part of process. */ protected void error( HttpServletRequest request, HttpServletResponse response, Exception cause ) throws ServletException, IOException { StringBuffer html = new StringBuffer(); html.append("<html>"); html.append("<title>Error</title>"); html.append("<body bgcolor=\"#ffffff\">"); html.append("<h2>VelocityServlet: Error processing the template</h2>"); html.append("<pre>"); String why = cause.getMessage(); if (why != null && why.trim().length() > 0) { html.append(why); html.append("<br>"); } StringWriter sw = new StringWriter(); cause.printStackTrace( new PrintWriter( sw ) ); html.append( sw.toString() ); html.append("</pre>"); html.append("</body>"); html.append("</html>"); response.getOutputStream().print( html.toString() ); } }
package org.jdesktop.swingx.painter; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; /** * <p>A Painter implemention that contains an array of Painters, and executes them * in order. This allows you to create a layered series of painters, similar to * the layer design style in Photoshop or other image processing software.</p> * * <p>For example, if I want to create a CompoundPainter that started with a blue * background, had pinstripes on it running at a 45 degree angle, and those * pinstripes appeared to "fade in" from left to right, I would write the following: * <pre><code> * Color blue = new Color(0x417DDD); * Color translucent = new Color(blue.getRed(), blue.getGreen(), blue.getBlue(), 0); * panel.setBackground(blue); * panel.setForeground(Color.LIGHT_GRAY); * GradientPaint blueToTranslucent = new GradientPaint( * new Point2D.Double(.4, 0), * blue, * new Point2D.Double(1, 0), * translucent); * Painter veil = new BasicGradientPainter(blueToTranslucent); * Painter pinstripes = new PinstripePainter(45); * Painter backgroundPainter = new BackgroundPainter(); * Painter p = new CompoundPainter(backgroundPainter, pinstripes, veil); * panel.setBackgroundPainter(p); * </code></pre></p> * * @author rbair */ public class CompoundPainter<T> extends AbstractPainter<T> { private Painter[] painters = new Painter[0]; private AffineTransform transform; private boolean clipPreserved = false; /** Creates a new instance of CompoundPainter */ public CompoundPainter() { } /** * Convenience constructor for creating a CompoundPainter for an array * of painters. A defensive copy of the given array is made, so that future * modification to the array does not result in changes to the CompoundPainter. * * @param painters array of painters, which will be painted in order */ public CompoundPainter(Painter... painters) { this.painters = new Painter[painters == null ? 0 : painters.length]; if (painters != null) { System.arraycopy(painters, 0, this.painters, 0, painters.length); } } private boolean useCaching; public CompoundPainter(boolean useCaching, Painter ... painters) { this(painters); this.useCaching = useCaching; } /* joshy: not used since we got rid of layers. public CompoundPainter(Map<Integer,List<Painter>> painterSet) { // create a flat list of painters List<Painter> painterList = new ArrayList<Painter>(); // loop through the painter by layer order Set<Integer> layerSet = painterSet.keySet(); List<Integer> layerList = new ArrayList(layerSet); Collections.sort(layerList); for(Integer n : layerList) { List<Painter> layer = painterSet.get(n); for(Painter p : layer) { painterList.add(p); } } this.painters = painterList.toArray(new Painter[0]); }*/ /** * Sets the array of Painters to use. These painters will be executed in * order. A null value will be treated as an empty array. * * @param painters array of painters, which will be painted in order */ public void setPainters(Painter... painters) { Painter[] old = getPainters(); this.painters = new Painter[painters == null ? 0 : painters.length]; if (painters != null) { System.arraycopy(painters, 0, this.painters, 0, painters.length); } firePropertyChange("painters", old, getPainters()); } /** * Gets the array of painters used by this CompoundPainter * @return a defensive copy of the painters used by this CompoundPainter. * This will never be null. */ public Painter[] getPainters() { Painter[] results = new Painter[painters.length]; System.arraycopy(painters, 0, results, 0, results.length); return results; } /** * Indicates if the clip produced by any painter is left set once it finishes painting. * Normally the clip will be reset between each painter. Setting clipPreserved to * true can be used to let one painter mask other painters that come after it. * @return if the clip should be preserved * @see #setClipPreserved(boolean) */ public boolean isClipPreserved() { return clipPreserved; } /** * Sets if the clip should be preserved. * Normally the clip will be reset between each painter. Setting clipPreserved to * true can be used to let one painter mask other painters that come after it. * * @param shouldRestoreState new value of the clipPreserved property * @see #isClipPreserved() */ public void setClipPreserved(boolean shouldRestoreState) { boolean oldShouldRestoreState = isClipPreserved(); this.clipPreserved = shouldRestoreState; firePropertyChange("shouldRestoreState",oldShouldRestoreState,shouldRestoreState); } /** * @inheritDoc */ @Override public void doPaint(Graphics2D g, T component, int width, int height) { Graphics2D g2 = (Graphics2D) g.create(); if(getTransform() != null) { g2.setTransform(getTransform()); } for (Painter p : getPainters()) { Graphics2D g3 = (Graphics2D) g2.create(); p.paint(g3, component, width, height); if(isClipPreserved()) { g2.setClip(g3.getClip()); } g3.dispose(); } g2.dispose(); } /** * Gets the current transform applied to all painters in this CompoundPainter. May be null. * @return the current AffineTransform */ public AffineTransform getTransform() { return transform; } /** * Set a transform to be applied to all painters contained in this GradientPainter * @param transform a new AffineTransform */ public void setTransform(AffineTransform transform) { AffineTransform old = getTransform(); this.transform = transform; firePropertyChange("transform",old,transform); } @Override protected boolean isUseCache() { return useCaching; } }
package org.tuckey.web.filters.urlrewrite.utils; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; public class Log { private static Log localLog = Log.getLog(Log.class); // static vars private static ServletContext context = null; private static final String DEFAULT_LOG_LEVEL = "INFO"; private static boolean usingSystemOut = false; private static boolean usingSystemErr = false; private static boolean usingLog4j = false; private static boolean usingSlf4j = false; private static boolean usingCommonsLogging = false; private static boolean traceLevelEnabled = false; private static boolean debugLevelEnabled = false; private static boolean infoLevelEnabled = false; private static boolean warnLevelEnabled = false; private static boolean errorLevelEnabled = false; private static boolean fatalLevelEnabled = false; private Class clazz = null; private org.apache.log4j.Logger log4jLogger = null; private org.slf4j.Logger slf4jLogger = null; private org.apache.commons.logging.Log commonsLog = null; private Log(Class clazz) { this.clazz = clazz; // check for log4j or commons isUsingLog4j(); isUsingSlf4j(); isUsingCommonsLogging(); } private boolean isUsingLog4j() { if (usingLog4j && log4jLogger == null) { this.log4jLogger = org.apache.log4j.Logger.getLogger(clazz); } return usingLog4j; } private boolean isUsingSlf4j() { if (usingSlf4j && slf4jLogger == null) { this.slf4jLogger = org.slf4j.LoggerFactory.getLogger(clazz); } return usingSlf4j; } public boolean isUsingCommonsLogging() { if (usingCommonsLogging && commonsLog == null) { this.commonsLog = org.apache.commons.logging.LogFactory.getLog(clazz); } return usingCommonsLogging; } public boolean isTraceEnabled() { if (isUsingLog4j()) return log4jLogger.isEnabledFor(org.apache.log4j.Priority.DEBUG); if (isUsingSlf4j()) return slf4jLogger.isTraceEnabled(); if (isUsingCommonsLogging()) return commonsLog.isTraceEnabled(); return traceLevelEnabled; } public boolean isDebugEnabled() { if (isUsingLog4j()) return log4jLogger.isEnabledFor(org.apache.log4j.Priority.DEBUG); if (isUsingSlf4j()) return slf4jLogger.isDebugEnabled(); if (isUsingCommonsLogging()) return commonsLog.isDebugEnabled(); return traceLevelEnabled || debugLevelEnabled; } public boolean isInfoEnabled() { if (isUsingLog4j()) return log4jLogger.isEnabledFor(org.apache.log4j.Priority.INFO); if (isUsingSlf4j()) return slf4jLogger.isInfoEnabled(); if (isUsingCommonsLogging()) return commonsLog.isInfoEnabled(); return traceLevelEnabled || debugLevelEnabled || infoLevelEnabled; } public boolean isWarnEnabled() { if (isUsingLog4j()) return log4jLogger.isEnabledFor(org.apache.log4j.Priority.WARN); if (isUsingSlf4j()) return slf4jLogger.isWarnEnabled(); if (isUsingCommonsLogging()) return commonsLog.isWarnEnabled(); return traceLevelEnabled || debugLevelEnabled || infoLevelEnabled || warnLevelEnabled; } public boolean isErrorEnabled() { if (isUsingLog4j()) return log4jLogger.isEnabledFor(org.apache.log4j.Priority.ERROR); if (isUsingSlf4j()) return slf4jLogger.isErrorEnabled(); if (isUsingCommonsLogging()) return commonsLog.isErrorEnabled(); return traceLevelEnabled || debugLevelEnabled || infoLevelEnabled || warnLevelEnabled || errorLevelEnabled; } public boolean isFatalEnabled() { if (isUsingLog4j()) return log4jLogger.isEnabledFor(org.apache.log4j.Priority.FATAL); if (isUsingSlf4j()) return slf4jLogger.isErrorEnabled(); // note: SLF4J has no fatal level if (isUsingCommonsLogging()) return commonsLog.isFatalEnabled(); return traceLevelEnabled || debugLevelEnabled || infoLevelEnabled || warnLevelEnabled || errorLevelEnabled || fatalLevelEnabled; } public void trace(Object o) { if (!isTraceEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.debug(o); return; } if (isUsingSlf4j()) { slf4jLogger.trace(String.valueOf(o)); return; } if (isUsingCommonsLogging()) { commonsLog.trace(o); return; } write("TRACE", o); } public void trace(Object o, Throwable throwable) { if (!isTraceEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.debug(o, throwable); return; } if (isUsingSlf4j()) { slf4jLogger.trace(String.valueOf(o), throwable); return; } if (isUsingCommonsLogging()) { commonsLog.trace(o, throwable); return; } write("TRACE", o, throwable); } public void trace(Throwable throwable) { if (!isTraceEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.debug(throwable); return; } if (isUsingSlf4j()) { slf4jLogger.trace("", throwable); return; } if (isUsingCommonsLogging()) { commonsLog.trace(throwable); return; } write("TRACE", throwable, throwable); } public void debug(Object o) { if (!isDebugEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.debug(o); return; } if (isUsingSlf4j()) { slf4jLogger.debug(String.valueOf(o)); return; } if (isUsingCommonsLogging()) { commonsLog.debug(o); return; } write("DEBUG", o); } public void debug(Object o, Throwable throwable) { if (!isDebugEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.debug(o, throwable); return; } if (isUsingSlf4j()) { slf4jLogger.debug(String.valueOf(o), throwable); return; } if (isUsingCommonsLogging()) { commonsLog.debug(o, throwable); return; } write("DEBUG", o, throwable); } public void debug(Throwable throwable) { if (!isDebugEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.debug(throwable); return; } if (isUsingSlf4j()) { slf4jLogger.debug("", throwable); return; } if (isUsingCommonsLogging()) { commonsLog.debug(throwable); return; } write("DEBUG", throwable, throwable); } public void info(Object o) { if (!isInfoEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.info(o); return; } if (isUsingSlf4j()) { slf4jLogger.info(String.valueOf(o)); return; } if (isUsingCommonsLogging()) { commonsLog.info(o); return; } write("INFO", o); } public void info(Object o, Throwable throwable) { if (!isInfoEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.info(o, throwable); return; } if (isUsingSlf4j()) { slf4jLogger.info(String.valueOf(o), throwable); return; } if (isUsingCommonsLogging()) { commonsLog.info(o, throwable); return; } write("INFO", o, throwable); } public void info(Throwable throwable) { if (!isInfoEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.info(throwable); return; } if (isUsingSlf4j()) { slf4jLogger.info("", throwable); return; } if (isUsingCommonsLogging()) { commonsLog.info(throwable); return; } write("INFO", throwable, throwable); } public void warn(Object o) { if (!isWarnEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.warn(o); return; } if (isUsingSlf4j()) { slf4jLogger.warn(String.valueOf(o)); return; } if (isUsingCommonsLogging()) { commonsLog.warn(o); return; } write("WARN", o); } public void warn(Object o, Throwable throwable) { if (!isWarnEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.warn(o, throwable); return; } if (isUsingSlf4j()) { slf4jLogger.warn(String.valueOf(o), throwable); return; } if (isUsingCommonsLogging()) { commonsLog.warn(o, throwable); return; } write("WARN", o, throwable); } public void warn(Throwable throwable) { if (!isWarnEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.warn(throwable); return; } if (isUsingSlf4j()) { slf4jLogger.warn("", throwable); return; } if (isUsingCommonsLogging()) { commonsLog.warn(throwable); return; } write("WARN", throwable, throwable); } public void error(Object o) { if (!isErrorEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.error(o); return; } if (isUsingSlf4j()) { slf4jLogger.error(String.valueOf(o)); return; } if (isUsingCommonsLogging()) { commonsLog.error(o); return; } write("ERROR", o); } public void error(Object o, Throwable throwable) { if (!isErrorEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.error(o, throwable); return; } if (isUsingSlf4j()) { slf4jLogger.error(String.valueOf(o), throwable); return; } if (isUsingCommonsLogging()) { commonsLog.error(o, throwable); return; } write("ERROR", o, throwable); } public void error(Throwable throwable) { if (!isErrorEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.error(throwable); return; } if (isUsingSlf4j()) { slf4jLogger.error("", throwable); return; } if (isUsingCommonsLogging()) { commonsLog.error(throwable); return; } write("ERROR", throwable, throwable); } public void fatal(Object o) { if (!isFatalEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.fatal(o); return; } if (isUsingSlf4j()) { slf4jLogger.error(String.valueOf(o)); // note: SLF4J has no fatal level return; } if (isUsingCommonsLogging()) { commonsLog.fatal(o); return; } write("FATAL", o); } public void fatal(Object o, Throwable throwable) { if (!isFatalEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.fatal(o, throwable); return; } if (isUsingSlf4j()) { slf4jLogger.error(String.valueOf(o), throwable); // note: SLF4J has no fatal level return; } if (isUsingCommonsLogging()) { commonsLog.fatal(o, throwable); return; } write("FATAL", o, throwable); } public void fatal(Throwable throwable) { if (!isFatalEnabled()) { return; } if (isUsingLog4j()) { log4jLogger.fatal(throwable); return; } if (isUsingSlf4j()) { slf4jLogger.error("", throwable); // note: SLF4J has no fatal level return; } if (isUsingCommonsLogging()) { commonsLog.fatal(throwable); return; } write("FATAL", throwable, throwable); } /** * Will get an instance of log for a given class. * * @param aClass to log for * @return the log instance */ public static Log getLog(Class aClass) { return new Log(aClass); } /** * Set the logging level (options are TRACE, DEBUG, INFO, WARN, ERROR, FATAL). * * @param level the level to log with */ public static void setLevel(String level) { usingSystemOut = false; usingSystemErr = false; // check for log type on the front if ("LOG4J".equalsIgnoreCase(level)) { usingLog4j = true; } else if ("SLF4J".equalsIgnoreCase(level)) { usingSlf4j = true; } else if ("COMMONS".equalsIgnoreCase(level)) { usingCommonsLogging = true; } else { // log need to parse level also if (level != null) { if (level.startsWith("SYSOUT:")) { usingSystemOut = true; level = level.substring("SYSOUT:".length()); } if (level.startsWith("STDOUT:")) { usingSystemOut = true; level = level.substring("STDOUT:".length()); } if (level.startsWith("STDERR:")) { usingSystemErr = true; level = level.substring("STDERR:".length()); } if (level.startsWith("SYSERR:")) { usingSystemErr = true; level = level.substring("SYSERR:".length()); } } setLevelInternal(level); } } /** * actually set the level. setLevel is really setting type. */ private static void setLevelInternal(String level) { // reset all level info traceLevelEnabled = false; debugLevelEnabled = false; infoLevelEnabled = false; warnLevelEnabled = false; errorLevelEnabled = false; fatalLevelEnabled = false; // set correct level boolean levelSelected = false; if ("TRACE".equalsIgnoreCase(level)) { traceLevelEnabled = true; levelSelected = true; } if ("DEBUG".equalsIgnoreCase(level)) { debugLevelEnabled = true; levelSelected = true; } if ("INFO".equalsIgnoreCase(level)) { infoLevelEnabled = true; levelSelected = true; } if ("WARN".equalsIgnoreCase(level)) { warnLevelEnabled = true; levelSelected = true; } if ("ERROR".equalsIgnoreCase(level)) { errorLevelEnabled = true; levelSelected = true; } if ("FATAL".equalsIgnoreCase(level)) { fatalLevelEnabled = true; levelSelected = true; } if (!levelSelected) { infoLevelEnabled = true; } } /** * Handles writing for throwable. * * @param level log level to log for * @param throwable to log * @param o object to log */ private void write(String level, Object o, Throwable throwable) { String msg = getMsg(level, o).toString(); if (usingSystemOut || context == null) { System.out.println(msg); throwable.printStackTrace(System.out); } else if (usingSystemErr) { System.err.println(msg); throwable.printStackTrace(System.err); } else { context.log(msg, throwable); } } /** * Handles writing of log lines. * * @param level log level to log for * @param o object to log (runs toString) */ private void write(String level, Object o) { String msg = getMsg(level, o).toString(); if (usingSystemOut || context == null) { System.out.println(msg); } else if (usingSystemErr) { System.err.println(msg); } else { context.log(msg); } } private StringBuffer getMsg(String level, Object o) { StringBuffer msg = new StringBuffer(); if (clazz == null) { msg.append("null"); } else { msg.append(clazz.getName()); } msg.append(" "); msg.append(level); msg.append(": "); msg.append(o.toString()); return msg; } /** * Resets log to default state. */ public static void resetAll() { Log.context = null; setLevel(DEFAULT_LOG_LEVEL); Log.usingSystemOut = false; Log.usingSystemErr = false; Log.usingLog4j = false; Log.usingSlf4j = false; Log.usingCommonsLogging = false; } /** * Will setup Log based on the filter config. Uses init paramater "logLevel" to get the log level. * Defaults to "INFO". * * @param filterConfig the filter config to use */ public static void setConfiguration(final FilterConfig filterConfig) { resetAll(); if (filterConfig == null) { localLog.error("no filter config passed"); return; } Log.context = filterConfig.getServletContext(); String logLevelConf = filterConfig.getInitParameter("logLevel"); if (logLevelConf != null) { logLevelConf = StringUtils.trim(logLevelConf); } setLevel(logLevelConf); localLog.debug("logLevel set to " + logLevelConf); } }
package jsettlers.main.android.resources; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.util.Scanner; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import jsettlers.logic.LogicRevision; import jsettlers.main.android.R; import jsettlers.main.android.Revision; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.SingleClientConnManager; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; public class ResourceUpdater implements Runnable { private static class ServerData { private final String revision; private final long size; public ServerData(String readData) throws IOException { String[] entries = readData.split("\n"); if (entries.length < 2) { throw new IOException("Server has not sent enogh data."); } if (!entries[1].matches("\\d+")) { throw new IOException("Size is not a number."); } revision = entries[0]; size = Long.parseLong(entries[1]); } } private static final int REVISION = Revision.REVISION + LogicRevision.REVISION * 10000; private static final String RESOURCE_PREFIX = ""; private static final String SERVER_ROOT = "https://michael2402.homeip.net/jsettlers/"; /** * The current program revision to force an update on program update. */ private static final String PREF_REVISION = "rev"; /** * If an update needs to be forced on next start. */ private static final String PREF_OUTDATED = "force"; /** * The revision of the resources we got. */ private static final String PREF_RESOURCEVERSION = "resources"; private final Resources resources; private final File destdir; private boolean isUpdating; private ServerData serverData = null; private final SharedPreferences prefs; private final Object updateMutex = new Object(); public ResourceUpdater(Context context, File destdir) { this.resources = context.getResources(); this.prefs = context.getSharedPreferences("resupdate", 0); this.destdir = destdir; int revHash = REVISION; if (prefs.getInt(PREF_REVISION, -1) != revHash) { requireUpdate(); } } @Override public void run() { try { synchronized(updateMutex ) { DefaultHttpClient httpClient = createClient(); serverData = loadRevision(httpClient); String myversion = prefs.getString(PREF_RESOURCEVERSION, ""); boolean serverrevIsNewer = serverData != null && !serverData.revision.equals(myversion); if (serverrevIsNewer) { } } } catch (Throwable e) { e.printStackTrace(); } } private void requireUpdate() { prefs.edit().putBoolean(PREF_OUTDATED, true).commit(); } public void startUpdate(final UpdateListener listener) { if (isUpdating()) { // bad. really bad. return; } setUpdating(true); new Thread(new Runnable() { @Override public void run() { try { synchronized (updateMutex) { updateFiles(createClient(), listener); } } catch (Throwable t) { t.printStackTrace(); } setUpdating(false); //TODO: i18n listener.setProgressState("Updating", 1); if (listener != null) { listener.resourceUpdateFinished(); } } }, "resource-update").start(); } private void updateFiles(DefaultHttpClient httpClient, UpdateListener c) throws IOException, ClientProtocolException { //TODO: i18n c.setProgressState("Updating", -1); if (serverData == null) { serverData = loadRevision(httpClient); } final String url = SERVER_ROOT + "resources.zip"; HttpGet httpRequest = new HttpGet(url); HttpResponse response = httpClient.execute(httpRequest); InputStream compressed = response.getEntity() .getContent(); ZipInputStream inputStream = new ZipInputStream(compressed); try { int files = 0; byte[] buffer = new byte[1024]; long read = 0; ZipEntry entry; while ((entry = inputStream.getNextEntry()) != null) { String name = entry.getName(); //TODO: i18n c.setProgressState("Updating", (float) read / serverData.size); System.out.println("Size: " + read + " of " + serverData.size); if (name.startsWith(RESOURCE_PREFIX)) { String outfilename = destdir.getAbsolutePath() + "/" + name.substring(RESOURCE_PREFIX.length()); File outfile = new File(outfilename); if (entry.isDirectory()) { if (outfile.exists() && !outfile.isDirectory()) { outfile.delete(); } if (!outfile.isDirectory()) { outfile.mkdirs(); } } else { File tmpFile = new File(outfilename + ".tmp"); tmpFile.getParentFile().mkdirs(); tmpFile.deleteOnExit(); // <- if something fails FileOutputStream out = new FileOutputStream(tmpFile); while (true) { int len = inputStream.read(buffer); if (len <= 0) { break; } read += len; out.write(buffer, 0, len); } out.close(); tmpFile.renameTo(outfile); files++; } } } System.out.println("Updated " + files + " files"); prefs.edit().putInt(PREF_REVISION, REVISION) .putBoolean(PREF_OUTDATED, false) .putString(PREF_RESOURCEVERSION, serverData.revision).commit(); } catch (Throwable t) { t.printStackTrace(); } setUpdating(false); } private static ServerData loadRevision(DefaultHttpClient httpClient) throws IOException, ClientProtocolException { final String url = SERVER_ROOT + "revision.txt"; HttpGet httpRequest = new HttpGet(url); HttpResponse response = httpClient.execute(httpRequest); InputStream inputStream = response.getEntity().getContent(); return new ServerData(getString(inputStream)); } private static String getString(InputStream inputStream) { return new Scanner(inputStream).useDelimiter("\\A").next(); } private DefaultHttpClient createClient() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException, UnrecoverableKeyException { HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; DefaultHttpClient client = new DefaultHttpClient(); KeyStore truststore = KeyStore.getInstance("BKS"); InputStream in = resources.openRawResource(R.raw.certs); truststore.load(in, "F2rORYtG".toCharArray()); SSLSocketFactory socketFactory = new SSLSocketFactory(truststore); SchemeRegistry registry = new SchemeRegistry(); socketFactory .setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); registry.register(new Scheme("https", socketFactory, 443)); SingleClientConnManager mgr = new SingleClientConnManager( client.getParams(), registry); DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams()); // Set verifier HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); return httpClient; } public synchronized boolean isUpdating() { return isUpdating; } public synchronized void waitUntilUpdateFinished() throws InterruptedException { while (isUpdating) { this.wait(); } } private synchronized void setUpdating(boolean isUpdating) { this.isUpdating = isUpdating; this.notifyAll(); } public boolean needsUpdate() { return prefs.getBoolean(PREF_OUTDATED, true); } }
package org.pm4j.core.pm; import static org.junit.Assert.assertEquals; import static org.pm4j.tools.test.PmAssert.setValue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.List; import org.apache.commons.lang.StringUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.pm4j.common.pageable.PageableCollectionUtil2; import org.pm4j.common.query.FilterCompareDefinition; import org.pm4j.common.query.QueryOptions; import org.pm4j.common.query.inmem.InMemSortOrder; import org.pm4j.common.util.CompareUtil; import org.pm4j.core.pm.PmTable2.UpdateAspect; import org.pm4j.core.pm.annotation.PmBeanCfg; import org.pm4j.core.pm.annotation.PmBoolean; import org.pm4j.core.pm.annotation.PmFactoryCfg; import org.pm4j.core.pm.annotation.PmTableCfg2; import org.pm4j.core.pm.annotation.PmTableColCfg2; import org.pm4j.core.pm.api.PmCacheApi; import org.pm4j.core.pm.api.PmCacheApi.CacheKind; import org.pm4j.core.pm.api.PmEventApi; import org.pm4j.core.pm.impl.PmAttrIntegerImpl; import org.pm4j.core.pm.impl.PmAttrStringImpl; import org.pm4j.core.pm.impl.PmBeanImpl; import org.pm4j.core.pm.impl.PmConversationImpl; import org.pm4j.core.pm.impl.PmTableColImpl2; import org.pm4j.core.pm.impl.PmTableImpl2; public class PmTable2Test { private TablePm myTablePm; private List<RowBean> editedRowBeanList = new ArrayList<RowBean>(Arrays.asList( new RowBean("b", "a 'b'", 2), new RowBean("a", "an 'a'", 1), new RowBean("c", "a 'c'", 3) )); private List<RowBean> alternateRowBeanList = new ArrayList<RowBean>(Arrays.asList( new RowBean("b", "new b", 2), new RowBean("a", "new a", 1), new RowBean("c", "new c", 3) )); @Before public void setUp() { myTablePm = new TablePm(new PmConversationImpl()) { /** We use here an in-memory data table. * The table represents the items of the collection provided by this method. */ @Override protected Collection<RowBean> getPmBeansImpl() { return editedRowBeanList; } }; } @Test public void testTable() { assertEquals(3, myTablePm.getTotalNumOfPmRows()); assertEquals("[a, b]", myTablePm.getRowPms().toString()); } @Test public void testReReadCollectionAfterCallingUpdateTablePm() { myTablePm.setNumOfPageRowPms(10); assertEquals("[a, b, c]", myTablePm.getRowPms().toString()); editedRowBeanList.add(new RowBean("d", "a d", 44)); assertEquals("There is no value change event that informs the table about the change.", 3, myTablePm.getTotalNumOfPmRows()); assertEquals("[a, b, c]", myTablePm.getRowPms().toString()); myTablePm.updatePmTable(UpdateAspect.CLEAR_CHANGES); assertEquals("[a, b, c, d]", myTablePm.getRowPms().toString()); } @Test public void testReReadCollectionAfterClearingCaches() { myTablePm.setNumOfPageRowPms(10); assertEquals("[a, b, c]", myTablePm.getRowPms().toString()); editedRowBeanList.add(new RowBean("d", "a d", 44)); assertEquals("[a, b, c]", myTablePm.getRowPms().toString()); PmCacheApi.clearPmCache(myTablePm, CacheKind.VALUE); assertEquals("[a, b, c, d]", myTablePm.getRowPms().toString()); } @Test public void testDisplayBeanListChanges() { assertEquals(3, myTablePm.getTotalNumOfPmRows()); assertEquals("[a, b]", myTablePm.getRowPms().toString()); // add an item to the represented list. editedRowBeanList.add(new RowBean("d", "d", 4)); assertEquals("Number of items is cached. Thus the change will not be reflected automatically", 3, myTablePm.getTotalNumOfPmRows()); PmCacheApi.clearPmCache(myTablePm); assertEquals("After clearing the PM value caches we see the data change.", 4, myTablePm.getTotalNumOfPmRows()); assertEquals("First page content is not changed.", "[a, b]", myTablePm.getRowPms().toString()); PageableCollectionUtil2.navigateToLastPage(myTablePm.getPmPageableCollection()); assertEquals("After a page switch the new item is visible.", "[c, d]", myTablePm.getRowPms().toString()); // remove an item on the current page. editedRowBeanList.remove(2); assertEquals("[b, a, d]", editedRowBeanList.toString()); assertEquals("Rerender the current page. It's not changed because the current page items are cached.", "[c, d]", myTablePm.getRowPms().toString()); PmCacheApi.clearPmCache(myTablePm); assertEquals("After an update call the table should display the current content.", "[d]", myTablePm.getRowPms().toString()); } @Test public void testExchangeEqualBeanInBackingCollectionAndFireValueChangeOnParent() { assertEquals(3, myTablePm.getTotalNumOfPmRows()); assertEquals("an 'a'", myTablePm.getRowPms().get(0).description.getValue()); editedRowBeanList = alternateRowBeanList; // the table did not yet receive an event that informs about the backing collection change // it provides data from it's page cache. assertEquals("an 'a'", myTablePm.getRowPms().get(0).description.getValue()); PmEventApi.firePmEvent(myTablePm.getPmParent(), PmEvent.VALUE_CHANGE); assertEquals("new a", myTablePm.getRowPms().get(0).description.getValue()); } @Test public void testExchangeEqualBeanInBackingCollectionAndCallUpdatePmTable() { assertEquals(3, myTablePm.getTotalNumOfPmRows()); assertEquals("an 'a'", myTablePm.getRowPms().get(0).description.getValue()); editedRowBeanList = alternateRowBeanList; // the table did not yet receive an event that informs about the backing collection change // it provides data from it's page cache. assertEquals("an 'a'", myTablePm.getRowPms().get(0).description.getValue()); myTablePm.updatePmTable(UpdateAspect.CLEAR_CHANGES); assertEquals("new a", myTablePm.getRowPms().get(0).description.getValue()); } @Test public void testSortByName() { assertEquals("[a, b]", myTablePm.getRowPms().toString()); setValue(myTablePm.name.getSortOrderAttr(), PmSortOrder.DESC); assertEquals("[c, b]", myTablePm.getRowPms().toString()); } @Test public void testSortByDescriptionUsingCustomComparator() { assertEquals("[a, b]", myTablePm.getRowPms().toString()); setValue(myTablePm.description.getSortOrderAttr(), PmSortOrder.ASC); assertEquals("[b, c]", myTablePm.getRowPms().toString()); } @Test public void testFilterByDescriptionExists() { assertEquals("[a, b]", myTablePm.getRowPms().toString()); FilterCompareDefinition fd = getFilterDefinition("description"); assertEquals(myTablePm.description.getPmTitle(), fd.getAttrTitle()); } @PmTableCfg2(defaultSortCol="name") @PmFactoryCfg(beanPmClasses=RowPm.class) public static class TablePm extends PmTableImpl2<RowPm, RowBean> { /** A column with an annotation based filter definition. */ @PmTableColCfg2(sortable=PmBoolean.TRUE) public final PmTableCol2 name = new PmTableColImpl2(this); /** A column with a method based filter definition. */ @PmTableColCfg2(filterType = String.class) public final PmTableCol2 description = new PmTableColImpl2(this); /** A column with a filter annotation that defines . */ public final PmTableCol2 counter = new PmTableColImpl2(this); /** Defines a page size of two items. */ public TablePm(PmObject pmParent) { super(pmParent); setNumOfPageRowPms(2); } /** * Adds a custom comparator for the description column. */ @Override protected QueryOptions getPmQueryOptions() { QueryOptions qo = super.getPmQueryOptions(); qo.addSortOrder("description", new InMemSortOrder(new Comparator<RowBean>() { @Override public int compare(RowBean o1, RowBean o2) { return CompareUtil.compare(o1.description, o2.description); } })); return qo; } } @PmBeanCfg(beanClass=RowBean.class) public static class RowPm extends PmBeanImpl<RowBean> { public final PmAttrString name = new PmAttrStringImpl(this); public final PmAttrString description = new PmAttrStringImpl(this); public final PmAttrInteger counter = new PmAttrIntegerImpl(this); /** for debugging */ @Override public String toString() { return getPmBean().toString(); } } public static class RowBean { public String name; public String description; public Integer counter; public RowBean(String name, String description, int counter) { assert name != null; this.name = name; this.description = description; this.counter = counter; } /** for debugging */ @Override public String toString() { return name; } @Override public boolean equals(Object obj) { return StringUtils.equals(this.name, ((RowBean)obj).name); } @Override public int hashCode() { return name.hashCode(); } } private FilterCompareDefinition getFilterDefinition(String colName) { QueryOptions qo = myTablePm.getPmPageableBeanCollection().getQueryOptions(); List<FilterCompareDefinition> compareDefinitions = qo.getCompareDefinitions(); for (FilterCompareDefinition f : compareDefinitions) { if (f.getAttr().getName().equals(colName)) { return f; } } Assert.fail("No filter found for column: " + colName); return null; } }
package application.controllers; import application.fxobjects.cell.graph.RectangleCell; import core.Annotation; import core.AnnotationParser; import core.AnnotationProcessor; import core.Node; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.geometry.Pos; import javafx.scene.image.ImageView; import javafx.scene.control.*; import javafx.scene.layout.*; import java.io.FileNotFoundException; import java.net.URL; import java.util.*; /** * MainController for GUI. */ public class MainController extends Controller<BorderPane> { /** * The Controllers used in this Class. */ private GraphController graphController; private TreeController treeController; /** * FXML Objects. */ @FXML private ScrollPane screen; @FXML private MenuBar menuBar; private HBox legend; private VBox listVBox; private ListView list; private int currentView; private ListFactory listFactory; private TextField genomeTextField; private StackPane box; private int count; private int secondCount; private int selectedIndex; /** * Constructor to create MainController based on abstract Controller. */ public MainController() { super(new BorderPane()); loadFXMLfile("/fxml/main.fxml"); this.count = -1; this.secondCount = -1; ImageView imageView = new ImageView("/DART2N.png"); imageView.fitWidthProperty().bind(this.getRoot().widthProperty()); imageView.fitHeightProperty().bind(this.getRoot().heightProperty()); this.getRoot().setCenter(imageView); // Create the new GraphController graphController = new GraphController(this); } /** * Initializes the graph. */ public void initGraph() { currentView = graphController.getGraph().getLevelMaps().size() - 1; //Fill the graph fillGraph(null, new ArrayList<>()); graphController.getGraph().getModel().matchNodesAndAnnotations(); } /** * Initializes the tree. * * @param s Path to the tree file. */ public void initTree(String s) { treeController = new TreeController(this, s); fillTree(); } /** * Initializes the annotation data. * * @param path Path to the annotation data file. */ public void initAnnotations(String path) { try { List<Annotation> annotations = AnnotationParser.readCDSFilteredGFF(path); graphController.getGraph().setAnnotations(annotations); graphController.getGraph().getModel().matchNodesAndAnnotations(); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * Getter method for the current view level. * * @return the current view level. */ public int getCurrentView() { return currentView; } /** * Initialize method for the controller. * * @param location location for relative paths. * @param resources resources to localize the root object. */ @SuppressFBWarnings("URF_UNREAD_FIELD") public final void initialize(URL location, ResourceBundle resources) { createMenu(false); } /** * Method to add items to the GUI */ private void initGUI() { createZoomBoxAndLegend(); this.getRoot().setCenter(graphController.getRoot()); if (secondCount == -1) { createList(); setListItems(); secondCount++; } this.getRoot().setCenter(graphController.getRoot()); this.getRoot().setRight(listVBox); } /** * Method to fill the graph. * * @param ref the reference string. * @param selectedGenomes the genomes to display. */ public void fillGraph(Object ref, List<String> selectedGenomes) { // Apply the selected genomes graphController.getGraph().setCurrentGenomes(selectedGenomes); graphController.update(ref, currentView); graphController.getZoomBox().fillZoomBox(count == -1); count++; initGUI(); } /** * If selections are made in the phylogenetic tree, * this method will visualize/highlight them specifically. * * @param s a List of selected strains. */ public void soloStrainSelection(List<String> s) { fillGraph(s.get(0), new ArrayList<>()); initGUI(); } /** * If selections are made in the phylogenetic tree, * this method will visualize/highlight them specifically. * * @param s a List of selected strains. */ public void strainSelection(List<String> s) { graphController.getGraph().reset(); fillGraph(null, s); initGUI(); setListItems(); } /** * Create the HBox containing the zoom box and legend. */ private void createZoomBoxAndLegend() { HBox hbox = new HBox(); // Place the legend createLegend(); legend.setAlignment(Pos.CENTER_RIGHT); // Place the zoom box box = graphController.getZoomBox().getZoomBox(); hbox.setAlignment(Pos.CENTER); hbox.getChildren().addAll(box, legend); this.getRoot().setBottom(hbox); } /** * Method to create the Legend */ private void createLegend() { LegendFactory legendFactory = new LegendFactory(); legend = legendFactory.createLegend(); } /** * Adds an action listener to the genome search and deselect buttons. * * @param searchButton The genome search button. * @param deselectButton The deselect button. */ private void setSearchAndDeselectButtonActionListener( Button searchButton, Button deselectButton) { searchButton.setOnAction(e -> { if (!genomeTextField.getText().isEmpty()) { application.fxobjects.cell.Cell cell = treeController.getCellByName( genomeTextField.textProperty().get().trim()); treeController.applyCellHighlight(cell); treeController.selectStrain(cell); genomeTextField.setText(""); fillTree(); } }); deselectButton.setOnAction(e -> { treeController.clearSelection(); fillTree(); }); } /** * Adds an action listener to the annotation highlight button. * * @param annotationTextField The annotation search field. * @param highlightButton The annotation highlight button. */ private void setHighlightButtonActionListener( TextField annotationTextField, Button highlightButton, Button deselectAnnotationButton) { highlightButton.setOnAction(e -> { if (currentView != 0) { return; } if (!annotationTextField.getText().isEmpty()) { List<Annotation> annotations = graphController.getGraph().getModel().getAnnotations(); try { Annotation ann = AnnotationProcessor .findAnnotation(annotations, annotationTextField.getText()); Map<Integer, application.fxobjects.cell.Cell> cellMap = graphController.getGraph().getModel().getCellMap(); for (Node n : ann.getSpannedNodes()) { ((RectangleCell) cellMap.get(n.getId())).setHighLight(); } } catch (AnnotationProcessor.TooManyAnnotationsFoundException e1) { e1.printStackTrace(); } } }); highlightButton.setOnAction(e -> { }); } /** * Method to create the menu bar. * * @param withSearch Which part of the menu to show. */ public void createMenu(boolean withSearch) { VBox vBox = new VBox(); HBox hBox = new HBox(); genomeTextField = new TextField(); Button searchButton = new Button("Search Genome (In Tree)"); Button deselectSearchButton = new Button("Deselect All"); TextField annotationTextField = new TextField(); Button highlightButton = new Button("Highlight annotation"); Button deselectAnnotationButton = new Button("Highlight annotation"); setSearchAndDeselectButtonActionListener(searchButton, deselectSearchButton); setHighlightButtonActionListener(annotationTextField, highlightButton, deselectAnnotationButton); hBox.getChildren().addAll(genomeTextField, searchButton, deselectSearchButton, annotationTextField, highlightButton); if (withSearch) { vBox.getChildren().addAll(menuBar, hBox); } else { MenuFactory menuFactory = new MenuFactory(this); menuBar = menuFactory.createMenu(menuBar); vBox.getChildren().addAll(menuBar); } this.getRoot().setTop(vBox); } /** * Method to create the Info-list */ public void createList() { listFactory = new ListFactory(); listVBox = listFactory.createInfoList(""); list = listFactory.getList(); list.setOnMouseClicked(event -> listSelect()); list.setOnMouseClicked(event -> { if (!(list.getSelectionModel().getSelectedItem() == null)) { graphController.getGraph().reset(); getTextField().setText((String) list.getSelectionModel().getSelectedItem()); fillGraph(list.getSelectionModel().getSelectedItem(), graphController.getGenomes()); graphController.takeSnapshot(); } }); list.setOnMouseReleased(event -> list.getFocusModel().focus(selectedIndex)); setListItems(); this.getRoot().setRight(listVBox); } /** * Method to perform action upon listItem selection */ public void listSelect() { if (!(list.getSelectionModel().getSelectedItem() == null)) { selectedIndex = list.getSelectionModel().getSelectedIndex(); graphController.getGraph().reset(); fillGraph(list.getSelectionModel().getSelectedItem(), graphController.getGenomes()); if (getGraphController().getGraphMouseHandling().getPrevClick() != null) { graphController.focus(getGraphController() .getGraphMouseHandling().getPrevClick()); } } } /** * Switches the scene to the graph view. * * @param delta the diff in view to apply. */ public void switchScene(int delta) { currentView += delta; currentView = Math.max(0, currentView); currentView = Math.min(graphController.getGraph().getLevelMaps().size() - 1, currentView); fillGraph(graphController.getGraph().getCurrentRef(), graphController.getGraph().getGenomes()); } /** * Method to fill the phylogenetic tree. */ public void fillTree() { screen = treeController.getRoot(); this.getRoot().setCenter(screen); this.getRoot().setBottom(null); hideListVBox(); } /** * Hide the info panel. */ private void hideListVBox() { this.getRoot().getChildren().remove(listVBox); } /** * Method to add items to the Info-List */ private void setListItems() { List<String> genomes = graphController.getGenomes(); genomes.sort(Comparator.naturalOrder()); list.setItems(FXCollections.observableArrayList(genomes)); } /** * Getter method for the graphController. * * @return the graphController. */ public GraphController getGraphController() { return graphController; } /** * Getter method for the treeController. * * @return the treeController. */ public TreeController getTreeController() { return treeController; } /** * Getter method for the ListFactory. * * @return the ListFactory. */ public ListFactory getListFactory() { return listFactory; } /** * Method to set the currentView. * * @param currentView the current View. */ public void setCurrentView(int currentView) { this.currentView = currentView; } /** * Getter for the textfiel.d * * @return the textfield. */ public TextField getTextField() { return genomeTextField; } }
public class test { //test // bonjour !!! }
package br.com.dbsoft.ui.bean.crud; import java.lang.annotation.Annotation; import java.math.BigDecimal; import java.sql.Connection; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.enterprise.context.Conversation; import javax.enterprise.context.ConversationScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.inject.Inject; import br.com.dbsoft.core.DBSApproval; import br.com.dbsoft.core.DBSApproval.APPROVAL_STAGE; import br.com.dbsoft.core.DBSSDK; import br.com.dbsoft.error.DBSIOException; import br.com.dbsoft.io.DBSColumn; import br.com.dbsoft.io.DBSDAO; import br.com.dbsoft.io.DBSResultDataModel; import br.com.dbsoft.message.DBSMessage; import br.com.dbsoft.message.IDBSMessage; import br.com.dbsoft.message.IDBSMessage.MESSAGE_TYPE; import br.com.dbsoft.ui.bean.DBSBeanModalMessages; import br.com.dbsoft.ui.bean.crud.DBSCrudBeanEvent.CRUD_EVENT; import br.com.dbsoft.ui.component.DBSUIInput; import br.com.dbsoft.ui.component.DBSUIInputText; import br.com.dbsoft.ui.component.modalcrudmessages.IDBSModalCrudMessages; import br.com.dbsoft.ui.core.DBSFaces; import br.com.dbsoft.util.DBSDate; import br.com.dbsoft.util.DBSIO; import br.com.dbsoft.util.DBSNumber; import br.com.dbsoft.util.DBSObject; import br.com.dbsoft.util.DBSIO.SORT_DIRECTION; public abstract class DBSCrudBean extends DBSBeanModalMessages implements IDBSModalCrudMessages{ private static final long serialVersionUID = -8550893738791483527L; public static enum FormStyle { DIALOG (0), TABLE (1), VIEW (2); private int wCode; private FormStyle(int pCode) { this.wCode = pCode; } public int getCode() { return wCode; } public static FormStyle get(int pCode) { switch (pCode) { case 0: return DIALOG; case 1: return TABLE; case 2: return VIEW; default: return DIALOG; } } } public static enum EditingMode { NONE ("Not Editing", 0), INSERTING ("Inserting", 1), UPDATING ("Updating", 2), DELETING ("Deleting", 3), APPROVING ("Approving", 4), REPROVING ("Reproving", 5); private String wName; private int wCode; private EditingMode(String pName, int pCode) { this.wName = pName; this.wCode = pCode; } public String getName() { return wName; } public int getCode() { return wCode; } public static EditingMode get(int pCode) { switch (pCode) { case 0: return NONE; case 1: return INSERTING; case 2: return UPDATING; case 3: return DELETING; case 4: return APPROVING; case 5: return REPROVING; default: return NONE; } } } public static enum EditingStage{ NONE ("None", 0), COMMITTING ("Committing", 1), IGNORING ("Ignoring", 2); private String wName; private int wCode; private EditingStage(String pName, int pCode) { this.wName = pName; this.wCode = pCode; } public String getName() { return wName; } public int getCode() { return wCode; } public static EditingStage get(int pCode) { switch (pCode) { case 0: return NONE; case 1: return COMMITTING; case 2: return IGNORING; default: return NONE; } } } @Inject private Conversation wConversation; private static final long wConversationTimeout = 600000; //10 minutos protected DBSDAO<?> wDAO; private List<IDBSCrudBeanEventsListener> wEventListeners = new ArrayList<IDBSCrudBeanEventsListener>(); private EditingMode wEditingMode = EditingMode.NONE; private EditingStage wEditingStage = EditingStage.NONE; private FormStyle wFormStyle = FormStyle.DIALOG; private List<Integer> wSelectedRowsIndexes = new ArrayList<Integer>(); private Collection<DBSColumn> wSavedCurrentColumns = null; private boolean wValueChanged; private int wCopiedRowIndex = -1; private boolean wValidateComponentHasError = false; private Boolean wDialogOpened = false; private String wDialogCaption; private Boolean wDialogCloseAfterInsert = false; private String wMessageConfirmationEdit = "Confirmar a edição?"; private String wMessageConfirmationInsert = "Confirmar a inclusão?"; private String wMessageConfirmationDelete = "Confirmar a exclusão?"; private String wMessageConfirmationApprove = "Confirmar a aprovação?"; private String wMessageConfirmationReprove = "Confirmar a reprovação?"; private String wMessageIgnoreEdit = "Ignorar a edição?"; private String wMessageIgnoreInsert = "Ignorar a inclusão?"; private String wMessageIgnoreDelete = "Ignorar a exclusão?"; private Boolean wAllowUpdate = true; private Boolean wAllowInsert = true; private Boolean wAllowDelete = true; private Boolean wAllowRefresh = true; private Boolean wAllowApproval = false; private Boolean wAllowApprove = true; private Boolean wAllowReprove = true; private Boolean wAllowCopy = true; private Boolean wAllowCopyOnUpdate = false; private Integer wApprovalUserStages = 0; private String wColumnNameApprovalStage = null; private String wColumnNameApprovalUserIdRegistered = null; private String wColumnNameApprovalUserIdVerified = null; private String wColumnNameApprovalUserIdConferred = null; private String wColumnNameApprovalUserIdApproved = null; private String wColumnNameApprovalDateApproved = null; private String wColumnNameDateOnInsert = null; private String wColumnNameDateOnUpdate = null; private String wColumnNameUserIdOnInsert = null; private String wColumnNameUserIdOnUpdate = null; private String wSortColumn = ""; private String wSortDirection = SORT_DIRECTION.DESCENDING.getCode(); private Boolean wRevalidateBeforeCommit = false; private Integer wUserId; private Boolean wMultipleSelection = false; private DBSCrudBean wParentCrudBean = null; private List<DBSCrudBean> wChildrenCrudBean = new ArrayList<DBSCrudBean>(); //Mensagens private IDBSMessage wMessageNoRowComitted = new DBSMessage(MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.noRowComitted")); private IDBSMessage wMessageOverSize = new DBSMessage(MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.overSize")); private IDBSMessage wMessageNoChange = new DBSMessage(MESSAGE_TYPE.INFORMATION, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.noChange")); private IDBSMessage wMessaggeApprovalSameUser = new DBSMessage(MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.approvalSameUser")); public String getCID(){ return wConversation.getId(); } public void conversationBegin(){ for (Annotation xAnnotation:this.getClass().getDeclaredAnnotations()){ if (xAnnotation.annotationType() == ConversationScoped.class){ pvConversationBegin(); break; } } } @Override protected void initializeClass() { conversationBegin(); pvFireEventInitialize(); //Finaliza os outros crudbeans antes de inicializar este. // DBSFaces.finalizeDBSBeans(this, false); << Comentado pois os beans passaram a ser criados como ConversationScoped - 12/Ago/2014 } @Override protected void finalizeClass(){ pvFireEventFinalize(); //Exclui os listeners associadao, antes de finalizar wEventListeners.clear(); } public void addEventListener(IDBSCrudBeanEventsListener pEventListener) { if (!wEventListeners.contains(pEventListener)){ wEventListeners.add(pEventListener); } } public void removeEventListener(IDBSCrudBeanEventsListener pEventListener) { if (wEventListeners.contains(pEventListener)){ wEventListeners.remove(pEventListener); } } public <T> void setValue(String pColumnName, Object pColumnValue, Class<T> pValueClass){ T xValue = DBSObject.<T>toClassValue(pColumnValue, pValueClass); setValue(pColumnName, xValue); } public void setValue(String pColumnName, Object pColumnValue){ //Utiliza ListValue para controlar os valores de todas as linhas if (wFormStyle == FormStyle.TABLE){ setListValue(pColumnName, pColumnValue); }else{ pvSetValueDAO(pColumnName, pColumnValue); } } public <T> T getValue(String pColumnName){ //Utiliza ListValue para controlar os valores de todas as linhas if (wFormStyle == FormStyle.TABLE){ return getListValue(pColumnName); }else{ return pvGetValue(pColumnName); } } public <T> T getValue(String pColumnName, Class<T> pValueClass){ return DBSObject.<T>toClassValue(getValue(pColumnName), pValueClass); } @SuppressWarnings("unchecked") public <T> T getValueOriginal(String pColumnName){ //Se existir registro corrente if (wDAO != null && (wDAO.getColumns().size() > 0 || wDAO.getCommandColumns().size() > 0)){ return (T) wDAO.getValueOriginal(pColumnName); }else{ return null; } } public <T> T getValueOriginal(String pColumnName, Class<T> pValueClass){ return DBSObject.<T>toClassValue(getValueOriginal(pColumnName), pValueClass); } @SuppressWarnings("unchecked") public <T> T getListValue(String pColumnName){ if (wDAO != null){ return (T) wDAO.getListValue(pColumnName); }else{ return null; } } public <T> T getListValue(String pColumnName, Class<T> pValueClass){ return DBSObject.<T>toClassValue(getListValue(pColumnName), pValueClass); } private void setListValue(String pColumnName, Object pColumnValue){ if (wDAO != null){ wDAO.setListValue(pColumnName, pColumnValue); } } public boolean getIsListNewRow(){ if (wDAO != null){ return wDAO.getIsNewRow(); }else{ return false; } } public String getListFormattedValue(String pColumnId) throws DBSIOException{return "pColumnId '" + pColumnId + "' desconhecida";} public IDBSMessage getColumnMessage(String pColumnName){ if (wDAO != null && (wDAO.getColumns().size() > 0 || wDAO.getCommandColumns().size() > 0)){ return wDAO.getMessage(pColumnName); }else{ return null; } } public void crudFormBeforeShowComponent(UIComponent pComponent){ if (wDAO!=null){ //Configura os campos do tipo input if (pComponent instanceof DBSUIInput){ DBSColumn xColumn = pvGetDAOColumnFromInputValueExpression((DBSUIInput) pComponent); if (xColumn!=null){ if (pComponent instanceof DBSUIInputText){ DBSUIInputText xInput = (DBSUIInputText) pComponent; xInput.setMaxLength(xColumn.getSize()); } } } } } public void crudFormValidateComponent(FacesContext pContext, UIComponent pComponent, Object pValue){ if (wEditingMode!=EditingMode.NONE){ if (wDAO!=null && pValue!=null){ String xSourceId = pContext.getExternalContext().getRequestParameterMap().get(DBSFaces.PARTIAL_SOURCE_PARAM); if (xSourceId !=null && !xSourceId.endsWith(":cancel")){ //TODO verificar se existe uma forma melhor de identificar se foi um cancelamento if (pComponent instanceof DBSUIInputText){ DBSUIInputText xInput = (DBSUIInputText) pComponent; DBSColumn xColumn = pvGetDAOColumnFromInputValueExpression(xInput); if (xColumn!=null){ String xValue = pValue.toString(); if (pValue instanceof Number){ xValue = DBSNumber.getOnlyNumber(xValue); } if (xValue.length() > xColumn.getSize()){ wMessageOverSize.setMessageTextParameters(xInput.getLabel(), xColumn.getSize()); addMessage(wMessageOverSize); wValidateComponentHasError = true; } } } } } } } public EditingMode getEditingMode() { return wEditingMode; } private synchronized void setEditingMode(EditingMode pEditingMode) { if (wEditingMode != pEditingMode){ //Qualquer troca no editingMode, desativa o editingstage setEditingStage(EditingStage.NONE); if (pEditingMode.equals(EditingMode.NONE)){ pvFireEventAfterEdit(wEditingMode); setValueChanged(false); } wEditingMode = pEditingMode; } } public EditingStage getEditingStage() { return wEditingStage; } private void setEditingStage(EditingStage pEditingStage) { if (wEditingStage != pEditingStage){ //Salva novo estado wEditingStage = pEditingStage; } } public void setDialogCaption(String pDialogCaption) {wDialogCaption = pDialogCaption;} public String getDialogCaption() {return wDialogCaption;} public Boolean getDialogOpened() { return wDialogOpened; } private synchronized void setDialogOpened(Boolean pDialogOpened) { if (wFormStyle == FormStyle.DIALOG){ if (wDialogOpened != pDialogOpened){ wDialogOpened = pDialogOpened; } } } public Boolean getDialogCloseAfterInsert() { return wDialogCloseAfterInsert; } public void setDialogCloseAfterInsert(Boolean pDialogCloseAfterInsert) { wDialogCloseAfterInsert = pDialogCloseAfterInsert; } public FormStyle getFormStyle() {return wFormStyle;} public void setFormStyle(FormStyle pFormStyle) {wFormStyle = pFormStyle;} @Override public String getMessageConfirmationEdit() {return wMessageConfirmationEdit;} @Override public void setMessageConfirmationEdit(String pMessageConfirmationEdit) {wMessageConfirmationEdit = pMessageConfirmationEdit;} @Override public String getMessageConfirmationInsert() {return wMessageConfirmationInsert;} @Override public void setMessageConfirmationInsert(String pDialogConfirmationInsertMessage) {wMessageConfirmationInsert = pDialogConfirmationInsertMessage;} @Override public String getMessageConfirmationDelete() {return wMessageConfirmationDelete;} @Override public void setMessageConfirmationDelete(String pMessageConfirmationDelete) {wMessageConfirmationDelete = pMessageConfirmationDelete;} @Override public String getMessageConfirmationApprove() {return wMessageConfirmationApprove;} @Override public void setMessageConfirmationApprove(String pMessageConfirmationApprove) {wMessageConfirmationApprove = pMessageConfirmationApprove;} @Override public String getMessageConfirmationReprove() {return wMessageConfirmationReprove;} @Override public void setMessageConfirmationReprove(String pMessageConfirmationReprove) {wMessageConfirmationReprove = pMessageConfirmationReprove;} @Override public String getMessageIgnoreEdit() {return wMessageIgnoreEdit;} @Override public void setMessageIgnoreEdit(String pMessageIgnoreEdit) {wMessageIgnoreEdit = pMessageIgnoreEdit;} @Override public String getMessageIgnoreInsert() {return wMessageIgnoreInsert;} @Override public void setMessageIgnoreInsert(String pMessageIgnoreInsert) {wMessageIgnoreInsert = pMessageIgnoreInsert;} @Override public String getMessageIgnoreDelete() {return wMessageIgnoreDelete;} @Override public void setMessageIgnoreDelete(String pMessageIgnoreDelete) {wMessageIgnoreDelete = pMessageIgnoreDelete;} @Override public Boolean getMessageConfirmationExists(){ if (getIsCommitting()){ if (getIsUpdating()){ if (DBSObject.isEmpty(getMessageConfirmationEdit())){ return false; } }else if (getIsInserting()){ if (DBSObject.isEmpty(getMessageConfirmationInsert())){ return false; } }else if (getIsDeleting()){ if (DBSObject.isEmpty(getMessageConfirmationDelete())){ return false; } }else{ return false; } return true; } return false; } @Override public Boolean getMessageIgnoreExists(){ if (getIsIgnoring()){ if (getIsUpdating()){ if (DBSObject.isEmpty(getMessageIgnoreEdit())){ return false; } }else if (getIsInserting()){ if (DBSObject.isEmpty(getMessageIgnoreInsert())){ return false; } }else if (getIsDeleting()){ if (DBSObject.isEmpty(getMessageIgnoreDelete())){ return false; } }else{ return false; } return true; } return false; } public DBSResultDataModel getList() throws DBSIOException{ if (wDAO==null){ pvSearchList(); if (wDAO==null || wDAO.getResultDataModel() == null){ return new DBSResultDataModel(); } clearMessages(); } return wDAO.getResultDataModel(); } /** * Retorna a quantidade de registros da pesquisa principal. * @return * @throws DBSIOException */ public Integer getRowCount() throws DBSIOException{ if (getList() != null){ return getList().getRowCount(); }else{ return 0; } } public Boolean getAllowDelete() throws DBSIOException { return wAllowDelete && pvApprovalUserAllowRegister() && getApprovalStage() == APPROVAL_STAGE.REGISTERED; } public void setAllowDelete(Boolean pAllowDelete) {wAllowDelete = pAllowDelete;} public Boolean getAllowUpdate() throws DBSIOException { return wAllowUpdate && pvApprovalUserAllowRegister() && getApprovalStage() == APPROVAL_STAGE.REGISTERED; } public void setAllowUpdate(Boolean pAllowUpdate) {wAllowUpdate = pAllowUpdate;} public Boolean getAllowInsert() { return wAllowInsert && pvApprovalUserAllowRegister(); } public void setAllowInsert(Boolean pAllowInsert) { wAllowInsert = pAllowInsert; setAllowCopy(pAllowInsert); } public Boolean getAllowRefresh() {return wAllowRefresh;} public void setAllowRefresh(Boolean pAllowRefresh) {wAllowRefresh = pAllowRefresh;} public Boolean getMultipleSelection() {return wMultipleSelection;} public void setMultipleSelection(Boolean pMultipleSelection) {wMultipleSelection = pMultipleSelection;} public Boolean getAllowApproval() {return wAllowApproval;} public void setAllowApproval(Boolean pAllowApproval) {wAllowApproval = pAllowApproval;} public Boolean getAllowApprove(){return wAllowApprove;} public void setAllowApprove(Boolean pAllowApprove){wAllowApprove = pAllowApprove;} public Boolean getAllowReprove(){return wAllowReprove;} public void setAllowReprove(Boolean pAllowReprove){wAllowReprove = pAllowReprove;} public Boolean getAllowCopy(){return wAllowCopy;} public void setAllowCopy(Boolean pAllowCopy){wAllowCopy = pAllowCopy;} public Boolean getAllowCopyOnUpdate(){return wAllowCopyOnUpdate;} public void setAllowCopyOnUpdate(Boolean pAllowCopyOnUpdate){wAllowCopyOnUpdate = pAllowCopyOnUpdate;} public APPROVAL_STAGE getApprovalStage() throws DBSIOException { return pvGetApprovalStage(true); } public APPROVAL_STAGE getApprovalStageListValue() throws DBSIOException { return pvGetApprovalStage(false); } public void setApprovalStage(APPROVAL_STAGE pApprovalStage) { setValue(getColumnNameApprovalStage(), pApprovalStage.getCode()); } public APPROVAL_STAGE getApprovalUserNextStage() throws DBSIOException{ return pvGetApprovalNextUserStage(); } public APPROVAL_STAGE getApprovalUserNextStageListValue() throws DBSIOException{ return pvGetApprovalNextUserStage(); } public APPROVAL_STAGE getApprovalUserMaxStage(){ return DBSApproval.getMaxStage(getApprovalUserStages()); } public Integer getApprovalUserStages() {return wApprovalUserStages;} public void setApprovalUserStages(Integer pApprovalUserStages) {wApprovalUserStages = pApprovalUserStages;} public Boolean getIsApprovalStageRegistered() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.REGISTERED; } public Boolean getIsApprovalStageVerified() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.VERIFIED; } public Boolean getIsApprovalStageConferred() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.CONFERRED; } public Boolean getIsApprovalStageApproved() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.APPROVED; } public String getColumnNameApprovalStage() {return wColumnNameApprovalStage;} public void setColumnNameApprovalStage(String pColumnNameApprovalStage) {wColumnNameApprovalStage = pColumnNameApprovalStage;} public String getColumnNameApprovalUserIdRegistered() {return wColumnNameApprovalUserIdRegistered;} public void setColumnNameApprovalUserIdRegistered(String pColumnNameApprovalUserIdRegistered) {wColumnNameApprovalUserIdRegistered = pColumnNameApprovalUserIdRegistered;} public String getColumnNameApprovalUserIdConferred() {return wColumnNameApprovalUserIdConferred;} public void setColumnNameApprovalUserIdConferred(String pColumnNameApprovalUserIdConferred) {wColumnNameApprovalUserIdConferred = pColumnNameApprovalUserIdConferred;} public String getColumnNameApprovalUserIdVerified() {return wColumnNameApprovalUserIdVerified;} public void setColumnNameApprovalUserIdVerified(String pColumnNameApprovalUserIdVerified) {wColumnNameApprovalUserIdVerified = pColumnNameApprovalUserIdVerified;} public String getColumnNameApprovalUserIdApproved() {return wColumnNameApprovalUserIdApproved;} public void setColumnNameApprovalUserIdApproved(String pColumnNameApprovalUserIdApproved) {wColumnNameApprovalUserIdApproved = pColumnNameApprovalUserIdApproved;} public String getColumnNameApprovalDateApproved() {return wColumnNameApprovalDateApproved;} public void setColumnNameApprovalDateApproved(String pColumnNameApprovalDateApproved) {wColumnNameApprovalDateApproved = pColumnNameApprovalDateApproved;} public String getColumnNameDateOnInsert() {return wColumnNameDateOnInsert;} public void setColumnNameDateOnInsert(String pColumnNameDateOnInsert) {wColumnNameDateOnInsert = pColumnNameDateOnInsert;} public String getColumnNameDateOnUpdate() {return wColumnNameDateOnUpdate;} public void setColumnNameDateOnUpdate(String pColumnNameDateOnUpdate) {wColumnNameDateOnUpdate = pColumnNameDateOnUpdate;} public String getColumnNameUserIdOnInsert() {return wColumnNameUserIdOnInsert;} public void setColumnNameUserIdOnInsert(String pColumnNameUserIdOnInsert) {wColumnNameUserIdOnInsert = pColumnNameUserIdOnInsert;} public String getColumnNameUserIdOnUpdate() {return wColumnNameUserIdOnUpdate;} public void setColumnNameUserIdOnUpdate(String pColumnNameUserIdOnUpdate) {wColumnNameUserIdOnUpdate = pColumnNameUserIdOnUpdate;} public void setSortColumn(String pSortColumn){wSortColumn = pSortColumn;} public String getSortColumn(){return wSortColumn;} public void setSortDirection(String pSortDirection){wSortDirection = pSortDirection;} public String getSortDirection(){return wSortDirection;} public Boolean getRevalidateBeforeCommit() {return wRevalidateBeforeCommit;} public void setRevalidateBeforeCommit(Boolean pRevalidateBeforeCommit) {wRevalidateBeforeCommit = pRevalidateBeforeCommit;} public Integer getUserId() {return wUserId;} public void setUserId(Integer pUserId) {wUserId = pUserId;} public void setParentCrudBean(DBSCrudBean pCrudBean) { wParentCrudBean = pCrudBean; if (!pCrudBean.getChildrenCrudBean().contains(this)){ pCrudBean.getChildrenCrudBean().add(this); } } public DBSCrudBean getParentCrudBean() { return wParentCrudBean; } public List<DBSCrudBean> getChildrenCrudBean() { return wChildrenCrudBean; } public void setValueChanged(Boolean pChanged){ wValueChanged = pChanged; } public boolean getIsValueChanged(){ return wValueChanged; } @Override public Boolean getIsCommitting(){ return (wEditingStage == EditingStage.COMMITTING); } @Override public Boolean getIsUpdating(){ return (wEditingMode == EditingMode.UPDATING); } public Boolean getIsEditing(){ return (wEditingMode != EditingMode.NONE); } @Override public Boolean getIsDeleting(){ return (wEditingMode == EditingMode.DELETING); } public Boolean getIsApproving(){ return (wEditingMode == EditingMode.APPROVING); } public Boolean getIsReproving(){ return (wEditingMode == EditingMode.REPROVING); } // public Boolean getIsApprovalStageApproved(Integer pApprovalStage){ // return DBSApproval.isApproved(pApprovalStage); // public Boolean getIsApprovalStageConferred(Integer pApprovalStage){ // return DBSApproval.isConferred(pApprovalStage); // public Boolean getIsApprovalStageVerified(Integer pApprovalStage){ // return DBSApproval.isVerified(pApprovalStage); // public Boolean getIsApprovalStageRegistered(Integer pApprovalStage){ // return DBSApproval.isRegistered(pApprovalStage); public Boolean getIsApprovingOrReproving(){ return (wEditingMode == EditingMode.APPROVING || wEditingMode == EditingMode.REPROVING); } @Override public Boolean getIsIgnoring(){ return (wEditingStage == EditingStage.IGNORING); } public Boolean getIsFirst(){ if (wDAO != null){ return wDAO.getIsFist(); }else{ return true; } } public Boolean getIsLast(){ if (wDAO != null){ return wDAO.getIsLast(); }else{ return true; } } public Boolean getIsViewing(){ return (wEditingMode == EditingMode.NONE); } @Override public Boolean getIsInserting(){ return (wEditingMode == EditingMode.INSERTING); } public Boolean getIsEditingDisabled(){ if (wAllowApproval || wAllowDelete || wAllowInsert || wAllowUpdate){ return false; } return true; } public void setDisableEditing(){ setAllowApproval(false); setAllowDelete(false); setAllowInsert(false); setAllowUpdate(false); } public Boolean getIsReadOnly(){ if (getIsViewing() || wEditingMode == EditingMode.DELETING){ return true; }else{ return false; } } public Boolean getIsClosed(){ return (!wDialogOpened); } /** * Se tem algumm registro copiado * @return */ public Boolean getIsCopied(){ if (wCopiedRowIndex != -1){ return true; }else{ return false; } } // Methods /** * Retorna lista dos itens selecionados * @return */ public List<Integer> getSelectedRowsIndexes(){ return wSelectedRowsIndexes; } public Boolean getSelected() throws DBSIOException { if (wSelectedRowsIndexes.contains(getList().getRowIndex())){ return true; } return false; } public void setSelected(Boolean pSelectOne) throws DBSIOException { // wDAO.synchronize(); pvSetSelected(pSelectOne); if (pvFireEventBeforeSelect()){ pvFireEventAfterSelect(); }else{ pvSetSelected(!pSelectOne); } } public boolean getHasSelected(){ if (wSelectedRowsIndexes != null){ if (wSelectedRowsIndexes.size()>0){ return true; } } return false; } /** * Selectiona todas as linhas que exibidas */ public synchronized String selectAll() throws DBSIOException{ if (!wDialogOpened){ pvSelectAll(); if (pvFireEventBeforeSelect()){ pvFireEventAfterSelect(); }else{ pvSelectAll(); } }else{ //exibir erro de procedimento } return DBSFaces.getCurrentView(); } // Methods public synchronized String confirmEditing() throws DBSIOException{ if (wEditingMode!=EditingMode.NONE){ if (wEditingStage==EditingStage.NONE){ if (wValidateComponentHasError){ wValidateComponentHasError = false; }else{ if ((getIsValueChanged() && getIsDeleting() == false) || getIsDeleting()){ if (pvFireEventBeforeValidate() && pvFireEventValidate()){ setEditingStage(EditingStage.COMMITTING); if (!getMessageConfirmationExists()){ return endEditing(true); } }else{ if(getIsDeleting() || getIsApprovingOrReproving()){ setEditingMode(EditingMode.NONE); } } }else{ addMessage(wMessageNoChange); } } }else{ //exibe mensagem de erro de procedimento } }else{ //exibe mensagem de erro de procedimento } return DBSFaces.getCurrentView(); } // Methods public synchronized String ignoreEditing() throws DBSIOException{ if (wEditingMode!=EditingMode.NONE){ if (wEditingStage==EditingStage.NONE){ //Disparado eventos antes de ignorar setEditingStage(EditingStage.IGNORING); if (!getIsValueChanged()){ return endEditing(true); } if (!getMessageIgnoreExists()){ return endEditing(true); } }else{ //exibe mensagem de erro de procedimento } }else{ //exibe mensagem de erro de procedimento } return DBSFaces.getCurrentView(); } @Override public synchronized String endEditing(Boolean pConfirm) throws DBSIOException{ try{ if (pConfirm){ if (wEditingStage!=EditingStage.NONE){ if (wEditingStage==EditingStage.COMMITTING){ //Disparando eventos if (pvFireEventValidate() && pvFireEventBeforeCommit()){ pvFireEventAfterCommit(); pvSearchList(); pvEndEditing(true); }else{ pvEndEditing(false); } }else if (wEditingStage==EditingStage.IGNORING){ //Disparando eventos if (pvFireEventBeforeIgnore()){ pvFireEventAfterIgnore(); pvEndEditing(true); }else{ pvEndEditing(false); } } }else{ //exibe mensagem de erro de procedimento } }else{ setEditingStage(EditingStage.NONE); switch(wEditingMode){ case UPDATING: break; case INSERTING: break; case DELETING: setEditingMode(EditingMode.NONE); view(); break; case APPROVING: setEditingMode(EditingMode.NONE); close(false); break; case REPROVING: setEditingMode(EditingMode.NONE); close(false); break; default: //Exibe mensagem de erro de procedimento } } }catch(Exception e){ wLogger.error("Crud:" + getDialogCaption() + ":endEditing", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } return DBSFaces.getCurrentView(); } public String beginEditingView() throws DBSIOException{ if (getFormStyle() != FormStyle.VIEW){ return DBSFaces.getCurrentView(); } if (getEditingMode() != EditingMode.NONE){ return DBSFaces.getCurrentView(); } try{ openConnection(); //Le o registro beforeRefresh(null); if (wConnection != null){ moveFirst(); //Verifica se existe registro corrente if (wDAO != null && wDAO.getCurrentRowIndex() > -1){ return update(); }else{ return insert(); } } return insert(); }finally{ if (wConnection != null){ closeConnection(); } } } // Methods public synchronized String searchList() throws DBSIOException{ boolean xOpenConnection = false; if (wParentCrudBean!=null && !DBSIO.isConnectionOpened(wParentCrudBean.wConnection)){ xOpenConnection = true; wParentCrudBean.openConnection(); } pvSearchList(); if (xOpenConnection){ wParentCrudBean.closeConnection(); } return DBSFaces.getCurrentView(); } public synchronized String refreshList() throws DBSIOException{ boolean xOpenConnection = false; if (wParentCrudBean!=null && !DBSIO.isConnectionOpened(wParentCrudBean.wConnection)){ xOpenConnection = true; wParentCrudBean.openConnection(); } pvFireEventInitialize(); if (xOpenConnection){ wParentCrudBean.closeConnection(); } return searchList(); } public synchronized String copy() throws DBSIOException{ if (wAllowCopy || wAllowCopyOnUpdate){ wCopiedRowIndex = wDAO.getCurrentRowIndex(); pvFireEventAfterCopy(); } return DBSFaces.getCurrentView(); } /** * Seta os valores atuais com os valores do registro copiado * @throws DBSIOException */ public synchronized String paste() throws DBSIOException{ if (wAllowCopy || wAllowCopyOnUpdate){ if (pvFireEventBeforePaste()){ //Seta o registro atual como sendo o registro copiado wDAO.paste(wCopiedRowIndex); setValueChanged(true); } } return DBSFaces.getCurrentView(); } /** * Exibe todos os itens selecionados */ public synchronized String viewSelection() throws DBSIOException{ if (wFormStyle == FormStyle.TABLE){return DBSFaces.getCurrentView();} //Limpa todas as mensagens que estiverem na fila clearMessages(); if (wDAO.getCurrentRowIndex() != -1){ if (!wDialogOpened){ if (wEditingStage==EditingStage.NONE){ //Chama evento if (pvFireEventBeforeView()){ setDialogOpened(true); pvFireEventAfterView(); } }else{ //exibir erro de procedimento } }else{ //exibir erro de procedimento } } return DBSFaces.getCurrentView(); } /** * Exibe o item selecionado */ public synchronized String view() throws DBSIOException{ if (wFormStyle == FormStyle.TABLE){return DBSFaces.getCurrentView();} if (wFormStyle == FormStyle.DIALOG){ //Limpa todas as mensagens que estiverem na fila clearMessages(); } if (wConnection != null && wDAO.getCurrentRowIndex()!=-1){ if (wEditingStage==EditingStage.NONE){ //Chama evento if (pvFireEventBeforeView()){ setDialogOpened(true); pvFireEventAfterView(); } }else{ //exibir erro de procedimento } }else{ //exibir erro de procedimento } return DBSFaces.getCurrentView(); } /** * Informa com cadastro foi fechado */ public synchronized String close() throws DBSIOException{ return close(true); } /** * Informa que cadastro foi fechado */ public synchronized String close(Boolean pClearMessage) throws DBSIOException{ if (wDialogOpened){ //Dispara evento if (pvFireEventBeforeClose()){ setDialogOpened(false); if (pClearMessage) { clearMessages(); } } //getLastInstance("a"); }else{ //exibe mensagem de erro de procedimento } return DBSFaces.getCurrentView(); } public synchronized String insertSelected() throws DBSIOException{ setDialogCloseAfterInsert(true); view(); copy(); insert(); paste(); wCopiedRowIndex = -1; return DBSFaces.getCurrentView(); } public synchronized void sort() throws DBSIOException{} public synchronized String insert() throws DBSIOException{ if (wAllowInsert || wDialogCloseAfterInsert){ if (!wDialogCloseAfterInsert){ if (wFormStyle == FormStyle.DIALOG){ clearMessages(); } } if (wFormStyle == FormStyle.TABLE && wEditingMode==EditingMode.UPDATING){ pvInsertEmptyRow(); }else{ if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeInsert() && pvFireEventBeforeEdit(EditingMode.INSERTING)){ //Desmarca registros selecionados wSelectedRowsIndexes.clear(); setEditingMode(EditingMode.INSERTING); setDialogOpened(true); }else{ setValueChanged(false); } // if (pvFireEventBeforeEdit(EditingMode.INSERTING)){ // //Desmarca registros selecionados // wSelectedRowsIndexes.clear(); // setEditingMode(EditingMode.INSERTING); // pvMoveBeforeFistRow(); // //Dispara evento BeforeInsert // if (pvFireEventBeforeInsert()){ // setDialogOpened(true); // }else{ // setValueChanged(false); // //exibe mensagem de erro de procedimento } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":insert", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } } return DBSFaces.getCurrentView(); } public synchronized String update() throws DBSIOException{ if (wAllowUpdate){ clearMessages(); if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.UPDATING)){ setEditingMode(EditingMode.UPDATING); pvInsertEmptyRow(); }else{ setValueChanged(false); //exibe mensagem de erro de procedimento } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":update", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } public synchronized String delete() throws DBSIOException{ if (wAllowDelete){ clearMessages(); if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.DELETING)){ setEditingMode(EditingMode.DELETING); confirmEditing(); //setEditingStage(EditingStage.COMMITTING); }else{ setValueChanged(false); //setEditingStage(EditingStage.COMMITTING); } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":delete", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } public synchronized String approve() throws DBSIOException{ if (wAllowApproval && wAllowApprove){ if (wUserId== null){ addMessage("UserId", MESSAGE_TYPE.ERROR,"DBSCrudBean: UserId - Não informado!"); return DBSFaces.getCurrentView(); } if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.APPROVING)){ setEditingMode(EditingMode.APPROVING); setValueChanged(true); confirmEditing(); }else{ setValueChanged(false); //exibe mensagem de erro de procedimento } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":approve", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } public synchronized String reprove() throws DBSIOException{ if (wAllowApproval && wAllowApprove){ if (wUserId== null){ addMessage("UserId", MESSAGE_TYPE.ERROR,"DBSCrudBean: UserId - Não informado!"); return DBSFaces.getCurrentView(); } if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.REPROVING)){ setEditingMode(EditingMode.REPROVING); setValueChanged(true); confirmEditing(); }else{ setValueChanged(false); //exibe mensagem de erro de procedimento } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":reprove", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } /** * Move para o primeiro registro. * @return * @throws DBSIOException */ public synchronized String moveFirst() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.moveFirstRow(); view(); } return DBSFaces.getCurrentView(); } /** * Move para o registro anterior * @return * @throws DBSIOException */ public synchronized String movePrevious() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.movePreviousRow(); view(); } return DBSFaces.getCurrentView(); } public synchronized String moveNext() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.moveNextRow(); view(); } return DBSFaces.getCurrentView(); } public synchronized String moveLast() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.moveLastRow(); view(); } return DBSFaces.getCurrentView(); } @Override protected void warningMessageValidated(String pMessageKey, Boolean pIsValidated) throws DBSIOException{ //Se mensagem de warning foi validade.. if (pIsValidated){ confirmEditing(); }else{ if (getEditingMode().equals(EditingMode.DELETING)){ ignoreEditing(); } } } @Override protected boolean openConnection() { if (wParentCrudBean == null){ if (!getIsEditing() && !wBrodcastingEvent){ super.openConnection(); if (wDAO !=null){ wDAO.setConnection(wConnection); } //Configura os crudbean filhos que possam existir pvBroadcastConnection(this); return true; } } return false; } @Override protected void closeConnection() { if (wParentCrudBean == null){ if (!getIsEditing() && !wBrodcastingEvent){ super.closeConnection(); //Configura os crudbean filhos que possam existir pvBroadcastConnection(this); } } } // Abstracted protected abstract void initialize(DBSCrudBeanEvent pEvent) throws DBSIOException; protected void finalize(DBSCrudBeanEvent pEvent){}; protected void beforeClose(DBSCrudBeanEvent pEvent) throws DBSIOException {} ; protected void beforeRefresh(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void afterRefresh(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforeEdit(DBSCrudBeanEvent pEvent) throws DBSIOException {}; protected void afterEdit(DBSCrudBeanEvent pEvent) throws DBSIOException {}; protected void beforeInsert(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforeView(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void afterView(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforeCommit(DBSCrudBeanEvent pEvent) throws DBSIOException { //Copia dos valores pois podem ter sido alterados durante o beforecommit if (wConnection == null){return;} if (getIsApprovingOrReproving()){ pvBeforeCommitSetAutomaticColumnsValues(pEvent); if (pEvent.isOk()){ pEvent.setCommittedRowCount(wDAO.executeUpdate()); }else{ return; } //Insert/Update/Delete }else{ pvBeforeCommitSetAutomaticColumnsValues(pEvent); if (pEvent.isOk()){ //Insert if(getIsInserting()){ if (wDAO.isAutoIncrementPK()){ wDAO.setValue(wDAO.getPK(), null); } pEvent.setCommittedRowCount(wDAO.executeInsert()); //Update }else if (getIsUpdating()){ if (wFormStyle == FormStyle.TABLE && wDAO.getIsNewRow()){ pEvent.setCommittedRowCount(wDAO.executeInsert()); }else{ pEvent.setCommittedRowCount(wDAO.executeUpdate()); } //Delete }else if(getIsDeleting()){ pEvent.setCommittedRowCount(wDAO.executeDelete()); } } } } protected void afterCommit(DBSCrudBeanEvent pEvent) throws DBSIOException {} protected void beforeIgnore(DBSCrudBeanEvent pEvent) throws DBSIOException {} protected void afterIgnore(DBSCrudBeanEvent pEvent){} protected void beforeSelect(DBSCrudBeanEvent pEvent) throws DBSIOException {} protected void afterSelect(DBSCrudBeanEvent pEvent){} protected void beforeValidate(DBSCrudBeanEvent pEvent) throws DBSIOException{} protected void validate(DBSCrudBeanEvent pEvent) throws DBSIOException{} protected void afterCopy(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforePaste(DBSCrudBeanEvent pEvent) throws DBSIOException{}; private void pvConversationBegin(){ // if (!FacesContext.getCurrentInstance().isPostback() && wConversation.isTransient()){ if (wConversation.isTransient()){ wConversation.begin(); wConversation.setTimeout(wConversationTimeout); } } /** * Atualiza dados da lista e dispara os eventos beforeRefresh e afterRefresh.<br/> * @throws DBSIOException */ private void pvSearchList() throws DBSIOException{ if (getEditingMode() == EditingMode.UPDATING){ ignoreEditing(); } //Dispara evento para atualizar os dados if (pvFireEventBeforeRefresh()){ //Apaga itens selecionados, se houver. wSelectedRowsIndexes.clear(); pvFireEventAfterRefresh(); } } private void pvEndEditing(Boolean pOk) throws DBSIOException{ switch(wEditingMode){ case UPDATING: if (wEditingStage==EditingStage.IGNORING){ setEditingMode(EditingMode.NONE); pvRestoreValuesOriginal(); pvSearchList(); view(); }else{ if (pOk){ setEditingMode(EditingMode.NONE); view(); }else{ setEditingStage(EditingStage.NONE); } } break; case INSERTING: if (pOk){ if (wEditingStage==EditingStage.IGNORING || wDialogCloseAfterInsert){ setEditingMode(EditingMode.NONE); close(); }else{ setEditingMode(EditingMode.NONE); if (getFormStyle() == FormStyle.VIEW){ view(); }else{ insert(); } } }else{ setEditingStage(EditingStage.NONE); } break; case DELETING: if (wEditingStage==EditingStage.IGNORING){ setEditingMode(EditingMode.NONE); }else{ wCopiedRowIndex = -1; setEditingMode(EditingMode.NONE); if (pOk){ setDialogOpened(false); } } break; case APPROVING: setEditingMode(EditingMode.NONE); setEditingStage(EditingStage.NONE); close(false); break; case REPROVING: setEditingMode(EditingMode.NONE); setEditingStage(EditingStage.NONE); close(false); break; default: setEditingMode(EditingMode.NONE); //Exibe mensagem de erro de procedimento } } private void pvRestoreValuesOriginal(){ wDAO.restoreValuesOriginal(); } /** * Move para o registro anterior ao primeiro registro. * @throws DBSIOException */ private void pvMoveBeforeFistRow() throws DBSIOException{ wDAO.moveBeforeFirstRow(); } private void pvInsertEmptyRow() throws DBSIOException{ if (wFormStyle != FormStyle.TABLE || wEditingMode != EditingMode.UPDATING || !wAllowInsert){ return; } wDAO.insertEmptyRow(); pvFireEventBeforeInsert(); } private DBSColumn pvGetDAOColumnFromInputValueExpression(DBSUIInput pInput){ String xColumnName = DBSFaces.getAttibuteNameFromInputValueExpression(pInput).toLowerCase(); if (xColumnName!=null && !xColumnName.equals("")){ //Retira do os prefixos controlados pelo sistema para encontrar o nome da coluna if (xColumnName.startsWith(DBSSDK.UI.ID_PREFIX.FIELD_CRUD.getName())){ xColumnName = xColumnName.substring(DBSSDK.UI.ID_PREFIX.FIELD_CRUD.getName().length()); }else if (xColumnName.startsWith(DBSSDK.UI.ID_PREFIX.FIELD_AUX.getName())){ xColumnName = xColumnName.substring(DBSSDK.UI.ID_PREFIX.FIELD_AUX.getName().length()); } if (wDAO.containsColumn(xColumnName)){ return wDAO.getColumn(xColumnName); } } return null; } private void pvBroadcastConnection(DBSCrudBean pBean){ for (DBSCrudBean xChildBean:pBean.getChildrenCrudBean()){ Connection xCn = xChildBean.getConnection(); if (!xCn.equals(pBean.getConnection())){ DBSIO.closeConnection(xCn); xChildBean.setConnection(pBean.getConnection()); } //Procura pelos netos pvBroadcastConnection(xChildBean); } } /** * Salva indice do linha selacionada * @param pSelectOne * @throws DBSIOException */ private void pvSetSelected(Boolean pSelectOne) throws DBSIOException{ Integer xRowIndex = getList().getRowIndex(); if (pSelectOne){ if (wFormStyle == FormStyle.TABLE){ setValueChanged(true); } if (!wSelectedRowsIndexes.contains(xRowIndex)){ wSelectedRowsIndexes.add(xRowIndex); } }else{ if (wSelectedRowsIndexes.contains(xRowIndex)){ wSelectedRowsIndexes.remove(xRowIndex); } } } private void pvSelectAll() throws DBSIOException{ for (Integer xX = 0; xX < getList().getRowCount(); xX++){ if (wSelectedRowsIndexes.contains(xX)){ wSelectedRowsIndexes.remove(xX); }else{ wSelectedRowsIndexes.add(xX); } } } /** * Seta o valor da coluna no DAO * @param pColumnName * @param pColumnValue */ private void pvSetValueDAO(String pColumnName, Object pColumnValue){ //Utiliza ListValue para controlar os valores de todas as linhas if (wDAO != null && (wDAO.getColumns().size() > 0 || wDAO.getCommandColumns().size() > 0)){ Object xOldValue = pvGetValue(pColumnName); if (pColumnValue != null){ xOldValue = DBSObject.toClassValue(xOldValue, pColumnValue.getClass()); } if(!DBSObject.getNotNull(xOldValue,"").toString().equals(DBSObject.getNotNull(pColumnValue,"").toString())){ if (getEditingMode() == EditingMode.INSERTING && getDialogOpened()){ wLogger.info("ALTERADO:" + pColumnName + "[" + DBSObject.getNotNull(xOldValue,"") + "] para [" + DBSObject.getNotNull(pColumnValue,"") + "]"); } //marca como valor alterado setValueChanged(true); wDAO.setValue(pColumnName, pColumnValue); } } } /** * Retorna valor da coluna a partir do DAO * @param pColumnName * @return */ @SuppressWarnings("unchecked") private <T> T pvGetValue(String pColumnName){ //Se existir registro corrente if (wDAO != null && (wDAO.getColumns().size() > 0 || wDAO.getCommandColumns().size() > 0)){ return (T) wDAO.getValue(pColumnName); }else{ return null; } } private APPROVAL_STAGE pvGetApprovalStage(boolean pFromValue){ if (!getAllowApproval()){ return APPROVAL_STAGE.REGISTERED; } APPROVAL_STAGE xStage; if (pFromValue){ xStage = APPROVAL_STAGE.get(getValue(getColumnNameApprovalStage())); }else{ xStage = APPROVAL_STAGE.get(getListValue(getColumnNameApprovalStage())); } if (xStage==null){ xStage = APPROVAL_STAGE.REGISTERED; } return xStage; } private boolean pvApprovalUserAllowRegister(){ if (getAllowApproval() && !DBSApproval.isRegistered(getApprovalUserStages())){ return false; } return true; } private Integer pvGetApprovalNextUserStages() throws DBSIOException{ return DBSApproval.getNextUserStages(getApprovalStage(), getApprovalUserStages()); } private APPROVAL_STAGE pvGetApprovalNextUserStage() throws DBSIOException{ return DBSApproval.getMaxStage(pvGetApprovalNextUserStages()); } private void pvBeforeCommitSetAutomaticColumnsValues(DBSCrudBeanEvent pEvent) throws DBSIOException{ DBSColumn xColumn = null; //Delete if(wConnection == null || getIsDeleting()){ return; } //Configura os valores das assinaturas se assinatura estive habilitada. if (getAllowApproval()){ pvBeforeCommitSetAutomaticColumnsValuesApproval(pEvent); } //Insert if(getIsInserting()){ xColumn = wDAO.getCommandColumn(getColumnNameUserIdOnInsert()); if (xColumn!=null){ xColumn.setValue(getUserId()); } xColumn = wDAO.getCommandColumn(getColumnNameDateOnInsert()); if (xColumn!=null){ xColumn.setValue(DBSDate.getNowDateTime()); } //Update }else if (getIsUpdating()){ xColumn = wDAO.getCommandColumn(getColumnNameUserIdOnUpdate()); if (xColumn!=null){ xColumn.setValue(getUserId()); } xColumn = wDAO.getCommandColumn(getColumnNameDateOnUpdate()); if (xColumn!=null){ xColumn.setValue(DBSDate.getNowDateTime()); } } } private void pvBeforeCommitSetAutomaticColumnsValuesApproval(DBSCrudBeanEvent pEvent) throws DBSIOException{ DBSColumn xColumn = null; APPROVAL_STAGE xApprovalNextStage = null; Integer xUserId = null; Timestamp xApprovalDate = null; Integer xApprovalNextUserStages = null; xUserId = getUserId(); xApprovalDate = DBSDate.getNowTimestamp(); if (getIsApproving()){ xApprovalNextUserStages = pvGetApprovalNextUserStages(); xApprovalNextStage = pvGetApprovalNextUserStage(); }else if (getIsReproving()){ xApprovalNextUserStages = DBSApproval.getApprovalStage(false, true, true, true); xApprovalNextStage = APPROVAL_STAGE.REGISTERED; xUserId = null; xApprovalDate = null; }else if(getIsInserting() || getIsUpdating()){ xApprovalNextStage = APPROVAL_STAGE.REGISTERED; xApprovalNextUserStages = APPROVAL_STAGE.REGISTERED.getCode(); } if (xApprovalNextStage==APPROVAL_STAGE.REGISTERED){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdRegistered()); if (xColumn!=null){xColumn.setValue(getUserId());} }else{ if (DBSApproval.isConferred(xApprovalNextUserStages)){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdConferred()); if (xColumn!=null){xColumn.setValue(xUserId);} } if (DBSApproval.isVerified(xApprovalNextUserStages)){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdVerified()); if (xColumn!=null){xColumn.setValue(xUserId);} } if (DBSApproval.isApproved(xApprovalNextUserStages)){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdRegistered()); if (xColumn!=null){ if (DBSNumber.toInteger(xColumn.getValue()).equals(xUserId)){ addMessage(wMessaggeApprovalSameUser); pEvent.setOk(false); return; } } xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdApproved()); if (xColumn!=null){xColumn.setValue(xUserId);} xColumn = wDAO.getCommandColumn(getColumnNameApprovalDateApproved()); if (xColumn!=null){xColumn.setValue(xApprovalDate);} } } setApprovalStage(xApprovalNextStage); } private void pvCurrentRowSave(){ wSavedCurrentColumns = null; if (wDAO != null){ wSavedCurrentColumns = wDAO.getCommandColumns(); //utiliza as colunas da query if (wDAO.getCommandColumns() == null || wDAO.getCommandColumns().size() == 0){ wSavedCurrentColumns = wDAO.getColumns(); } } } private void pvCurrentRowRestore() throws DBSIOException{ boolean xOk; Object xSavedValue = null; Object xCurrentValue = null; BigDecimal xSavedNumberValue = null; BigDecimal xCurrentNumberValue = null; boolean xEqual; if (wDAO != null){ wDAO.moveBeforeFirstRow(); if (wSavedCurrentColumns !=null && wSavedCurrentColumns.size() > 0 && wDAO.getResultDataModel() != null){ DBSResultDataModel xQueryRows = wDAO.getResultDataModel(); for (int xRowIndex = 0; xRowIndex <= xQueryRows.getRowCount()-1; xRowIndex++){ xQueryRows.setRowIndex(xRowIndex); xOk = true; //Loop por todas as colunas da linha da query for (String xQueryColumnName:xQueryRows.getRowData().keySet()){ Object xQueryColumnValue = xQueryRows.getRowData().get(xQueryColumnName); //Procura pelo coluna que possua o mesmo nome for (DBSColumn xColumnSaved: wSavedCurrentColumns){ if (xColumnSaved.getColumnName().equalsIgnoreCase(xQueryColumnName)){ xSavedValue = DBSObject.getNotNull(xColumnSaved.getValue(),""); xCurrentValue = DBSObject.getNotNull(xQueryColumnValue,""); xEqual = false; if (xCurrentValue == null && xSavedValue == null){ xEqual = true; }else if (xCurrentValue instanceof Number){ xCurrentNumberValue = DBSNumber.toBigDecimal(xCurrentValue); if (xSavedValue instanceof Number){ xSavedNumberValue = DBSNumber.toBigDecimal(xSavedValue); } if (xSavedNumberValue != null && xCurrentNumberValue != null){ if (xCurrentNumberValue.compareTo(xSavedNumberValue) == 0){ xEqual = true; } } }else{ xEqual = xSavedValue.equals(xCurrentValue); } if (!xEqual){ xOk = false; } break; } } if (!xOk){ break; } } if (xOk){ return; } } if (wDAO != null){ wDAO.moveFirstRow(); } } } } // private void pvCurrentRowRestore() throws DBSIOException{ // boolean xOk; // Integer xRowIndex; // Object xSavedValue = null; // Object xCurrentValue = null; // BigDecimal xSavedNumberValue = null; // BigDecimal xCurrentNumberValue = null; // boolean xEqual; // if (wDAO != null // && wSavedCurrentColumns !=null // && wSavedCurrentColumns.size() > 0 // && wDAO.getResultDataModel() != null){ // //Recupera todas as linhas // Iterator<SortedMap<String, Object>> xIR = wDAO.getResultDataModel().iterator(); // xRowIndex = -1; // while (xIR.hasNext()){ // xOk = true; // xRowIndex++; // //Recupera todas as colunas da linha // SortedMap<String, Object> xColumns = xIR.next(); // //Loop por todas as colunas da linha // for (Entry<String, Object> xC:xColumns.entrySet()){ // Iterator<DBSColumn> xIS = wSavedCurrentColumns.iterator(); // //Procura pelo coluna que possua o mesmo nome // while (xIS.hasNext()){ // DBSColumn xSC = xIS.next(); // if (xSC.getColumnName().equalsIgnoreCase(xC.getKey())){ // xSavedValue = DBSObject.getNotNull(xSC.getValue(),""); // xCurrentValue = DBSObject.getNotNull(xC.getValue(),""); // xEqual = false; // if (xCurrentValue == null // && xSavedValue == null){ // xEqual = true; // }else if (xCurrentValue instanceof Number){ // xCurrentNumberValue = DBSNumber.toBigDecimal(xCurrentValue); // if (xSavedValue instanceof Number){ // xSavedNumberValue = DBSNumber.toBigDecimal(xSavedValue); // if (xSavedNumberValue != null // && xCurrentNumberValue != null){ // if (xCurrentNumberValue.compareTo(xSavedNumberValue) == 0){ // xEqual = true; // }else{ // xEqual = xSavedValue.equals(xCurrentValue); // if (!xEqual){ // xOk = false; // break; // if (!xOk){ // break; // if (xOk){ // wDAO.setCurrentRowIndex(xRowIndex); // return; //// if (wParentCrudBean == null){ // if (wDAO != null){ // wDAO.moveFirstRow(); private void pvFireEventInitialize(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.INITIALIZE, getEditingMode()); try { pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventInitialize",e); } } private void pvFireEventFinalize(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.FINALIZE, getEditingMode()); try { pvBroadcastEvent(xE, false, false, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventFinalize",e); } } private boolean pvFireEventBeforeClose(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_CLOSE, getEditingMode()); try { pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeClose",e); } return xE.isOk(); } private boolean pvFireEventBeforeView(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_VIEW, getEditingMode()); try { pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeView",e); } return xE.isOk(); } private void pvFireEventAfterView(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_VIEW, getEditingMode()); setValueChanged(false); try { pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterView",e); } } private boolean pvFireEventBeforeInsert() throws DBSIOException{ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_INSERT, getEditingMode()); if (wDAO != null){ openConnection(); pvMoveBeforeFistRow(); closeConnection(); } // pvBeforeInsertResetValues(wCrudForm); try { pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeInsert",e); } setValueChanged(false); return xE.isOk(); } private boolean pvFireEventBeforeEdit(EditingMode pEditingMode){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_EDIT, pEditingMode); setValueChanged(false); try{ pvBroadcastEvent(xE, false, true, false); return xE.isOk(); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeEdit",e); } return xE.isOk(); } private boolean pvFireEventAfterEdit(EditingMode pEditingMode){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_EDIT, pEditingMode); try{ pvBroadcastEvent(xE, false, false, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterEdir",e); } return xE.isOk(); } private boolean pvFireEventBeforeRefresh(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_REFRESH, getEditingMode()); try{ pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeRefresh",e); } return xE.isOk(); } private void pvFireEventAfterRefresh(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_REFRESH, getEditingMode()); try{ pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventInitialize",e); } } private boolean pvFireEventBeforeIgnore(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_IGNORE, getEditingMode()); try{ pvBroadcastEvent(xE, false, false, false); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeIgnore",e); } return xE.isOk(); } private void pvFireEventAfterIgnore(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_IGNORE, getEditingMode()); try{ pvBroadcastEvent(xE, false, false, false); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterIgnore",e); } } private boolean pvFireEventBeforeValidate(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_VALIDATE, getEditingMode()); try{ if (getIsApprovingOrReproving() || wFormStyle == FormStyle.TABLE){ if (getHasSelected()){ wDAO.setCurrentRowIndex(-1); for (Integer xRowIndex : wSelectedRowsIndexes){ wDAO.setCurrentRowIndex(xRowIndex); pvBroadcastEvent(xE, false, false, false); } }else{ xE.setOk(false); addMessage("erroselecao", MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.notSelected")); } }else{ pvBroadcastEvent(xE, false, false, false); } } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeValidate",e); } return xE.isOk(); } private boolean pvFireEventValidate(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.VALIDATE, getEditingMode()); try{ if (getIsApprovingOrReproving() || wFormStyle == FormStyle.TABLE){ if (getHasSelected()){ wDAO.setCurrentRowIndex(-1); for (Integer xRowIndex : wSelectedRowsIndexes){ wDAO.setCurrentRowIndex(xRowIndex); pvBroadcastEvent(xE, false, false, false); if (!xE.isOk()){ if (getIsApprovingOrReproving()){ addMessage("erroassinatura", MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.approvalAll")); break; }else{ addMessage("erroselecao", MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.editAll")); break; } } } }else{ xE.setOk(false); addMessage("erroselecao", MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.notSelected")); } }else{ pvBroadcastEvent(xE, false, false, false); } } catch (Exception e) { xE.setOk(false); wLogger.error("EventValidate",e); } return xE.isOk(); } private boolean pvFireEventBeforeCommit(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_COMMIT, getEditingMode()); String xErrorMsg = null; //Chame o metodo(evento) local para quando esta classe for extendida try { //Zera a quantidade de registros afetados xE.setCommittedRowCount(0); if (wConnection != null){ wDAO.setConnection(wConnection); //Se for o crud principal if (wParentCrudBean == null){ DBSIO.beginTrans(wConnection); } } if (getIsApprovingOrReproving() || wFormStyle == FormStyle.TABLE){ if (getHasSelected()){ int xCount = 0; wDAO.setCurrentRowIndex(-1); for (Integer xRowIndex : wSelectedRowsIndexes){ wDAO.setCurrentRowIndex(xRowIndex); if (wFormStyle == FormStyle.TABLE){ wDAO.setExecuteOnlyChangedValues(false); } pvBroadcastEvent(xE, false, false, false); xCount += xE.getCommittedRowCount(); if (!xE.isOk()){ break; } } //Ignora assinatura caso quantidade todal de registros afetados seja inferior a quantidade de itens selectionados if (xCount < wSelectedRowsIndexes.size()){ xE.setCommittedRowCount(0); xE.setOk(false); addMessage("erroassinatura", MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.approvelAll")); }else{ xE.setCommittedRowCount(xCount); } } }else{ pvBroadcastEvent(xE, false, false, false); } if (!wMessages.hasMessages() && (!xE.isOk() || (wConnection != null && xE.getCommittedRowCount().equals(0)))){ xE.setOk(false); addMessage(wMessageNoRowComitted); } //Se for o crud principal if (wConnection != null){ if (wParentCrudBean == null){ DBSIO.endTrans(wConnection, xE.isOk()); } } } catch (Exception e) { xE.setOk(false); try { //Se for o crud principal if (wConnection != null){ if (wParentCrudBean == null){ DBSIO.endTrans(wConnection, false); } } if (e instanceof DBSIOException){ DBSIOException xDBException = (DBSIOException) e; xErrorMsg = e.getMessage(); if (xDBException.isIntegrityConstraint()){ clearMessages(); // addMessage("integridate", MESSAGE_TYPE.ERROR, xDBException.getLocalizedMessage()); }else{ wLogger.error("EventBeforeCommit", e); } wMessageError.setMessageText(xDBException.getLocalizedMessage()); wMessageError.setMessageTooltip(xErrorMsg); addMessage(wMessageError); }else{ wMessageError.setMessageText(DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.support")); wMessageError.setMessageTooltip(e.getLocalizedMessage()); addMessage(wMessageError); } } catch (DBSIOException e1) { xErrorMsg = e1.getMessage(); } wMessageNoRowComitted.setMessageTooltip(xErrorMsg); addMessage(wMessageNoRowComitted); } return xE.isOk(); } private void pvFireEventAfterCommit(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_COMMIT, getEditingMode()); try{ pvBroadcastEvent(xE, false, false, false); if (wParentCrudBean!=null){ wParentCrudBean.setValueChanged(true); } } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterCommit",e); } } private boolean pvFireEventBeforeSelect(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_SELECT, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeIgnore",e); } return xE.isOk(); } private void pvFireEventAfterSelect(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_SELECT, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterIgnore",e); } } private void pvFireEventAfterCopy(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_COPY, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterCopy",e); } } /** * Disparado antes do paste. * @return */ private boolean pvFireEventBeforePaste(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_PASTE, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforePaste",e); } return xE.isOk(); } private void pvBroadcastEvent(DBSCrudBeanEvent pEvent, boolean pInvokeChildren, boolean pOpenConnection, boolean pCloseConnection) throws Exception { try{ if (pOpenConnection){ openConnection(); } wBrodcastingEvent = true; pvFireEventLocal(pEvent); if (pInvokeChildren){ pvFireEventChildren(pEvent); } pvFireEventListeners(pEvent); }catch(DBSIOException e){ wMessageError.setMessageText(e.getLocalizedMessage()); wMessageError.setMessageTooltip(e.getOriginalException().getLocalizedMessage()); if (!DBSObject.isEmpty(e.getCause())){ wMessageError.setMessageTooltip(e.getCause().getMessage() + "<br/>" + e.getMessage()); } addMessage(wMessageError); pEvent.setOk(false); // wLogger.error(pEvent.getEvent().toString(), e); }catch(Exception e){ String xStr = pEvent.getEvent().toString() + ":" + DBSObject.getNotNull(this.getDialogCaption(),"") + ":"; if (e.getLocalizedMessage()!=null){ xStr = xStr + e.getLocalizedMessage(); }else{ xStr = xStr + e.getClass(); } wMessageError.setMessageTextParameters(xStr); addMessage(wMessageError); pEvent.setOk(false); wLogger.error(pEvent.getEvent().toString(), e); throw e; }finally{ wBrodcastingEvent = false; if (pCloseConnection || !pEvent.isOk()){ closeConnection(); } } } private void pvFireEventLocal(DBSCrudBeanEvent pEvent) throws DBSIOException{ if (pEvent.isOk()){ switch (pEvent.getEvent()) { case INITIALIZE: initialize(pEvent); break; case FINALIZE: finalize(pEvent); break; case BEFORE_CLOSE: beforeClose(pEvent); break; case BEFORE_VIEW: beforeView(pEvent); break; case AFTER_VIEW: afterView(pEvent); break; case BEFORE_INSERT: beforeInsert(pEvent); break; case BEFORE_REFRESH: pvCurrentRowSave(); beforeRefresh(pEvent); pvCurrentRowRestore(); break; case AFTER_REFRESH: afterRefresh(pEvent); break; case BEFORE_COMMIT: beforeCommit(pEvent); break; case AFTER_COMMIT: afterCommit(pEvent); break; case BEFORE_IGNORE: beforeIgnore(pEvent); break; case AFTER_IGNORE: afterIgnore(pEvent); break; case BEFORE_EDIT: beforeEdit(pEvent); break; case AFTER_EDIT: afterEdit(pEvent); break; case BEFORE_SELECT: beforeSelect(pEvent); break; case AFTER_SELECT: afterSelect(pEvent); break; case BEFORE_VALIDATE: beforeValidate(pEvent); break; case VALIDATE: validate(pEvent); break; case AFTER_COPY: afterCopy(pEvent); break; case BEFORE_PASTE: beforePaste(pEvent); break; default: break; } } } /** * Dispara o evento nos beans vinculados a este bean * @param pEvent * @throws DBSIOException */ private void pvFireEventChildren(DBSCrudBeanEvent pEvent) throws DBSIOException{ if (pEvent.isOk()){ //Busca por beans vinculados e este bean for (DBSCrudBean xBean:wChildrenCrudBean){ if (pEvent.getEvent() == CRUD_EVENT.BEFORE_VIEW || pEvent.getEvent() == CRUD_EVENT.BEFORE_INSERT){ xBean.searchList(); } switch (pEvent.getEvent()) { case INITIALIZE: xBean.initialize(pEvent); break; case FINALIZE: xBean.finalize(pEvent); break; case BEFORE_CLOSE: xBean.beforeClose(pEvent); break; case BEFORE_VIEW: xBean.beforeView(pEvent); break; case AFTER_VIEW: xBean.afterView(pEvent); break; case BEFORE_INSERT: xBean.beforeInsert(pEvent); break; case BEFORE_REFRESH: xBean.beforeRefresh(pEvent); break; case AFTER_REFRESH: xBean.afterRefresh(pEvent); break; case BEFORE_COMMIT: xBean.beforeCommit(pEvent); break; case AFTER_COMMIT: xBean.afterCommit(pEvent); break; case BEFORE_IGNORE: xBean.beforeIgnore(pEvent); break; case AFTER_IGNORE: xBean.afterIgnore(pEvent); break; case BEFORE_EDIT: xBean.beforeEdit(pEvent); break; case AFTER_EDIT: xBean.afterEdit(pEvent); break; case BEFORE_SELECT: xBean.beforeSelect(pEvent); break; case AFTER_SELECT: xBean.afterSelect(pEvent); break; case BEFORE_VALIDATE: xBean.beforeValidate(pEvent); break; case VALIDATE: xBean.validate(pEvent); break; case AFTER_COPY: xBean.afterCopy(pEvent); break; case BEFORE_PASTE: xBean.beforePaste(pEvent); break; default: break; } if (!pEvent.isOk()){ break; } } } } private void pvFireEventListeners(DBSCrudBeanEvent pEvent) throws DBSIOException{ if (pEvent.isOk()){ for (int xX=0; xX<wEventListeners.size(); xX++){ switch (pEvent.getEvent()) { case INITIALIZE: wEventListeners.get(xX).initialize(pEvent); break; case FINALIZE: wEventListeners.get(xX).finalize(pEvent); break; case BEFORE_CLOSE: wEventListeners.get(xX).beforeClose(pEvent); break; case BEFORE_VIEW: wEventListeners.get(xX).beforeView(pEvent); break; case AFTER_VIEW: wEventListeners.get(xX).afterView(pEvent); break; case BEFORE_REFRESH: wEventListeners.get(xX).beforeRefresh(pEvent); break; case BEFORE_INSERT: wEventListeners.get(xX).beforeInsert(pEvent); break; case AFTER_REFRESH: wEventListeners.get(xX).afterRefresh(pEvent); break; case BEFORE_COMMIT: wEventListeners.get(xX).beforeCommit(pEvent); break; case AFTER_COMMIT: wEventListeners.get(xX).afterCommit(pEvent); break; case BEFORE_IGNORE: wEventListeners.get(xX).beforeIgnore(pEvent); break; case AFTER_IGNORE: wEventListeners.get(xX).afterIgnore(pEvent); break; case BEFORE_EDIT: wEventListeners.get(xX).beforeEdit(pEvent); break; case AFTER_EDIT: wEventListeners.get(xX).afterEdit(pEvent); break; case BEFORE_SELECT: wEventListeners.get(xX).beforeSelect(pEvent); break; case AFTER_SELECT: wEventListeners.get(xX).afterSelect(pEvent); break; case BEFORE_VALIDATE: wEventListeners.get(xX).beforeValidate(pEvent); break; case VALIDATE: wEventListeners.get(xX).validate(pEvent); break; case AFTER_COPY: wEventListeners.get(xX).afterCopy(pEvent); break; case BEFORE_PASTE: wEventListeners.get(xX).beforePaste(pEvent); break; default: break; } //Sa do loop se encontrar erro if (!pEvent.isOk()){ break; } } } } }
package ch.bind.philib.util; import java.util.Arrays; import ch.bind.philib.util.ClusteredIndex.Entry; import ch.bind.philib.validation.Validation; // TODO: round tablesize up (2^x) and use bitmasks // TODO: strengthen hashcodes through an avalanche phase // TODO: concurrent version public final class ClusteredHashIndex<K, T extends Entry<K>> implements ClusteredIndex<K, T> { private final Entry<K>[] table; @SuppressWarnings("unchecked") public ClusteredHashIndex(int capacity) { table = new Entry[capacity]; } @Override public boolean add(final T entry) { Validation.isTrue(entry != null && entry.getNextIndexEntry() == null && entry.getKey() != null, "newly added entries must not be null and cleared"); final K key = entry.getKey(); final int hash = key.hashCode(); final int position = hashPosition(hash); Entry<K> scanNow = table[position]; if (scanNow == null) { table[position] = entry; return true; } Entry<K> scanPrev = null; do { K nowKey = scanNow.getKey(); if (hash == nowKey.hashCode() && key.equals(nowKey)) { // key is already in the table return false; } scanPrev = scanNow; scanNow = scanNow.getNextIndexEntry(); } while (scanNow != null); assert (scanPrev != null); scanPrev.setNextIndexEntry(entry); return true; } @Override public boolean remove(final T entry) { Validation.notNull(entry); final K key = entry.getKey(); final int hash = key.hashCode(); final int position = hashPosition(hash); Entry<K> scanPrev = null; Entry<K> scanNow = table[position]; while (scanNow != null && scanNow != entry) { scanPrev = scanNow; scanNow = scanNow.getNextIndexEntry(); } if (scanNow == entry) { if (scanPrev == null) { // first entry in the table table[position] = entry.getNextIndexEntry(); } else { // there are entries before this one scanPrev.setNextIndexEntry(entry.getNextIndexEntry()); } entry.setNextIndexEntry(null); return true; // entry found and removed } return false; // entry not found } // returns null if a pair does not exist @Override @SuppressWarnings("unchecked") public T get(final K key) { Validation.notNull(key); final int hash = key.hashCode(); final int position = hashPosition(hash); Entry<K> entry = table[position]; while (entry != null) { K entryKey = entry.getKey(); if (hash == entryKey.hashCode() && key.equals(entryKey)) { return (T) entry; } entry = entry.getNextIndexEntry(); } return null; } private int hashPosition(int hash) { int p = hash % table.length; return Math.abs(p); } @Override public void clear() { for (Entry<K> e : table) { while (e != null) { Entry<K> next = e.getNextIndexEntry(); e.setNextIndexEntry(null); e = next; } } Arrays.fill(table, null); } }
package ch.eiafr.cojac.interval; import ch.eiafr.cojac.Methods; public class DoubleInterval implements Comparable<DoubleInterval> { private double inf; private double sup; private boolean isNan; /** * Constructor * @param inf need to be smaller than sup * @param sup need to be bigger than inf */ public DoubleInterval(double inf, double sup) { if(Double.isNaN(inf) || Double.isNaN(sup)) { this.isNan = true; } else { this.inf = inf; this.sup = sup; this.isNan = false; } } /** * Constructor * @param value value of the created interval, same has new DoubleInterval(a,a); */ public DoubleInterval(double value) { if(Double.isNaN(inf) || Double.isNaN(sup)) { this.isNan = true; } else { this.inf = this.sup = value; this.isNan = false; } } /** * @param o another DoubleInterval to be compared with this * * @return * - 1 if this is absolutely bigger than o * - 0 if there is some shared region * - -1 if this is absolutely smaller than o */ @Override public int compareTo(DoubleInterval o) { if(this.isNan && o.isNan) { return 0; } if(this.isNan) { return -1; } if(o.isNan) { return 1; } if(o.sup < this.inf) { return 1; } if(o.inf > this.sup) { return -1; } return 0; } /* value < inf -> 1 , the value is under the set value > inf && value < sup -> 0 , the value is in the set ! value > sup -> -1 , the value is over the set */ public int compareTo(double value) { if (value < inf) { return 1; } if (value > sup) { return -1; } return 0; } /** * @param o DoubleInterval to be compared with this * * @return true only if the Interval are strictly equals */ public boolean strictCompareTo(DoubleInterval o) { return (this.inf == o.inf && this.sup == o.sup); } @Override public String toString() { return String.format("[%f;%f]", this.inf, this.sup); } /** * Test if b is in the interval a * @param a DoubleInterval see has a set * @param b double b to test * * @return true if b is in a, else false */ /* Interval operation */ public static boolean isIn(DoubleInterval a, double b) { return (b >= a.inf && b <= a.sup); } /** * @param a DoubleInterval supposed to bee the encompassing one * @param b DoubleInterval supposed to be inside the DoubleInterval a * * @return true if b is completely in the Interval a, false otherwise */ public static boolean isIn(DoubleInterval a, DoubleInterval b) { return (b.inf >= a.inf && b.sup <= a.sup); } /** * Used for some test... test if the Interval is Degenerated * <p> * Note : is the Interval is NaN, return true... * </p> * @return true if the interval ins't degenerated : this.inf <= this.sup, else false */ public boolean testBounds() { if(this.isNan) { return true; } return this.inf <= this.sup; } /* Mathematical operations */ // Todo : complete this /** * @param a 1st operand of the addition * @param b 2st operand of the addition * * @return a new DoubleInterval that's the result of the a + b operation */ public static DoubleInterval add(DoubleInterval a, DoubleInterval b) { double v1 = a.inf + b.inf; double v2 = a.sup + b.sup; return roundedInterval(v1,v2); } public static DoubleInterval sub(DoubleInterval a, DoubleInterval b) { return null; } public static DoubleInterval mul(DoubleInterval a, DoubleInterval b) { return null; } public static DoubleInterval div(DoubleInterval a, DoubleInterval b) { return null; } public static DoubleInterval pow2(DoubleInterval base) { return null; } public static DoubleInterval pow(DoubleInterval base, double exponent) { return null; } public static DoubleInterval pow(DoubleInterval base, DoubleInterval exponent) { return null; } public static DoubleInterval exp(DoubleInterval a) { return null; } public static DoubleInterval log(DoubleInterval a) { return null; } public static DoubleInterval log2(DoubleInterval a) { return null; } public static DoubleInterval log10(DoubleInterval a) { return null; } private static DoubleInterval roundedInterval(double v1, double v2) { return new DoubleInterval(v1 - Math.ulp(v1),v2 + Math.ulp(v2)); } }
package ch.openech.datagenerator; import java.lang.reflect.Field; import java.time.LocalDate; import java.util.List; import org.minimalj.model.EnumUtils; import org.minimalj.model.properties.FlatProperties; import org.minimalj.util.Codes; import org.minimalj.util.mock.MockDate; import org.minimalj.util.mock.MockName; import org.minimalj.util.mock.MockOrganisation; import org.minimalj.util.mock.MockPrename; import ch.openech.model.code.NationalityStatus; import ch.openech.model.common.Address; import ch.openech.model.common.Canton; import ch.openech.model.common.CountryIdentification; import ch.openech.model.common.DwellingAddress; import ch.openech.model.common.MunicipalityIdentification; import ch.openech.model.common.Place; import ch.openech.model.organisation.Organisation; import ch.openech.model.person.Occupation; import ch.openech.model.person.Person; import ch.openech.model.person.PlaceOfOrigin; import ch.openech.model.person.Relation; import ch.openech.model.person.types.DataLock; import ch.openech.model.person.types.KindOfEmployment; import ch.openech.model.person.types.MaritalStatus; import ch.openech.model.person.types.PaperLock; import ch.openech.model.person.types.Separation; import ch.openech.model.person.types.TypeOfHousehold; import ch.openech.model.person.types.TypeOfRelationship; import ch.openech.model.types.Language; import ch.openech.model.types.Sex; import ch.openech.model.types.TypeOfResidence; import ch.openech.util.Plz; import ch.openech.util.PlzImport; public class DataGenerator { public static Person person() { Person person = new Person(); person.officialName = MockName.officialName(); boolean male = Math.random() > .5; person.firstName = MockPrename.getFirstName(male); person.sex = male ? Sex.maennlich : Sex.weiblich; person.dateOfBirth.value = MockDate.generateRandomDatePartiallyKnown(); if (Math.random() > .9) { person.dateOfDeath = MockDate.generateRandomDate(); } person.vn.mock(); person.callName = "Lorem Ipsum"; person.placeOfBirth = place(); person.arrivalDate = MockDate.generateRandomDate(); person.residence.reportingMunicipality = createJona(); person.placeOfOrigin.add(placeOfOrigin()); while (Math.random() > .65) { person.placeOfOrigin.add(placeOfOrigin()); } person.dwellingAddress = dwellingAddress(); if (Math.random() < .2) { person.comesFrom = place(); } return person; } public static Person completeFilledPerson() { Person person = new Person(); for (Field field : person.getClass().getFields()) { String key = field.getName(); if (key.endsWith("Name")) { FlatProperties.set(person, key, key.substring(0, key.length() -4) + "Test"); } } person.sex = Sex.weiblich; person.dateOfBirth.value = "1999-01-02"; person.dateOfDeath = LocalDate.of(2010, 3, 4); person.vn.mock(); person.placeOfBirth = place(); person.maritalStatus.maritalStatus = MaritalStatus.ledig; person.maritalStatus.dateOfMaritalStatus = LocalDate.of(2004, 2, 3); person.separation.separation = Separation.gerichtlich; person.separation.dateOfSeparation = LocalDate.of(2005, 5, 12); person.typeOfResidence = TypeOfResidence.hasMainResidence; person.arrivalDate = LocalDate.of(1999, 1, 2); person.departureDate = LocalDate.of(2010, 3, 4); person.residence.reportingMunicipality = createJona(); person.placeOfOrigin.add(placeOfOrigin()); person.dwellingAddress = dwellingAddress(); person.comesFrom = place(); person.goesTo = place(); person.dataLock = DataLock.adresssperre; person.paperLock = PaperLock.sperre; person.languageOfCorrespondance = Language.fr; Occupation occupation = new Occupation(); occupation.kindOfEmployment = KindOfEmployment.selbstaendiger; person.occupation.add(occupation); Relation relation = new Relation(); relation.typeOfRelationship = TypeOfRelationship.Ehepartner; person.relation.add(relation); person.typeOfResidence = TypeOfResidence.hasSecondaryResidence; person.nationality.nationalityStatus = EnumUtils.createEnum(NationalityStatus.class, "3"); return person; } private static MunicipalityIdentification createJona() { MunicipalityIdentification reportingMunicipality = new MunicipalityIdentification(); reportingMunicipality.historyMunicipalityId = 14925; reportingMunicipality.canton = Codes.findCode(Canton.class, "SG"); reportingMunicipality.id = 3340; reportingMunicipality.municipalityName = "Rapperswil-Jona"; return reportingMunicipality; } public static Canton canton() { List<Canton> cantons = Codes.get(Canton.class); return cantons.get((int)(Math.random() * cantons.size())); } public static Place place() { Place place = new Place(); if (Math.random() < 0.86) { place.municipalityIdentification = municipalityIdentification(); } else { place.municipalityIdentification = municipalityIdentification(); place.countryIdentification = countryIdentification(); } return place; } public static PlaceOfOrigin placeOfOrigin() { PlaceOfOrigin placeOfOrigin = new PlaceOfOrigin(); placeOfOrigin.naturalizationDate = MockDate.generateRandomDate(); MunicipalityIdentification municipalityIdentification = municipalityIdentification(); placeOfOrigin.originName = municipalityIdentification.municipalityName; placeOfOrigin.canton = municipalityIdentification.canton; return placeOfOrigin; } public static MunicipalityIdentification municipalityIdentification() { List<MunicipalityIdentification> municipalities = Codes.get(MunicipalityIdentification.class); MunicipalityIdentification municipalityIdentification; do { municipalityIdentification = municipalities.get((int)(Math.random() * municipalities.size())); } while (municipalityIdentification.canton == null); return municipalityIdentification; } public static CountryIdentification countryIdentification() { List<CountryIdentification> countries = Codes.get(CountryIdentification.class); return countries.get((int)(Math.random() * countries.size())); } public static DwellingAddress dwellingAddress() { DwellingAddress dwellingAddress = new DwellingAddress(); dwellingAddress.EGID = "" + (int)(Math.random() * 999999998 + 1); dwellingAddress.EWID = "" + (int)(Math.random() * 998 + 1); dwellingAddress.typeOfHousehold = TypeOfHousehold.values()[(int)(Math.random() * TypeOfHousehold.values().length)]; dwellingAddress.mailAddress = address(true, false, false); return dwellingAddress; } public static Address address(boolean swiss, boolean person, boolean organisation) { Address address = new Address(); address.street = MockName.street(); if (Math.random() < 0.75) { address.houseNumber.houseNumber = "" + (int)(1 + Math.random() * 42); } else if (Math.random() < 0.8) { address.houseNumber.houseNumber = "" + (int)(1 + Math.random() * 420); } if (swiss || Math.random() < .9) { List<Plz> plzList = PlzImport.getInstance().getPlzList(); int pos = (int) (Math.random() * plzList.size()); Plz plz = plzList.get(pos); address.country = "CH"; address.zip = "" + plz.postleitzahl; address.town = plz.ortsbezeichnung; } else { if (Math.random() < .5) { address.postOfficeBoxText = "POSTFACH"; address.postOfficeBoxNumber = (int)(1000 + Math.random() * 9000); } address.zip = "" + ((int)(Math.random() * 90000 + 10000)); address.town = MockName.officialName() + "Town"; address.country = "DE"; } return address; } public static Organisation organisation() { Organisation organisation = new Organisation(); organisation.organisationName = MockOrganisation.getName(); if (organisation.organisationName.length() > 60) { organisation.organisationAdditionalName = organisation.organisationName.substring(60); organisation.organisationName = organisation.organisationName.substring(0, 60); } organisation.uid.value = "ADM323423421"; organisation.foundationDate.value = MockDate.generateRandomDatePartiallyKnown(); organisation.arrivalDate = MockDate.generateRandomDate(); organisation.reportingMunicipality = createJona(); organisation.businessAddress = dwellingAddress(); if (Math.random() < .2) { organisation.comesFrom = place(); } return organisation; } }
package ch.tkuhn.nanopub.server; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.commonjava.mimeparse.MIMEParse; import org.nanopub.Nanopub; import org.nanopub.NanopubUtils; import org.openrdf.rio.RDFFormat; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBCursor; public class NanopubServlet extends HttpServlet { private static final long serialVersionUID = -4542560440919522982L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String r = req.getServletPath().substring(1); String presentationFormat = null; if (r.endsWith(".txt")) { presentationFormat = "text/plain"; r = r.replaceFirst("\\.txt$", ""); } String extension = null; String artifactCode; if (r.matches(".*\\.[a-z]{1,10}")) { extension = r.replaceFirst("^.*\\.([a-z]{1,10})$", "$1"); artifactCode = r.replaceFirst("^(.*)\\.[a-z]{1,10}$", "$1"); } else { artifactCode = r; } if (r.isEmpty()) { ServletOutputStream out = resp.getOutputStream(); out.println("<!DOCTYPE HTML>"); out.println("<html><body>"); out.println("<h1>Nanopub Server</h1>"); long c = NanopubDb.get().getNanopubCollection().count(); out.println("<p>Number of stored nanopubs: " + c + "</p>"); out.println("<p><a href=\"+\">List of stored nanopubs (up to " + ServerConf.get().getMaxListSize() + ")</a></p>"); out.println("</body></html>"); resp.setContentType("text/html"); } else if (artifactCode.matches("RA[A-Za-z0-9\\-_]{43}")) { Nanopub nanopub; try { nanopub = NanopubDb.get().getNanopub(artifactCode); } catch (Exception ex) { resp.sendError(500, "Internal error: " + ex.getMessage()); ex.printStackTrace(); return; } if (nanopub == null) { resp.sendError(404, "Nanopub not found: " + artifactCode); return; } RDFFormat format = null; if (extension != null) { format = RDFFormat.forFileName("np." + extension); if (format == null) { resp.sendError(400, "Unknown format: " + extension); return; } } else if (presentationFormat == null) { format = RDFFormat.forMIMEType(getMimeType(req, "application/x-trig,text/x-nquads,application/trix")); } if (format == null) { format = RDFFormat.TRIG; } if (!format.supportsContexts()) { resp.sendError(400, "Unsuitable RDF format: " + extension); return; } if (presentationFormat != null) { resp.setContentType(presentationFormat); } else { resp.setContentType(format.getDefaultMIMEType()); } try { NanopubUtils.writeToStream(nanopub, resp.getOutputStream(), format); } catch (Exception ex) { resp.sendError(500, "Internal error: " + ex.getMessage()); ex.printStackTrace(); } } else if (r.matches("[A-Za-z0-9\\-_]{0,45}\\+")) { DBCollection coll = NanopubDb.get().getNanopubCollection(); Pattern p = Pattern.compile(r.substring(0, r.length()-1) + ".*"); BasicDBObject query = new BasicDBObject("_id", p); DBCursor cursor = coll.find(query); int c = 0; int maxListSize = ServerConf.get().getMaxListSize(); while (cursor.hasNext()) { c++; if (c > maxListSize) { resp.getOutputStream().println("..."); break; } String npUri = cursor.next().get("uri").toString(); resp.getOutputStream().println(npUri); } resp.setContentType("text/plain"); } else { resp.sendError(400, "Invalid request: " + r); } resp.getOutputStream().close(); } private static String getMimeType(HttpServletRequest req, String supported) { List<String> supportedList = Arrays.asList(StringUtils.split(supported, ',')); String mimeType = supportedList.get(0); try { mimeType = MIMEParse.bestMatch(supportedList, req.getHeader("Accept")); } catch (Exception ex) {} return mimeType; } }
package ch.uzh.csg.reimbursement.model; import static ch.uzh.csg.reimbursement.model.ExpenseState.ASSIGNED_TO_FINANCE_ADMIN; import static ch.uzh.csg.reimbursement.model.ExpenseState.ASSIGNED_TO_PROF; import static ch.uzh.csg.reimbursement.model.ExpenseState.DRAFT; import static ch.uzh.csg.reimbursement.model.ExpenseState.PRINTED; import static ch.uzh.csg.reimbursement.model.ExpenseState.REJECTED; import static ch.uzh.csg.reimbursement.model.ExpenseState.SIGNED; import static ch.uzh.csg.reimbursement.model.ExpenseState.TO_BE_ASSIGNED; import static ch.uzh.csg.reimbursement.model.ExpenseState.TO_SIGN_BY_FINANCE_ADMIN; import static ch.uzh.csg.reimbursement.model.ExpenseState.TO_SIGN_BY_PROF; import static ch.uzh.csg.reimbursement.model.ExpenseState.TO_SIGN_BY_USER; import static ch.uzh.csg.reimbursement.model.Role.FINANCE_ADMIN; import static ch.uzh.csg.reimbursement.model.Role.PROF; import static java.util.UUID.randomUUID; import static javax.persistence.CascadeType.ALL; import static javax.persistence.EnumType.STRING; import static javax.persistence.FetchType.EAGER; import static javax.persistence.GenerationType.IDENTITY; import java.io.IOException; import java.util.Date; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; import lombok.Getter; import lombok.Setter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import ch.uzh.csg.reimbursement.model.exception.MaxFileSizeViolationException; import ch.uzh.csg.reimbursement.model.exception.PdfExportViolationException; import ch.uzh.csg.reimbursement.model.exception.PdfSignViolationException; import ch.uzh.csg.reimbursement.model.exception.ServiceException; import ch.uzh.csg.reimbursement.model.exception.UnexpectedStateException; import ch.uzh.csg.reimbursement.serializer.UserSerializer; import ch.uzh.csg.reimbursement.service.ExpenseService; import ch.uzh.csg.reimbursement.utils.PropertyProvider; import ch.uzh.csg.reimbursement.view.View; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @Entity @Table(name = "Expense") @Transactional @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "uid") public class Expense { @Transient private final Logger LOG = LoggerFactory.getLogger(ExpenseService.class); @Id @GeneratedValue(strategy = IDENTITY) private int id; @JsonView(View.SummaryWithUid.class) @Getter @Column(nullable = false, updatable = true, unique = true, name = "uid") private String uid; @JsonView(View.DashboardSummary.class) @JsonSerialize(using = UserSerializer.class) @Getter @Setter @ManyToOne @JoinColumn(name = "user_id") private User user; @JsonView(View.DashboardSummary.class) @Getter @Setter @Column(nullable = false, updatable = true, unique = false, name = "date") private Date date; @JsonView(View.DashboardSummary.class) @Getter @Enumerated(STRING) @Column(nullable = true, updatable = true, unique = false, name = "state") private ExpenseState state; @JsonView(View.Summary.class) @JsonSerialize(using = UserSerializer.class) @Getter @Setter @ManyToOne @JoinColumn(name = "finance_admin_id") private User financeAdmin; @JsonView(View.Summary.class) @JsonSerialize(using = UserSerializer.class) @Getter @Setter @ManyToOne @JoinColumn(name = "assigned_manager_id") private User assignedManager; @JsonView(View.DashboardSummary.class) @Getter @Setter @Column(nullable = false, updatable = true, unique = false, name = "accounting") private String accounting; @JsonView(View.DashboardSummary.class) public double getTotalAmount() { double totalAmount = 0; for (ExpenseItem item : getExpenseItems()) { totalAmount += item.getCalculatedAmount(); } return totalAmount; } @JsonView(View.Summary.class) @Getter @Setter @Column(nullable = true, updatable = true, unique = false, name = "comment") private String rejectComment; @Getter @OneToMany(mappedBy = "expense", fetch = EAGER, orphanRemoval = true) private Set<ExpenseItem> expenseItems; @OneToOne(cascade = ALL, orphanRemoval = true) @JoinColumn(name = "document_id") private Document expensePdf; public Expense(User user, Date date, User financeAdmin, String accounting, ExpenseState state) { setUser(user); setDate(date); setState(state); setFinanceAdmin(financeAdmin); setAccounting(accounting); this.uid = randomUUID().toString(); } public void updateExpense(Date date, User financeAdmin, String accounting, User assignedManager, ExpenseState state) { setDate(date); setFinanceAdmin(financeAdmin); setAccounting(accounting); setAssignedManager(assignedManager); setState(state); } public Document setPdf(MultipartFile multipartFile) { // TODO remove PropertyProvider and replace it with @Value values in the // calling class of this method. // you can find examples in the method Token.isExpired. if (this.getExpensePdf() == null) { LOG.error("PDF has never been exported"); throw new PdfExportViolationException(); } else if (multipartFile.getSize() <= this.getExpensePdf().getFileSize()) { LOG.error("File has not been changed"); throw new PdfSignViolationException(); } else if (multipartFile.getSize() >= Long.parseLong(PropertyProvider.INSTANCE .getProperty("reimbursement.filesize.maxUploadFileSize"))) { LOG.error("File too big, allowed: " + PropertyProvider.INSTANCE.getProperty("reimbursement.filesize.maxUploadFileSize") + " actual: " + multipartFile.getSize()); throw new MaxFileSizeViolationException(); } else { byte[] content = null; try { content = multipartFile.getBytes(); expensePdf.updateDocument(multipartFile.getContentType(), multipartFile.getSize(), content); goToNextState(); LOG.debug("The expensePdf has been updated with a signedPdf"); } catch (IOException e) { LOG.error("An IOException has been caught while creating a signature.", e); throw new ServiceException(); } } return expensePdf; } public Document setPdf(Document document) { return this.expensePdf = document; } public Document getExpensePdf() { return expensePdf; } public void goToNextState() { if (state.equals(DRAFT) && !(user.getRoles().contains(PROF) || user.getRoles().contains(FINANCE_ADMIN))) { setState(ASSIGNED_TO_PROF); } else if (state.equals(DRAFT) && (user.getRoles().contains(PROF) || user.getRoles().contains(FINANCE_ADMIN))) { setState(TO_BE_ASSIGNED); } else if (state.equals(ASSIGNED_TO_PROF)) { setState(TO_BE_ASSIGNED); } else if (state.equals(TO_BE_ASSIGNED)) { setState(ASSIGNED_TO_FINANCE_ADMIN); } else if (state.equals(ASSIGNED_TO_FINANCE_ADMIN)) { setState(TO_SIGN_BY_USER); } else if (state.equals(TO_SIGN_BY_USER)) { setState(TO_SIGN_BY_PROF); } else if (state.equals(TO_SIGN_BY_PROF)) { setState(TO_SIGN_BY_FINANCE_ADMIN); } else if (state.equals(TO_SIGN_BY_FINANCE_ADMIN)) { setState(SIGNED); } else if (state.equals(SIGNED)) { setState(PRINTED); } else { LOG.error("Unexpected State"); throw new UnexpectedStateException(); } } public void reject(String comment) { setState(REJECTED); rejectComment = comment; } private void setState(ExpenseState state) { this.state = state; } /* * The default constructor is needed by Hibernate, but should not be used at * all. */ protected Expense() { } }
package com.accenture.multibank.dao; /** * @author manuel * @version 11/23/16 */ public interface AccountDAO { void save(AbstractAccount account); AbstractAccount find(int accountNumber); }
package com.avairebot.orion.cache; import com.avairebot.orion.Orion; import com.avairebot.orion.contracts.cache.CacheAdapter; import com.avairebot.orion.contracts.cache.CacheClosure; public class CacheManager extends CacheAdapter { protected final Orion orion; public CacheManager(Orion orion) { this.orion = orion; } @Override public boolean put(String token, Object value, int seconds) { return getAdapter(null).put(token, value, seconds); } public boolean put(CacheType type, String token, Object value, int seconds) { return getAdapter(type).put(token, value, seconds); } @Override public Object remember(String token, int seconds, CacheClosure closure) { return getAdapter(null).remember(token, seconds, closure); } public Object remember(CacheType type, String token, int seconds, CacheClosure closure) { return getAdapter(type).remember(token, seconds, closure); } @Override public boolean forever(String token, Object value) { return getAdapter(null).forever(token, value); } public boolean forever(CacheType type, String token, Object value) { return getAdapter(type).forever(token, value); } @Override public Object get(String token) { return getAdapter(null).get(token); } public Object get(CacheType type, String token) { return getAdapter(type).get(token); } @Override public CacheItem getRaw(String token) { return getAdapter(null).getRaw(token); } public CacheItem getRaw(CacheType type, String token) { return getAdapter(type).getRaw(token); } @Override public boolean has(String token) { return getAdapter(null).has(token); } public boolean has(CacheType type, String token) { return getAdapter(type).has(token); } @Override public CacheItem forget(String token) { return getAdapter(null).forget(token); } public CacheItem forget(CacheType type, String token) { return getAdapter(type).forget(token); } @Override public boolean flush() { return getAdapter(null).flush(); } public boolean flush(CacheType type) { return getAdapter(type).flush(); } public CacheAdapter getAdapter(CacheType type) { if (type != null) { type.getAdapter(); } return CacheType.getDefault().getAdapter(); } }
package com.builtbroken.industry; import com.builtbroken.industry.content.machines.TileFurnace; import com.builtbroken.industry.content.machines.TileOreCrusher; import com.builtbroken.industry.content.machines.TileOreGrinder; import com.builtbroken.mc.lib.mod.AbstractMod; import com.builtbroken.mc.lib.mod.AbstractProxy; import com.builtbroken.mc.lib.mod.ModCreativeTab; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.ModMetadata; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import net.minecraft.item.ItemStack; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @Mod(modid = BasicIndustry.DOMAIN, name = BasicIndustry.NAME, version = BasicIndustry.VERSION, dependencies = "required-after:VoltzEngine") public class BasicIndustry extends AbstractMod { /** Name of the channel and mod ID. */ public static final String NAME = "Basic_Industry"; public static final String DOMAIN = "basicindustry"; public static final String PREFIX = DOMAIN + ":"; /** The version of ICBM. */ public static final String MAJOR_VERSION = "@MAJOR@"; public static final String MINOR_VERSION = "@MINOR@"; public static final String REVISION_VERSION = "@REVIS@"; public static final String BUILD_VERSION = "@BUILD@"; public static final String VERSION = MAJOR_VERSION + "." + MINOR_VERSION + "." + REVISION_VERSION + "." + BUILD_VERSION; public static final String ASSETS_PATH = "/assets/"+ DOMAIN + "/"; public static final String TEXTURE_PATH = "textures/"; public static final String GUI_PATH = TEXTURE_PATH + "gui/"; public static final String MODEL_PREFIX = "models/"; public static final String MODEL_DIRECTORY = ASSETS_PATH + MODEL_PREFIX; public static final String MODEL_TEXTURE_PATH = TEXTURE_PATH + MODEL_PREFIX; public static final String BLOCK_PATH = TEXTURE_PATH + "blocks/"; public static final String ITEM_PATH = TEXTURE_PATH + "items/"; public static final Logger LOGGER = LogManager.getLogger(NAME); @Mod.Instance(DOMAIN) public static BasicIndustry INSTANCE; @Mod.Metadata(DOMAIN) public static ModMetadata metadata; @SidedProxy(clientSide = "com.builtbroken.industry.ClientProxy", serverSide = "com.builtbroken.industry.CommonProxy") public static CommonProxy proxy; public BasicIndustry() { super(DOMAIN, "BasicIndustry"); } @Override public AbstractProxy getProxy() { return proxy; } @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { super.preInit(event); manager.setTab(new ModCreativeTab(NAME)); ((ModCreativeTab)manager.defaultTab).itemStack = new ItemStack(manager.newBlock(TileFurnace.class)); manager.newBlock(TileOreCrusher.class); manager.newBlock(TileOreGrinder.class); } @Mod.EventHandler public void init(FMLInitializationEvent event) { super.init(event); } @Mod.EventHandler public void postInit(FMLPostInitializationEvent event) { super.postInit(event); } }
package com.carlosefonseca.common; import android.content.Context; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import com.carlosefonseca.common.utils.*; import com.google.gson.*; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.loopj.android.http.TextHttpResponseHandler; import junit.framework.Assert; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Locale; import static com.carlosefonseca.common.utils.CodeUtils.getTag; import static com.carlosefonseca.common.utils.CodeUtils.isMainThread; public class CFRestClient { protected static final String EMPTY_MESSAGE = "EMPTY"; private static final String TAG = CodeUtils.getTag(CFRestClient.class); public static boolean offline = false; /** * Convenience method to invoke the HttpClient's GET by passing only the elements that usually change. * * @param url The URL to be requested, either an absolute URL or a sufix for * {@link com.carlosefonseca.common.CFRestClient.CFAPIClient#getBaseUrl()}. * @param requestParams The request parameters specific to this request. * @param file The file to use in case it's an offline request. * @param clazz The class representing the JSON data to deserialize. * @param handler The handler that will receive the deserialized object or the errors that might occur. */ protected static <T> void get(String url, @Nullable RequestParams requestParams, @Nullable String file, Class<T> clazz, DataHandler<T> handler) { get(url, requestParams, file, clazz, handler, CFRestClient.offline); } /** * Convenience method to invoke the HttpClient's GET by passing only the elements that usually change. * * @param url The URL to be requested, either an absolute URL or a sufix for * {@link com.carlosefonseca.common.CFRestClient.CFAPIClient#getBaseUrl()}. * @param requestParams The request parameters specific to this request. * @param clazz The class representing the JSON data to deserialize. * @param handler The handler that will receive the deserialized object or the errors that might occur. * @param offline Set to true to force the use of the offline file. Set to false to obey global offline flag. * If true, everything will be synchronous so you can count on something being returned ASAP. */ public static <T> void get(String url, @Nullable RequestParams requestParams, @Nullable String file, Class<T> clazz, DataHandler<T> handler, boolean offline) { final ResponseHandler<T> responseHandler = new ResponseHandler<>(clazz, handler); if (offline) { // if caller forced the offline, we better do it synchronously since he probably needs the data right away. responseHandler.setUseSynchronousMode(true); CFAPIClient.getOffline(file, responseHandler, false); } else if (CFRestClient.offline) { CFAPIClient.getOffline(file, responseHandler); } else { url = CFAPIClient.getAbsoluteUrl(url); // ONLINE final String fullUrl = "GET: " + url + (requestParams == null ? "" : "?" + requestParams.toString()); if (!NetworkingUtils.hasInternet()) { Log.w(TAG, "NO INTERNET! " + fullUrl); responseHandler.onFailure(0, null, (String)null, new NetworkingUtils.NotConnectedException()); } else { Log.d(responseHandler.TAG, fullUrl); CFAPIClient.client.get(url, requestParams, responseHandler); } } } /** * Convenience method to invoke the HttpClient's GET by passing only the elements that usually change. * * @param url The URL to be requested, either an absolute URL or a sufix for * {@link com.carlosefonseca.common.CFRestClient.CFAPIClient#getBaseUrl()}. * @param requestParams The request parameters specific to this request. * @param clazz The class representing the JSON data to deserialize. * @param handler The handler that will receive the deserialized object or the errors that might occur. * @param offline Set to true to force the use of the offline file. Set to false to obey global offline flag. * If true, everything will be synchronous so you can count on something being returned ASAP. */ public static <T> void post(@NotNull String url, @Nullable RequestParams requestParams, @Nullable String body, @Nullable String file, @NotNull Class<T> clazz, @Nullable DataHandler<T> handler, boolean offline) { final ResponseHandler<T> responseHandler = new ResponseHandler<>(clazz, handler); if (offline) { // if caller forced the offline, we better do it synchronously since he probably needs the data right away. responseHandler.setUseSynchronousMode(true); CFAPIClient.getOffline(file, responseHandler, false); } else if (CFRestClient.offline) { CFAPIClient.getOffline(file, responseHandler); } else { url = CFAPIClient.getAbsoluteUrl(url); // ONLINE String longUrl = url + (requestParams == null ? "" : ("?" + requestParams.toString())); if (!NetworkingUtils.hasInternet()) { Log.w(TAG, "NO INTERNET! GET: " + longUrl); responseHandler.onFailure(0, null, (String) null, new NetworkingUtils.NotConnectedException()); } else { Log.v(responseHandler.TAG, "GET: " + longUrl); CFAPIClient.post(url, requestParams, body, responseHandler); } } } public static boolean isOffline() { return offline; } public static void setOffline(boolean offline) { CFRestClient.offline = offline; } public static abstract class DataHandler<T> { public void onData(@NotNull T data) { } public void onError(@NotNull Throwable error) { } public void onFinish() { } } /** * Actual communication logic */ public static class CFAPIClient { public static String TAG = getTag(CFAPIClient.class); private static String URL; private static AsyncHttpClient client; private static Context context = CFApp.getContext(); static { client = new AsyncHttpClient(); client.setTimeout(60 * 1000); client.setMaxRetriesAndTimeout(5, 2000); // client.setMaxConnections(2); } private CFAPIClient() {} public static String getBaseUrl() { return URL; } public static void setBaseURL(String baseUrl) { if (baseUrl.startsWith("http")) { URL = baseUrl; } else { throw new IllegalArgumentException("URL doesn't start with http"); } } public static String getAbsoluteUrl(String relativeUrl) { if (relativeUrl.startsWith("http")) return relativeUrl; if (BuildConfig.DEBUG) Assert.assertNotNull(URL); return URL + relativeUrl; } public static void getOffline(@Nullable final String file, final TextHttpResponseHandler responseHandler) { getOffline(file, responseHandler, true); } public static void getOffline(@Nullable final String file, final TextHttpResponseHandler responseHandler, boolean async) { if (file == null) { responseHandler.onFailure(404, new Header[0], "", new IOException("Offline file not specified")); return; } try { Log.v(TAG, "Reading local file " + file); Runnable r = new Runnable() { @Override public void run() { String response = FileUtils.StrFromFileInAssets(file); responseHandler.onSuccess(200, new Header[0], response.getBytes()); } }; if (async) { new Handler().post(r); } else { r.run(); } } catch (Exception e) { responseHandler.onFailure(500, new Header[0], "Offline Fail!", e); } } public static void post(String url, RequestParams params, TextHttpResponseHandler responseHandler) { Log.v(TAG, "POST " + getAbsoluteUrl(url) + " + " + params.toString()); client.post(getAbsoluteUrl(url), params, responseHandler); } public static void post(final String url, @Nullable final RequestParams params, @Nullable String jsonBody, final AsyncHttpResponseHandler responseHandler) { StringEntity se = null; try { // se = new StringEntity(StringEscapeUtils.escapeJava(jsonBody)); se = new StringEntity(jsonBody, HTTP.UTF_8); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Exception", e); } final StringEntity s = se; final String url1 = getAbsoluteUrl(url) + (params != null ? "?" + params : ""); Log.d(TAG, "POST: " + url1); Log.d(TAG, "POST: " + jsonBody); Runnable runnable = new Runnable() { @Override public void run() { client.post(context, url1, s, "application/json", responseHandler); } }; if (!isMainThread()) { new Handler(Looper.getMainLooper()).post(runnable); } else { runnable.run(); } } public static void post(@NotNull final String url, final File file, final TextHttpResponseHandler responseHandler) { new AsyncTask<String, Void, Void>() { Exception error; String status; @Override protected Void doInBackground(String... params) { String absurl = getAbsoluteUrl(url); HttpParams httpParameters = new BasicHttpParams(); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); HttpPost httpPost = new HttpPost(absurl); HttpResponse execute; try { InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(false); httpPost.setEntity(reqEntity); Log.i(TAG, "Sending File " + file.getName()); execute = httpClient.execute(httpPost); status = execute.toString(); Log.i(TAG, "File Sent"); } catch (Exception e) { error = e; } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if (error == null) { responseHandler.onSuccess(200, new Header[0], ""); } else { responseHandler.onFailure(500, new Header[0], "", new Exception(status + " / " + error.getMessage(), error)); } } }.execute(); } } public static class MultiDateDeserializer implements JsonDeserializer<Date> { private final String[] formats; public MultiDateDeserializer(String[] formats) { this.formats = formats; } @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { for (String format : formats) { try { return new SimpleDateFormat(format, Locale.US).parse(json.getAsString()); } catch (ParseException ignored) { } } throw new JsonParseException(String.format("Unparseable date: \"%s\". Supported formats: %s", json.getAsString(), Arrays.toString(formats))); } } public static class ResponseHandler<T> extends GsonHttpResponseHandler<T> { @Nullable private final DataHandler<T> handler; private final String name; private String TAG; public static Gson gson; public ResponseHandler(@NotNull Class<T> dataClass, @Nullable DataHandler<T> handler) { super(dataClass, gson); this.name = dataClass.getSimpleName(); this.handler = handler; TAG = CFRestClient.TAG + " [" + name + "] "; } // @Override // public void onStart() { // Log.v(TAG, "onStart"); // @Override // public void onFinish() { // Log.v(TAG, "onFinish"); @Override public void onSuccess(final T response) { try { if (response == null) { Log.d(TAG, "returned empty!"); if (handler != null) handler.onError(new Exception(EMPTY_MESSAGE)); } else { if (response instanceof JSONDeserializable) ((JSONDeserializable) response).afterDeserialization(); Log.d(TAG, "succeed."); if (handler != null) { handler.onData(response); handler.onFinish(); } } } catch (Exception e) { Log.e(TAG, "" + e.getMessage(), e); } } @Override public void onFailure(int statusCode, @Nullable Header[] headers, @Nullable String responseBody, Throwable error) { try { if (!(error instanceof NetworkingUtils.NotConnectedException)) { Log.w(TAG, "Error! " + error.getMessage() + " — " + responseBody); } if (handler != null) { handler.onError(error); handler.onFinish(); } } catch (Exception e) { Log.e(TAG, "" + e.getMessage(), e); } } } }
package com.cegeka.tetherj.api; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.UndeclaredThrowableException; import java.math.BigInteger; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.cegeka.tetherj.EthCall; import com.cegeka.tetherj.EthRpcClient; import com.cegeka.tetherj.EthSignedTransaction; import com.cegeka.tetherj.EthTransaction; import com.cegeka.tetherj.EthWallet; import com.cegeka.tetherj.crypto.CryptoUtil; import com.cegeka.tetherj.pojo.Block; import com.cegeka.tetherj.pojo.CompileOutput; import com.cegeka.tetherj.pojo.FilterLogRequest; import com.cegeka.tetherj.pojo.Transaction; import com.cegeka.tetherj.pojo.TransactionReceipt; import com.googlecode.jsonrpc4j.HttpException; import com.googlecode.jsonrpc4j.JsonRpcClientException; /** * Implementation for an Ethereum service api * * @author Andrei Grigoriu * */ public class EthereumService { public final static int defaultExecutorThreads = 2; /** * A generic wrapper for a rpc call. * * @author Andrei Grigoriu * * @param <T> * return type of rpc call */ public interface RpcAction<T> { /** * Execute rpc call here * * @return rpc response */ public T call(); } /** * Interval between receipt check polls */ public static final int receiptCheckIntervalMillis = 1000; /** * Max receipt checks to do */ public static final int receiptMaxChecks = 60 * 1000 * 10 / receiptCheckIntervalMillis; private final EthRpcClient rpc; private final ScheduledExecutorService executor; private static final Logger logger = LogManager.getLogger(EthereumService.class); /** * Creates executor automatically */ public EthereumService() { this(EthereumService.defaultExecutorThreads, EthRpcClient.defaultHostname, EthRpcClient.defaultPort); } /** * Creates executor with custom number of threads. * * @param executorThreads * to spawn, 0 to disable async support */ public EthereumService(int executorThreads) { this(executorThreads, EthRpcClient.defaultHostname, EthRpcClient.defaultPort); } /** * Creates custom number of threads and custom ethereum client connection * info. * * @param executorThreads * to spawn, 0 to disable async support * @param rpcHostname * of the ethereum client * @param port * of the ethereum client */ public EthereumService(int executorThreads, String rpcHostname, int port) { if (executorThreads > 0) { ScheduledExecutorService executor = Executors.newScheduledThreadPool(executorThreads, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { handleUnknownThrowables(e); } }); return t; } }); this.executor = executor; logger.info("Created ethereum service with async support on " + executorThreads + " threads!"); } else { /* when 0 threads specified, service is always blocking */ this.executor = null; logger.info("Created ethereum service with no async support!"); } rpc = new EthRpcClient(rpcHostname, port); logger.info("Created ethereum service"); } /** * * @param executor * to use for async and future calls, also for polling, null to * disable async support */ public EthereumService(ScheduledExecutorService executor) { this(executor, EthRpcClient.defaultHostname, EthRpcClient.defaultPort); } /** * * @param executor * to use for async and future calls, also for polling, null to * disable async support * @param rpcHostname * ethereum client hostname */ public EthereumService(ScheduledExecutorService executor, String rpcHostname) { this(executor, rpcHostname, EthRpcClient.defaultPort); } /** * * @param executor * to use for async and future calls, also for polling * @param rpcHostname * ethereum client hostname * @param port * ethereum client port */ public EthereumService(ScheduledExecutorService executor, String rpcHostname, int port) { this.executor = executor; rpc = new EthRpcClient(rpcHostname, port); if (this.executor != null) { logger.info("Created ethereum service with async support on custom executor!"); } else { logger.info("Created ethereum service with no async support!"); } } /** * Call this when you don't know what to do with e * * @param e * the exception thrown somewhere */ private void handleUnknownThrowables(Throwable e) { if (e != null) { StringWriter esw = new StringWriter(); PrintWriter epw = new PrintWriter(esw); e.printStackTrace(epw); String eStack = esw.toString(); String message = "Tetherj uncaught exception: " + e.toString() + " " + e.getMessage() + " at \n" + eStack; if (e.getCause() != null) { StringWriter csw = new StringWriter(); PrintWriter cpw = new PrintWriter(csw); Throwable c = e.getCause(); c.printStackTrace(cpw); String cStack = csw.toString(); message += "\n CAUSE: " + c.toString() + " " + c.getMessage() + " at \n" + cStack; } logger.error(message); } } /** * Generate wallet with a random key pair. * * @param passphrase * @return */ public EthWallet createWallet(String passphrase) { return EthWallet.createWallet(passphrase); } /** * Get internal rpc client used to communicate with the ethereum client * * @return rpc client */ public EthRpcClient getRpcClient() { return rpc; } /** * Blocking execute of rpc action. Wraps errors into a tetherj response. * * @param rpcAction * @return response */ private <T> TetherjResponse<T> performBlockingRpcAction(RpcAction<T> rpcAction) { ErrorType err = null; Exception e = null; T rpcResponse = null; try { rpcResponse = rpcAction.call(); } catch (JsonRpcClientException rpcEx) { err = ErrorType.BLOCKCHAIN_CLIENT_OPERATION_ERROR; e = rpcEx; } catch (UndeclaredThrowableException | HttpException ex) { err = ErrorType.BLOCKCHAIN_CLIENT_BAD_CONNECTION; e = ex; } catch (Exception generalException) { err = ErrorType.UNKNOWN_ERROR; e = generalException; } return new TetherjResponse<T>(err, e, rpcResponse); } /** * Async execute of rpc action. Runs callable handle when done. * * @param rpcAction * to execute * @param callable * to execute after rpcAction operation ends */ private <T> void performAsyncRpcAction(RpcAction<T> rpcAction, TetherjHandle<T> callable) { if (executor != null && !executor.isShutdown()) { synchronized (executor) { try { executor.submit(new Runnable() { @Override public void run() { try { callable.call(performBlockingRpcAction(rpcAction)); } catch (Throwable t) { handleUnknownThrowables(t); } } }); } catch (Exception ex) { ex.printStackTrace(); } } } else { /* no async available, execute it blocking */ callable.call(performBlockingRpcAction(rpcAction)); } } /** * Async execute of rpc action. Returns a future to get when operation ends. * * @param rpcAction * to execute */ private <T> Future<TetherjResponse<T>> performFutureRpcAction(RpcAction<T> rpcAction) { if (executor != null && !executor.isShutdown()) { synchronized (executor) { try { return executor.submit(new Callable<TetherjResponse<T>>() { @Override public TetherjResponse<T> call() throws Exception { return performBlockingRpcAction(rpcAction); } }); } catch (Exception ex) { ex.printStackTrace(); return null; } } } else { return CompletableFuture.completedFuture(performBlockingRpcAction(rpcAction)); } } /** * Async get accounts registered in the ethereum client. * * @param callable * to call after the accounts are fetched */ public void getAccounts(TetherjHandle<String[]> callable) { performAsyncRpcAction(new RpcAction<String[]>() { @Override public String[] call() { return rpc.getAccounts(); } }, callable); } /** * Blocking get accounts registered in the ethereum client. * * @return rpc accounts response */ public TetherjResponse<String[]> getAccounts() { return performBlockingRpcAction(new RpcAction<String[]>() { @Override public String[] call() { return rpc.getAccounts(); } }); } /** * Future get accounts registered in the ethereum client. * * @return Future for the accounts response. */ public Future<TetherjResponse<String[]>> getAccountsFuture() { return performFutureRpcAction(new RpcAction<String[]>() { @Override public String[] call() { return rpc.getAccounts(); } }); } /** * Async get balance of an account. * * @param address * to get balance of. * @param callable * to execute when balance is fetched */ public void getBalance(final String address, TetherjHandle<BigInteger> callable) { performAsyncRpcAction(new RpcAction<BigInteger>() { @Override public BigInteger call() { return rpc.getBalance(address); } }, callable); } /** * Blocking get balance of an account * * @param address * to get balance of * @return response with balance */ public TetherjResponse<BigInteger> getBalance(final String address) { return performBlockingRpcAction(new RpcAction<BigInteger>() { @Override public BigInteger call() { return rpc.getBalance(address); } }); } /** * Future get balance of an account * * @param address * to get balance of * @return future to get balance response. */ public Future<TetherjResponse<BigInteger>> getBalanceFuture(final String address) { return performFutureRpcAction(new RpcAction<BigInteger>() { @Override public BigInteger call() { return rpc.getBalance(address); } }); } /** * Async get account nonce of address (does not currently count pending * executions) * * @param address * to get account nonce of. * @param callable * to execute with nonce response */ public void getAccountNonce(final String address, TetherjHandle<BigInteger> callable) { performAsyncRpcAction(new RpcAction<BigInteger>() { @Override public BigInteger call() { return rpc.getAccountNonce(address); } }, callable); } /** * Blocking get account nonce of address (does not currently count pending * executions) * * @param address * to get account nonce of. * @return nonce response */ public TetherjResponse<BigInteger> getAccountNonce(final String address) { return performBlockingRpcAction(new RpcAction<BigInteger>() { @Override public BigInteger call() { return rpc.getAccountNonce(address); } }); } /** * Future get account nonce of address (does not currently count pending * executions) * * @param address * @return future to get nonce response */ public Future<TetherjResponse<BigInteger>> getAccountNonceFuture(final String address) { return performFutureRpcAction(new RpcAction<BigInteger>() { @Override public BigInteger call() { return rpc.getAccountNonce(address); } }); } /** * Blocking send transaction. Generates nonce automatically (by rpc) * * @param from * wallet to sign transaction with * @param transaction * to send * @return response for transaction hash * @throws WalletLockedException */ public TetherjResponse<String> sendTransaction(EthWallet from, EthTransaction transaction) throws WalletLockedException { TetherjResponse<BigInteger> nonceResponse = getAccountNonce(from.getAddress()); if (nonceResponse.getErrorType() == null) { return sendTransaction(from, transaction, nonceResponse.getValue()); } return new TetherjResponse<String>(nonceResponse); } /** * Blocking send transaction. * * @param from * wallet to sign transaction with * @param transaction * to send * @param nonce * to sign transaction with * @return response for transaction hash * @throws WalletLockedException */ public TetherjResponse<String> sendTransaction(EthWallet from, EthTransaction transaction, BigInteger nonce) throws WalletLockedException { EthSignedTransaction txSigned = transaction.signWithWallet(from, nonce); byte[] rawEncoded = txSigned.getSignedEncodedData(); return performBlockingRpcAction(new RpcAction<String>() { @Override public String call() { logger.debug("Sending transaction {from:" + from.getAddress() + ", nonce: " + nonce + " " + transaction.toString()); return rpc.sendRawTransaction(rawEncoded); } }); } /** * Future send transaction. * * @param from * wallet to sign transaction with * @param transaction * to send * @param nonce * to sign transaction with * @return future to get response for transaction hash. * @throws WalletLockedException */ public Future<TetherjResponse<String>> sendTransactionFuture(EthWallet from, EthTransaction transaction, BigInteger nonce) throws WalletLockedException { EthSignedTransaction txSigned = transaction.signWithWallet(from, nonce); byte[] rawEncoded = txSigned.getSignedEncodedData(); return performFutureRpcAction(new RpcAction<String>() { @Override public String call() { logger.debug("Sending transaction {from:" + from.getAddress() + ", nonce: " + nonce + " " + transaction.toString()); return rpc.sendRawTransaction(rawEncoded); } }); } /** * Async send transaction. Nonce gets generated automatically via rpc. * * @param from * wallet to sign transaction with * @param transaction * to send * @param callable * to execute when transaction was submitted. */ public void sendTransaction(EthWallet from, EthTransaction transaction, TetherjHandle<String> callable) { String address = from.getAddress(); getAccountNonce(address, new TetherjHandle<BigInteger>() { @Override public void call(TetherjResponse<BigInteger> response) { if (response.getErrorType() == null) { sendTransaction(from, transaction, response.getValue(), callable); } else { callable.call(new TetherjResponse<>(response)); } } }); } /** * Async send transaction. * * @param from * wallet to sign transaction with * @param transaction * to send * @param nonce * to sign transaction with * @param callable * to execute when transaction was submitted. */ public void sendTransaction(EthWallet from, EthTransaction transaction, BigInteger nonce, TetherjHandle<String> callable) { try { EthSignedTransaction txSigned = transaction.signWithWallet(from, nonce); byte[] rawEncoded = txSigned.getSignedEncodedData(); performAsyncRpcAction(new RpcAction<String>() { @Override public String call() { return rpc.sendRawTransaction(rawEncoded); } }, callable); } catch (WalletLockedException e) { callable.call(new TetherjResponse<String>(ErrorType.BAD_STATE, e)); } } /** * Blocking sign transaction * * @param transaction * signed transaction to send * @return response for signed transaction * @throws WalletLockedException */ public TetherjResponse<EthSignedTransaction> signTransaction(EthTransaction transaction, EthWallet wallet) throws WalletLockedException { String from = wallet.getAddress(); TetherjResponse<BigInteger> nonceResponse = getAccountNonce(from); if (nonceResponse.getErrorType() != null) { return new TetherjResponse<EthSignedTransaction>(nonceResponse); } EthSignedTransaction txSigned = transaction.signWithWallet(wallet, nonceResponse.getValue()); return new TetherjResponse<EthSignedTransaction>(null, null, txSigned); } /** * Sign transaction * * @param transaction * signed transaction to send * @return the signed transaction * @throws WalletLockedException */ public EthSignedTransaction signTransaction(EthTransaction transaction, EthWallet wallet, BigInteger nonce) throws WalletLockedException { return transaction.signWithWallet(wallet, nonce); } /** * Blocking send signed transaction. * * @param transaction * signed transaction to send * @return response for transaction hash * @throws WalletLockedException */ public TetherjResponse<String> sendSignedTransaction(EthSignedTransaction transaction) { return performBlockingRpcAction(new RpcAction<String>() { @Override public String call() { logger.debug("Sending transaction {from:" + transaction.getFrom() + " " + transaction.toString()); return rpc.sendRawTransaction(transaction.getSignedEncodedData()); } }); } /** * Async send signed transaction. * * @param transaction * signed transaction to send * @param callable * to execute when transaction was submitted. */ public void sendSignedTransaction(EthSignedTransaction transaction, TetherjHandle<String> callable) { performAsyncRpcAction(new RpcAction<String>() { @Override public String call() { return rpc.sendRawTransaction(transaction.getSignedEncodedData()); } }, callable); } /** * Future send signed transaction. * * @param transaction * signed transaction to send * @param callable * to execute when transaction was submitted. */ public Future<TetherjResponse<String>> sendSignedTransactionFuture(EthSignedTransaction transaction) { return performFutureRpcAction(new RpcAction<String>() { @Override public String call() { return rpc.sendRawTransaction(transaction.getSignedEncodedData()); } }); } /** * Async listen for tx receipt. Will call when transaction is mined or was * already mined. * * @param txHash * transaction hash to listen for * @param secondsTimeout * seconds until you want give up listening * @param callable * to execute when transaction is mined */ public void listenForTxReceipt(final String txHash, int secondsTimeout, final TetherjHandle<TransactionReceipt> callable) { int checks = secondsTimeout * 1000 / receiptCheckIntervalMillis; listenForTxReceipt(txHash, receiptCheckIntervalMillis, checks, callable); } /** * Async listen for tx receipt. Will call when transaction is mined or was * already mined. * * @param txHash * transaction hash to listen for * @param callable * to execute when transaction is mined */ public void listenForTxReceipt(final String txHash, final TetherjHandle<TransactionReceipt> callable) { listenForTxReceipt(txHash, receiptCheckIntervalMillis, receiptMaxChecks, callable); } private void listenForTxReceipt(final String txHash, final int checkIntervalMillis, final int checks, final TetherjHandle<TransactionReceipt> callable) { performAsyncRpcAction(new RpcAction<TransactionReceipt>() { @Override public TransactionReceipt call() { TransactionReceipt receipt = rpc.getTransactionReceipt(txHash); return receipt; } }, new TetherjHandle<TransactionReceipt>() { @Override public void call(TetherjResponse<TransactionReceipt> response) { if (response.getErrorType() != null) { callable.call(response); } else { TransactionReceipt receipt = response.getValue(); if (receipt != null && receipt.getBlockNumber() != null) { callable.call(response); } else if (checks <= 0) { callable.call(new TetherjResponse<TransactionReceipt>(ErrorType.OPERATION_TIMEOUT, new TxReceiptTimeoutException())); } else { if (executor != null && !executor.isShutdown()) { synchronized (executor) { executor.schedule(new Runnable() { @Override public void run() { listenForTxReceipt(txHash, checkIntervalMillis, checks - 1, callable); } }, checkIntervalMillis, TimeUnit.MILLISECONDS); } } else { callable.call(new TetherjResponse<TransactionReceipt>(ErrorType.OPERATION_TIMEOUT, new TxReceiptTimeoutException())); } } } } }); } /** * Async calls and fetches the output of an ethereum function. * * @param call * to execute on the ethereum chain * @param callable * to execute with output data. */ public void makeCall(final EthCall call, TetherjHandle<Object[]> callable) { performAsyncRpcAction(new RpcAction<Object[]>() { @Override public Object[] call() { return call.decodeOutput(rpc.callMethod(call)); } }, callable); } /** * Blocking calls and fetches the output of an ethereum function. * * @param call * to execute on the ethereum chain * @return output response */ public TetherjResponse<Object[]> makeCall(final EthCall call) { return performBlockingRpcAction(new RpcAction<Object[]>() { @Override public Object[] call() { return call.decodeOutput(rpc.callMethod(call)); } }); } /** * Future calls and fetches the output of an ethereum function. * * @param call * to execute on the ethereum chain * @return future to get output response */ public Future<TetherjResponse<Object[]>> makeCallFuture(final EthCall call) { return performFutureRpcAction(new RpcAction<Object[]>() { @Override public Object[] call() { return call.decodeOutput(rpc.callMethod(call)); } }); } /** * Async compile solidity. * * @param sourceCode * to compiled * @param callable * with compile output response */ public void compileSolidity(String sourceCode, TetherjHandle<CompileOutput> callable) { performAsyncRpcAction(new RpcAction<CompileOutput>() { @Override public CompileOutput call() { return rpc.compileSolidity(sourceCode); } }, callable); } /** * Blocking compile solidity. * * @param sourceCode * to compile * @return compile output response */ public TetherjResponse<CompileOutput> compileSolidity(String sourceCode) { return performBlockingRpcAction(new RpcAction<CompileOutput>() { @Override public CompileOutput call() { return rpc.compileSolidity(sourceCode); } }); } /** * Future compile solidity. * * @param sourceCode * to compile * @return future for compile output response */ public Future<TetherjResponse<CompileOutput>> compileSolidityFuture(String sourceCode) { return performFutureRpcAction(new RpcAction<CompileOutput>() { @Override public CompileOutput call() { return rpc.compileSolidity(sourceCode); } }); } /** * Async get a transaction by transaction hash. * * @param txHash * to get data by. * @param callable * with Transaction response */ public void getTransaction(String txHash, TetherjHandle<Transaction> callable) { performAsyncRpcAction(new RpcAction<Transaction>() { @Override public Transaction call() { return rpc.getTransaction(txHash); } }, callable); } /** * Blocking get a transaction by transaction hash. * * @param txHash * to get data by. * @return with Transaction response */ public TetherjResponse<Transaction> getTransaction(String txHash) { return performBlockingRpcAction(new RpcAction<Transaction>() { @Override public Transaction call() { return rpc.getTransaction(txHash); } }); } /** * Future get a transaction by transaction hash. * * @param sourceCode * to get data by. * @return future for Transaction response */ public Future<TetherjResponse<Transaction>> getTransactionFuture(String txHash) { return performFutureRpcAction(new RpcAction<Transaction>() { @Override public Transaction call() { return rpc.getTransaction(txHash); } }); } /** * Async get the latest block. * * @param callable * with Block response */ public void getLatestBlock(TetherjHandle<Block> callable) { performAsyncRpcAction(new RpcAction<Block>() { @Override public Block call() { return rpc.getLatestBlock(); } }, callable); } /** * Blocking get the latest block. * * @param callable * with Block response */ public TetherjResponse<Block> getLatestBlock() { return performBlockingRpcAction(new RpcAction<Block>() { @Override public Block call() { return rpc.getLatestBlock(); } }); } /** * Future get the latest block. * * @param callable * with Block response */ public Future<TetherjResponse<Block>> getLatestBlockFuture() { return performFutureRpcAction(new RpcAction<Block>() { @Override public Block call() { return rpc.getLatestBlock(); } }); } /** * Async get the transaction receipt. * * @param txHash * to receipt transaction by. * @param callable * with TransactionReceipt response */ public void getTransactionReceipt(String txHash, TetherjHandle<TransactionReceipt> callable) { performAsyncRpcAction(new RpcAction<TransactionReceipt>() { @Override public TransactionReceipt call() { return rpc.getTransactionReceipt(txHash); } }, callable); } /** * Blocking get the transaction receipt. * * @param txHash * to receipt transaction by. */ public TetherjResponse<TransactionReceipt> getTransactionReceipt(String txHash) { return performBlockingRpcAction(new RpcAction<TransactionReceipt>() { @Override public TransactionReceipt call() { return rpc.getTransactionReceipt(txHash); } }); } /** * Future get the transaction receipt. * * @param txHash * to receipt transaction by. */ public Future<TetherjResponse<TransactionReceipt>> getTransactionReceiptFuture(String txHash) { return performFutureRpcAction(new RpcAction<TransactionReceipt>() { @Override public TransactionReceipt call() { return rpc.getTransactionReceipt(txHash); } }); } /** * Async create filter * * @param callable * with Block response */ public void newFilter(TetherjHandle<BigInteger> callable) { performAsyncRpcAction(new RpcAction<BigInteger>() { @Override public BigInteger call() { return CryptoUtil.hexToBigInteger(rpc.newFilter()); } }, callable); } /** * Async create filter with custom request * * @param custom * request * @param callable * with Block response */ public void newFilter(FilterLogRequest request, TetherjHandle<BigInteger> callable) { performAsyncRpcAction(new RpcAction<BigInteger>() { @Override public BigInteger call() { return CryptoUtil.hexToBigInteger(rpc.newFilter(request)); } }, callable); } /** * Blocking create new filter * */ public TetherjResponse<BigInteger> newFilter() { return performBlockingRpcAction(new RpcAction<BigInteger>() { @Override public BigInteger call() { return CryptoUtil.hexToBigInteger(rpc.newFilter()); } }); } /** * Blocking create new filter with custom request * * @param custom * request * @return response for filter id */ public TetherjResponse<BigInteger> newFilter(FilterLogRequest request) { return performBlockingRpcAction(new RpcAction<BigInteger>() { @Override public BigInteger call() { return CryptoUtil.hexToBigInteger(rpc.newFilter(request)); } }); } /** * Future create new filter * * @return future to get response for filter id */ public Future<TetherjResponse<BigInteger>> newFilterFuture() { return performFutureRpcAction(new RpcAction<BigInteger>() { @Override public BigInteger call() { return CryptoUtil.hexToBigInteger(rpc.newFilter()); } }); } /** * Future create new filter with custom request. * * @param custom * request * @return future to get response for filter id */ public Future<TetherjResponse<BigInteger>> newFilterFuture(FilterLogRequest request) { return performFutureRpcAction(new RpcAction<BigInteger>() { @Override public BigInteger call() { return CryptoUtil.hexToBigInteger(rpc.newFilter(request)); } }); } /** * Async create pending transaction filter * * @param callable * with Block response */ public void newPendingTransactionFilter(TetherjHandle<BigInteger> callable) { performAsyncRpcAction(new RpcAction<BigInteger>() { @Override public BigInteger call() { return CryptoUtil.hexToBigInteger(rpc.newPendingTransactionFilter()); } }, callable); } /** * Blocking create new pending transaction filter * */ public TetherjResponse<BigInteger> newPendingTransactionFilter() { return performBlockingRpcAction(new RpcAction<BigInteger>() { @Override public BigInteger call() { return CryptoUtil.hexToBigInteger(rpc.newPendingTransactionFilter()); } }); } /** * Future create new pending transaction filter * * @return future to get response for filter id */ public Future<TetherjResponse<BigInteger>> newPendingTransactionFilterFuture() { return performFutureRpcAction(new RpcAction<BigInteger>() { @Override public BigInteger call() { return CryptoUtil.hexToBigInteger(rpc.newPendingTransactionFilter()); } }); } }
package com.edwardsit.spark4n6; import edu.nps.jlibewf.EWFFileReader; import edu.nps.jlibewf.EWFSegmentFileReader; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.log4j.Logger; import org.apache.log4j.Level; import org.apache.spark.SparkConf; import java.io.IOException; public class EWFRecordReader extends RecordReader<LongWritable, BytesWritable> { private static Logger log = Logger.getLogger(EWFRecordReader.class); private static long nChunksPerSplit = -1L; private long chunkSize = 0L; private EWFFileReader stream = null; public EWFRecordReader() { } long start = 0L; long end = 0L; long currentStart = 0L; long currentEnd = 0L; boolean notReadYet = true; boolean atEOF = false; BytesWritable currentValue = new BytesWritable(); FileSystem fs = null; Path file = null; @Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { FileSplit fileSplit = (FileSplit) split; Configuration conf = context.getConfiguration(); file = fileSplit.getPath(); start = fileSplit.getStart(); end = start + fileSplit.getLength(); stream = new EWFFileReader(file.getFileSystem(context.getConfiguration()), file); fs = file.getFileSystem(conf); chunkSize = new EWFSegmentFileReader(fs).DEFAULT_CHUNK_SIZE; log.setLevel(Level.DEBUG); } @Override public boolean nextKeyValue() throws IOException, InterruptedException { if (atEOF || currentEnd >= end) return false; else if (notReadYet) { currentStart = start; notReadYet = false; } else { currentStart = currentEnd; } long bytesToRead = ((end - currentStart) > (getChunksPerSplit() * chunkSize)) ? (getChunksPerSplit() * chunkSize) : (end - currentStart); byte[] buf = stream.readImageBytes(currentStart, (int) bytesToRead); log.debug("stream.readImageBytes(" + currentStart + ", (int) " + bytesToRead + ") = " + buf.length + ";"); currentValue.set(buf,0,buf.length); currentEnd = currentStart + buf.length; return currentEnd <= end; } @Override public LongWritable getCurrentKey() { return new LongWritable(currentStart); } @Override public BytesWritable getCurrentValue() { return new BytesWritable(currentValue.copyBytes()); } @Override public float getProgress() throws IOException { if (start == end) return 0.0f; else return (float) (currentEnd - start) / (end - start); } @Override public void close() throws IOException { if(stream != null) stream.close(); } protected long getChunksPerSplit() throws IOException { SparkConf sparkConf = new SparkConf(); if (nChunksPerSplit == -1L) { // Use the smaller of Spark's blocksize or the HDFS filesystem's block size long sparkBlockSize = (sparkConf.contains("spark.broadcast.blockSize") ? sparkConf.getSizeAsBytes("spark.broadcast.blockSize") : Long.MAX_VALUE); long hdfsBlockSize = fs.getFileStatus(file).getBlockSize(); nChunksPerSplit = (Math.min(sparkBlockSize,hdfsBlockSize)/chunkSize) - 1L; } return nChunksPerSplit; } }
package com.feeyo.redis.nio; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.feeyo.redis.nio.util.TimeUtil; import com.feeyo.util.JavaUtils; /** * ZeroCopy * * diskutil list * * @author zhuam */ public class ZeroCopyConnection extends ClosableConnection { private static Logger LOGGER = LoggerFactory.getLogger( ZeroCopyConnection.class ); private static final int MAPPED_SIZE = 1024 * 1024 * 2; protected AtomicBoolean rwLock = new AtomicBoolean(false); private String fileName; private File file; private RandomAccessFile randomAccessFile; protected FileChannel fileChannel; private MappedByteBuffer mappedByteBuffer; public ZeroCopyConnection(SocketChannel channel) { super(channel); try { // OPS tmpfs or ramdisk path String path = System.getProperty("feeyo.zerocopy.path"); if ( path == null ) { if ( JavaUtils.isLinux() ) path = "/dev/shm"; // Linux tmpfs else path = ""; } this.fileName = path + id + ".mapped"; this.file = new File( this.fileName ); // ensure ensureDirOK(this.file.getParent()); // mmap this.randomAccessFile = new RandomAccessFile(file, "rw"); this.randomAccessFile.setLength(MAPPED_SIZE); this.randomAccessFile.seek(0); this.fileChannel = randomAccessFile.getChannel(); this.mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, MAPPED_SIZE); } catch (IOException e) { LOGGER.error("create mapped err:", e); } } // , reactor @SuppressWarnings("unchecked") @Override public void asynRead() throws IOException { if (isClosed.get()) { return; } if ( !rwLock.compareAndSet(false, true) ) { return; } lastReadTime = TimeUtil.currentTimeMillis(); try { for(;;) { int position = mappedByteBuffer.position(); int count = MAPPED_SIZE - position; int tranfered = (int) fileChannel.transferFrom(socketChannel, position, count); mappedByteBuffer.position( position + tranfered ); // fixbug: transferFrom() always return 0 when client closed abnormally! // So decide whether the connection closed or not by read()! if( tranfered == 0 && count > 0 ){ tranfered = socketChannel.read(mappedByteBuffer); } if ( tranfered > 0 ) { netInBytes += tranfered; netInCounter++; byte[] data = new byte[ tranfered ]; mappedByteBuffer.flip(); mappedByteBuffer.get(data, 0, tranfered); //System.out.println( "asynRead, tranfered="+ tranfered + ", " + new String(data) ); if ( isNested ) handler.handleReadEvent(parent, data); else handler.handleReadEvent(this, data); break; } else if ( tranfered == 0 ) { LOGGER.warn("sockect read abnormal, tranfered={}", tranfered); if (!this.socketChannel.isOpen()) { this.close("socket closed"); return; } // not enough space this.mappedByteBuffer.clear(); } else { this.close("stream closed"); return; } } } finally { rwLock.set(false); } } @Override public void write(byte[] buf) { write( ByteBuffer.wrap(buf) ); } @Override public void write(ByteBuffer buf) { try { for (;;) { if ( !rwLock.compareAndSet(false, true) ) { break; } } buf.flip(); int bufSize = buf.limit(); if ( bufSize <= MAPPED_SIZE ) { mappedByteBuffer.clear(); int position = 0; int count = fileChannel.write(buf, position); if ( buf.hasRemaining() ) { throw new IOException("can't write whole buffer ,writed " + count + " remains " + buf.remaining()); } int tranfered = write0(position, count); netOutCounter++; netOutBytes += tranfered; lastWriteTime = TimeUtil.currentTimeMillis(); // recycle NetSystem.getInstance().getBufferPool().recycle(buf); } else { int cnt = ( bufSize / MAPPED_SIZE ) + ( bufSize % MAPPED_SIZE > 0 ? 1 : 0); int postion = 0; for (int i = 1; i <= cnt; i++) { int limit = MAPPED_SIZE * i; if ( limit > bufSize ) { limit = bufSize; } buf.position( postion ); buf.limit( limit ); ByteBuffer tmpBuf = buf.slice(); mappedByteBuffer.clear(); int count = fileChannel.write(tmpBuf, 0); if ( tmpBuf.hasRemaining() ) { throw new IOException("can't write whole buffer ,writed " + count + " remains " + tmpBuf.remaining()); } int tranfered = write0(0, count); postion += tranfered; netOutCounter++; netOutBytes += tranfered; lastWriteTime = TimeUtil.currentTimeMillis(); } // recycle NetSystem.getInstance().getBufferPool().recycle(buf); } } catch (IOException e) { LOGGER.error("write err:", e); this.close("write err:" + e); } finally { rwLock.set(false); } } private int write0(int position, int count) throws IOException { // socketChannel int tranfered = (int) fileChannel.transferTo(position, count, socketChannel); boolean noMoreData = tranfered == count; if (noMoreData) { if ((processKey.isValid() && (processKey.interestOps() & SelectionKey.OP_WRITE) != 0)) { disableWrite(); } } else { if ((processKey.isValid() && (processKey.interestOps() & SelectionKey.OP_WRITE) == 0)) { enableWrite(false); } } return tranfered; } @Override public void doNextWriteCheck() { // ignore } @Override protected void cleanup() { try { unmap(mappedByteBuffer); randomAccessFile.close(); fileChannel.close(); if ( file != null ){ boolean result = this.file.delete(); LOGGER.info("delete file, name={}, result={}" , this.fileName , result ); } } catch (IOException e) { LOGGER.error(" cleanup err: fileName=" + fileName, e); } } // unmap private void unmap(final MappedByteBuffer buffer) { AccessController.doPrivileged(new PrivilegedAction<MappedByteBuffer>() { @SuppressWarnings("restriction") public MappedByteBuffer run() { try { Method cleanerMethod = buffer.getClass().getMethod("cleaner", new Class[0]); cleanerMethod.setAccessible(true); sun.misc.Cleaner cleaner = (sun.misc.Cleaner) cleanerMethod.invoke(buffer, new Object[0]); cleaner.clean(); } catch (Exception e) { LOGGER.error("cannot clean Buffer", e); } return null; } }); } private void ensureDirOK(final String dirName) { if (dirName != null) { File f = new File(dirName); if (!f.exists()) { boolean result = f.mkdirs(); LOGGER.info(dirName + " mkdir " + (result ? "OK" : "Failed")); } } } @Override public String toString() { StringBuffer sbuffer = new StringBuffer(100); sbuffer.append( "Conn [" ); sbuffer.append("reactor=").append( reactor ); sbuffer.append(", host=").append( host ).append(":").append( port ); sbuffer.append(", id=").append( id ); sbuffer.append(", startup=").append( startupTime ); sbuffer.append(", lastRT=").append( lastReadTime ); sbuffer.append(", lastWT=").append( lastWriteTime ); sbuffer.append(", attempts=").append( writeAttempts ); sbuffer.append(", cc=").append( netInCounter ).append("/").append( netOutCounter ); if ( isClosed.get() ) { sbuffer.append(", isClosed=").append( isClosed ); sbuffer.append(", closedTime=").append( closeTime ); sbuffer.append(", closeReason=").append( closeReason ); } sbuffer.append("]"); return sbuffer.toString(); } }
package com.github.bedrin.jdbc.sniffer; import java.util.concurrent.atomic.AtomicInteger; public class Sniffer { private static final AtomicInteger counter = new AtomicInteger(); public static void executeStatement() { counter.incrementAndGet(); } public static int executedStatements() { return counter.get(); } public static void reset() { counter.set(0); } public static void verifyNotMore() { verifyNotMoreThan(0); } public static void verifyNotMoreThanOne() { verifyNotMoreThan(1); } public static void verifyNotMoreThan(int allowedStatements) throws IllegalStateException { if (executedStatements() > allowedStatements) throw new IllegalStateException(String.format("Allowed not more than %d statements, but actually caught %d statements", allowedStatements, actualStatements)); reset(); } }
package com.github.bot.curiosone.core.nlp; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; /** * Handles a Word. * A Word is like a Token, but with a restricted Set of Meanings. * Provides methods to create a new Word and retrieve its information. * */ public class Word { /** * Stores the textual representation of this Word. */ String text; /** * Stores the base form of this Word. */ String lemma; /** * Stores all the possible meanings of this Word. */ Set<Meaning> means; /** * Constructs a Word starting from a text, a lemma and a Set of meanings. * @param text a textual representation of this Word * @param lemma the lemma for this Word * @param means Set containing all the possible meanings for this Word */ public Word(String text, String lemma, Set<Meaning> means) { this.text = text; this.lemma = lemma; this.means = means; } /** * Constructs a Word starting from a text, a lemma and a single meaning. * @param text textual representation of this Word * @param lemma the lemma for this Word * @param mean meaning of this Word */ public Word(String text, String lemma, Meaning mean) { this.text = text; this.lemma = lemma; this.means = new HashSet<>(); means.add(mean); } /** * Returns the textual representation of this Word. */ public String getText() { return text; } /** * Returns the lemma of this Word. */ public String getLemma() { return lemma; } /** * Returns the Set of the meanings of this Word. */ public Set<Meaning> getMeanings() { return means; } /** * Checks whether this Word has the given meaning or not. * @param mean the meaning to be checked * @return {@code true} if the given meaning is associated with this Word, {@code false} otherwise */ public boolean itMeans(Meaning mean) { return means.contains(mean); } /** * Checks whether this Word is the given Part of Speech Type or not. * @param pos the POS to be checked * @return {@code true} if this Word is the given POS, {@code false} otherwise */ public boolean itMeans(POS pos) { return means.stream() .map(Meaning::getPOS) .collect(Collectors.toList()) .contains(pos); } /** * Checks whether this Word is the given Lexical Type or not. * @param lex the LEX to be checked * @return {@code true} if this Word is the given LEX, {@code false} otherwise */ public boolean itMeans(LEX lex) { return means.stream() .map(Meaning::getLEX) .collect(Collectors.toList()) .contains(lex); } /** * Returns a String representation of this Word in the form [text, word, meanings]. */ @Override public String toString() { return "[" + text + " (" + lemma + ")" + ", " + means + "]"; } /** * Checks whether this Word equals to the given Object. * @param other the other Word to be compared against * @return {@code true} if this Word equals the other Word; * {@code false} otherwise */ @Override public boolean equals(Object other) { if (other == this) { return true; } if (other == null || other.getClass() != this.getClass()) { return false; } Word that = (Word) other; return this.text.equals(that.text); } /** * Returns the HashCode of this Word. * The HashCode is based on the HashCode of the textual representation of this Word. */ @Override public int hashCode() { return text.hashCode(); } }
package com.github.target2sell; import com.datastax.driver.core.*; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaModule; import com.fasterxml.jackson.module.scala.DefaultScalaModule; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigRenderOptions; import org.joda.time.DateTime; import org.slf4j.Logger; import scala.Option; import scala.Predef; import scala.Tuple2; import scala.collection.Seq; import scala.collection.immutable.Map; import scala.collection.mutable.ArraySeq; import spark.jobserver.io.JobDAO; import spark.jobserver.io.JobInfo; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.StreamSupport; import static com.typesafe.config.ConfigValueFactory.fromAnyRef; import static java.nio.file.StandardOpenOption.CREATE_NEW; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import static org.slf4j.LoggerFactory.getLogger; import static scala.Option.empty; import static scala.collection.JavaConversions.asScalaBuffer; import static scala.collection.JavaConversions.asScalaMap; public class JobCassandraDao implements JobDAO { private final Logger logger = getLogger(JobCassandraDao.class); private final ObjectMapper mapper; private final Path jarCacheDirectory; private Session session; private PreparedStatement saveJobConfigStatement; private PreparedStatement findJobConfigStatement; private PreparedStatement saveJobInfoStatement; private PreparedStatement findJobInfoStatement; private PreparedStatement findJobInfosStatement; private PreparedStatement saveJarStatement; private PreparedStatement findAppsStatement; private PreparedStatement findJar; public JobCassandraDao(Config config) { Config defaultConfig = ConfigFactory.empty() .withValue("spark.jobserver.cassandradao.datacenter", fromAnyRef("dc1")) .withValue("spark.jobserver.cassandradao.keyspace", fromAnyRef("jobserver")) .withValue("spark.jobserver.cassandradao.contactsPoints", fromAnyRef("127.0.0.1")) .withValue("spark.jobserver.cassandradao.consistencyLevel", fromAnyRef("ONE")) .withValue("spark.jobserver.cassandradao.datacenter", fromAnyRef("datacenter1")) .withValue("spark.jobserver.cassandradao.jarCache", fromAnyRef("/tmp/jobserver/cassandradao/")); Config configMerged = config.withFallback(defaultConfig); String datacenter = configMerged.getString("spark.jobserver.cassandradao.datacenter"); String keyspace = configMerged.getString("spark.jobserver.cassandradao.keyspace"); String contactsPoints = configMerged.getString("spark.jobserver.cassandradao.contactsPoints"); String consistencyLevel = configMerged.getString("spark.jobserver.cassandradao.consistencyLevel"); SessionProvider sessionProvider = new SessionProvider(datacenter, keyspace, contactsPoints, consistencyLevel); session = sessionProvider.getInstance(); this.jarCacheDirectory = Paths.get(configMerged.getString("spark.jobserver.cassandradao.jarCache")); init(); mapper = new ObjectMapper(); mapper.registerModules(new DefaultScalaModule(), new JodaModule()); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } private void init() { saveJobInfoStatement = session.prepare("INSERT INTO job_info(job_id, content) VALUES (:job_id, :content)"); findJobInfoStatement = session.prepare("SELECT job_id, content FROM job_info WHERE job_id = :job_id"); findJobInfosStatement = session.prepare("SELECT job_id, content FROM job_info"); saveJobConfigStatement = session.prepare("INSERT INTO job_config(job_id, content) VALUES (:job_id, :content)"); findJobConfigStatement = session.prepare("SELECT job_id, content FROM job_config"); saveJarStatement = session.prepare("INSERT INTO applications(app_name, upload_time, jar_content) VALUES (:app_name, :upload_time, :jar_content)"); findAppsStatement = session.prepare("SELECT app_name, upload_time FROM applications"); findJar = session.prepare("SELECT jar_content FROM applications WHERE app_name = :app_name AND upload_time = :upload_time"); } @Override public void saveJar(String appName, DateTime uploadTime, byte[] jarBytes) { BoundStatement statement = saveJarStatement.bind() .setString("app_name", appName) .setDate("upload_time", uploadTime.toDate()) .setBytes("jar_content", ByteBuffer.wrap(jarBytes)); session.execute(statement); } @Override public Map<String, DateTime> getApps() { java.util.Map<String, DateTime> apps = StreamSupport.stream(session.execute(findAppsStatement.bind()).spliterator(), false) .collect(toMap(row -> row.getString("app_name"), row -> new DateTime(row.getDate("upload_time").getTime()))); return convertMapToImmutableMap(apps); } @Override public String retrieveJarFile(String appName, DateTime uploadTime) { Path jar = jarCacheDirectory.resolve(Paths.get(uploadTime.toString(), appName + ".jar")); boolean jarExists = jar.toFile().exists() || fetchJarToCacheFile(appName, uploadTime, jar); if (!jarExists) return ""; return jar.toAbsolutePath().toString(); } private boolean fetchJarToCacheFile(String appName, DateTime uploadTime, Path jar) { if (!jar.getParent().toFile().exists() && !jar.getParent().toFile().mkdirs()) { logger.error("Unable to make jar cache directory in: {}", jar.getParent().toString()); return false; } BoundStatement boundStatement = findJar.bind() .setString("app_name", appName) .setDate("upload_time", uploadTime.toDate()); ResultSet resultSet = session.execute(boundStatement); if (resultSet.isExhausted()) { return false; } ByteBuffer jarContent = resultSet.one().getBytes("jar_content"); try (OutputStream jarOutputStream = Files.newOutputStream(jar, CREATE_NEW)) { jarOutputStream.write(jarContent.array()); } catch (IOException e) { logger.error("Unable to write jar content: {}", e.getMessage(), e); return false; } return true; } @Override public void saveJobInfo(JobInfo jobInfo) { try { String content = mapper.writeValueAsString(jobInfo); session.execute(saveJobInfoStatement.bind(jobInfo.jobId(), content)); } catch (JsonProcessingException e) { logger.error("Unable to parse serialize jobinfo: {}", e.getMessage(), e); throw new RuntimeException("Unable to parse serialize jobinfo: " + e.getMessage(), e); } } @Override public Option<JobInfo> getJobInfo(String jobId) { final ResultSet resultSet = session.execute(findJobInfoStatement.bind(jobId)); if (resultSet.isExhausted()) { return empty(); } return Option.apply(parseStringToJobInfo(resultSet.one())); } @Override public Seq<JobInfo> getJobInfos(int limit) { final ResultSet resultSet = session.execute(findJobInfosStatement.bind()); if (resultSet.isExhausted()) { return new ArraySeq<>(0); } List<JobInfo> jobInfoList = StreamSupport.stream(resultSet.spliterator(), false) .map(this::parseStringToJobInfo) .filter(jobInfo -> jobInfo != null) .limit(limit) .collect(toList()); return asScalaBuffer(jobInfoList).toList(); } private JobInfo parseStringToJobInfo(Row row) { try { return mapper.readValue(row.getString("content"), JobInfo.class); } catch (IOException e) { logger.error("Unable to parse jobinfo: {}", e.getMessage(), e); throw new RuntimeException("Unable to parse jobinfo: " + e.getMessage(), e); } } @Override public void saveJobConfig(String jobId, Config jobConfig) { String content = jobConfig.root().render(ConfigRenderOptions.concise()); session.execute(saveJobConfigStatement.bind(jobId, content)); } @Override public Map<String, Config> getJobConfigs() { ResultSet resultSet = session.execute(findJobConfigStatement.bind()); java.util.Map<String, Config> jobConfigs = StreamSupport.stream(resultSet.spliterator(), false) .map(this::parseStringToJobConfig) .filter(jobConfig -> jobConfig != null) .collect(toMap(Tuple2::_1, Tuple2::_2)); return convertMapToImmutableMap(jobConfigs); } private <T, U> Map<T, U> convertMapToImmutableMap(java.util.Map<T, U> javaMap) { return asScalaMap(javaMap).toMap(Predef.<Tuple2<T, U>>conforms()); } private Tuple2<String, Config> parseStringToJobConfig(Row row) { return new Tuple2<>(row.getString("job_id"), ConfigFactory.parseString(row.getString("content"))); } @Override public Option<DateTime> getLastUploadTime(String appName) { return this.getApps().get(appName); } }
package com.google.sps.workspace; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import com.google.sps.utils.StringUtils; public class WorkspaceFile { private final Query q; private final String docBase; private final String fileName; protected WorkspaceFile(DataSnapshot snap) { fileName = decodeFilename(snap.getKey()); if (snap.hasChild("checkpoint/id")) { docBase = (String) snap.child("checkpoint").child("o").getValue(); q = snap.getRef() .child("history") .orderByKey() .startAt((String) snap.child("checkpoint").child("id").getValue()); } else { docBase = ""; q = snap.getRef().child("history").orderByKey(); } } public Future<String> getContents() { CompletableFuture<String> future = new CompletableFuture<>(); q.addListenerForSingleValueEvent( new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { try { String doc = padSurrogatePairs(docBase); for (DataSnapshot ops : snapshot.getChildren()) { long idx = 0; for (Object op : (List<Object>) ops.child("o").getValue()) { if (op instanceof Long) { long longOp = ((Long) op).longValue(); if (longOp > 0) { // retain idx += longOp; } else { // delete doc = StringUtils.slice(doc, (int) idx, (int) -longOp); // doc.substring(0, (int) idx + 1) + doc.substring((int) (idx - longOp + 1)); } } else { // insert String stringOp = padSurrogatePairs((String) op); doc = StringUtils.insert(doc, stringOp, (int) idx); } } // Remove surrogate pair padding. doc.replaceAll("\0", ""); } future.complete(doc); } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); future.complete(sw.toString()); } } @Override public void onCancelled(DatabaseError error) { future.completeExceptionally(error.toException()); } }); return future; } private static String padSurrogatePairs(String str) { String newStr = str; int offset = 0; for (int i = 0; i < str.length(); i++) { if (str.codePointAt(i) >= 0x10000 && str.codePointAt(i) <= 0x10FFFF) { newStr = StringUtils.insert(newStr, "\0", i + offset); offset++; } } return newStr; } public String getFilename() { return fileName; } private String decodeFilename(String filename) { try { return URLDecoder.decode(filename.replaceAll("%2E", "."), StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { return filename; } } }
package com.greghaskins.spectrum; import static com.greghaskins.spectrum.Spectrum.compositeSpec; import static com.greghaskins.spectrum.Spectrum.describe; import static com.greghaskins.spectrum.Spectrum.it; /** * A translation from Spectrum describe/it to Gherkin-like Feature/Scenario/Given/When/Then syntax * Note - the beforeEach and afterEach will still be executed between given/when/then steps which * may not make sense in many situations. */ public interface GherkinSyntax { /** * Describes a feature of the system. A feature may have many scenarios. * * @param featureName name of feature * @param block the contents of the feature * * @see #scenario */ public static void feature(final String featureName, final Block block) { describe("Feature: " + featureName, block); } /** * Describes a scenario of the system. These can be at root level, though scenarios are best * grouped inside {@link #feature} declarations. * * @param scenarioName name of scenario * @param block the contents of the scenario - given/when/then steps * * @see #feature * @see #given * @see #when * @see #then */ public static void scenario(final String scenarioName, final Block block) { compositeSpec("Scenario: " + scenarioName, block); } /** * Define a precondition step with a Gherkin-like {@code given} block. Must be used inside a * {@link #scenario}. * * @param behavior the behavior to associate with the precondition * @param block how to execute that precondition * * @see #when * @see #then */ public static void given(final String behavior, final Block block) { it("Given " + behavior, block); } /** * Define the action performed by the system under test using a Gherkin-like {@code when } block. * Must be used inside a {@link #scenario}. * * @param behavior the behavior to associate with the manipulation of the system under test * @param block how to execute that behavior * * @see #given * @see #then */ public static void when(final String behavior, final Block block) { it("When " + behavior, block); } /** * Define a postcondition step with a Gherkin-like {@code then} block. Must be used inside a * {@link #scenario}. * * @param behavior the behavior to associate with the postcondition * @param block how to execute that postcondition * * @see #given * @see #when */ public static void then(final String behavior, final Block block) { it("Then " + behavior, block); } /** * Syntactic sugar for an additional {@link #given} or {@link then} step. Must be used inside a * {@link #scenario}. * * @param behavior what we would like to describe as an and * @param block how to achieve the and block * * @see #given * @see #when * @see #then */ public static void and(final String behavior, final Block block) { it("And " + behavior, block); } }
package com.hjh.files.sync.client; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.http.util.Asserts; import com.hjh.files.sync.common.HLogFactory; import com.hjh.files.sync.common.ILog; import com.hjh.files.sync.common.RemoteFile; import com.hjh.files.sync.common.RemoteFileFactory; import com.hjh.files.sync.common.RemoteFileManage; import com.hjh.files.sync.common.RemoteSyncConfig; import com.hjh.files.sync.common.StopAble; import com.hjh.files.sync.common.util.MD5; public class ClientFolder { private static ILog logger = HLogFactory.create(ClientFolder.class); private final static String CLIENT_CACHE_FOLDER_NAME = ".c.cache"; private RemoteFileManage fromManage; private String store_folder; private String name; private String url; private File cache; public ClientFolder(String name, String store_folder, String url) { this.name = name; this.store_folder = store_folder; this.url = url; this.cache = new File(store_folder, CLIENT_CACHE_FOLDER_NAME); this.cache = new File(this.cache, "_" + RemoteSyncConfig.getBlockSize()); if (!this.cache.isDirectory()) { Asserts.check(this.cache.mkdirs(), "can not create cache folder for client on :" + this.cache.getAbsolutePath()); } } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getStore_folder() { return store_folder; } public void setStore_folder(String store_folder) { this.store_folder = store_folder; } public void sync(StopAble stop) throws IOException { String store_path = new File(new File(store_folder), name).getCanonicalPath(); if (null == fromManage) { fromManage = RemoteFileFactory.queryManage(url); } logger.stdout(String.format("sync[%s] %s => %s", name, url, store_path)); File root = new File(store_path); if (!root.exists()) { root.mkdir(); } Asserts.check(root.isDirectory(), "must be a directory :" + store_path); long time = System.currentTimeMillis(); try { if (stop.isStop()) { return; } doSync(stop, null, root); } finally { long end = System.currentTimeMillis(); logger.stdout(String.format("sync finish[%s](cost: %s) %s => %s", name, (end - time) / 1000 + "s", url, store_path)); } } private void doSync(StopAble stop, RemoteFile from, File target) throws IOException { if (null == from || from.isFolder()) { String path = null == from ? null : from.path(); if (stop.isStop()) { return; } RemoteFile[] remotes = fromManage.list(path); if (stop.isStop()) { return; } if (target.isFile()) { logger.stdout("remove file:" + target.getAbsolutePath()); Asserts.check(target.delete(), "delete file fail : " + target.getAbsolutePath()); } if (!target.exists()) { logger.stdout(String.format("sync folder[%s] %s => %s", name, path, target.getAbsolutePath())); Asserts.check(target.mkdir(), "create folder fail : " + target.getAbsolutePath()); } String[] exists = target.list(); for (RemoteFile item : remotes) { doSync(stop, item, new File(target, item.name())); if (null != exists) { for (int i = 0; i < exists.length; i++) { if (exists[i] != null && exists[i].equals(item.name())) { exists[i] = null; break; } } } } if (null != exists) { for (int i = 0; i < exists.length; i++) { if (exists[i] != null) { File cur_exist = new File(target, exists[i]); if (cur_exist.isDirectory()) { logger.stdout("remove directory:" + cur_exist.getAbsolutePath()); FileUtils.deleteDirectory(cur_exist); } else { logger.stdout("remove file:" + cur_exist.getAbsolutePath()); Asserts.check(cur_exist.delete(), "can not delete file :" + cur_exist.getAbsolutePath()); } } } } } else { if (!isSame(from, target)) { logger.stdout(String.format("sync file[%s] %s => %s", name, from.path(), target.getAbsolutePath())); if (stop.isStop()) { return; } String md5 = fromManage.md5(from.path()); if (stop.isStop()) { return; } if (target.isDirectory()) { logger.stdout("remove directory:" + target.getAbsolutePath()); FileUtils.deleteDirectory(target); } String local_md5 = target.isFile() ? MD5.md5(target) : null; if (!md5.equals(local_md5)) { File current_cache_root = new File(cache, md5.substring(0, 2)); if (!current_cache_root.exists()) { current_cache_root.mkdir(); } current_cache_root = new File(current_cache_root, md5); if (!current_cache_root.exists()) { current_cache_root.mkdir(); } if (stop.isStop()) { return; } int totalParts = fromManage.partCount(from.length()); if (stop.isStop()) { return; } for (int i = 0; i < totalParts; i++) { File cur_part = new File(current_cache_root, i + ""); if (!cur_part.exists()) { if (stop.isStop()) { return; } byte[] part_data = fromManage.part(from.path(), i); logger.debug(String.format("[%s] [%s] [%d] receive part data %d K", name, from.path(), i + 1, part_data.length / 1024)); FileUtils.writeByteArrayToFile(cur_part, part_data); if (stop.isStop()) { return; } } } File target_temp = new File(current_cache_root, "temp"); if (target_temp.isDirectory()) { logger.stdout("remove directory:" + target_temp.getAbsolutePath()); FileUtils.deleteDirectory(target_temp); } if (target_temp.isFile()) { String cache_md5 = MD5.md5(target_temp); if (!md5.equals(cache_md5)) { Asserts.check(target_temp.delete(), "can not delete wrong file[md5 do not match]:" + target_temp.getAbsolutePath()); } } if (!target_temp.exists()) { target_temp.createNewFile(); FileOutputStream out = new FileOutputStream(target_temp); try { for (int i = 0; i < totalParts; i++) { File cur_part = new File(current_cache_root, i + ""); out.write(FileUtils.readFileToByteArray(cur_part)); } } finally { out.close(); } } { String cache_md5 = MD5.md5(target_temp); if (!md5.equals(cache_md5)) { logger.stdout("clear dirty directory : " + current_cache_root.getAbsolutePath()); FileUtils.deleteDirectory(current_cache_root); throw new RuntimeException("can not fetch correct data from remote for:" + from.path()); } } if (target.isFile()) { logger.stdout("remove unmatch file:" + target.getAbsolutePath()); Asserts.check(target.delete(), String.format("can not delete file : %s", target.getAbsolutePath())); } Asserts.check(target_temp.renameTo(target), String.format("can not move file: %s => %s", target_temp.getAbsolutePath(), target.getAbsolutePath())); } target.setLastModified(from.lastModify()); } } } private boolean isSame(RemoteFile from, File to) { if (!to.exists()) { return false; } if (from.isFolder()) { if (!to.isDirectory()) { return false; } } else { if (to.isDirectory()) { return false; } } if (!from.name().equals(to.getName())) { return false; } if (from.lastModify() != to.lastModified()) { logger.debug(String.format("[%s] %d <> %d", from.path(), from.lastModify(), to.lastModified())); if (Math.abs(from.lastModify() - to.lastModified()) > RemoteSyncConfig.getMinDiffTime()) { return false; } } if (from.length() != to.length()) { return false; } return true; } }
package com.openspection.service; import com.openspection.model.Person; import com.openspection.model.Role; import com.openspection.model.Userprofile; import com.openspection.persistence.SystemDataAccess; import java.security.Principal; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller public class PersonService { //PEOPLE //GET @RequestMapping(value = "people", method = RequestMethod.GET) @ResponseBody public final List< Person> getAllPeople() { return SystemDataAccess.getAll("select p from Person p "); } @RequestMapping(value = "people/{id}", method = RequestMethod.GET) @ResponseBody public final Person getPerson(@PathVariable("id") final Long id) { return (Person) SystemDataAccess.get(Person.class, id); } public final Person getPersonByEmail(final String tvsEmail) { Object[][] tvoObject = new Object[1][2]; tvoObject[0][0] = "email"; tvoObject[0][1] = tvsEmail; List<Person> ppAll = SystemDataAccess.getWithParams("select p from Person p where p.email in (:email) ", tvoObject); if (ppAll.size() > 0) { return (Person) ppAll.get(0); } return null; } @RequestMapping(value = "profile/{id}", method = RequestMethod.GET) @ResponseBody public final Userprofile getPersonProfile(@PathVariable("id") final Long id) { return (Userprofile) SystemDataAccess.get(Userprofile.class, id.toString()); } @RequestMapping(value = "profile", method = RequestMethod.GET) @ResponseBody public final Userprofile getLoggedInPersonProfile(@RequestParam String day) { PersonService tvoPersonService = new PersonService(); Person tvoPerson = tvoPersonService.getPersonByEmail(fvoPrincipal.getName()); return (Userprofile) SystemDataAccess.get(Userprofile.class, tvoPerson.getId().toString()); } //POST @RequestMapping(value = "people", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public final Person addPerson(@RequestBody final Person p) { Person tvoReturn = getPersonByEmail(p.getEmail()); if (tvoReturn != null) { return (Person) tvoReturn; } p.setId(null); p.setIsenabled(true); BCryptPasswordEncoder tvoBCryptEncoder = new BCryptPasswordEncoder(); p.setPassword(tvoBCryptEncoder.encode(p.getPassword())); Person pNew = (Person) SystemDataAccess.add(p); Role tvoRole = new Role(); tvoRole.setName("ROLE_CANPOST"); tvoRole.setPersonid(pNew.getId()); SystemDataAccess.add(tvoRole); Userprofile upNew = new Userprofile(); upNew.setId_str(pNew.getId().toString()); upNew.setName(pNew.getName()); upNew.setReputation(1L); SystemDataAccess.add(upNew); return pNew; } @RequestMapping(value = "people/{id}/changepassword/", method = RequestMethod.POST) @ResponseStatus(HttpStatus.OK) public void changePassword(@PathVariable("id") final Long id, @RequestParam String oldpassword, @RequestParam String newpassword, @RequestParam String confirmpassword, Principal fvoPrincipal ) { //TODO: Validate new and confirm match if (!newpassword.equals(confirmpassword)) return; //TODO: confirm person exists if (!doesExist(id)) return; //TODO: confirm person is principal Person tvoPerson = getPerson(id); if (!tvoPerson.getEmail().equals(fvoPrincipal.getName())) return; //TODO: Validate old and person match BCryptPasswordEncoder tvoBCryptEncoder = new BCryptPasswordEncoder(); String tvsEncryptedOldPassword = tvoBCryptEncoder.encode(oldpassword); if (!tvoPerson.getPassword().equals(tvsEncryptedOldPassword)) return; String tvsEncryptedNewPassword = tvoBCryptEncoder.encode(newpassword); tvoPerson.setPassword(tvsEncryptedNewPassword); setPerson(id, tvoPerson); } public boolean doesExist(Long personid){ Person tvoPerson = getPerson(personid); if (tvoPerson!=null) return true; return false; } //PUT @RequestMapping(value = "people/{id}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody public final Person setPerson(@PathVariable("id") final Long id, @RequestBody final Person p, Principal fvoPrincipal) { if (!doesExist(id)) return null; Person tvoPerson = getPerson(id); if (!tvoPerson.getEmail().equals(fvoPrincipal.getName())) return null; return (Person) SystemDataAccess.set(Person.class, id, p); } //DELETE @RequestMapping(value = "people/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) public final void deletePerson(@PathVariable("id") final Long id) { SystemDataAccess.delete(Person.class, id); } }
package com.redhat.ceylon.compiler.js; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import com.redhat.ceylon.cmr.api.ArtifactContext; import com.redhat.ceylon.cmr.ceylon.CeylonUtils; import com.redhat.ceylon.cmr.impl.ShaSigner; import com.redhat.ceylon.common.Constants; import com.redhat.ceylon.common.FileUtil; import com.redhat.ceylon.compiler.js.util.JsIdentifierNames; import com.redhat.ceylon.compiler.js.util.JsJULLogger; import com.redhat.ceylon.compiler.js.util.JsOutput; import com.redhat.ceylon.compiler.js.util.Options; import com.redhat.ceylon.compiler.loader.MetamodelVisitor; import com.redhat.ceylon.compiler.loader.ModelEncoder; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.model.typechecker.model.Module; /** A simple program that takes the main JS module file and replaces #include markers with the contents of other files. * * @author Enrique Zamudio */ public class Stitcher { private static TypeCheckerBuilder langmodtc; private static Path tmpDir; private static final File baseDir = new File("../ceylon.language"); private static final File srcDir = new File("src"); private static final File jsDir = new File("runtime-js"); private static final File clSrcDir = new File(baseDir, "src"); private static final File clSrcFileDir = new File(clSrcDir, "ceylon/language/"); public static final File LANGMOD_JS_SRC = new File(baseDir, "runtime-js"); private static final File clJsFileDir = new File(LANGMOD_JS_SRC, "ceylon/language"); private static JsIdentifierNames names; private static Module mod; private static final HashSet<File> compiledFiles = new HashSet<>(256); private static int compileLanguageModule(final String line, final JsOutput writer) throws IOException { File clsrcTmpDir = Files.createTempDirectory(tmpDir, "clsrc").toFile(); final File tmpout = new File(clsrcTmpDir, Constants.DEFAULT_MODULE_DIR); tmpout.mkdir(); final Options opts = new Options().addRepo("build/runtime").comment(false).optimize(true) .outRepo(tmpout.getAbsolutePath()).modulify(false).minify(true); //Typecheck the whole language module if (langmodtc == null) { langmodtc = new TypeCheckerBuilder() .addSrcDirectory(clSrcDir) .addSrcDirectory(LANGMOD_JS_SRC) .encoding("UTF-8"); langmodtc.setRepositoryManager(CeylonUtils.repoManager().systemRepo(opts.getSystemRepo()) .userRepos(opts.getRepos()).outRepo(opts.getOutRepo()).buildManager()); } final File mod2 = new File(clJsFileDir, "module.ceylon"); if (!mod2.exists()) { try (FileWriter w2 = new FileWriter(mod2); FileReader r2 = new FileReader(new File(clSrcFileDir, "module.ceylon"))) { char[] c = new char[512]; int r = r2.read(c); while (r != -1) { w2.write(c, 0, r); r = r2.read(c); } mod2.deleteOnExit(); } finally { } } final TypeChecker tc = langmodtc.getTypeChecker(); tc.process(true); if (tc.getErrors() > 0) { return 1; } //Compile these files final List<File> includes = new ArrayList<File>(); for (String filename : line.split(",")) { filename = filename.trim(); final boolean isJsSrc = filename.endsWith(".js"); final boolean isDir = filename.endsWith("/"); final boolean exclude = filename.charAt(0)=='-'; if (exclude) { filename = filename.substring(1); } final File src = ".".equals(filename) ? clSrcFileDir : new File(isJsSrc ? LANGMOD_JS_SRC : clSrcFileDir, isJsSrc || isDir ? filename : String.format("%s.ceylon", filename)); if (!addFiles(includes, src, exclude)) { final File src2 = new File(clJsFileDir, isDir ? filename : String.format("%s.ceylon", filename)); if (!addFiles(includes, src2, exclude)) { throw new IllegalArgumentException("Invalid Ceylon language module source " + src + " or " + src2); } } } if (includes.isEmpty()) { return 0; } //Compile only the files specified in the line //Set this before typechecking to share some decls that otherwise would be private JsCompiler jsc = new JsCompiler(tc, opts, true).stopOnErrors(false); jsc.setSourceFiles(includes); if (!jsc.generate()) { jsc.printErrorsAndCount(new OutputStreamWriter(System.out)); return 1; } else { // We still call this here for any warning there might be jsc.printErrorsAndCount(new OutputStreamWriter(System.out)); } if (names == null) { names = jsc.getNames(); } File compsrc = new File(tmpout, "delete/me/delete-me.js"); if (compsrc.exists() && compsrc.isFile() && compsrc.canRead()) { try { writer.outputFile(compsrc); } finally { compsrc.delete(); } } else { System.out.println("Can't find generated js for language module in " + compsrc.getAbsolutePath()); return 1; } return 0; } private static boolean addFiles(final List<File> includes, final File src, boolean exclude) { if (src.exists() && src.isFile() && src.canRead()) { if (exclude) { System.out.println("EXCLUDING " + src); compiledFiles.add(src); } else if (!compiledFiles.contains(src)) { includes.add(src); compiledFiles.add(src); } } else if (src.exists() && src.isDirectory()) { for (File sub : src.listFiles()) { if (!compiledFiles.contains(sub)) { includes.add(sub); compiledFiles.add(sub); } } } else { return false; } return true; } private static int encodeModel(final File moduleFile) throws IOException { final String name = moduleFile.getName(); final File file = new File(moduleFile.getParentFile(), name.substring(0,name.length()-3)+ArtifactContext.JS_MODEL); System.out.println("Generating language module compile-time model in JSON..."); TypeCheckerBuilder tcb = new TypeCheckerBuilder().usageWarnings(false); tcb.addSrcDirectory(clSrcDir); TypeChecker tc = tcb.getTypeChecker(); tc.process(true); MetamodelVisitor mmg = null; final ErrorCollectingVisitor errVisitor = new ErrorCollectingVisitor(tc); for (PhasedUnit pu : tc.getPhasedUnits().getPhasedUnits()) { pu.getCompilationUnit().visit(errVisitor); if (errVisitor.getErrorCount() > 0) { errVisitor.printErrors(false, false); System.out.println("whoa, errors in the language module " + pu.getCompilationUnit().getLocation()); return 1; } if (mmg == null) { mmg = new MetamodelVisitor(pu.getPackage().getModule()); } pu.getCompilationUnit().visit(mmg); } mod = tc.getPhasedUnits().getPhasedUnits().get(0).getPackage().getModule(); try (FileWriter writer = new FileWriter(file)) { JsCompiler.beginWrapper(writer); writer.write("ex$.$CCMM$="); ModelEncoder.encodeModel(mmg.getModel(), writer); writer.write(";\n"); final JsOutput jsout = new JsOutput(mod, "UTF-8", true) { @Override public Writer getWriter() throws IOException { return writer; } }; jsout.outputFile(new File(LANGMOD_JS_SRC, "MODEL.js")); JsCompiler.endWrapper(writer); } finally { ShaSigner.sign(file, new JsJULLogger(), true); } return 0; } private static int stitch(File infile, final JsOutput writer) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(infile), "UTF-8")); try { String line = null; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() > 0) { if (line.startsWith("COMPILE ")) { final String sourceFiles = line.substring(8); System.out.println("Compiling language module sources: " + sourceFiles); int exitCode = compileLanguageModule(sourceFiles, writer); if (exitCode != 0) { return exitCode; } } } } } finally { if (reader != null) reader.close(); } return 0; } public static void main(String[] args) throws IOException { if (args.length < 2) { System.err.println("This program requires 2 arguments to run:"); System.err.println("1. The path to the master file (the one with the list of files to compile)"); System.err.println("2. The path of the resulting JS file"); System.exit(1); return; } int exitCode = 0; tmpDir = Files.createTempDirectory("ceylon-jsstitcher-"); try { File infile = new File(args[0]); if (infile.exists() && infile.isFile() && infile.canRead()) { File outfile = new File(args[1]); if (!outfile.getParentFile().exists()) { outfile.getParentFile().mkdirs(); } exitCode = encodeModel(outfile); if (exitCode == 0) { final int p0 = args[1].indexOf(".language-"); final String version = args[1].substring(p0+10,args[1].length()-3); try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8")) { final JsOutput jsout = new JsOutput(mod, "UTF-8", true) { @Override public Writer getWriter() throws IOException { return writer; } }; //CommonJS wrapper JsCompiler.beginWrapper(writer); //Model jsout.out("var _CTM$;function $CCMM$(){if (_CTM$===undefined)_CTM$=require('", "ceylon/language/", version, "/ceylon.language-", version, "-model", "').$CCMM$;return _CTM$;}\nex$.$CCMM$=$CCMM$;"); //Compile all the listed files exitCode = stitch(infile, jsout); //Unshared declarations if (names != null) { jsout.publishUnsharedDeclarations(names); } //Close the commonJS wrapper JsCompiler.endWrapper(writer); } finally { ShaSigner.sign(outfile, new JsJULLogger(), true); } } } else { System.err.println("Input file is invalid: " + infile); exitCode = 2; } } finally { FileUtil.deleteQuietly(tmpDir.toFile()); } if (exitCode != 0) { System.exit(exitCode); } } }
package com.sandwell.JavaSimulation; import java.util.Arrays; import com.jaamsim.input.Input; import com.jaamsim.input.Keyword; import com.jaamsim.input.Output; import com.jaamsim.input.OutputHandle; import com.jaamsim.input.UnitTypeInput; import com.jaamsim.input.ValueInput; import com.jaamsim.units.TimeUnit; import com.jaamsim.units.Unit; import com.jaamsim.units.UserSpecifiedUnit; import com.sandwell.JavaSimulation3D.DisplayEntity; public class TimeSeries extends DisplayEntity implements TimeSeriesProvider { @Keyword(description = "A list of time series records with format { 'YYYY-MM-DD hh:mm:ss' value units }, where\n" + "YYYY is the year\n" + "MM is the month (01-12)\n" + "DD is the day of the month\n" + "hh is the hour of day (00-23)\n" + "mm is the minutes (00-59)\n" + "ss is the seconds (00-59)\n" + "value is the time series value for the given date and time\n" + "units is the optional units for the value\n" + "The date and times must be given in increasing order.", example = "TimeSeries1 Value { { '2010-01-01 00:00:00' 0.5 m } { '2010-01-01 03:00:00' 1.5 m } { '2010-01-01 06:00:00' 1.2 m } }") private final TimeSeriesDataInput value; @Keyword(description = "The unit type for the time series (e.g. DistanceUnit, TimeUnit, MassUnit). " + "If the UnitType keyword is specified, it must be specified before the Value keyword.", example = "TimeSeries1 UnitType { DistanceUnit }") private final UnitTypeInput unitType; @Keyword(description = "Defines when the time series will repeat from the start.", example = "TimeSeries1 CycleTime { 8760.0 h }") private final ValueInput cycleTime; { unitType = new UnitTypeInput( "UnitType", "Key Inputs", UserSpecifiedUnit.class ); this.addInput( unitType ); value = new TimeSeriesDataInput("Value", "Key Inputs", null); value.setUnitType(UserSpecifiedUnit.class); this.addInput(value); cycleTime = new ValueInput( "CycleTime", "Key Inputs", Double.POSITIVE_INFINITY ); cycleTime.setUnitType(TimeUnit.class); this.addInput( cycleTime ); } public TimeSeries() { } @Override public void validate() { super.validate(); if( unitType.getValue() == null ) throw new InputErrorException( "UnitType must be specified first" ); if( value.getValue() == null || value.getValue().timeList.length == 0 ) throw new InputErrorException( "Time series Value must be specified" ); double[] tList = value.getValue().timeList; if (this.getCycleTimeInHours() < tList[tList.length - 1]) throw new InputErrorException( "CycleTime must be larger than the last time in the series" ); } @Override public void updateForInput( Input<?> in ) { super.updateForInput( in ); if (in == unitType) { value.setUnitType( unitType.getUnitType() ); this.getOutputHandle("PresentValue").setUnitType( unitType.getUnitType() ); return; } } @Override public OutputHandle getOutputHandle(String outputName) { OutputHandle out = super.getOutputHandle(outputName); if( out.getUnitType() == UserSpecifiedUnit.class ) out.setUnitType( unitType.getUnitType() ); return out; } @Output(name = "PresentValue", description = "The time series value for the present time.", unitType = UserSpecifiedUnit.class) @Override public final double getNextSample(double simTime) { return this.getValueForTimeHours(simTime / 3600.0); } /** * Return the value for the given simulation time in hours */ @Override public double getValueForTimeHours( double time ) { double[] valueList = value.getValue().valueList; return valueList[ getIndexForTimeHours( time ) ]; } /** * Return the index for the given simulation time in hours */ public int getIndexForTimeHours( double time ) { double[] timeList = value.getValue().timeList; // Determine the time in the cycle for the given time double timeInCycle = time; if (this.getCycleLength() < Double.POSITIVE_INFINITY) { int completedCycles = (int)Math.floor( time / this.getCycleTimeInHours() ); timeInCycle -= completedCycles * this.getCycleTimeInHours(); if( Tester.equalCheckTolerance(timeInCycle, this.getCycleTimeInHours()) ) { timeInCycle = 0; } } // If the time in the cycle is greater than the last time, return the last value if( Tester.greaterOrEqualCheckTimeStep( timeInCycle, timeList[ timeList.length - 1 ] ) ) { return timeList.length - 1; } else { // Otherwise, find the index with a binary search int index = Arrays.binarySearch(timeList, timeInCycle); // If the returned index is greater or equal to zero, // then an exact match was found if( index >= 0 ) { return index; } else { // If the returned index is negative, // then index = -(insertion index)-1 // or (insertion index) = -(index+1) = -index-1 // If the time at the insertion index is within one tick, // then return it if( Tester.equalCheckTimeStep( timeInCycle, timeList[-index - 1] ) ) return -index - 1; else // Otherwise, return the index before the insertion index if( index == -1 ) throw new ErrorException( this + " does not have a value at time " + time ); else return -index - 2; } } } /** * Return the first time that the value will be updated, after the given time. */ @Override public double getNextChangeTimeAfterHours( double time ) { // Collect parameters for the current time int startIndex = this.getIndexForTimeHours(time)+1; double cycleTime = this.getCycleTimeInHours(); // Determine how many cycles through the time series have been completed int completedCycles = (int)Math.floor( time / cycleTime ); // Tolerance check for essentially through a cycle double timeInCycle = time - (completedCycles * this.getCycleTimeInHours()); if( Tester.equalCheckTolerance(timeInCycle, this.getCycleTimeInHours()) ) { completedCycles++; } double[] timeList = value.getValue().timeList; // If this is the last point in the cycle, need to cycle around to get the next point if( startIndex > timeList.length - 1 ) { // If the series does not cycle, the value will never change if( cycleTime == Double.POSITIVE_INFINITY ) { return Double.POSITIVE_INFINITY; } else { double cycleOffset = 0.0; if( cycleTime != Double.POSITIVE_INFINITY ) { cycleOffset = (completedCycles+1)*cycleTime; } return timeList[0] + cycleOffset; } } // No cycling required, return the next value double cycleOffset = 0.0; if( cycleTime != Double.POSITIVE_INFINITY ) { cycleOffset = (completedCycles)*cycleTime; } return timeList[startIndex] + cycleOffset; } public double getCycleTimeInHours() { return cycleTime.getValue() / 3600; } double getCycleLength() { return cycleTime.getValue(); } @Override public double getMaxTimeValue() { if (this.getCycleLength() < Double.POSITIVE_INFINITY) return this.getCycleLength(); double[] tList = value.getValue().timeList; return tList[ tList.length-1 ] * 3600.0d; } @Override public Class<? extends Unit> getUnitType() { return unitType.getUnitType(); } @Override public double getMaxValue() { return value.getValue().getMaxValue(); } @Override public double getMinValue() { return value.getValue().getMinValue(); } @Override public double getMeanValue(double simTime) { return this.getNextSample(simTime); } }
package com.sdl.selenium.extjs6.form; import com.sdl.selenium.extjs6.button.Button; import com.sdl.selenium.extjs6.slider.Slider; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; import com.sdl.selenium.web.utils.Utils; import org.openqa.selenium.WebDriverException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class DateField extends TextField { private static final Logger LOGGER = LoggerFactory.getLogger(DateField.class); private WebLocator trigger = new WebLocator(this).setRoot("/../../").setClasses("x-form-date-trigger"); private WebLocator calendarLayer = new WebLocator().setClasses("x-datepicker", "x-layer").withAttribute("aria-hidden", "false").setVisibility(true); private Button monthYearButton = new Button(calendarLayer); private WebLocator selectOkButton = new WebLocator(calendarLayer).setText("OK").setVisibility(true).withInfoMessage("Ok"); private WebLocator yearAndMonth = new WebLocator(calendarLayer).setClasses("x-monthpicker").setVisibility(true); private WebLocator nextYears = new WebLocator(yearAndMonth).setClasses("x-monthpicker-yearnav-next").setVisibility(true); private WebLocator prevYears = new WebLocator(yearAndMonth).setClasses("x-monthpicker-yearnav-prev").setVisibility(true); private WebLocator yearContainer = new WebLocator(yearAndMonth).withClasses("x-monthpicker-years"); private WebLocator monthContainer = new WebLocator(yearAndMonth).withClasses("x-monthpicker-months"); private WebLocator dayContainer = new WebLocator(calendarLayer).withClasses("x-datepicker-cell").setExcludeClasses("x-datepicker-disabled"); private WebLocator hourLayer = new WebLocator().setClasses("x-panel", "x-layer").setVisibility(true); private Slider hourSlider = new Slider(hourLayer).setLabel("Hour", SearchType.DEEP_CHILD_NODE_OR_SELF); private Slider minuteSlider = new Slider(hourLayer).setLabel("Min", SearchType.DEEP_CHILD_NODE_OR_SELF); private WebLocator tooltip = new WebLocator().setClasses("x-tip").setAttribute("aria-hidden", "false"); public DateField() { withClassName("DateField"); } public DateField(WebLocator container) { this(); withContainer(container); } public DateField(WebLocator container, String label) { this(container); withLabel(label); } /** * example new DataField().setDate("19", "05", "2013") * * @param day String 'dd' * @param month String 'MMM' * @param year String 'yyyy' * @return true if is selected date, false when DataField doesn't exist */ private boolean setDate(String day, String month, String year) { String fullDate = monthYearButton.getText().trim(); if (!fullDate.contains(month) || !fullDate.contains(year)) { monthYearButton.click(); if (!yearAndMonth.ready()) { monthYearButton.click(); } goToYear(year, fullDate); WebLocator monthEl = new WebLocator(monthContainer).setText(month, SearchType.EQUALS).withInfoMessage("month " + month); monthEl.click(); selectOkButton.click(); } WebLocator dayEl = new WebLocator(dayContainer).withText(day, SearchType.EQUALS).setVisibility(true).withInfoMessage("day " + day); Utils.sleep(50); return dayEl.click(); } private boolean setHour(String hour, String minute) { return hourSlider.move(Integer.parseInt(hour)) && minuteSlider.move(Integer.parseInt(minute)); } private void goToYear(String year, String fullDate) { int currentYear = Integer.parseInt(fullDate.split(" ")[1]); int yearInt = Integer.parseInt(year); int con = yearInt > currentYear ? -4 : 4; int count = (int) Math.ceil((yearInt - currentYear - con) / 10); selectYearPage(count); WebLocator yearEl = new WebLocator(yearContainer).setText(year, SearchType.EQUALS).withInfoMessage("year " + year); if (!yearEl.waitToRender(200)) { selectYearPage(count > 0 ? 1 : -1); } try { yearEl.click(); } catch (WebDriverException e) { if (tooltip.waitToRender(500)) { WebLocator monthEl = new WebLocator(monthContainer).setText("Jan", SearchType.EQUALS).withInfoMessage("month Jan"); monthEl.focus(); } yearEl.click(); } } private void selectYearPage(int count) { WebLocator btn = count > 0 ? nextYears : prevYears; count = Math.abs(count); while (count > 0) { btn.click(); count } } /** * example new DataField().select("19/05/2013") * * @param date accept only this format: 'dd/MM/yyyy' * @return true if is selected date, false when DataField doesn't exist */ public boolean select(String date) { return select(date, "dd/MM/yyyy"); } public boolean select(String date, String format) { return select(date, format, Locale.ENGLISH); } public boolean select(String date, String format, Locale locale) { SimpleDateFormat inDateFormat = new SimpleDateFormat(format, locale); SimpleDateFormat outDateForm = new SimpleDateFormat("dd/MMM/yyyy H:m", locale); Date fromDate; try { fromDate = inDateFormat.parse(date); date = outDateForm.format(fromDate); } catch (ParseException e) { LOGGER.error("ParseException: {}", e); } LOGGER.debug("select: " + date); String[] dates = date.split("/"); trigger.click(); String[] extraDates = dates[2].split(" "); String year = extraDates[0]; if (format.contains("H")) { String[] hours = extraDates[1].split(":"); String hour = hours[0]; String minutes = hours[1]; return setHour(hour, minutes) && setDate(Integer.parseInt(dates[0]) + "", dates[1], year); } else { return setDate(Integer.parseInt(dates[0]) + "", dates[1], year); } } public boolean select(Date date) { SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/YYYY"); String dateStr = sdf.format(date); return select(dateStr); } public boolean selectToday() { return select(new Date()); } }
package com.shinycraft.streamermod; import com.shinycraft.streamermod.keybinds.GameModeKeyBind; import com.shinycraft.streamermod.keybinds.SpectatorHighlightKeyBind; import com.shinycraft.streamermod.listeners.RenderListener; import com.shinycraft.streamermod.renderer.ModRenderer; import com.shinycraft.streamermod.renderer.ScreenDisplay; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent; import java.io.File; @Mod(modid = StreamerMod.MODID, version = StreamerMod.VERSION) public class StreamerMod { public static final String MODID = "streamermod"; public static final String VERSION = "1.1"; public static File team1File; public static File team2File; public static int defaultYLevel = 16; public static boolean scoreboard = true; public static boolean playerDisplay = true; public static boolean coreLeakDistance = true; public static File timeFile; public static File mapNameFile; public static File team1ColorInput; public static File team1ColorOutput; public static File team2ColorInput; public static File team2ColorOutput; public static boolean seePlayerHighlights = false; public static ScreenDisplay screenDisplay; @EventHandler public void init(FMLInitializationEvent event) { MinecraftForge.EVENT_BUS.register(RenderListener.instance); FMLCommonHandler.instance().bus().register(new GameModeKeyBind()); FMLCommonHandler.instance().bus().register(new SpectatorHighlightKeyBind()); screenDisplay = new ScreenDisplay(); } @EventHandler public void preInit(FMLPreInitializationEvent event) { // you will be able to find the config file in .minecraft/config/ and it will be named Dummy.cfg // here our Configuration has been instantiated, and saved under the name "config" Configuration config = new Configuration(event.getSuggestedConfigurationFile()); config.load(); config.save(); String team1FileString = config.getString("Team1txtFile", Configuration.CATEGORY_GENERAL, "team1.txt", "This is where the first team's name will export to"); String team2FileString = config.getString("Team2txtFile", Configuration.CATEGORY_GENERAL, "team2.txt", "This is where the second team's name will export to"); defaultYLevel = config.getInt("DefaultGUIyLevel", Configuration.CATEGORY_GENERAL, 16, 0, 1980, "How far down the GUI starts"); scoreboard = config.getBoolean("ScoreboardEnabled", Configuration.CATEGORY_GENERAL, true, "Enables the scoreboard"); playerDisplay = config.getBoolean("PlayerDisplayEnabled", Configuration.CATEGORY_GENERAL, true, "Enables the player display"); coreLeakDistance = config.getBoolean("CoreLeakDistanceEnabled", Configuration.CATEGORY_GENERAL, true, "Enables the core leak distance display"); timeFile = new File(config.getString("TimetxtFile", Configuration.CATEGORY_GENERAL, "time.txt", "Displays how much time is left in a match")); mapNameFile = new File(config.getString("MapNametxtFile", Configuration.CATEGORY_GENERAL, "mapname.txt", "Shows what map is currently being played")); team1ColorInput = new File(config.getString("Team1OverlayInputFile", Configuration.CATEGORY_GENERAL, "team1overlayinput.png", "Links the template required for team 1's color changing overlay output")); team1ColorOutput = new File(config.getString("Team1OverlayOutputFile", Configuration.CATEGORY_GENERAL, "team1overlayoutput.png", "An image that is colored based on team 1's color")); team2ColorInput = new File(config.getString("Team2OverlayInputFile", Configuration.CATEGORY_GENERAL, "team2overlayinput.png", "Links the template required for team 2's color changing overlay output")); team2ColorOutput = new File(config.getString("Team2OverlayOutputFile", Configuration.CATEGORY_GENERAL, "team2overlayoutput.png", "An image that is colored based on team 2's color")); team1File = new File(team1FileString); team2File = new File(team2FileString); config.load(); config.save(); } @EventHandler public void change(PlayerEvent.PlayerLoggedInEvent event) { ModRenderer.teams.clear(); } }
package com.sissi.pipeline.in; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.sissi.commons.Trace; import com.sissi.context.JIDContext; import com.sissi.pipeline.Input; import com.sissi.protocol.Error; import com.sissi.protocol.Protocol; import com.sissi.protocol.Stream; import com.sissi.protocol.error.ServerError; import com.sissi.protocol.error.detail.BadRequest; /** * @author kim 2013-11-14 */ public class ChainedProcessor implements Input { private final static Error error = new ServerError().add(BadRequest.DETAIL); private final static Log log = LogFactory.getLog(ChainedProcessor.class); private final List<Input> processors; protected final boolean next; public ChainedProcessor(List<Input> processors) { this(false, processors); } /** * @param next inputtruePipeline * @param processors */ public ChainedProcessor(boolean next, List<Input> processors) { super(); this.next = next; this.processors = processors; } @Override public boolean input(JIDContext context, Protocol protocol) { try { for (Input each : this.processors) { if (!each.input(context, protocol)) { return false; } } } catch (Exception e) { log.warn(e.toString()); Trace.trace(log, e); context.write(Stream.closeWhenRunning(error)); } return this.next; } }
package com.sri.ai.praise.demo.model; import com.google.common.annotations.Beta; @Beta public class ChurchEg8 extends Example { public ChurchEg8() { super("Church Example 8 Program"); setModel(getExampleFromResource("churcheg8.prog")); setEvidence(getExampleFromResource("empty.es")); setQueryToRun("breast_cancer(X)"); } }
package com.tobedevoured.naether.maven; import com.tobedevoured.naether.NaetherException; import org.apache.maven.shared.invoker.*; import java.io.File; import java.util.Arrays; /** * Invoke Maven goals */ public class Invoker { private DefaultInvoker invoker; /** * Construct Invoker * @param localRepo local Maven repo to use * @param mavenHome path to Maven home */ public Invoker(String localRepo, String mavenHome) { invoker = new DefaultInvoker(); invoker.setLocalRepositoryDirectory( new File(localRepo) ); if ( mavenHome != null ) { invoker.setMavenHome(new File(mavenHome)); } } /** * Execute goals for a pom * * @param pom String path * @param goals String * @return {@link InvocationResult} * @throws NaetherException */ public InvocationResult execute(String pom, String... goals) throws NaetherException { InvocationRequest request = new DefaultInvocationRequest(); request.setPomFile(new File(pom)); request.setInteractive(false); request.setGoals( Arrays.asList(goals) ); try { return invoker.execute( request ); } catch (MavenInvocationException e) { throw new NaetherException("Failed to execute maven task",e); } } }
package org.jgroups.tests; import org.jgroups.*; import org.jgroups.conf.ConfiguratorFactory; import org.jgroups.conf.ProtocolData; import org.jgroups.conf.ProtocolParameter; import org.jgroups.conf.ProtocolStackConfigurator; import org.jgroups.util.Util; import java.util.LinkedList; import java.util.List; /** * Tests which test the shared transport * @author Bela Ban * @version $Id: SharedTransportTest.java,v 1.8 2008/01/25 11:58:59 belaban Exp $ */ public class SharedTransportTest extends ChannelTestBase { private JChannel a, b, c; private MyReceiver r1, r2, r3; static final String SINGLETON_1="singleton-1", SINGLETON_2="singleton-2"; protected void tearDown() throws Exception { if(c != null) c.close(); if(b != null) b.close(); if(a != null) a.close(); r1=r2=r3=null; super.tearDown(); } public void testCreationNonSharedTransport() throws Exception { a=createChannel(); a.connect("x"); View view=a.getView(); System.out.println("view = " + view); assertEquals(1, view.size()); } public void testCreationOfDuplicateCluster() throws Exception { a=createSharedChannel(SINGLETON_1); b=createSharedChannel(SINGLETON_1); a.connect("x"); try { b.connect("x"); fail("b should not be able to join cluster 'x' as a has already joined it"); } catch(Exception ex) { System.out.println("b was not able to join the same cluster (\"x\") as expected"); } } public void testView() throws Exception { a=createSharedChannel(SINGLETON_1); b=createSharedChannel(SINGLETON_2); a.setReceiver(new MyReceiver(SINGLETON_1)); b.setReceiver(new MyReceiver(SINGLETON_2)); a.connect("x"); b.connect("x"); View view=a.getView(); assertEquals(2, view.size()); view=b.getView(); assertEquals(2, view.size()); } public void testView2() throws Exception { a=createSharedChannel(SINGLETON_1); b=createSharedChannel(SINGLETON_1); a.setReceiver(new MyReceiver("first-channel")); b.setReceiver(new MyReceiver("second-channel")); a.connect("x"); b.connect("y"); View view=a.getView(); assertEquals(1, view.size()); view=b.getView(); assertEquals(1, view.size()); } public void testCreationOfDifferentCluster() throws Exception { a=createSharedChannel(SINGLETON_1); b=createSharedChannel(SINGLETON_2); a.connect("x"); b.connect("x"); View view=b.getView(); System.out.println("b's view is " + view); assertEquals(2, view.size()); } public void testReferenceCounting() throws ChannelException { a=createSharedChannel(SINGLETON_1); r1=new MyReceiver("a"); a.setReceiver(r1); b=createSharedChannel(SINGLETON_1); r2=new MyReceiver("b"); b.setReceiver(r2); c=createSharedChannel(SINGLETON_1); r3=new MyReceiver("c"); c.setReceiver(r3); a.connect("A"); b.connect("B"); c.connect("C"); a.send(null, null, "message from a"); b.send(null, null, "message from b"); c.send(null, null, "message from c"); Util.sleep(500); assertEquals(1, r1.size()); assertEquals(1, r2.size()); assertEquals(1, r3.size()); r1.clear(); r2.clear(); r3.clear(); b.disconnect(); System.out.println("\n"); a.send(null, null, "message from a"); c.send(null, null, "message from c"); Util.sleep(500); assertEquals(1, r1.size()); assertEquals(1, r3.size()); r1.clear(); r3.clear(); c.disconnect(); System.out.println("\n"); a.send(null, null, "message from a"); Util.sleep(500); assertEquals(1, r1.size()); } /** * Tests that a second channel with the same group name can be * created and connected once the first channel is disconnected. * * @throws Exception */ public void testSimpleReCreation() throws Exception { a=createSharedChannel(SINGLETON_1); a.setReceiver(new MyReceiver("A")); a.connect("A"); a.disconnect(); b=createSharedChannel(SINGLETON_1); b.setReceiver(new MyReceiver("A'")); b.connect("A"); } /** * Tests that a second channel with the same group name can be * created and connected once the first channel is disconnected even * if 3rd channel with a different group name is still using the shared * transport. * * @throws Exception */ public void testCreationFollowedByDeletion() throws Exception { a=createSharedChannel(SINGLETON_1); a.setReceiver(new MyReceiver("A")); a.connect("A"); b=createSharedChannel(SINGLETON_1); b.setReceiver(new MyReceiver("B")); b.connect("B"); b.close(); a.close(); } public void test2ChannelsCreationFollowedByDeletion() throws Exception { a=createSharedChannel(SINGLETON_1); a.setReceiver(new MyReceiver("A")); a.connect("A"); b=createSharedChannel(SINGLETON_2); b.setReceiver(new MyReceiver("B")); b.connect("A"); c=createSharedChannel(SINGLETON_2); c.setReceiver(new MyReceiver("C")); c.connect("B"); c.send(null, null, "hello world from C"); } public void testReCreationWithSurvivingChannel() throws Exception { // Create 2 channels sharing a transport System.out.println("-- creating A"); a=createSharedChannel(SINGLETON_1); a.setReceiver(new MyReceiver("A")); a.connect("A"); System.out.println("-- creating B"); b=createSharedChannel(SINGLETON_1); b.setReceiver(new MyReceiver("B")); b.connect("B"); System.out.println("-- disconnecting A"); a.disconnect(); // a is disconnected so we should be able to create a new channel with group "A" System.out.println("-- creating A'"); c=createSharedChannel(SINGLETON_1); c.setReceiver(new MyReceiver("A'")); c.connect("A"); } private static JChannel createSharedChannel(String singleton_name) throws ChannelException { ProtocolStackConfigurator config=ConfiguratorFactory.getStackConfigurator(CHANNEL_CONFIG); ProtocolData[] protocols=config.getProtocolStack(); ProtocolData transport=protocols[0]; transport.getParameters().put(Global.SINGLETON_NAME, new ProtocolParameter(Global.SINGLETON_NAME, singleton_name)); return new JChannel(config); } private static class MyReceiver extends ReceiverAdapter { final List<Message> list=new LinkedList<Message>(); final String name; private MyReceiver(String name) { this.name=name; } public List<Message> getList() { return list; } public int size() { return list.size(); } public void clear() { list.clear(); } public void receive(Message msg) { System.out.println("[" + name + "]: received message from " + msg.getSrc() + ": " + msg.getObject()); list.add(msg); } public void viewAccepted(View new_view) { System.out.println("[" + name + "]: view = " + new_view); } } }
package common.base.adapters; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.BaseAdapter; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Set; /** * ,itemListView * ListView * itemViewholder * @param <T><br/> * 20151023-10:20:03 * @author lifei */ public abstract class BaseCommonAdapter<T> extends BaseAdapter implements OnScrollListener{ protected boolean isScrolling; protected Collection<T> dataList; private OnScrollListener outScrollListener; protected Context mContext; /** * ListViewitem,1item */ protected int viewTypeCount = 1; public BaseCommonAdapter(Context curContext,Collection<T> data){ if(data != null){ dataList = data; } else{ dataList = new ArrayList<T>(0); } mContext = curContext; } public BaseCommonAdapter(AbsListView listView, Collection<T> data) { if(data != null){ dataList = data; } else{ dataList = new ArrayList<T>(0); } if(listView != null){ mContext = listView.getContext(); listView.setOnScrollListener(this); } } @Override public int getCount() { return dataList == null ? 0 : dataList.size(); } @Override public T getItem(int position) { if(dataList == null || dataList.isEmpty()) return null; if(dataList instanceof List){ return ((List<T>) dataList).get(position); } if(dataList instanceof Set){ return new ArrayList<T>(dataList).get(position); } return null; } @Override public long getItemId(int position) { return position; } /** * itemIDitem(Mode,APk) * @param itemPosition * @return ID */ protected abstract int getItemLayoutResId(int itemPosition); /** * ListView * @param outListener */ public void addOutScrollListener(OnScrollListener outListener){ this.outScrollListener = outListener; } public void setViewTypeCount(int itemViewTypeCount){ this.viewTypeCount = itemViewTypeCount; } @Override public View getView(int position, View convertView, ViewGroup parent) { AdapterViewHolder viewHolder = AdapterViewHolder.getViewHolder(convertView, parent, getItemLayoutResId(position), position); convert(viewHolder, getItem(position), isScrolling, position); return viewHolder.getConvertView(); } /** * item * @param viewHolder * @param itemData * @param isScrolling */ public void convert(AdapterViewHolder viewHolder, T itemData, boolean isScrolling) { } public void convert(AdapterViewHolder viewHolder, T itemData, boolean isScrolling, int position) { convert(viewHolder, itemData, isScrolling); } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if(OnScrollListener.SCROLL_STATE_IDLE == scrollState){ isScrolling = false; notifyDataSetChanged(); } else{ isScrolling = true; } if(outScrollListener != null){ outScrollListener.onScrollStateChanged(view, scrollState); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if(outScrollListener != null){ outScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } } public void setData(Collection<T> newData){ dataList = newData; notifyDataSetChanged(); } public void addItems(Collection<T> toAddItems){ if(toAddItems != null){ dataList.addAll(toAddItems); } notifyDataSetChanged(); } public void addItems(T addedOne,boolean insertToFirst){ if(insertToFirst){ addItemToFirst(addedOne); } else{ dataList.add(addedOne); } sortDataList(); notifyDataSetChanged(); } protected void addItemToFirst(T addedOne) { //Let subClass which can append to add item to implements this method } public void addItems(T addedOne){ addItems(addedOne, false); } public void removeItem(int itemPosition) { if (dataList != null) { if (dataList instanceof List) { List<T> datas = (List<T>) dataList; datas.remove(itemPosition); } else{ dataList.remove(getItem(itemPosition)); } notifyDataSetChanged(); } } public void clearData(){ dataList.clear(); notifyDataSetChanged(); } protected String getStrFromRes(int resStrID,Object... args){ return mContext == null ? "" : mContext.getString(resStrID, args); } protected String getStrFromRes(int resStrID){ return mContext == null ? "" : mContext.getString(resStrID); } protected String[] getArrStrFromRes(int resStrID){ return (String[]) (mContext == null ? "" : mContext.getResources().getStringArray(resStrID)); } public List<T> getDatas() { return new ArrayList<T>(dataList); } protected void sortDataList(){ } Comparator<T> dataComparator; }
package org.jgroups.tests; import org.jgroups.*; import org.jgroups.conf.ConfiguratorFactory; import org.jgroups.conf.ProtocolData; import org.jgroups.conf.ProtocolParameter; import org.jgroups.conf.ProtocolStackConfigurator; import org.jgroups.protocols.BasicTCP; import org.jgroups.protocols.TCPPING; import org.jgroups.protocols.TP; import org.jgroups.protocols.UDP; import org.jgroups.stack.Protocol; import org.jgroups.stack.ProtocolStack; import org.jgroups.util.ResourceManager; import org.jgroups.util.TimeScheduler; import org.jgroups.util.Util; import org.testng.AssertJUnit; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import java.net.InetAddress; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Tests which test the shared transport * @author Bela Ban * @version $Id: SharedTransportTest.java,v 1.25 2008/10/28 14:28:55 vlada Exp $ */ @Test(groups=Global.STACK_DEPENDENT,sequential=true) public class SharedTransportTest extends ChannelTestBase { private JChannel a, b, c; private MyReceiver r1, r2, r3; static final String SINGLETON_1="singleton-1", SINGLETON_2="singleton-2"; @AfterMethod protected void tearDown() throws Exception { Util.close(c,b,a); r1=r2=r3=null; } public void testCreationNonSharedTransport() throws Exception { a=createChannel(true); a.connect("SharedTransportTest.testCreationNonSharedTransport"); View view=a.getView(); System.out.println("view = " + view); assert view.size() == 1; } public void testCreationOfDuplicateCluster() throws Exception { a=createSharedChannel(SINGLETON_1); // makeUnique(a, 2); b=createSharedChannel(SINGLETON_1); a.connect("x"); try { b.connect("x"); assert false : "b should not be able to join cluster 'x' as a has already joined it"; } catch(Exception ex) { System.out.println("b was not able to join the same cluster (\"x\") as expected"); } } public void testView() throws Exception { a=createSharedChannel(SINGLETON_1); b=createSharedChannel(SINGLETON_2); a.setReceiver(new MyReceiver(SINGLETON_1)); b.setReceiver(new MyReceiver(SINGLETON_2)); a.connect("x"); b.connect("x"); View view=a.getView(); assert view.size() == 2; view=b.getView(); assert view.size() == 2; } public void testView2() throws Exception { a=createSharedChannel(SINGLETON_1); b=createSharedChannel(SINGLETON_1); a.setReceiver(new MyReceiver("first-channel")); b.setReceiver(new MyReceiver("second-channel")); a.connect("x"); b.connect("y"); View view=a.getView(); assert view.size() == 1; view=b.getView(); assert view.size() == 1; } public void testView3() throws Exception { a=createSharedChannel(SINGLETON_1); b=createSharedChannel(SINGLETON_1); c=createSharedChannel(SINGLETON_2); r1=new MyReceiver("A::" + SINGLETON_1); r2=new MyReceiver("B::" + SINGLETON_1); r3=new MyReceiver("C::" + SINGLETON_2); a.setReceiver(r1); b.setReceiver(r2); c.setReceiver(r3); a.connect("a"); c.connect("a"); View view=a.getView(); assert view.size() == 2; view=c.getView(); assert view.size() == 2; a.send(new Message(null, null, "msg-1")); c.send(new Message(null, null, "msg-2")); Util.sleep(1000); // async sending - wait a little List<Message> list=r1.getList(); assert list.size() == 2; list=r3.getList(); assert list.size() == 2; r1.clear(); r2.clear(); r3.clear(); b.connect("b"); a.send(new Message(null, null, "msg-3")); b.send(new Message(null, null, "msg-4")); c.send(new Message(null, null, "msg-5")); Util.sleep(1000); // async sending - wait a little // printLists(r1, r2, r3); list=r1.getList(); assert list.size() == 2; list=r2.getList(); assert list.size() == 1; list=r3.getList(); assert list.size() == 2; } public void testSharedTransportAndNonsharedTransport() throws Exception { a=createSharedChannel(SINGLETON_1); b=createChannel(); a.setReceiver(new MyReceiver("first-channel")); b.setReceiver(new MyReceiver("second-channel")); a.connect("x"); b.connect("x"); View view=a.getView(); assert view.size() == 2; view=b.getView(); assert view.size() == 2; } public void testCreationOfDifferentCluster() throws Exception { a=createSharedChannel(SINGLETON_1); b=createSharedChannel(SINGLETON_2); a.connect("x"); b.connect("x"); View view=b.getView(); System.out.println("b's view is " + view); assert view.size() == 2; } public void testReferenceCounting() throws ChannelException { a=createSharedChannel(SINGLETON_1); r1=new MyReceiver("a"); a.setReceiver(r1); b=createSharedChannel(SINGLETON_1); r2=new MyReceiver("b"); b.setReceiver(r2); c=createSharedChannel(SINGLETON_1); r3=new MyReceiver("c"); c.setReceiver(r3); a.connect("A"); b.connect("B"); c.connect("C"); a.send(null, null, "message from a"); b.send(null, null, "message from b"); c.send(null, null, "message from c"); Util.sleep(500); assert r1.size() == 1; assert r2.size() == 1; assert r3.size() == 1; r1.clear(); r2.clear(); r3.clear(); b.disconnect(); System.out.println("\n"); a.send(null, null, "message from a"); c.send(null, null, "message from c"); Util.sleep(500); assert r1.size() == 1 : "size should be 1 but is " + r1.size(); assert r3.size() == 1 : "size should be 1 but is " + r3.size(); r1.clear(); r3.clear(); c.disconnect(); System.out.println("\n"); a.send(null, null, "message from a"); Util.sleep(500); assert r1.size() == 1; } /** * Tests that a second channel with the same group name can be * created and connected once the first channel is disconnected. * @throws Exception */ public void testSimpleReCreation() throws Exception { a=createSharedChannel(SINGLETON_1); a.setReceiver(new MyReceiver("A")); a.connect("A"); a.disconnect(); b=createSharedChannel(SINGLETON_1); b.setReceiver(new MyReceiver("A'")); b.connect("A"); } /** * Tests that a second channel with the same group name can be * created and connected once the first channel is disconnected even * if 3rd channel with a different group name is still using the shared * transport. * @throws Exception */ public void testCreationFollowedByDeletion() throws Exception { a=createSharedChannel(SINGLETON_1); a.setReceiver(new MyReceiver("A")); a.connect("A"); b=createSharedChannel(SINGLETON_1); b.setReceiver(new MyReceiver("B")); b.connect("B"); b.close(); a.close(); } public void test2ChannelsCreationFollowedByDeletion() throws Exception { a=createSharedChannel(SINGLETON_1); a.setReceiver(new MyReceiver("A")); a.connect("A"); b=createSharedChannel(SINGLETON_2); b.setReceiver(new MyReceiver("B")); b.connect("A"); c=createSharedChannel(SINGLETON_2); c.setReceiver(new MyReceiver("C")); c.connect("B"); c.send(null, null, "hello world from C"); } public void testReCreationWithSurvivingChannel() throws Exception { // Create 2 channels sharing a transport System.out.println("-- creating A"); a=createSharedChannel(SINGLETON_1); a.setReceiver(new MyReceiver("A")); a.connect("A"); System.out.println("-- creating B"); b=createSharedChannel(SINGLETON_1); b.setReceiver(new MyReceiver("B")); b.connect("B"); System.out.println("-- disconnecting A"); a.disconnect(); // a is disconnected so we should be able to create a new channel with group "A" System.out.println("-- creating A'"); c=createSharedChannel(SINGLETON_1); c.setReceiver(new MyReceiver("A'")); c.connect("A"); } public void testShutdownOfTimer() throws Exception { a=createSharedChannel(SINGLETON_1); b=createSharedChannel(SINGLETON_1); a.connect("x"); b.connect("y"); TimeScheduler timer1=a.getProtocolStack().getTransport().getTimer(); TimeScheduler timer2=b.getProtocolStack().getTransport().getTimer(); assert timer1 == timer2; assert !timer1.isShutdown(); assert !timer2.isShutdown(); Util.sleep(500); b.close(); assert !timer2.isShutdown(); assert !timer1.isShutdown(); a.close(); // now, reference counting reaches 0, so the timer thread pool is stopped assert timer2.isShutdown(); assert timer1.isShutdown(); } public void testSendingOfMessagesAfterChannelClose() throws ChannelException { MyReceiver rec_a=new MyReceiver("A"), rec_b=new MyReceiver("B"), rec_c=new MyReceiver("C"); System.out.println("-- creating A"); a=createSharedChannel(SINGLETON_1); a.setReceiver(rec_a); a.connect("A"); System.out.println("-- creating B"); b=createSharedChannel(SINGLETON_1); b.setReceiver(rec_b); b.connect("B"); System.out.println("-- creating C"); c=createSharedChannel(SINGLETON_2); c.setReceiver(rec_c); c.connect("B"); b.send(null, null, "first"); Util.sleep(500); // msg delivery is asynchronous, so give members some time to receive the msg (incl retransmission) assertSize(1, rec_b, rec_c); assertSize(0, rec_a); a.close(); b.send(null, null, "second"); Util.sleep(500); assertSize(0, rec_a); assertSize(2, rec_b, rec_c); } /** * Use a CountDownLatch to concurrently connect 3 channels; confirms * the channels connect * * @throws ChannelException * @throws InterruptedException */ public void testConcurrentCreation() throws ChannelException, InterruptedException { a=createSharedChannel(SINGLETON_1); r1=new MyReceiver("a"); a.setReceiver(r1); b=createSharedChannel(SINGLETON_1); r2=new MyReceiver("b"); b.setReceiver(r2); c=createSharedChannel(SINGLETON_1); r3=new MyReceiver("c"); c.setReceiver(r3); CountDownLatch startLatch = new CountDownLatch(1); CountDownLatch finishLatch = new CountDownLatch(3); ConnectTask connectA = new ConnectTask(a, "a", startLatch, finishLatch); Thread threadA = new Thread(connectA); threadA.setDaemon(true); threadA.start(); ConnectTask connectB = new ConnectTask(b, "b", startLatch, finishLatch); Thread threadB = new Thread(connectB); threadB.setDaemon(true); threadB.start(); ConnectTask connectC = new ConnectTask(c, "c", startLatch, finishLatch); Thread threadC = new Thread(connectC); threadC.setDaemon(true); threadC.start(); startLatch.countDown(); try { boolean finished = finishLatch.await(20, TimeUnit.SECONDS); if (connectA.exception != null) { AssertJUnit.fail("connectA threw exception " + connectA.exception); } if (connectB.exception != null) { AssertJUnit.fail("connectB threw exception " + connectB.exception); } if (connectC.exception != null) { AssertJUnit.fail("connectC threw exception " + connectC.exception); } if (!finished) { if (threadA.isAlive()) AssertJUnit.fail("threadA did not finish"); if (threadB.isAlive()) AssertJUnit.fail("threadB did not finish"); if (threadC.isAlive()) AssertJUnit.fail("threadC did not finish"); } } finally { if (threadA.isAlive()) threadA.interrupt(); if (threadB.isAlive()) threadB.interrupt(); if (threadC.isAlive()) threadC.interrupt(); } } private static void assertSize(int expected, MyReceiver... receivers) { for(MyReceiver recv: receivers) { assertEquals(expected, recv.size()); } } private JChannel createSharedChannel(String singleton_name) throws ChannelException { ProtocolStackConfigurator config=ConfiguratorFactory.getStackConfigurator(channel_conf); ProtocolData[] protocols=config.getProtocolStack(); ProtocolData transport=protocols[0]; transport.getParameters().put(Global.SINGLETON_NAME, new ProtocolParameter(Global.SINGLETON_NAME, singleton_name)); return new JChannel(config); } protected static void makeUnique(Channel channel, int num) throws Exception { ProtocolStack stack=channel.getProtocolStack(); TP transport=stack.getTransport(); InetAddress bind_addr=transport.getBindAddressAsInetAddress(); if(transport instanceof UDP) { String mcast_addr=ResourceManager.getNextMulticastAddress(); short mcast_port=ResourceManager.getNextMulticastPort(bind_addr); ((UDP)transport).setMulticastAddress(mcast_addr); ((UDP)transport).setMulticastPort(mcast_port); } else if(transport instanceof BasicTCP) { List<Short> ports=ResourceManager.getNextTcpPorts(bind_addr, num); transport.setBindPort(ports.get(0)); transport.setPortRange(num); Protocol ping=stack.findProtocol(TCPPING.class); if(ping == null) throw new IllegalStateException("TCP stack must consist of TCP:TCPPING - other config are not supported"); List<String> initial_hosts=new LinkedList<String>(); for(short port: ports) { initial_hosts.add(bind_addr + "[" + port + "]"); } String tmp=Util.printListWithDelimiter(initial_hosts, ","); ((TCPPING)ping).setInitialHosts(tmp); } else { throw new IllegalStateException("Only UDP and TCP are supported as transport protocols"); } } private static class MyReceiver extends ReceiverAdapter { final List<Message> list=new LinkedList<Message>(); final String name; private MyReceiver(String name) { this.name=name; } public List<Message> getList() { return list; } public int size() { return list.size(); } public void clear() { list.clear(); } public void receive(Message msg) { System.out.println("[" + name + "]: received message from " + msg.getSrc() + ": " + msg.getObject()); list.add(msg); } public void viewAccepted(View new_view) { StringBuilder sb=new StringBuilder(); sb.append("[" + name + "]: view = " + new_view); System.out.println(sb); } public String toString() { return super.toString() + " (size=" + list.size() + ")"; } } private static class ConnectTask implements Runnable { private final Channel channel; private final String clusterName; private final CountDownLatch startLatch; private final CountDownLatch finishLatch; private Exception exception; ConnectTask(Channel channel, String clusterName, CountDownLatch startLatch, CountDownLatch finishLatch) { this.channel = channel; this.clusterName = clusterName; this.startLatch = startLatch; this.finishLatch = finishLatch; } public void run() { try { startLatch.await(); channel.connect(clusterName); } catch (Exception e) { e.printStackTrace(System.out); this.exception = e; } finally { finishLatch.countDown(); } } } }
package de.bmoth.backend; import com.microsoft.z3.BoolExpr; import com.microsoft.z3.Context; import com.microsoft.z3.Expr; import com.microsoft.z3.Sort; import de.bmoth.parser.ast.nodes.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class MachineToZ3Translator { private final MachineNode machineNode; private final Context z3Context; private final BoolExpr initialisationConstraint; private final BoolExpr invariantConstraint; private final HashMap<String, String> primedVariablesToVariablesMap; private final List<BoolExpr> operationConstraints; public MachineToZ3Translator(MachineNode machineNode, Context ctx) { this.machineNode = machineNode; this.z3Context = ctx; this.initialisationConstraint = visitSubstitution(machineNode.getInitialisation()); this.invariantConstraint = (BoolExpr) FormulaToZ3Translator.translatePredicate(machineNode.getInvariant(), z3Context); this.operationConstraints = visitOperations(machineNode.getOperations()); { primedVariablesToVariablesMap = new HashMap<>(); for (DeclarationNode node : machineNode.getVariables()) { primedVariablesToVariablesMap.put(getPrimedName(node.getName()), node.getName()); } } } private List<BoolExpr> visitOperations(List<OperationNode> operations) { List<BoolExpr> results = new ArrayList<>(operations.size()); for (OperationNode operationNode : this.machineNode.getOperations()) { results.add(visitSubstitution(operationNode.getSubstitution())); } return results; } public List<DeclarationNode> getVariables() { return machineNode.getVariables(); } public List<DeclarationNode> getConstants() { return machineNode.getConstants(); } public Expr getPrimedVariable(DeclarationNode node) { String primedName = getPrimedName(node.getName()); Sort type = FormulaToZ3Translator.bTypeToZ3Sort(z3Context, node.getType()); Expr expr = z3Context.mkConst(primedName, type); return expr; } public BoolExpr getInitialValueConstraint() { return initialisationConstraint; } public BoolExpr getInvariantConstraint() { return invariantConstraint; } private BoolExpr visitSubstitution(SubstitutionNode node) { if (node instanceof SingleAssignSubstitutionNode) { return visitSingleAssignSubstitution((SingleAssignSubstitutionNode) node); } else if (node instanceof ParallelSubstitutionNode) { return visitParallelSubstitution((ParallelSubstitutionNode) node); } else if (node instanceof AnySubstitutionNode) { return visitAnySubstitution((AnySubstitutionNode) node); } else if (node instanceof SelectSubstitutionNode) { return visitSelectSubstitutionNode((SelectSubstitutionNode) node); } throw new AssertionError("Not implemented" + node.getClass()); } private BoolExpr visitSelectSubstitutionNode(SelectSubstitutionNode node) { BoolExpr condition = (BoolExpr) FormulaToZ3Translator.translatePredicate(node.getCondition(), z3Context); BoolExpr substitution = visitSubstitution(node.getSubstitution()); return z3Context.mkAnd(condition, substitution); } private BoolExpr visitAnySubstitution(AnySubstitutionNode node) { throw new AssertionError("Not implemented: " + node.getClass());// TODO } private BoolExpr visitParallelSubstitution(ParallelSubstitutionNode node) { List<SubstitutionNode> substitutions = node.getSubstitutions(); BoolExpr boolExpr = null; for (SubstitutionNode substitutionNode : substitutions) { BoolExpr temp = visitSubstitution(substitutionNode); if (boolExpr == null) { boolExpr = temp; } else { boolExpr = z3Context.mkAnd(boolExpr, temp); } } return boolExpr; } private BoolExpr visitSingleAssignSubstitution(SingleAssignSubstitutionNode node) { Sort bTypeToZ3Sort = FormulaToZ3Translator.bTypeToZ3Sort(z3Context, node.getIdentifier().getType()); Expr value = FormulaToZ3Translator.translateExpr(node.getValue(), z3Context); String name = getPrimedName(node.getIdentifier().getName()); Expr variable = z3Context.mkConst(name, bTypeToZ3Sort); return this.z3Context.mkEq(variable, value); } private String getPrimedName(String name) { return name + "'"; } public List<BoolExpr> getOperationConstraints() { return operationConstraints; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cz.vutbr.fit.pdb; import cz.vutbr.fit.pdb.containers.DataContainer; import cz.vutbr.fit.pdb.containers.SpatialContainer; import cz.vutbr.fit.pdb.control.EditControl; import cz.vutbr.fit.pdb.control.MapControl; import cz.vutbr.fit.pdb.control.RootControl; import cz.vutbr.fit.pdb.db.DatabaseAPI; import cz.vutbr.fit.pdb.model.DataObject; import cz.vutbr.fit.pdb.model.PlantsObject; import cz.vutbr.fit.pdb.model.SignObject; import cz.vutbr.fit.pdb.model.SpatialObject; import cz.vutbr.fit.pdb.view.EditPanel; import cz.vutbr.fit.pdb.view.InfoPanel; import cz.vutbr.fit.pdb.view.MainMenu; import cz.vutbr.fit.pdb.view.MapPanel; import cz.vutbr.fit.pdb.view.RootPanel; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPasswordField; import javax.swing.JTextField; /** * * @author casey */ public class Core { private JFrame mainWindow; private RootPanel rootPanel; private MainMenu mainMenu; private RootControl rootControl; private MapControl mapControl; private MapPanel mp; private InfoPanel ip; private EditPanel ep; private EditControl ec; private DatabaseAPI dbAPI; private DataContainer dc; private SpatialContainer sc; public Core(){ mainWindow = new JFrame("PDB 2013"); mainMenu = new MainMenu(); dc = null; sc = null; mp = null; } public void initGui(){ MenuControl mc = new MenuControl(); mainMenu.registerActionListener(mc); mainMenu.registerItemListener(mc); mainWindow.setJMenuBar(mainMenu); mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainWindow.setSize(800, 600); } public void initMainPanel(){ sc = new SpatialContainer(dbAPI); sc.initialize(); dc = new DataContainer(dbAPI); dc.initialize(); ip = new InfoPanel(); mp = new MapPanel(sc); ep = new EditPanel(); rootPanel = new RootPanel(mp, ip, ep); rootControl = new RootControl(rootPanel); mapControl = new MapControl(mp, ip, sc, dc); rootPanel.rebake(); mainWindow.add(rootPanel); mainWindow.invalidate(); } public void showGui(){ mainWindow.setVisible(true); mainWindow.setExtendedState(mainWindow.getExtendedState() | JFrame.MAXIMIZED_BOTH); } private void setOnCenter(Dimension frameSize){ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); mainWindow.setLocation(screenSize.width / 2 -frameSize.width / 2, screenSize.height /2 - frameSize.height / 2); } class MenuControl implements ActionListener,ItemListener{ @Override public void actionPerformed(ActionEvent e) { if("f_quit".equals(e.getActionCommand())){ System.exit(0); }else if("db_connect".equals(e.getActionCommand())){ dbSetUp(); }else if("db_init".equals(e.getActionCommand())){ if(dbAPI == null){ dbSetUp(); } if(dbAPI != null){ JOptionPane.showMessageDialog(mainWindow, "Inicializace Databaze, prosim cekejte."); dbAPI.resetDBData(); } } else if ("s_bed_by_soil".equals(e.getActionCommand())) { getBedBySoilDialog(); } else if ("s_beds_with_fences".equals(e.getActionCommand())) { getBedsWithFencesDialog(); } else if ("s_dist_btw_beds".equals(e.getActionCommand())) { getDistBtwBedsDialog(); }else if ("s_biggest_bed".equals(e.getActionCommand())) { getBiggestBedDialog(); } else if ("s_smallest_bed".equals(e.getActionCommand())) { getSmallestBedDialog(); } else if ("m_find_similar".equals(e.getActionCommand())) { getSimilarDialog(); } else if ("t_sign_desc".equals(e.getActionCommand())) { getSignDescDialog(); } else if ("t_plant_names".equals(e.getActionCommand())) { getPlantNamesDialog(); } else if ("t_sign_desc_for_plants".equals(e.getActionCommand())) { getSignDescForPlantsDialog(); } else if ("t_change_date".equals(e.getActionCommand())) { changeDateDialog(); } else if("a_help".equals(e.getActionCommand())){ }else if("a_about".equals(e.getActionCommand())){ JOptionPane.showMessageDialog(mainWindow, "PDB Projekt 2013 - Botanická zahrada \nJan Jeřábek - xjerab13\nMartin Šimon - xsimon14\nMilan Bárta - xbarta32"); }else if("a".equals(e.getActionCommand())){ }else if("b".equals(e.getActionCommand())){ }else if("c".equals(e.getActionCommand())){ }else if("d".equals(e.getActionCommand())){ } } @Override public void itemStateChanged(ItemEvent e) { if(((JMenuItem)(e.getSource())).isSelected()){ rootControl.enableEdit(); ec = new EditControl(ep, mp, ip, sc, dc, dbAPI); mapControl.enableEdit(ec); }else{ rootControl.disableEdit(); mapControl.disableEdit(); } } } public void dbSetUp() { JTextField username = new JTextField("xjerab13"); JPasswordField password = new JPasswordField("w0z7dnrt"); JTextField url = new JTextField("berta.fit.vutbr.cz"); JTextField port = new JTextField("1522"); JTextField serviceName = new JTextField("DBFIT"); final JComponent[] inputs = new JComponent[]{ new JLabel("Login"), username, new JLabel("Password"), password, new JLabel("URL"), url, new JLabel("Port"), port, new JLabel("Service Name"), serviceName,}; int a = JOptionPane.showInternalConfirmDialog(mainMenu, inputs, "Connect to...", JOptionPane.OK_CANCEL_OPTION); if (a == JOptionPane.OK_OPTION) { dbAPI = new DatabaseAPI(username.getText(), password.getText()); initMainPanel(); } } public void getBedBySoilDialog() { if (dc == null) { return; } ArrayList<String> plant_types = new ArrayList<String>(); for (DataObject o: dc.getPlantType()) { plant_types.add(o.getName()); } ArrayList<String> soil_types = new ArrayList<String>(); for (DataObject o: dc.getSoilType()) { soil_types.add(o.getName()); } JList soil_type_list = new JList(soil_types.toArray()); soil_type_list.setSelectedIndex(0); JList plant_type_list = new JList(plant_types.toArray()); plant_type_list.setSelectedIndex(0); final JComponent[] inputs = new JComponent[]{ new JLabel("Soil type"), soil_type_list, new JLabel("Plant type"), plant_type_list }; int a = JOptionPane.showInternalConfirmDialog(mainMenu, inputs, "Select soil type", JOptionPane.OK_CANCEL_OPTION); if (a == JOptionPane.OK_OPTION) { ArrayList<Integer> bedsID = dbAPI.getBedsBySoil(plant_type_list.getSelectedIndex()+1, soil_type_list.getSelectedIndex()+1); ArrayList<SpatialObject> bedsSpatial = new ArrayList<SpatialObject>(); for (Integer i: bedsID) { bedsSpatial.add(sc.getBed(i)); } sc.setTheseAsSelected(bedsSpatial); mp.updateUI(); } } public void getBedsWithFencesDialog() { if (sc == null || dbAPI == null) { return; } ArrayList<Integer> bedsID = dbAPI.getBedsBorderedWithFence(); ArrayList<SpatialObject> bedsSpatial = new ArrayList<SpatialObject>(); for (Integer i : bedsID) { bedsSpatial.add(sc.getBed(i)); } sc.setTheseAsSelected(bedsSpatial); mp.updateUI(); } public void getDistBtwBedsDialog() { // final JComponent[] inputs = new JComponent[]{ // new JLabel("?? TODO") //int a = JOptionPane.showConfirmDialog(mainMenu, inputs, "Select beds to measure distance between", JOptionPane.OK_CANCEL_OPTION); //if (a == JOptionPane.OK_OPTION) { // ArrayList<Integer> bedsID = dbAPI.getBedsBySoil(plant_type_list.getSelectedIndex()+1, soil_type_list.getSelectedIndex()+1); // ArrayList<SpatialObject> bedsSpatial = new ArrayList<SpatialObject>(); // for (Integer i: bedsID) { // bedsSpatial.add(sc.getBed(i)); // sc.setTheseAsSelected(bedsSpatial); // mp.updateUI(); } public void getBiggestBedDialog() { if (sc == null || dbAPI == null) { return; } ArrayList<Integer> bedsID = dbAPI.getBiggestBed(); ArrayList<SpatialObject> bedsSpatial = new ArrayList<SpatialObject>(); for (Integer i : bedsID) { bedsSpatial.add(sc.getBed(i)); } sc.setTheseAsSelected(bedsSpatial); mp.updateUI(); } public void getSmallestBedDialog() { if (sc == null || dbAPI == null) { return; } ArrayList<Integer> bedsID = dbAPI.getSmallestBed(); ArrayList<SpatialObject> bedsSpatial = new ArrayList<SpatialObject>(); for (Integer i : bedsID) { bedsSpatial.add(sc.getBed(i)); } sc.setTheseAsSelected(bedsSpatial); mp.updateUI(); } public void getSimilarDialog() { if (dc == null || dbAPI == null) { return; } ArrayList<String> plant_names = new ArrayList<String>(); for (DataObject o: dc.getPlants()) { plant_names.add(o.getName()); } Collections.sort(plant_names); JList plant_name_list = new JList(plant_names.toArray()); plant_name_list.setSelectedIndex(0); final JComponent[] inputs = new JComponent[]{ new JLabel("Plant name"), plant_name_list }; int a = JOptionPane.showInternalConfirmDialog(mainMenu, inputs, "Select plant name", JOptionPane.OK_CANCEL_OPTION); if (a == JOptionPane.OK_OPTION) { String selected_plant_name = (String) plant_name_list.getSelectedValue(); DataObject selected_plant = dc.getPlants(selected_plant_name); Integer similarPlantID = dbAPI.getMostSimilar((PlantsObject)selected_plant); DataObject similar_plant = dc.getPlants(similarPlantID); JLabel sim_plant_name = new JLabel(similar_plant.getName()); final JComponent[] outputs = new JComponent[]{ sim_plant_name // TODO: Pridat do outputs obrazek podobne rostliny }; JOptionPane.showInternalMessageDialog(mainMenu, outputs, "Similar plant", JOptionPane.INFORMATION_MESSAGE); } } public void getSignDescDialog() { DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy"); Calendar cal = Calendar.getInstance(); JTextField textdate_from = new JTextField(dateFormat.format(cal.getTime())); JTextField textdate_to = new JTextField(dateFormat.format(cal.getTime())); final JComponent[] inputs = new JComponent[]{ new JLabel("From (MM-DD-YYYY)"), textdate_from, new JLabel("To (MM-DD-YYYY)"), textdate_to }; int a = JOptionPane.showInternalConfirmDialog(mainMenu, inputs, "Select from ... to ...", JOptionPane.OK_CANCEL_OPTION); if (a == JOptionPane.OK_OPTION) { try { dateFormat.parse(textdate_from.getText()); dateFormat.parse(textdate_to.getText()); ArrayList<SpatialObject> lst = dbAPI.getSignsInTimePeriod(textdate_from.getText(), textdate_to.getText()); String str = new String(); str += "<html>"; for (SpatialObject o : lst) { str += dc.getPlants((((SignObject) o).getPlant())).getName() + " - " + ((SignObject) o).getDescription() + "<br />"; } str += "</html>"; JLabel desc_list = new JLabel(str); final JComponent[] outputs = new JComponent[]{desc_list}; JOptionPane.showInternalMessageDialog(mainMenu, outputs, "Result", JOptionPane.INFORMATION_MESSAGE); } catch (ParseException ex) { final JComponent[] result = new JComponent[]{new JLabel("The date you have entered is invalid!")}; JOptionPane.showInternalMessageDialog(mainMenu, result, "Error!", JOptionPane.ERROR_MESSAGE); } } } public void getPlantNamesDialog() { DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy"); Calendar cal = Calendar.getInstance(); JTextField textdate_from = new JTextField(dateFormat.format(cal.getTime())); JTextField textdate_to = new JTextField(dateFormat.format(cal.getTime())); final JComponent[] inputs = new JComponent[]{ new JLabel("From (MM-DD-YYYY)"), textdate_from, new JLabel("To (MM-DD-YYYY)"), textdate_to }; int a = JOptionPane.showInternalConfirmDialog(mainMenu, inputs, "Select from ... to ...", JOptionPane.OK_CANCEL_OPTION); if (a == JOptionPane.OK_OPTION) { try { dateFormat.parse(textdate_from.getText()); dateFormat.parse(textdate_to.getText()); ArrayList<DataObject> lst = dbAPI.getPlantsInTimePeriod(textdate_from.getText(), textdate_to.getText()); String str = new String(); str += "<html>"; for (DataObject o : lst) { str += o.getName() + "<br />"; } str += "</html>"; JLabel desc_list = new JLabel(str); final JComponent[] outputs = new JComponent[]{desc_list}; JOptionPane.showInternalMessageDialog(mainMenu, outputs, "Result", JOptionPane.INFORMATION_MESSAGE); } catch (ParseException ex) { final JComponent[] result = new JComponent[]{new JLabel("The date you have entered is invalid!")}; JOptionPane.showInternalMessageDialog(mainMenu, result, "Error!", JOptionPane.ERROR_MESSAGE); } } } public void getSignDescForPlantsDialog() { DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy"); Calendar cal = Calendar.getInstance(); JTextField textdate_from = new JTextField(dateFormat.format(cal.getTime())); JTextField textdate_to = new JTextField(dateFormat.format(cal.getTime())); final JComponent[] inputs = new JComponent[]{ new JLabel("From (MM-DD-YYYY)"), textdate_from, new JLabel("To (MM-DD-YYYY)"), textdate_to }; int a = JOptionPane.showInternalConfirmDialog(mainMenu, inputs, "Select from ... to ...", JOptionPane.OK_CANCEL_OPTION); if (a == JOptionPane.OK_OPTION) { try { dateFormat.parse(textdate_from.getText()); dateFormat.parse(textdate_to.getText()); ArrayList<SpatialObject> lst = dbAPI.getSignsByPlantsInTimePeriod(textdate_from.getText(), textdate_to.getText()); String str = new String(); str += "<html>"; for (SpatialObject o : lst) { str += dc.getPlants((((SignObject) o).getPlant())).getName() + " - " + ((SignObject) o).getDescription() + "<br />"; } str += "</html>"; JLabel desc_list = new JLabel(str); final JComponent[] outputs = new JComponent[]{desc_list}; JOptionPane.showInternalMessageDialog(mainMenu, outputs, "Result", JOptionPane.INFORMATION_MESSAGE); } catch (ParseException ex) { final JComponent[] result = new JComponent[]{new JLabel("The date you have entered is invalid!")}; JOptionPane.showInternalMessageDialog(mainMenu, result, "Error!", JOptionPane.ERROR_MESSAGE); } } } public void changeDateDialog() { if (sc == null) { return; } DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy"); Calendar cal = Calendar.getInstance(); JTextField textdate = new JTextField(dateFormat.format(cal.getTime())); final JComponent[] inputs = new JComponent[]{ new JLabel("Date (MM-DD-YYYY)"), textdate}; int a = JOptionPane.showInternalConfirmDialog(mainMenu, inputs, "Select actual date (MM-DD-YYYY)", JOptionPane.OK_CANCEL_OPTION); if (a == JOptionPane.OK_OPTION) { dateFormat.setLenient(false); try { dateFormat.parse(textdate.getText()); sc.setDate(textdate.getText()); mp.updateUI(); final JComponent[] result = new JComponent[]{new JLabel("The date has been set.")}; JOptionPane.showInternalMessageDialog(mainMenu, result, "Date has been set.", JOptionPane.INFORMATION_MESSAGE); } catch (ParseException ex) { final JComponent[] result = new JComponent[]{new JLabel("The date you have entered is invalid!")}; JOptionPane.showInternalMessageDialog(mainMenu, result, "Error!", JOptionPane.ERROR_MESSAGE); } } } public static void main(String[] args){ javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Core c = new Core(); c.initGui(); c.showGui(); c.dbSetUp(); } }); } }
package de.hwrberlin.it2014.sweproject.cbr; import de.hwrberlin.it2014.sweproject.cbr.Case; import java.util.ArrayList; /** * controls the cbr-cycle. Start the algorithm with startCBR(ArrayList<String>) method. * @author Max Bock * */ public class CBR { private ArrayList<Case> activeCases; //all cases from current userRequests public String startCBR(ArrayList<String> usersInput) { retrieve(usersInput); return null; //calls retrieve:CaseList //calls reuse and revise //build HTTPResponse } public String saveUserEvaluate(String evaluation) { return evaluation; //calls retain and write Case to DB } private ArrayList<Case> retrieve(ArrayList<String> usersInput) { Case c = new Case(usersInput); activeCases.add(c); return activeCases; //create new CaseObject //save case in activeCases //new query to DB //recieves and returns a CaseList with similiar cases } private ArrayList<Case> reuse(ArrayList<Case> caseListFromDBQuery) { return caseListFromDBQuery; //edit and control the caselist from DB-query } private ArrayList<Case> revise(ArrayList<Case> caseListFromReuse) { return caseListFromReuse; //build HTTPResponse } private void retain(Case evaluatedCase) { //return something; boolean or HTTPCode(int)? //save the evalution from userResponse to the DB } }
package de.slikey.effectlib.effect; import de.slikey.effectlib.EffectManager; import de.slikey.effectlib.EffectType; import de.slikey.effectlib.util.RandomUtils; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.entity.Entity; public class BleedEffect extends de.slikey.effectlib.Effect { /** * Play the Hurt Effect for the Player */ public boolean hurt = true; /** * Duration in ticks, the blood-particles take to despawn. * Not used anymore */ @Deprecated public int duration = 10; /** * Height of the blood spurt */ public double height = 1.75; /** * Color of blood. Default is red (152) */ public int color = 152; public BleedEffect(EffectManager effectManager) { super(effectManager); type = EffectType.REPEATING; period = 4; iterations = 25; } @Override public void onRun() { // Location to spawn the blood-item. Location location = getLocation(); location.add(0, RandomUtils.random.nextFloat() * height, 0); location.getWorld().playEffect(location, Effect.STEP_SOUND, color); Entity entity = getEntity(); if (hurt && entity != null) { entity.playEffect(org.bukkit.EntityEffect.HURT); } } }
package edu.ouc.principle.netty; /** * ChannelHandler * * @author wqx * */ public interface ChannelHandler { void channelActive(ChannelHandler handler) throws Exception; void exceptionCaught(ChannelHandler handler, Throwable cause) throws Exception; void channelRead(ChannelHandler handler, Object msg) throws Exception; }
// of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // File created: 2011-06-14 13:38:57 package fi.tkk.ics.hadoop.bam.cli.plugins; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; import net.sf.samtools.BAMFileWriter; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMFileReader.ValidationStringency; import net.sf.samtools.SAMFileWriterImpl; import net.sf.samtools.SAMFormatException; import net.sf.samtools.SAMRecordIterator; import net.sf.samtools.SAMSequenceRecord; import net.sf.samtools.SAMTextWriter; import net.sf.samtools.seekablestream.SeekableStream; import org.apache.hadoop.fs.Path; import fi.tkk.ics.hadoop.bam.SAMFormat; import fi.tkk.ics.hadoop.bam.cli.CLIPlugin; import fi.tkk.ics.hadoop.bam.cli.Utils; import fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser; import fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser.Option.BooleanOption; import fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser.Option.StringOption; import fi.tkk.ics.hadoop.bam.util.Pair; import fi.tkk.ics.hadoop.bam.util.WrapSeekable; public final class View extends CLIPlugin { private static final List<Pair<CmdLineParser.Option, String>> optionDescs = new ArrayList<Pair<CmdLineParser.Option, String>>(); private static final CmdLineParser.Option headerOnlyOpt = new BooleanOption('H', "header-only"), formatOpt = new StringOption ('F', "format=FMT"), stringencyOpt = new StringOption("validation-stringency=S"); public View() { super("view", "SAM and BAM viewing", "1.2", "PATH [regions...]", optionDescs, "Reads the BAM or SAM file in PATH and, by default, outputs it in "+ "SAM format. If any number of regions is given, only the alignments "+ "overlapping with those regions are output. Then an index is also "+ "required, expected at PATH.bai by default."+ "\n\n"+ "Regions can be given as only reference sequence names or indices "+ "like 'chr1', or with position ranges as well like 'chr1:100-200'. "+ "These coordinates are 1-based, with 0 representing the start or "+ "end of the sequence."); } static { optionDescs.add(new Pair<CmdLineParser.Option, String>( headerOnlyOpt, "print header only")); optionDescs.add(new Pair<CmdLineParser.Option, String>( formatOpt, "select the output format based on FMT: SAM or BAM")); optionDescs.add(new Pair<CmdLineParser.Option, String>( stringencyOpt, Utils.getStringencyOptHelp())); } @Override protected int run(CmdLineParser parser) { final List<String> args = parser.getRemainingArgs(); if (args.isEmpty()) { System.err.println("view :: PATH not given."); return 3; } Utils.toStringency(parser.getOptionValue(stringencyOpt, ValidationStringency.DEFAULT_STRINGENCY.toString()), "view"); final String path = args.get(0); final List<String> regions = args.subList(1, args.size()); final boolean headerOnly = parser.getBoolean(headerOnlyOpt); final SAMFileReader reader; try { final Path p = new Path(path); SeekableStream idx; try { idx = WrapSeekable.openPath(getConf(), p.suffix(".bai")); } catch (Exception e) { idx = null; } final SeekableStream sam = WrapSeekable.openPath(getConf(), p); reader = idx == null ? new SAMFileReader(sam, false) : new SAMFileReader(sam, idx, false); } catch (Exception e) { System.err.printf("view :: Could not open '%s': %s\n", path, e.getMessage()); return 4; } reader.setValidationStringency(ValidationStringency.SILENT); final SAMFileHeader header; try { header = reader.getFileHeader(); } catch (SAMFormatException e) { System.err.printf("view :: Could not parse '%s': %s\n", path, e.getMessage()); return 4; } final String fmt = (String)parser.getOptionValue(formatOpt); final SAMFormat format = fmt == null ? SAMFormat.SAM : SAMFormat.valueOf(fmt.toUpperCase(Locale.ENGLISH)); final SAMFileWriterImpl writer; switch (format) { case BAM: writer = new BAMFileWriter(System.out, new File("<stdout>")); break; case SAM: writer = new SAMTextWriter(System.out); break; default: writer = null; assert false; } writer.setSortOrder(header.getSortOrder(), true); writer.setHeader(header); if (regions.isEmpty() || headerOnly) { if (!headerOnly) if (!writeIterator(writer, reader.iterator(), path)) return 4; writer.close(); return 0; } if (!reader.isBinary()) { System.err.println("view :: Cannot output regions from SAM file"); return 4; } if (!reader.hasIndex()) { System.err.println( "view :: Cannot output regions from BAM file lacking an index"); return 4; } reader.enableIndexCaching(true); boolean errors = false; for (final String region : regions) { final StringTokenizer st = new StringTokenizer(region, ":-"); final String refStr = st.nextToken(); final int beg, end; if (st.hasMoreTokens()) { beg = parseCoordinate(st.nextToken()); end = st.hasMoreTokens() ? parseCoordinate(st.nextToken()) : -1; if (beg < 0 || end < 0) { errors = true; continue; } if (end < beg) { System.err.printf( "view :: Invalid range, cannot end before start: '%d-%d'\n", beg, end); errors = true; continue; } } else beg = end = 0; SAMSequenceRecord ref = header.getSequence(refStr); if (ref == null) try { ref = header.getSequence(Integer.parseInt(refStr)); } catch (NumberFormatException e) {} if (ref == null) { System.err.printf( "view :: Not a valid sequence name or index: '%s'\n", refStr); errors = true; continue; } final SAMRecordIterator it = reader.queryOverlapping(ref.getSequenceName(), beg, end); if (!writeIterator(writer, it, path)) return 4; } writer.close(); return errors ? 5 : 0; } private boolean writeIterator( SAMFileWriterImpl writer, SAMRecordIterator it, String path) { try { while (it.hasNext()) writer.addAlignment(it.next()); return true; } catch (SAMFormatException e) { writer.close(); System.err.printf("view :: Could not parse '%s': %s\n", path, e.getMessage()); return false; } } private int parseCoordinate(String s) { int c; try { c = Integer.parseInt(s); } catch (NumberFormatException e) { c = -1; } if (c < 0) System.err.printf("view :: Not a valid coordinate: '%s'\n", s); return c; } }
package fr.foodlimit.api.place; import fr.foodlimit.api.security.jwt.JWTFilter; import fr.foodlimit.api.security.jwt.TokenProvider; import fr.foodlimit.api.shared.models.Place; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.List; @RestController @CrossOrigin @RequestMapping("/places") public class PlaceController { @Autowired private Environment environment; private final TokenProvider tokenProvider; @Autowired private PlaceService placeService; public PlaceController(TokenProvider tokenProvider) { this.tokenProvider = tokenProvider; } @GetMapping public ResponseEntity<List<Place>> getPlaces(HttpServletRequest request) { return ResponseEntity.ok(placeService.getPlaces(tokenProvider.getUsername(JWTFilter.resolveToken(request)))); } @GetMapping("/{id}") public ResponseEntity<Place> getPlace(HttpServletRequest request, @PathVariable("id") Long id) { Place place = placeService.getPlace(id); String username = tokenProvider.getUsername(JWTFilter.resolveToken(request)); if (!this.environment.getActiveProfiles()[0].equals("test") && !place.getUser().getUsername().equals(username)) { return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); } return ResponseEntity.ok(placeService.getPlace(id)); } /** * Supprime un foyer de l'utilisateur * @param id */ @DeleteMapping("/{id}") public ResponseEntity deletePlace(HttpServletRequest request, @PathVariable("id") Long id) { Place place = placeService.getPlace(id); String username = tokenProvider.getUsername(JWTFilter.resolveToken(request)); if (!this.environment.getActiveProfiles()[0].equals("test") && !place.getUser().getUsername().equals(username)) { return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); } placeService.deletePlace(id); return ResponseEntity.noContent().build(); } @PostMapping public ResponseEntity<Place> createPlace(HttpServletRequest request, @RequestBody Place place) { return ResponseEntity.ok(placeService.createPlace(place, tokenProvider.getUsername(JWTFilter.resolveToken(request)))); } /** * Modifie un foyer de l'utilisateur * @param request * @param id * @param place * @return */ @PutMapping("/{id}") public ResponseEntity<Place> updatePlace(HttpServletRequest request, @PathVariable("id") Long id, @RequestBody Place place) { Place dbPlace = placeService.getPlace(id); String username = tokenProvider.getUsername(JWTFilter.resolveToken(request)); if (!this.environment.getActiveProfiles()[0].equals("test") && !dbPlace.getUser().getUsername().equals(username)) { return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); } place.setId(id); return ResponseEntity.ok(placeService.updatePlace(place, username)); } }
package ge.edu.freeuni.sdp.xo.chat; import com.microsoft.azure.storage.StorageException; import ge.edu.freeuni.sdp.xo.chat.data.MessageEntity; import ge.edu.freeuni.sdp.xo.chat.data.Repository; import ge.edu.freeuni.sdp.xo.chat.data.RepositoryFactory; import org.glassfish.jersey.client.ClientConfig; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; import javax.validation.constraints.NotNull; import javax.ws.rs.*; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; @Path("/") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public class ChatService { @Context private UriInfo uriInfo; private static final String XO_LOGIN_SERVICE = "http://xo-login.herokuapp.com/webapi/login/"; private static final String XO_ROOMS_SERVICE = "http://xo-rooms.herokuapp.com/room_id?token="; public static final int UNPROCESSABLE_ENTITY = 422; public FakeAuthorizationChecker checker = new FakeAuthorizationChecker(); public RepositoryFactory getRepositoryFactory() throws StorageException { return RepositoryFactory.create(); } /** * * @return 200 (OK), list of messages. * @throws StorageException */ @GET public List<MessageDo> publicChatMessages( @QueryParam("token") String token) throws StorageException { final List result = new ArrayList<>(); if (!isTokenValid(token)) throw new WebApplicationException(UNPROCESSABLE_ENTITY); Repository repository = getRepositoryFactory().getPublicRepository(); for (MessageEntity message : repository.getMessages("-1")) { result.add(message.toDo()); } return result; } /** * * @return 200 (OK), list of messages. * @throws StorageException */ @GET @Path("{roomId}") public List<MessageDo> privateChatMessages( @PathParam("roomId") String roomId, @QueryParam("token") String token) throws StorageException { if (!isTokenValid(token)) throw new WebApplicationException(UNPROCESSABLE_ENTITY); Repository repository = getRepositoryFactory().getPrivateRepository(); final List result = new ArrayList<>(); for (MessageEntity message : repository.getMessages(roomId)) { result.add(message.toDo()); } return result; } /** * * @param message * @return 201 (Created) * @throws StorageException */ @POST public Response addPrivateChatMessage(@QueryParam("token") String token, @NotNull MessageDo message) throws StorageException { if (message.getText().trim().isEmpty()) return Response.status(Status.BAD_REQUEST).build(); if (!isTokenValid(token)) return Response.status(UNPROCESSABLE_ENTITY).build(); String userName = getUserNameFromToken(token); message.setId(uniqueSequentialId()); message.setSenderUserName(userName); MessageEntity messageEntity = new MessageEntity(message); String roomId = messageEntity.getRoomID(); Repository repository; if ("-1".equals(roomId)) { repository = getRepositoryFactory().getPublicRepository(); repository.postMessage(messageEntity); } else { if (!isCorectRoomId(roomId, token)) { return Response.status(Status.FORBIDDEN).build(); } repository = getRepositoryFactory().getPrivateRepository(); repository.postMessage(messageEntity); } tryDeleteOldRecords(repository, roomId); return Response.status(Status.CREATED).build(); } private boolean isCorectRoomId(String roomID, String token) { return roomID.equals(getRoomIDFromToken(token)); } private String getRoomIDFromToken(String token) { Client client = ClientBuilder.newClient(new ClientConfig()); try { Response response = client.target(XO_ROOMS_SERVICE + token) .request(MediaType.APPLICATION_JSON_TYPE) .get(Response.class); if (response.getStatus() != Status.OK.getStatusCode()) return null; RoomDo room = response.readEntity(RoomDo.class); return room.getId(); } catch (WebApplicationException e) { return null; } } private String getUserNameFromToken(String token) { if (token == null) return null; Client client = ClientBuilder.newClient(new ClientConfig()); try { Response response = client.target(XO_LOGIN_SERVICE + token) .request(MediaType.APPLICATION_JSON_TYPE) .get(Response.class); if (response.getStatus() != Status.OK.getStatusCode()) return null; UserName username = response.readEntity(UserName.class); return username.username; } catch (WebApplicationException e) { return null; } } private boolean isTokenValid(String token) { return getUserNameFromToken(token) != null; } private static final AtomicInteger seq = new AtomicInteger(); private String uniqueSequentialId() { int nextVal = seq.incrementAndGet(); DateTime dt = new DateTime(DateTimeZone.UTC); LocalDate ld = dt.toLocalDate(); return ld + "-" + System.currentTimeMillis() + "-" + nextVal; } private static final int threshold = 5; private void tryDeleteOldRecords(Repository repository, String roomId) throws StorageException { final List<MessageEntity> result = new ArrayList<>(); for (MessageEntity message : repository.getMessages(roomId)) { result.add(message); } for (int i=0; i<result.size()-threshold; i++) { repository.deleteMessage(result.get(i)); } } }
package hu.bme.mit.codemodel.rifle; import com.shapesecurity.functional.Pair; import com.shapesecurity.functional.data.*; import com.shapesecurity.shift.ast.Script; import com.shapesecurity.shift.parser.JsError; import com.shapesecurity.shift.parser.Parser; import com.shapesecurity.shift.scope.GlobalScope; import com.shapesecurity.shift.scope.ScopeAnalyzer; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Arrays; public class Application { public static void main(String[] args) throws JsError { String source = "function bytes(n, maxBytes) {\n" + " if (maxBytes == null) {\n" + " maxBytes = Math.max(1, Math.ceil(Math.log2(n + 1) / 8));\n" + " }\n" + " var rv = Array(maxBytes);\n" + " for (var bIndex = maxBytes - 1; bIndex >= 0; --bIndex) {\n" + " rv[bIndex] = n & 0xFF;\n" + " n >>>= 8;\n" + " }\n" + " return rv;\n" + "}"; Script program = Parser.parseScript(source); // System.out.println("@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns System.out.println("@prefix id: <http://inf.mit.bme.hu/codemodel GlobalScope global = ScopeAnalyzer.analyze(program); // String serializeScope = new ScopeSerializer().serializeScope(global); new Application().iterate(global); } protected ArrayList<Object> done = new ArrayList<>(); public void iterate(Object node) { if (node == null || done.contains(node)) { return; } done.add(node); System.out.println(); // print class Class<?> aClass = node.getClass(); //printType(id, aClass.getSimpleName()); String id = generateId(node); // list superclasses, interfaces // List<Class<?>> interfaces = Arrays.asList(aClass.getInterfaces()); // interfaces.forEach(elem -> printType(id, elem.getSimpleName())); // Class<?> superclass = aClass.getSuperclass(); // while (superclass != Object.class) { // printType(id, superclass.getSimpleName()); // superclass = superclass.getSuperclass(); // list fields Arrays.asList(aClass.getFields()).forEach( field -> { // System.out.print(indentation + (Modifier.isPublic(field.getModifiers()) ? "public " : "NOT public ")); Class<?> type = field.getType(); // System.out.print(indentation + type.getSimpleName() + " "); String fieldName = field.getName(); if (type == ImmutableList.class) { try { ImmutableList list = (ImmutableList) field.get(node); handleImmutableList(list, id, fieldName); } catch (IllegalAccessException e) { e.printStackTrace(); } } else if (type == ConcatList.class) { try { ImmutableList list = ((ConcatList) field.get(node)).toList(); handleImmutableList(list, id, fieldName); } catch (IllegalAccessException e) { e.printStackTrace(); } } else if (type.isEnum()) { try { printTriple(id, fieldName, field.get(node).toString()); } catch (IllegalAccessException e) { e.printStackTrace(); } } else if (type.getName().startsWith("com.shapesecurity.shift.ast")) { try { Object el = field.get(node); printTripleRef(id, fieldName, generateId(el)); iterate(el); } catch (IllegalAccessException e) { e.printStackTrace(); } } else if (type == Maybe.class) { try { Maybe el = (Maybe) field.get(node); if (el.isJust()) { Object obj = el.just(); printTripleRef(id, fieldName, generateId(obj)); iterate(obj); } else { printTripleRef(id, fieldName, "null"); } } catch (IllegalAccessException e) { e.printStackTrace(); } } else if (type == HashTable.class) { try { HashTable table = (HashTable) field.get(node); String tableId = generateId(table); // id -- [field] -> table printTripleRef(id, fieldName, tableId); for (Object el : table.entries()) { Pair pair = (Pair) el; if (pair.b instanceof ImmutableList) { // table -- [a] -> b.* // handleImmutableList((ImmutableList) pair.b, tableId, pair.a.toString()); // id -- [field] -> b.* handleImmutableList((ImmutableList) pair.b, id, fieldName); } else { printTripleRef(id, fieldName, generateId(pair.b)); // printTripleRef(tableId, pair.a.toString(), generateId(pair.b)); iterate(pair.b); } } } catch (IllegalAccessException e) { e.printStackTrace(); } } else if (type == Either.class) { } else if (type.getName().startsWith("com.shapesecurity.functional.data")) { // TODO System.out.println("boop"); } else { try { Object el = field.get(node); printTriple(id, fieldName, generateId(el)); iterate(el); } catch (IllegalAccessException e) { e.printStackTrace(); } } } ); System.out.println(); // list methods // System.out.println(indentation + aClass.getMethods()); } protected void handleImmutableList(ImmutableList list, String id, String fieldName) { list.forEach( el -> { printTripleRef(id, fieldName, generateId(el)); iterate(el); } ); // TODO create a list node with numbered connections } @NotNull private String generateId(Object obj) { return obj.getClass().getSimpleName() + "_" + obj.hashCode(); } protected void printType(String subject, String object) { System.out.println("id:" + subject.replace('-', '_') + " a \"" + object + "\" ."); } protected void printTriple(String subject, String predicate, String object) { System.out.println("id:" + subject.replace('-', '_') + " <" + predicate + "> \"" + object + "\" ."); } protected void printTripleRef(String subject, String predicate, String id) { System.out.println("id:" + subject.replace('-', '_') + " <" + predicate + "> id:" + id.replace('-', '_') + " ."); } }
package hudson.plugins.ec2.ssh; import hudson.model.Descriptor; import hudson.model.Hudson; import hudson.plugins.ec2.EC2ComputerLauncher; import hudson.plugins.ec2.EC2Cloud; import hudson.plugins.ec2.EC2Computer; import hudson.remoting.Channel; import hudson.remoting.Channel.Listener; import hudson.slaves.ComputerLauncher; import java.io.IOException; import java.io.PrintStream; import java.net.URL; import org.apache.commons.io.IOUtils; import com.amazonaws.AmazonClientException; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.KeyPair; import com.trilead.ssh2.Connection; import com.trilead.ssh2.SCPClient; import com.trilead.ssh2.ServerHostKeyVerifier; import com.trilead.ssh2.Session; /** * {@link ComputerLauncher} that connects to a Unix slave on EC2 by using SSH. * * @author Kohsuke Kawaguchi */ public class EC2UnixLauncher extends EC2ComputerLauncher { private final int FAILED=-1; private final int SAMEUSER=0; private final int RECONNECT=-2; protected String buildUpCommand(EC2Computer computer, String command) { if (!computer.getRemoteAdmin().equals("root")) { command = computer.getRootCommandPrefix() + " " + command; } return command; } @Override protected void launch(EC2Computer computer, PrintStream logger, Instance inst) throws IOException, AmazonClientException, InterruptedException { final Connection bootstrapConn; final Connection conn; Connection cleanupConn = null; // java's code path analysis for final doesn't work that well. boolean successful = false; try { bootstrapConn = connectToSsh(computer, logger); int bootstrapResult = bootstrap(bootstrapConn, computer, logger); if (bootstrapResult == FAILED) { logger.println("bootstrapresult failed"); return; // bootstrap closed for us. } else if (bootstrapResult == SAMEUSER) { cleanupConn = bootstrapConn; // take over the connection logger.println("take over connection"); } else { // connect fresh as ROOT logger.println("connect fresh as root"); cleanupConn = connectToSsh(computer, logger); KeyPair key = computer.getCloud().getKeyPair(); if (!cleanupConn.authenticateWithPublicKey(computer.getRemoteAdmin(), key.getKeyMaterial().toCharArray(), "")) { logger.println("Authentication failed"); return; // failed to connect as root. } } conn = cleanupConn; SCPClient scp = conn.createSCPClient(); String initScript = computer.getNode().initScript; if(initScript!=null && initScript.trim().length()>0 && conn.exec("test -e ~/.hudson-run-init", logger) !=0) { logger.println("Executing init script"); scp.put(initScript.getBytes("UTF-8"),"init.sh","/tmp","0700"); Session sess = conn.openSession(); sess.requestDumbPTY(); // so that the remote side bundles stdout and stderr sess.execCommand(buildUpCommand(computer, "/tmp/init.sh")); sess.getStdin().close(); // nothing to write here sess.getStderr().close(); // we are not supposed to get anything from stderr IOUtils.copy(sess.getStdout(),logger); int exitStatus = waitCompletion(sess); if (exitStatus!=0) { logger.println("init script failed: exit code="+exitStatus); return; } sess.close(); // Needs a tty to run sudo. sess = conn.openSession(); sess.requestDumbPTY(); // so that the remote side bundles stdout and stderr sess.execCommand(buildUpCommand(computer, "touch ~/.hudson-run-init")); sess.close(); } // TODO: parse the version number. maven-enforcer-plugin might help logger.println("Verifying that java exists"); if(conn.exec("java -fullversion", logger) !=0) { logger.println("Installing Java"); String jdk = "java1.6.0_12"; String path = "/hudson-ci/jdk/linux-i586/" + jdk + ".tgz"; URL url = computer.getCloud().buildPresignedURL(path); if(conn.exec("wget -nv -O /tmp/" + jdk + ".tgz '" + url + "'", logger) !=0) { logger.println("Failed to download Java"); return; } if(conn.exec(buildUpCommand(computer, "tar xz -C /usr -f /tmp/" + jdk + ".tgz"), logger) !=0) { logger.println("Failed to install Java"); return; } if(conn.exec(buildUpCommand(computer, "ln -s /usr/" + jdk + "/bin/java /bin/java"), logger) !=0) { logger.println("Failed to symlink Java"); return; } } // TODO: on Windows with ec2-sshd, this scp command ends up just putting slave.jar as c:\tmp // bug in ec2-sshd? logger.println("Copying slave.jar"); scp.put(Hudson.getInstance().getJnlpJars("slave.jar").readFully(), "slave.jar","/tmp"); String jvmopts = computer.getNode().jvmopts; String launchString = "java " + (jvmopts != null ? jvmopts : "") + " -jar /tmp/slave.jar"; logger.println("Launching slave agent: " + launchString); final Session sess = conn.openSession(); sess.execCommand(launchString); computer.setChannel(sess.getStdout(),sess.getStdin(),logger,new Listener() { @Override public void onClosed(Channel channel, IOException cause) { sess.close(); conn.close(); } }); successful = true; } finally { if(cleanupConn != null && !successful) cleanupConn.close(); } } private int bootstrap(Connection bootstrapConn, EC2Computer computer, PrintStream logger) throws IOException, InterruptedException, AmazonClientException { logger.println("bootstrap()" ); boolean closeBootstrap = true; try { int tries = 20; boolean isAuthenticated = false; logger.println("Getting keypair..." ); KeyPair key = computer.getCloud().getKeyPair(); logger.println("Using key: " + key.getKeyName() + "\n" + key.getKeyFingerprint() + "\n" + key.getKeyMaterial().substring(0, 160) ); while (tries logger.println("Authenticating as " + computer.getRemoteAdmin()); isAuthenticated = bootstrapConn.authenticateWithPublicKey(computer.getRemoteAdmin(), key.getKeyMaterial().toCharArray(), ""); if (isAuthenticated) { break; } logger.println("Authentication failed. Trying again..."); Thread.sleep(10000); } if (!isAuthenticated) { logger.println("Authentication failed"); return FAILED; } closeBootstrap = false; return SAMEUSER; } finally { if (closeBootstrap) bootstrapConn.close(); } } private Connection connectToSsh(EC2Computer computer, PrintStream logger) throws AmazonClientException, InterruptedException { final long timeout = computer.getNode().getLaunchTimeoutInMillis(); final long startTime = System.currentTimeMillis(); while(true) { try { long waitTime = System.currentTimeMillis() - startTime; if ( waitTime > timeout ) { throw new AmazonClientException("Timed out after "+ (waitTime / 1000) + " seconds of waiting for ssh to become available. (maximum timeout configured is "+ (timeout / 1000) + ")" ); } Instance instance = computer.updateInstanceDescription(); String vpc_id = instance.getVpcId(); String host; if (computer.getNode().usePrivateDnsName) { host = instance.getPrivateDnsName(); } else { /* VPC hosts don't have public DNS names, so we need to use an IP address instead */ if (vpc_id == null || vpc_id.equals("")) { host = instance.getPublicDnsName(); } else { host = instance.getPrivateIpAddress(); } } if ("0.0.0.0".equals(host)) { logger.println("Invalid host 0.0.0.0, your host is most likely waiting for an ip address."); throw new IOException("goto sleep"); } int port = computer.getSshPort(); logger.println("Connecting to " + host + " on port " + port + ". "); Connection conn = new Connection(host, port); // currently OpenSolaris offers no way of verifying the host certificate, so just accept it blindly, // hoping that no man-in-the-middle attack is going on. conn.connect(new ServerHostKeyVerifier() { public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception { return true; } }); logger.println("Connected via SSH."); return conn; // successfully connected } catch (IOException e) { // keep retrying until SSH comes up logger.println("Waiting for SSH to come up. Sleeping 5."); Thread.sleep(5000); } } } private int waitCompletion(Session session) throws InterruptedException { // I noticed that the exit status delivery often gets delayed. Wait up to 1 sec. for( int i=0; i<10; i++ ) { Integer r = session.getExitStatus(); if(r!=null) return r; Thread.sleep(100); } return -1; } @Override public Descriptor<ComputerLauncher> getDescriptor() { throw new UnsupportedOperationException(); } }
package io.druid.data.input.impl; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Function; import com.metamx.common.parsers.ParserUtils; import org.joda.time.DateTime; import java.util.Map; public class TimestampSpec { private static final String DEFAULT_COLUMN = "timestamp"; private static final String DEFAULT_FORMAT = "auto"; private static final DateTime DEFAULT_MISSING_VALUE = null; private final String timestampColumn; private final String timestampFormat; private final Function<String, DateTime> timestampConverter; // this value should never be set for production data private final DateTime missingValue; @JsonCreator public TimestampSpec( @JsonProperty("column") String timestampColumn, @JsonProperty("format") String format, // this value should never be set for production data @JsonProperty("missingValue") DateTime missingValue ) { this.timestampColumn = (timestampColumn == null) ? DEFAULT_COLUMN : timestampColumn; this.timestampFormat = format == null ? DEFAULT_FORMAT : format; this.timestampConverter = ParserUtils.createTimestampParser(timestampFormat); this.missingValue = missingValue == null ? DEFAULT_MISSING_VALUE : missingValue; } @JsonProperty("column") public String getTimestampColumn() { return timestampColumn; } @JsonProperty("format") public String getTimestampFormat() { return timestampFormat; } @JsonProperty("missingValue") public DateTime getMissingValue() { return missingValue; } public DateTime extractTimestamp(Map<String, Object> input) { final Object o = input.get(timestampColumn); return o == null ? missingValue : timestampConverter.apply(o.toString()); } }
package it.richkmeli.rmc.controller; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import it.richkmeli.jframework.crypto.Crypto; import it.richkmeli.jframework.network.tcp.client.okhttp.Network; import it.richkmeli.jframework.network.tcp.client.okhttp.NetworkCallback; import it.richkmeli.jframework.network.tcp.client.okhttp.util.ResponseParser; import it.richkmeli.jframework.util.Logger; import it.richkmeli.rmc.model.Device; import it.richkmeli.rmc.model.ModelException; import it.richkmeli.rmc.network.SocketCallback; import it.richkmeli.rmc.network.SocketManager; import it.richkmeli.rmc.network.SocketThread; import it.richkmeli.rmc.swing.ListCallback; import it.richkmeli.rmc.swing.RichkwareCallback; import it.richkmeli.rmc.utils.Utils; import org.json.JSONArray; import org.json.JSONObject; import java.io.File; import java.lang.reflect.Type; import java.util.*; public class Controller { private static final String SECURE_DATA_CLIENT = "secureDataClient"; private static final String CLIENT_KEY = "clientKey"; private static final String SERVER_RESPONSE = "serverResponse"; private static final int SECURE_CONNECTION_MAX_ATTEMPT = 5; private Network network; private Crypto.Client cryptoClient; private static String clientID = null; private List<String> devicesList; private Map<Device, SocketThread> devicesMap; public Controller() { network = new Network(); cryptoClient = new Crypto.Client(); } public Network getNetwork() { return network; } public void login(String email, String password, RichkwareCallback callback) { JSONObject payload = new JSONObject(); payload.put("email", email); payload.put("password", Crypto.hashPassword(password, true)); network.getRequest("LogIn", payload.toString(),"channel=rmc", cryptoClient, new NetworkCallback() { @Override public void onSuccess(String response) { if (ResponseParser.isStatusOK(response)) callback.onSuccess(ResponseParser.parseMessage(response)); else callback.onFailure(ResponseParser.parseMessage(response)); } @Override public void onFailure(Exception e) { callback.onFailure(e.getMessage()); } }); } public void logout(Boolean encryption, RichkwareCallback callback) { network.getRequest("LogOut", null,"channel=rmc", encryption ? cryptoClient : null, new NetworkCallback() { @Override public void onSuccess(String response) { if (ResponseParser.isStatusOK(response)) callback.onSuccess(ResponseParser.parseMessage(response)); else callback.onFailure(ResponseParser.parseMessage(response)); network.deleteSession(); } @Override public void onFailure(Exception e) { callback.onFailure(e.getMessage()); } }); } public void userStatus(Boolean encryption, RichkwareCallback callback) { network.getRequest("user", null,"channel=rmc", encryption ? cryptoClient : null, new NetworkCallback() { @Override public void onSuccess(String response) { if (ResponseParser.isStatusOK(response)) callback.onSuccess(ResponseParser.parseMessage(response)); else callback.onFailure(ResponseParser.parseMessage(response)); } @Override public void onFailure(Exception e) { callback.onFailure(e.getMessage()); } }); } public void devicesList(boolean encryption, ListCallback callback) throws ModelException { String sDevicesList = null; Gson gson = new Gson(); network.getRequest("devicesList", null,"channel=rmc", encryption ? cryptoClient : null, new NetworkCallback() { @Override public void onSuccess(String response) { if (ResponseParser.isStatusOK(response)) { Type listType = new TypeToken<ArrayList<Device>>() { }.getType(); callback.onSuccess(gson.fromJson(ResponseParser.parseMessage(response), listType)); } else callback.onFailure(ResponseParser.parseMessage(response)); } @Override public void onFailure(Exception e) { callback.onFailure(e.getMessage()); } }); } public void connectDevice(Device device) { devicesList = new ArrayList<>(); devicesList.add(device.getName()); } // //DONE // private void reverseCommand(ArrayList device, String commands, boolean encryption, RichkwareCallback callback) { // String[] commandsArray = commands.split("\n"); // String encodedCommands = ""; // for (int i = 0; i < commandsArray.length; i++) { // encodedCommands += (Base64.getEncoder().encodeToString(commandsArray[i].getBytes())); // if (i != commandsArray.length - 1) // encodedCommands += " // encodedCommands = Base64.getEncoder().encodeToString(encodedCommands.getBytes()); // JSONObject jsonParameters = new JSONObject() // .put("device", device.getName()) // .put("commands", encodedCommands); // network.putRequest("command", jsonParameters.toString(), encryption, new NetworkCallback() { // @Override // public void onSuccess(String response) { // if (ResponseParser.isStatusOK(response)) // callback.onSuccess(ResponseParser.parseMessage(response)); // else // callback.onFailure(ResponseParser.parseMessage(response)); // @Override // public void onFailure(Exception e) { // callback.onFailure(e.getMessage()); // //DONE // public void reverseCommand(ArrayList<String> commands, boolean encryption, ReverseCommandCallback callback) { // Map<String, String> responseMap = new HashMap<>(); // for (int i = 0; i < devicesList.size(); i++) { // int finalI = i; // reverseCommand(devicesList.get(i), commands, encryption, new RichkwareCallback() { // @Override // public void onSuccess(String response) { // reverseReturn(finalI, responseMap, callback); // @Override // public void onFailure(String response) { // responseMap.put(devicesList.get(finalI), response); // reverseReturn(finalI, responseMap, callback); public void connectDevice(List<Device> devices) { List<String> list = new ArrayList<>(); for (Device device : devices) { String name = device.getName(); list.add(name); } devicesList = list; } // private void reverseReturn(int i, Map<String, String> map, ReverseCommandCallback callback) { // if (i == devicesList.size()-1){ // if(map.isEmpty()){ // callback.onSuccess(); // } else { // callback.onFailure(map); public void reverseCommand(String commands, boolean encryption, RichkwareCallback callback) { String[] commandsArray = commands.split("\n"); StringBuilder encodedCommands = new StringBuilder(); for (int i = 0; i < commandsArray.length; i++) { encodedCommands.append(Base64.getEncoder().encodeToString(commandsArray[i].getBytes())); if (i != commandsArray.length - 1) encodedCommands.append(" } encodedCommands = new StringBuilder(Base64.getEncoder().encodeToString(encodedCommands.toString().getBytes())); JSONObject jsonParameters = new JSONObject() .put("devices", new JSONArray(devicesList)) .put("commands", encodedCommands.toString()); //TODO encryption network.putRequest("command", jsonParameters.toString(), null, new NetworkCallback() { @Override public void onSuccess(String response) { if (ResponseParser.isStatusOK(response)) callback.onSuccess(ResponseParser.parseMessage(response)); else callback.onFailure(ResponseParser.parseMessage(response)); } @Override public void onFailure(Exception e) { callback.onFailure(e.getMessage()); } }); } public void reverseCommandResponse(RichkwareCallback callback) { JSONObject jsonParameters = new JSONObject(); jsonParameters.put("data0", devicesList.get(0)); //TODO encryption network.getRequest("command", jsonParameters.toString(),"channel=rmc", cryptoClient, new NetworkCallback() { @Override public void onSuccess(String response) { if (ResponseParser.isStatusOK(response)) callback.onSuccess(ResponseParser.parseMessage(response)); else callback.onFailure(ResponseParser.parseMessage(response)); } @Override public void onFailure(Exception e) { callback.onFailure(e.getMessage()); } }); } public void openSocket(Device device, boolean forceEncryption, RichkwareCallback callback) { devicesMap = new HashMap<>(); SocketManager.openSocket(device.getIp(), device.getServerPort(), device.getEncryptionKey(), forceEncryption, new SocketCallback() { @Override public void onSuccess(SocketThread socketThread) { devicesMap.put(device, socketThread); callback.onSuccess(""); } @Override public void onFailure(Exception e) { callback.onFailure(e.getMessage()); } }); } public void openSocket(List<Device> devices, boolean forceEncryption, RichkwareCallback callback) { for (Device device : devices) { openSocket(device, forceEncryption, callback); } } public void sendCommand(String command, RichkwareCallback callback) { for (SocketThread socketThread : devicesMap.values()) { socketThread.sendCommand(command, callback); } } public void closeSocket() { for (SocketThread socketThread : devicesMap.values()) { socketThread.disconnect(); } } public void deleteCryptoState() { cryptoClient.reset(); network.deleteSession(); } private void asyncInit(Map<String, Object> map, int attempt, RichkwareCallback callback) { // callback chiamata allo stato 3 String clientResponse = cryptoClient.init((File) map.get(SECURE_DATA_CLIENT), (String) map.get(CLIENT_KEY), (String) map.get(SERVER_RESPONSE)); Logger.info(clientResponse); int clientState = new JSONObject(clientResponse).getInt("state"); JSONObject parametersJson = new JSONObject(); parametersJson.put("clientID", clientID); parametersJson.put("data", new JSONObject(clientResponse).getString("payload")); Logger.info("clientState: " + clientState); getNetwork().getRequestCompat("SecureConnection", parametersJson.toString(), new NetworkCallback() { @Override public void onSuccess(String response) { if (attempt < SECURE_CONNECTION_MAX_ATTEMPT) { String clientResponse = cryptoClient.init((File) map.get(SECURE_DATA_CLIENT), (String) map.get(CLIENT_KEY), response); int clientState = new JSONObject(clientResponse).getInt("state"); Logger.info("clientState: " + clientState); if (clientState == -1) { callback.onFailure("Corrupted state"); } else if (clientState != 3) { map.remove(SERVER_RESPONSE); map.put(SERVER_RESPONSE, response); Logger.info(map.get(SECURE_DATA_CLIENT) + " " + (String) map.get(CLIENT_KEY) + " " + (String) map.get(SERVER_RESPONSE)); asyncInit(map, attempt + 1, callback); } else { //TODO chaiamata a se stesso se stato <3, oppure chiama callback callback.onSuccess(String.valueOf(clientState)); } } else { callback.onFailure("Connection timeout"); } } @Override public void onFailure(Exception e) { callback.onFailure(e.getMessage()); } }); } private void setClientID() { if (clientID == null) { String id = "RMC_" + Utils.getDeviceIdentifier(); clientID = Base64.getUrlEncoder().encodeToString(id.getBytes()); } Logger.info(Utils.getDeviceInfo()); } public void initSecureConnection(RichkwareCallback callback) { Logger.info("initSecureConnection..."); setClientID(); //TODO verificare che non si leghi ad un unico server, altrimenti diverso file TXT, nome server nel file TXT // re-init to allow a connection to a different server cryptoClient = new Crypto.Client(); File secureDataClient = new File("TESTsecureDataClient.txt"); String clientKey = "testkeyClient"; String serverResponse = ""; Map<String, Object> map = new HashMap<>(); map.put(SECURE_DATA_CLIENT, secureDataClient); map.put(CLIENT_KEY, clientKey); map.put(SERVER_RESPONSE, serverResponse); asyncInit(map, 0, callback); } }
package kodkod.engine; import java.util.Iterator; import kodkod.ast.Formula; import kodkod.ast.Relation; import kodkod.engine.config.DecomposedOptions; import kodkod.engine.config.DecomposedOptions.DMode; import kodkod.engine.config.ExtendedOptions; import kodkod.engine.config.PardinusOptions; import kodkod.engine.decomp.DProblemExecutor; import kodkod.engine.decomp.DProblemExecutorImpl; import kodkod.engine.decomp.StatsExecutor; import kodkod.instance.Instance; import kodkod.instance.PardinusBounds; /** * A computational engine for solving relational satisfiability problems in a * decomposed strategy. Such a problem is described by a * {@link kodkod.ast.Formula formula} in first order relational logic; finite * {@link ExtendedOptions bounds} on the value of each {@link Relation * relation} constrained by the formula that have been split into two sets; and * a set of {@link PardinusOptions options} specifying, among other global * parameters, which solver should be used in the second stage of the process. A * different set of options can be used to control the regular {@link Solver * Kodkod solver} used in the first stage. * * <p> * A {@link DecomposedPardinusSolver} takes as input a relational problem and * produces a satisfying model or an {@link Instance instance} of it, if one * exists. The current process solves each of the second stage problems in * parallel, and support a hybrid mode that keeps an amalgamated problem running * in background. * </p> * * @author Eduardo Pessoa, Nuno Macedo // [HASLab] decomposed model finding * */ public class DecomposedPardinusSolver<S extends AbstractSolver<PardinusBounds, ExtendedOptions>> implements DecomposedSolver<ExtendedOptions>, IterableSolver<PardinusBounds, ExtendedOptions> { /** the regular Kodkod solver used in the parallelization */ final private ExtendedSolver solver1; final private S solver2; /** a manager for the decomposed solving process */ private DProblemExecutor<S> executor; /** the decomposed problem options */ final private ExtendedOptions options; public DecomposedPardinusSolver(ExtendedOptions options, S solver) { this.options = options; this.solver1 = new ExtendedSolver(options.configOptions()); this.solver2 = solver; } /** * Solves a decomposed model finding problem, comprised by a pair of * {@link kodkod.ast.Formula formulas} and a pair of * {@link kodkod.instance.Bounds bounds}. Essentially launches an * {@link kodkod.engine.decomp.DProblemExecutor executor} to handle the * decomposed problem in parallel, given the defined * {@link kodkod.pardinus.decomp.DOptions options}. * @param f1 * the partial problem formula. * @param f2 * the remainder problem formula. * @param b1 * the partial problem bounds. * @param b2 * the remainder problem bounds. * * @requires f1 to be defined over b1 and f2 over b2. * @return a decomposed solution. * @throws InterruptedException * if the solving process is interrupted. */ @Override public Solution solve(Formula formula, PardinusBounds bounds) { if (!options.configOptions().solver().incremental()) throw new IllegalArgumentException("An incremental solver is required to iterate the configurations."); if (options.decomposedMode() == DMode.EXHAUSTIVE) executor = new StatsExecutor<S>(formula, bounds, solver1, solver2, options.threads(), options.reporter()); else executor = new DProblemExecutorImpl<S>(options.reporter(), formula, bounds, solver1, solver2, options.threads(), options.decomposedMode() == DMode.HYBRID); executor.start(); Solution sol = null; try { sol = executor.next(); executor.terminate(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sol; } /** * Retrieves the decomposed problem executor that handled the decomposed problem. * * @return the decomposed problem executor that solved the problem. */ public DProblemExecutor<S> executor() { return executor; } /** * Releases the resources, if any. */ public void free() {} @Override public ExtendedOptions options() { return options; } @Override public Iterator<Solution> solveAll(Formula formula, PardinusBounds bounds) { if (!options.configOptions().solver().incremental()) throw new IllegalArgumentException("cannot enumerate solutions without an incremental solver."); return new DSolutionIterator<S>(formula, bounds, options, solver1, solver2); } private static class DSolutionIterator<S extends AbstractSolver<PardinusBounds, ExtendedOptions>> implements Iterator<Solution> { private DProblemExecutor<S> executor; /** * Constructs a solution iterator for the given formula, bounds, and options. */ DSolutionIterator(Formula formula, PardinusBounds bounds, DecomposedOptions options, ExtendedSolver solver1, S solver2) { if (options.decomposedMode() == DMode.EXHAUSTIVE) executor = new StatsExecutor<S>(formula, bounds, solver1, solver2, options.threads(), options.reporter()); else if (options.decomposedMode() == DMode.HYBRID) executor = new DProblemExecutorImpl<S>(options.reporter(), formula, bounds, solver1, solver2, options.threads(), true); else executor = new DProblemExecutorImpl<S>(options.reporter(), formula, bounds, solver1, solver2, options.threads(), false); executor.start(); } /** * Returns true if there is another solution. * @see java.util.Iterator#hasNext() */ public boolean hasNext() { try { return executor.hasNext(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } /** * Returns the next solution if any. * @see java.util.Iterator#next() */ public Solution next() { if (!hasNext()) return null; try { return executor.next(); } catch (InterruptedException e) { try { executor.terminate(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Should throw AbortedException e.printStackTrace(); } return null; } /** @throws UnsupportedOperationException */ public void remove() { throw new UnsupportedOperationException(); } } // TODO: delete temp files // if (!Options.isDebug()) { // File[] contents = dir.listFiles(); // if (contents != null) // for (File f : contents) // f.delete(); // dir.delete(); }
package me.newyith.fortress.core; import me.newyith.fortress.util.Debug; import me.newyith.fortress.util.Point; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.Chest; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.HashSet; import java.util.Set; public class CoreMaterials { private static class Model { private final Point chestPoint; private final String worldName; private final transient World world; private final transient Set<Material> generatableWallMaterials; private final transient Set<Material> protectableWallMaterials; private final transient Set<Material> alterableWallMaterials; private final transient Set<String> flags; @JsonCreator public Model(@JsonProperty("chestPoint") Point chestPoint, @JsonProperty("worldName") String worldName) { this.chestPoint = chestPoint; this.worldName = worldName; //rebuild transient fields this.world = Bukkit.getWorld(worldName); this.generatableWallMaterials = new HashSet<>(); this.protectableWallMaterials = new HashSet<>(); this.alterableWallMaterials = new HashSet<>(); this.flags = new HashSet<>(); } } private Model model = null; @JsonCreator public CoreMaterials(@JsonProperty("model") Model model) { this.model = model; refresh(); } public CoreMaterials(World world, Point chestPoint) { model = new Model(chestPoint, world.getName()); refresh(); } // - Getters - public Set<Material> getGeneratableWallMaterials() { return model.generatableWallMaterials; } public boolean isProtectable(Block b) { return model.protectableWallMaterials.contains(b.getType()); } public boolean isAlterable(Block b) { return model.alterableWallMaterials.contains(b.getType()); } public boolean isProtectable(Material m) { if (m != null) { return model.protectableWallMaterials.contains(m); } return false; } public boolean isAlterable(Material m) { if (m != null) { return model.alterableWallMaterials.contains(m); } return false; } public Set<Material> getInvalidWallMaterials() { return refresh(); } public boolean getFastAnimationFlag() { refresh(); //needed in case items in chest have changed (such as when items are added by hopper) return model.flags.contains("fastAnimation"); } // - Refreshing - public Set<Material> refresh() { //Debug.msg("CoreMaterials refresh()ed. chest: " + chestPoint); resetToDefaultBlockTypesAndFlags(); Set<Material> invalidWallMaterials = new HashSet<>(); ItemStack[] items = getChestContents(); for (ItemStack item : items) { if (item != null) { Material mat = item.getType(); switch (mat) { //non protectable //*/ /*/ //*/
package me.newyith.fortress.core; import javafx.util.Pair; import me.newyith.fortress.main.FortressPlugin; import me.newyith.fortress.main.FortressesManager; import me.newyith.fortress.rune.generator.GeneratorRune; import me.newyith.fortress.util.Blocks; import me.newyith.fortress.util.Debug; import me.newyith.fortress.util.Point; import me.newyith.fortress.util.particle.ParticleEffect; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.codehaus.jackson.annotate.JsonCreator; import org.codehaus.jackson.annotate.JsonProperty; import java.util.*; import java.util.concurrent.CompletableFuture; public class GeneratorCore extends BaseCore { private static class Model extends BaseCore.Model { private String datum = null; //placeholder since GeneratorCore doesn't need its own data (at least not yet) private final transient Random random = new Random(); //showRipple() needs model.random to be final @JsonCreator public Model(@JsonProperty("anchorPoint") Point anchorPoint, @JsonProperty("claimedPoints") Set<Point> claimedPoints, @JsonProperty("claimedWallPoints") Set<Point> claimedWallPoints, @JsonProperty("animator") CoreAnimator animator, @JsonProperty("placedByPlayerId") UUID placedByPlayerId, @JsonProperty("layerOutsideFortress") Set<Point> layerOutsideFortress, @JsonProperty("pointsInsideFortress") Set<Point> pointsInsideFortress, @JsonProperty("worldName") String worldName, @JsonProperty("datum") String datum) { super(anchorPoint, claimedPoints, claimedWallPoints, animator, placedByPlayerId, layerOutsideFortress, pointsInsideFortress, worldName); this.datum = datum; //rebuild transient fields //this.random = new Random(); //this.random is final so can't init here } //should this be JsonCreator instead? if not, delete this comment public Model(BaseCore.Model model, String datum) { super(model); this.datum = datum; } } private Model model = null; @JsonCreator public GeneratorCore(@JsonProperty("model") Model model) { super(model); this.model = model; } public GeneratorCore(World world, Point anchorPoint, CoreMaterials coreMats) { super(world, anchorPoint, coreMats); //sets super.model String datum = "myDatum"; model = new Model(super.model, datum); } protected Set<Point> getFallbackWhitelistSignPoints() { Set<Point> fallbackSigns = new HashSet<>(); GeneratorRune rune = FortressesManager.getRune(model.world, model.anchorPoint); if (rune != null) { Set<Point> potentialSigns = getLayerAround(rune.getPattern().getPoints(), Blocks.ConnectedThreshold.FACES).join(); //fill fallbackSigns (from potentialSigns) for (Point potentialSign : potentialSigns) { Material mat = potentialSign.getBlock(model.world).getType(); if (Blocks.isSign(mat)) { fallbackSigns.add(potentialSign); } } if (!fallbackSigns.isEmpty()) { //fallbackSigns.addAll(connected signs) Point origin = model.anchorPoint; Set<Point> originLayer = fallbackSigns; Set<Material> traverseMaterials = Blocks.getSignMaterials(); Set<Material> returnMaterials = Blocks.getSignMaterials(); int rangeLimit = model.generationRangeLimit * 2; Set<Point> ignorePoints = null; Set<Point> searchablePoints = null; Set<Point> connectedSigns = Blocks.getPointsConnected(model.world, origin, originLayer, traverseMaterials, returnMaterials, rangeLimit, ignorePoints, searchablePoints).join(); fallbackSigns.addAll(connectedSigns); } } return fallbackSigns; } public void onPlayerRightClickWall(Player player, Block block, BlockFace face) { Material materialInHand = player.getItemInHand().getType(); if (materialInHand == Material.AIR) { Point origin = new Point(block); Point towardFace = origin.add(face.getModX(), face.getModY(), face.getModZ()); //particleEffect = heart/flame/smoke (inside/outside/disabled) boolean originGenerated = getGeneratedPoints().contains(origin); ParticleEffect particleEffect = ParticleEffect.SMOKE_NORMAL; if (originGenerated) { boolean inside = getPointsInsideFortress().contains(towardFace); if (inside) particleEffect = ParticleEffect.HEART; else particleEffect = ParticleEffect.FLAME; } //display particleEffect Pair<Point, Point> wallOutside = new Pair<>(origin, towardFace); model.coreParticles.showParticleForWallOutsidePair(model.world, wallOutside, particleEffect, 3); //show bedrock ripple if (originGenerated) { showRipple(origin); } } } private void showRipple(Point origin) { //get rippleLayers int layerLimit = 20; Set<Point> searchablePoints = getGeneratedPoints(); CompletableFuture<List<Set<Point>>> future = Blocks.getPointsConnectedAsLayers(model.world, origin, layerLimit - 1, searchablePoints); future.join(); //wait for future to resolve List<Set<Point>> rippleLayersFromFuture = future.getNow(null); if (rippleLayersFromFuture != null) { Set<Point> originLayer = new HashSet<>(); originLayer.add(origin); List<Set<Point>> rippleLayers = new ArrayList<>(); rippleLayers.add(originLayer); rippleLayers.addAll(rippleLayersFromFuture); //remove some blocks from last 4 rippleLayers to create a fizzle out effect for (int i = 0; i < 4; i++) { int index = (layerLimit-1) - i; if (index < rippleLayers.size()) { Set<Point> rippleLayer = rippleLayers.get(index); if (rippleLayer != null) { Iterator<Point> it = rippleLayer.iterator(); while (it.hasNext()) { it.next(); int percentSkipChance = 0; if (i == 0) percentSkipChance = 50; else if (i == 1) percentSkipChance = 40; else if (i == 2) percentSkipChance = 30; else if (i == 3) percentSkipChance = 20; if (model.random.nextInt(99) < percentSkipChance) { it.remove(); } } } } } int layerIndex = 0; for (Set<Point> layer : rippleLayers) { int min = 2000; int max = 2000; int layersRemaining = rippleLayers.size() - layerIndex; if (layersRemaining < 4) { min = 450 * layersRemaining; max = Math.min(2000, min + 500); } final int msMin = min; final int msMax = max; Bukkit.getScheduler().scheduleSyncDelayedTask(FortressPlugin.getInstance(), () -> { for (Point p : layer) { int ms = msMin; if (msMin < msMax) { //model.random must be final if (model.random != null) { ms += model.random.nextInt(msMax - msMin); } else { //this can happen if model.random is not final ms = msMin; Debug.warn("GeneratorCore::showRipple() model.random == null"); } } TimedBedrockManager.convert(model.world, p, ms); } }, layerIndex * 3); //20 ticks per second layerIndex++; } } } //*/
package mil.dds.anet.resources; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.annotation.Timed; import graphql.ExceptionWhileDataFetching; import graphql.ExecutionInput; import graphql.ExecutionResult; import graphql.GraphQL; import graphql.GraphQLError; import graphql.schema.GraphQLSchema; import graphql.schema.visibility.NoIntrospectionGraphqlFieldVisibility; import io.dropwizard.auth.Auth; import io.leangen.graphql.GraphQLSchemaGenerator; import io.leangen.graphql.annotations.GraphQLInputField; import io.leangen.graphql.generator.mapping.common.ScalarMapper; import io.leangen.graphql.metadata.strategy.DefaultInclusionStrategy; import io.leangen.graphql.metadata.strategy.InputFieldInclusionParams; import io.leangen.graphql.metadata.strategy.query.AnnotatedResolverBuilder; import java.lang.invoke.MethodHandles; import java.lang.reflect.AnnotatedElement; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.function.Function; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import mil.dds.anet.AnetObjectEngine; import mil.dds.anet.beans.Person; import mil.dds.anet.config.AnetConfiguration; import mil.dds.anet.graphql.DateTimeMapper; import mil.dds.anet.graphql.outputtransformers.JsonToXlsxTransformer; import mil.dds.anet.graphql.outputtransformers.JsonToXmlTransformer; import mil.dds.anet.graphql.outputtransformers.XsltXmlTransformer; import mil.dds.anet.utils.AuthUtils; import mil.dds.anet.utils.BatchingUtils; import org.apache.commons.lang3.StringUtils; import org.dataloader.DataLoaderRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Path("/graphql") public class GraphQlResource { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final String MEDIATYPE_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; private final AnetObjectEngine engine; private final List<Object> resources; private final MetricRegistry metricRegistry; private GraphQLSchema graphqlSchema; private GraphQLSchema graphqlSchemaWithoutIntrospection; private final List<ResourceTransformer> resourceTransformers = new LinkedList<ResourceTransformer>(); abstract static class ResourceTransformer implements Function<Map<String, Object>, ResponseBuilder> { public final String outputType; public final String mediaType; public ResourceTransformer(String outputType, String mediaType) { this.outputType = outputType; this.mediaType = mediaType; } } private static final ResourceTransformer jsonTransformer = new ResourceTransformer("json", MediaType.APPLICATION_JSON) { @Override public ResponseBuilder apply(Map<String, Object> json) { return Response.ok(json, this.mediaType); } }; public GraphQlResource(AnetObjectEngine engine, AnetConfiguration config, List<Object> resources, MetricRegistry metricRegistry) { this.engine = engine; this.resources = resources; this.metricRegistry = metricRegistry; resourceTransformers.add(GraphQlResource.jsonTransformer); resourceTransformers.add(new ResourceTransformer("xml", MediaType.APPLICATION_XML) { final JsonToXmlTransformer jsonToXmlTransformer = new JsonToXmlTransformer(); @Override public ResponseBuilder apply(final Map<String, Object> json) { return Response.ok(jsonToXmlTransformer.apply(json), this.mediaType); } }); resourceTransformers.add(new ResourceTransformer("xlsx", MEDIATYPE_XLSX) { final JsonToXlsxTransformer xlsxTransformer = new JsonToXlsxTransformer(config); @Override public ResponseBuilder apply(final Map<String, Object> json) { return Response.ok(xlsxTransformer.apply(json), this.mediaType) .header("Content-Disposition", "attachment; filename=" + "anet_export.xslx"); } }); resourceTransformers.add(new ResourceTransformer("nvg", MediaType.APPLICATION_XML) { final JsonToXmlTransformer jsonToXmlTransformer = new JsonToXmlTransformer(); final XsltXmlTransformer xsltXmlTransformer = new XsltXmlTransformer( GraphQlResource.class.getResourceAsStream("/stylesheets/nvg.xslt")); @Override public ResponseBuilder apply(final Map<String, Object> json) { return Response.ok(xsltXmlTransformer.apply(jsonToXmlTransformer.apply(json)), this.mediaType); } }); resourceTransformers.add(new ResourceTransformer("kml", MediaType.APPLICATION_XML) { final JsonToXmlTransformer jsonToXmlTransformer = new JsonToXmlTransformer(); final XsltXmlTransformer xsltXmlTransformer = new XsltXmlTransformer( GraphQlResource.class.getResourceAsStream("/stylesheets/kml.xslt")); @Override public ResponseBuilder apply(final Map<String, Object> json) { return Response.ok(xsltXmlTransformer.apply(jsonToXmlTransformer.apply(json)), this.mediaType); } }); buildGraph(); } /** * Constructs the GraphQL "Graph" of ANET. 1) Scans all Resources to find methods it can use as * graph entry points. These should all be annotated with @GraphQLFetcher 2) For each of the types * that the Resource can return, scans those to find methods annotated with GraphQLFetcher */ private void buildGraph() { final String topPackage = "mil.dds.anet"; final GraphQLSchemaGenerator schemaGenerator = new GraphQLSchemaGenerator() // Load only our own packages: .withBasePackages(topPackage) // Resolve queries by @GraphQLQuery annotations only: .withNestedResolverBuilders(new AnnotatedResolverBuilder()) // Resolve inputs by @GraphQLInputField annotations only: .withInclusionStrategy(new DefaultInclusionStrategy(topPackage) { @Override public boolean includeInputField(InputFieldInclusionParams params) { return super.includeInputField(params) && params.getElements().stream().anyMatch(this::isAnnotated); } protected boolean isAnnotated(AnnotatedElement element) { return element.isAnnotationPresent(GraphQLInputField.class); } }) // Load our DateTimeMapper: .withTypeMappers( (config, defaults) -> defaults.insertBefore(ScalarMapper.class, new DateTimeMapper())); for (final Object resource : resources) { schemaGenerator.withOperationsFromSingleton(resource); } graphqlSchema = schemaGenerator.generate(); graphqlSchemaWithoutIntrospection = GraphQLSchema.newSchema(graphqlSchema) .codeRegistry(graphqlSchema.getCodeRegistry() .transform(builder -> builder.fieldVisibility( NoIntrospectionGraphqlFieldVisibility.NO_INTROSPECTION_FIELD_VISIBILITY))) .build(); } @POST @Timed @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MEDIATYPE_XLSX}) public Response graphqlPost(@Auth Person user, Map<String, Object> body) { final String operationName = (String) body.get("operationName"); final String query = (String) body.get("query"); @SuppressWarnings("unchecked") Map<String, Object> variables = (Map<String, Object>) body.get("variables"); if (variables == null) { variables = new HashMap<String, Object>(); } final String output = (String) body.get("output"); // Non-GraphQL return graphql(user, operationName, query, variables, output); } @GET @Timed @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MEDIATYPE_XLSX}) public Response graphqlGet(@Auth Person user, @QueryParam("operationName") String operationName, @QueryParam("query") String query, @QueryParam("output") String output) { return graphql(user, operationName, query, new HashMap<String, Object>(), output); } protected Response graphql(@Auth Person user, String operationName, String query, Map<String, Object> variables, String output) { final ExecutionResult executionResult = dispatchRequest(user, operationName, query, variables); final Map<String, Object> result = executionResult.toSpecification(); if (executionResult.getErrors().size() > 0) { WebApplicationException actual = null; for (GraphQLError error : executionResult.getErrors()) { if (error instanceof ExceptionWhileDataFetching) { ExceptionWhileDataFetching exception = (ExceptionWhileDataFetching) error; if (exception.getException() instanceof WebApplicationException) { actual = (WebApplicationException) exception.getException(); break; } } } Status status = (actual != null) ? Status.fromStatusCode(actual.getResponse().getStatus()) : Status.INTERNAL_SERVER_ERROR; logger.warn("Errors: {}", executionResult.getErrors()); return Response.status(status).entity(result).build(); } ResourceTransformer transformer = StringUtils.isEmpty(output) ? GraphQlResource.jsonTransformer : resourceTransformers.stream().filter(t -> t.outputType.equals(output)).findFirst().get(); return transformer.apply(result).build(); } private ExecutionResult dispatchRequest(Person user, String operationName, String query, Map<String, Object> variables) { final BatchingUtils batchingUtils = new BatchingUtils(engine, true, true); final DataLoaderRegistry dataLoaderRegistry = batchingUtils.getDataLoaderRegistry(); final Map<String, Object> context = new HashMap<>(); context.put("user", user); context.put("dataLoaderRegistry", dataLoaderRegistry); final ExecutionInput executionInput = ExecutionInput.newExecutionInput().operationName(operationName).query(query) .variables(variables).dataLoaderRegistry(dataLoaderRegistry).context(context).build(); final GraphQL graphql = GraphQL .newGraphQL(AuthUtils.isAdmin(user) ? graphqlSchema : graphqlSchemaWithoutIntrospection) // Prevent adding .instrumentation(new DataLoaderDispatcherInstrumentation()) .doNotAddDefaultInstrumentations().build(); final CompletableFuture<ExecutionResult> request = graphql.executeAsync(executionInput); final Runnable dispatcher = () -> { while (!request.isDone()) { // Wait a while, giving other threads the chance to do some work try { Thread.yield(); Thread.sleep(50); } catch (InterruptedException ignored) { // just retry } // Dispatch all our data loaders until the request is done; // we have data loaders at various depths (one dependent on another), // e.g. in {@link Report#loadWorkflow} final CompletableFuture<?>[] dispatchersWithWork = dataLoaderRegistry.getDataLoaders() .stream().filter(dl -> dl.dispatchDepth() > 0) .map(dl -> (CompletableFuture<?>) dl.dispatch()).toArray(CompletableFuture<?>[]::new); if (dispatchersWithWork.length > 0) { CompletableFuture.allOf(dispatchersWithWork).join(); } } }; dispatcher.run(); try { return request.get(); } catch (InterruptedException | ExecutionException e) { throw new WebApplicationException("failed to complete graphql request", e); } finally { batchingUtils.updateStats(metricRegistry, dataLoaderRegistry); batchingUtils.shutdown(); } } }
package io.rong; import io.rong.models.ChatroomInfo; import io.rong.models.FormatType; import io.rong.models.GroupInfo; import io.rong.models.Message; import io.rong.models.SdkHttpResult; import io.rong.util.HttpUtil; import java.net.HttpURLConnection; import java.net.URLEncoder; import java.util.List; public class ApiHttpClient { private static final String RONGCLOUDURI = "http://api.cn.ronghub.com"; private static final String UTF8 = "UTF-8"; // token public static SdkHttpResult getToken(String appKey, String appSecret, String userId, String userName, String portraitUri, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil .CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/user/getToken." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("userId=").append(URLEncoder.encode(userId, UTF8)); sb.append("&name=").append(URLEncoder.encode(userName, UTF8)); sb.append("&portraitUri=").append(URLEncoder.encode(portraitUri, UTF8)); HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult checkOnline(String appKey, String appSecret, String userId, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/user/checkOnline." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("userId=").append(URLEncoder.encode(userId, UTF8)); HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult refreshUser(String appKey, String appSecret, String userId, String userName, String portraitUri, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/user/refresh." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("userId=").append(URLEncoder.encode(userId, UTF8)); sb.append("&name=").append(URLEncoder.encode(userName, UTF8)); sb.append("&portraitUri=").append(URLEncoder.encode(portraitUri, UTF8)); HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult blockUser(String appKey, String appSecret, String userId, int minute, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/user/block." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("userId=").append(URLEncoder.encode(userId, UTF8)); sb.append("&minute=").append( URLEncoder.encode(String.valueOf(minute), UTF8)); HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult unblockUser(String appKey, String appSecret, String userId, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/user/unblock." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("userId=").append(URLEncoder.encode(userId, UTF8)); HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult queryBlockUsers(String appKey, String appSecret, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/user/block/query." + format.toString()); return HttpUtil.returnResult(conn); } public static SdkHttpResult blackUser(String appKey, String appSecret, String userId, List<String> blackUserIds, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/user/blacklist/add." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("userId=").append(URLEncoder.encode(userId, UTF8)); if (blackUserIds != null) { for (String blackId : blackUserIds) { sb.append("&blackUserId=").append( URLEncoder.encode(blackId, UTF8)); } } HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult unblackUser(String appKey, String appSecret, String userId, List<String> blackUserIds, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/user/blacklist/remove." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("userId=").append(URLEncoder.encode(userId, UTF8)); if (blackUserIds != null) { for (String blackId : blackUserIds) { sb.append("&blackUserId=").append( URLEncoder.encode(blackId, UTF8)); } } HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult QueryblackUser(String appKey, String appSecret, String userId, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/user/blacklist/query." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("userId=").append(URLEncoder.encode(userId, UTF8)); HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult createGroup(String appKey, String appSecret, List<String> userIds, String groupId, String groupName, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/group/create." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("groupId=").append(URLEncoder.encode(groupId, UTF8)); sb.append("&groupName=").append(URLEncoder.encode(groupName, UTF8)); if (userIds != null) { for (String id : userIds) { sb.append("&userId=").append(URLEncoder.encode(id, UTF8)); } } HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult joinGroup(String appKey, String appSecret, String userId, String groupId, String groupName, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/group/join." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("userId=").append(URLEncoder.encode(userId, UTF8)); sb.append("&groupId=").append(URLEncoder.encode(groupId, UTF8)); sb.append("&groupName=").append(URLEncoder.encode(groupName, UTF8)); HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult joinGroupBatch(String appKey, String appSecret, List<String> userIds, String groupId, String groupName, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/group/join." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("groupId=").append(URLEncoder.encode(groupId, UTF8)); sb.append("&groupName=").append(URLEncoder.encode(groupName, UTF8)); if (userIds != null) { for (String id : userIds) { sb.append("&userId=").append(URLEncoder.encode(id, UTF8)); } } HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult quitGroup(String appKey, String appSecret, String userId, String groupId, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/group/quit." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("userId=").append(URLEncoder.encode(userId, UTF8)); sb.append("&groupId=").append(URLEncoder.encode(groupId, UTF8)); HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult quitGroupBatch(String appKey, String appSecret, List<String> userIds, String groupId, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/group/quit." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("groupId=").append(URLEncoder.encode(groupId, UTF8)); if (userIds != null) { for (String id : userIds) { sb.append("&userId=").append(URLEncoder.encode(id, UTF8)); } } HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult dismissGroup(String appKey, String appSecret, String userId, String groupId, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil .CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/group/dismiss." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("userId=").append(URLEncoder.encode(userId, UTF8)); sb.append("&groupId=").append(URLEncoder.encode(groupId, UTF8)); HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult syncGroup(String appKey, String appSecret, String userId, List<GroupInfo> groups, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/group/sync." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("userId=").append(URLEncoder.encode(userId, UTF8)); if (groups != null) { for (GroupInfo info : groups) { if (info != null) { sb.append( String.format("&group[%s]=", URLEncoder.encode(info.getId(), UTF8))) .append(URLEncoder.encode(info.getName(), UTF8)); } } } HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult refreshGroupInfo(String appKey, String appSecret, String groupId, String groupName, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil .CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/group/refresh." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("groupId=").append(URLEncoder.encode(groupId, UTF8)); sb.append("&groupName=").append(URLEncoder.encode(groupName, UTF8)); HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult refreshGroupInfo(String appKey, String appSecret, GroupInfo group, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil .CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/group/refresh." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("groupId=").append(URLEncoder.encode(group.getId(), UTF8)); sb.append("&groupName=").append( URLEncoder.encode(group.getName(), UTF8)); HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult publishMessage(String appKey, String appSecret, String fromUserId, List<String> toUserIds, Message msg, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/message/private/publish." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8)); if (toUserIds != null) { for (int i = 0; i < toUserIds.size(); i++) { sb.append("&toUserId=").append( URLEncoder.encode(toUserIds.get(i), UTF8)); } } sb.append("&objectName=") .append(URLEncoder.encode(msg.getType(), UTF8)); sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8)); HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult publishMessage(String appKey, String appSecret, String fromUserId, List<String> toUserIds, Message msg, String pushContent, String pushData, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/message/publish." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8)); if (toUserIds != null) { for (int i = 0; i < toUserIds.size(); i++) { sb.append("&toUserId=").append( URLEncoder.encode(toUserIds.get(i), UTF8)); } } sb.append("&objectName=") .append(URLEncoder.encode(msg.getType(), UTF8)); sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8)); if (pushContent != null) { sb.append("&pushContent=").append( URLEncoder.encode(pushContent, UTF8)); } if (pushData != null) { sb.append("&pushData=").append(URLEncoder.encode(pushData, UTF8)); } HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult publishSystemMessage(String appKey, String appSecret, String fromUserId, List<String> toUserIds, Message msg, String pushContent, String pushData, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/message/system/publish." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8)); if (toUserIds != null) { for (int i = 0; i < toUserIds.size(); i++) { sb.append("&toUserId=").append( URLEncoder.encode(toUserIds.get(i), UTF8)); } } sb.append("&objectName=") .append(URLEncoder.encode(msg.getType(), UTF8)); sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8)); if (pushContent != null) { sb.append("&pushContent=").append( URLEncoder.encode(pushContent, UTF8)); } if (pushData != null) { sb.append("&pushData=").append(URLEncoder.encode(pushData, UTF8)); } HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult publishGroupMessage(String appKey, String appSecret, String fromUserId, List<String> toGroupIds, Message msg, String pushContent, String pushData, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/message/group/publish." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8)); if (toGroupIds != null) { for (int i = 0; i < toGroupIds.size(); i++) { sb.append("&toGroupId=").append( URLEncoder.encode(toGroupIds.get(i), UTF8)); } } sb.append("&objectName=") .append(URLEncoder.encode(msg.getType(), UTF8)); sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8)); if (pushContent != null) { sb.append("&pushContent=").append( URLEncoder.encode(pushContent, UTF8)); } if (pushData != null) { sb.append("&pushData=").append(URLEncoder.encode(pushData, UTF8)); } HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult publishChatroomMessage(String appKey, String appSecret, String fromUserId, List<String> toChatroomIds, Message msg, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil .CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/message/chatroom/publish." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8)); if (toChatroomIds != null) { for (int i = 0; i < toChatroomIds.size(); i++) { sb.append("&toChatroomId=").append( URLEncoder.encode(toChatroomIds.get(i), UTF8)); } } sb.append("&objectName=") .append(URLEncoder.encode(msg.getType(), UTF8)); sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8)); HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult broadcastMessage(String appKey, String appSecret, String fromUserId, Message msg,String pushContent, String pushData, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/message/broadcast." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("fromUserId=").append(URLEncoder.encode(fromUserId, UTF8)); sb.append("&objectName=") .append(URLEncoder.encode(msg.getType(), UTF8)); sb.append("&content=").append(URLEncoder.encode(msg.toString(), UTF8)); if (pushContent != null) { sb.append("&pushContent=").append( URLEncoder.encode(pushContent, UTF8)); } if (pushData != null) { sb.append("&pushData=").append(URLEncoder.encode(pushData, UTF8)); } HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult createChatroom(String appKey, String appSecret, List<ChatroomInfo> chatrooms, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/chatroom/create." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("1=1"); if (chatrooms != null) { for (ChatroomInfo info : chatrooms) { if (info != null) { sb.append( String.format("&chatroom[%s]=", URLEncoder.encode(info.getId(), UTF8))) .append(URLEncoder.encode(info.getName(), UTF8)); } } } HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult destroyChatroom(String appKey, String appSecret, List<String> chatroomIds, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/chatroom/destroy." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("1=1"); if (chatroomIds != null) { for (String id : chatroomIds) { sb.append("&chatroomId=").append(URLEncoder.encode(id, UTF8)); } } HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult queryChatroom(String appKey, String appSecret, List<String> chatroomIds, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/chatroom/query." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("1=1"); if (chatroomIds != null) { for (String id : chatroomIds) { sb.append("&chatroomId=").append(URLEncoder.encode(id, UTF8)); } } HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult getMessageHistoryUrl(String appKey, String appSecret, String date, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/message/history." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("date=").append(URLEncoder.encode(date, UTF8)); HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } public static SdkHttpResult deleteMessageHistory(String appKey, String appSecret, String date, FormatType format) throws Exception { HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI + "/message/history/delete." + format.toString()); StringBuilder sb = new StringBuilder(); sb.append("date=").append(URLEncoder.encode(date, UTF8)); HttpUtil.setBodyParameter(sb, conn); return HttpUtil.returnResult(conn); } }
package net.gpedro.integrations.slack; import com.google.gson.JsonObject; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class SlackApi { private String service; public SlackApi(String service) { if (service == null) { throw new IllegalArgumentException( "Missing WebHook URL Configuration @ SlackApi"); } else if (!service.startsWith("https://hooks.slack.com/services/")) { throw new IllegalArgumentException( "Invalid Service URL. WebHook URL Format: https://hooks.slack.com/services/{id_1}/{id_2}/{token}"); } this.service = service; } /** * Prepare Message and send to Slack */ public void call(SlackMessage message) { if (message != null) { this.send(message.prepare()); } } private String send(JsonObject message) { URL url; HttpURLConnection connection = null; try { // Create connection url = new URL(this.service); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setConnectTimeout(5000); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); String payload = "payload=" + URLEncoder.encode(message.toString(), "UTF-8"); // Send request DataOutputStream wr = new DataOutputStream( connection.getOutputStream()); wr.writeBytes(payload); wr.flush(); wr.close(); // Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); return response.toString(); } catch (Exception e) { throw new RuntimeException(e); } finally { if (connection != null) { connection.disconnect(); } } } }
package net.mingsoft.cms.action.web; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.alibaba.fastjson.JSONArray; import net.mingsoft.base.constant.Const; import net.mingsoft.basic.util.SpringUtil; import net.mingsoft.basic.util.StringUtil; import net.mingsoft.cms.bean.ContentBean; import net.mingsoft.cms.biz.ICategoryBiz; import net.mingsoft.cms.biz.IContentBiz; import net.mingsoft.cms.entity.CategoryEntity; import net.mingsoft.cms.entity.ContentEntity; import net.mingsoft.mdiy.biz.IContentModelBiz; import net.mingsoft.mdiy.biz.IModelBiz; import net.mingsoft.mdiy.entity.ContentModelEntity; import net.mingsoft.mdiy.entity.ModelEntity; import net.mingsoft.mdiy.parser.TagParser; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.PageUtil; import freemarker.core.ParseException; import freemarker.template.MalformedTemplateNameException; import freemarker.template.TemplateNotFoundException; import net.mingsoft.basic.entity.ColumnEntity; import net.mingsoft.basic.util.BasicUtil; import net.mingsoft.cms.util.CmsParserUtil; import net.mingsoft.mdiy.bean.PageBean; import net.mingsoft.mdiy.biz.IPageBiz; import net.mingsoft.mdiy.entity.PageEntity; import net.mingsoft.mdiy.util.ParserUtil; /** * * * @author * @date 20181217 */ @Controller("dynamicPageAction") @RequestMapping("/mcms") public class MCmsAction extends net.mingsoft.cms.action.BaseAction { @Autowired private IPageBiz pageBiz; @Autowired private IContentBiz contentBiz; @Autowired private ICategoryBiz categoryBiz; public static final String SEARCH = "search"; @Autowired private IModelBiz modelBiz; // :/mall/{key}.do /** * {diy}.do, * * @param key */ @RequestMapping("/{diy}.do") @ExceptionHandler(java.lang.NullPointerException.class) public void diy(@PathVariable(value = "diy") String diy, HttpServletRequest req, HttpServletResponse resp) { Map map = BasicUtil.assemblyRequestMap(); map.put(ParserUtil.URL, BasicUtil.getUrl()); map.put(ParserUtil.IS_DO,true); map.put(ParserUtil.MODEL_NAME, "mcms"); String content = ""; PageEntity page = new PageEntity(); page.setPageKey(diy); PageEntity _page = (PageEntity) pageBiz.getEntity(page); try { content = CmsParserUtil.generate(_page.getPagePath(), map, isMobileDevice(req)); } catch (TemplateNotFoundException e) { e.printStackTrace(); } catch (MalformedTemplateNameException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } this.outString(resp, content); } @GetMapping("/index.do") public void index(HttpServletRequest req, HttpServletResponse resp) { Map map = BasicUtil.assemblyRequestMap(); map.put(ParserUtil.URL, BasicUtil.getUrl()); map.put(ParserUtil.IS_DO,true); map.put(ParserUtil.MODEL_NAME, "mcms"); String content = ""; try { content = CmsParserUtil.generate(ParserUtil.INDEX+ParserUtil.HTM_SUFFIX, map, isMobileDevice(req)); } catch (TemplateNotFoundException e) { e.printStackTrace(); } catch (MalformedTemplateNameException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } this.outString(resp, content); } /** * * @param req * @param resp */ @GetMapping("/list.do") public void list(HttpServletRequest req, HttpServletResponse resp) { Map map = BasicUtil.assemblyRequestMap(); int typeId = BasicUtil.getInt(ParserUtil.TYPE_ID,0); int size = BasicUtil.getInt(ParserUtil.SIZE,10); List<ContentBean> columnArticles = contentBiz.queryIdsByCategoryIdForParser(String.valueOf(typeId), null, null); if(columnArticles.size()==0){ this.outJson(resp, false); } PageBean page = new PageBean(); int total = PageUtil.totalPage(columnArticles.size(), size); map.put(ParserUtil.COLUMN, columnArticles.get(0)); page.setTotal(total); map.put(ParserUtil.TYPE_ID, typeId); map.put(ParserUtil.PAGE_NO, BasicUtil.getInt(ParserUtil.PAGE_NO,1)); map.put(ParserUtil.URL, BasicUtil.getUrl()); map.put(ParserUtil.PAGE, page); map.put(ParserUtil.IS_DO,true); map.put(ParserUtil.MODEL_NAME, "mcms"); String content = ""; try { content = CmsParserUtil.generate(columnArticles.get(0).getCategoryListUrl(),map, isMobileDevice(req)); } catch (TemplateNotFoundException e) { e.printStackTrace(); } catch (MalformedTemplateNameException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } this.outString(resp, content); } /** * * @param id */ @GetMapping("/view.do") public void view(String orderby,String order,HttpServletRequest req, HttpServletResponse resp) { ContentEntity article = (ContentEntity) contentBiz.getEntity(BasicUtil.getInt(ParserUtil.ID)); if(ObjectUtil.isNull(article)){ this.outJson(resp, null,false,getResString("err.empty", this.getResString("id"))); return; } if(StringUtils.isNotBlank(order)){ if(!order.toLowerCase().equals("asc")&&!order.toLowerCase().equals("desc")){ this.outJson(resp, null,false,getResString("err.error", this.getResString("order"))); return; } } PageBean page = new PageBean(); CategoryEntity column = (CategoryEntity) categoryBiz.getEntity(Integer.parseInt(article.getContentCategoryId())); String content = ""; Map map = BasicUtil.assemblyRequestMap(); map.put(ParserUtil.IS_DO,true); map.put(ParserUtil.MODEL_NAME, "mcms"); map.put(ParserUtil.URL, BasicUtil.getUrl()); map.put(ParserUtil.PAGE, page); map.put(ParserUtil.ID, article.getId()); List<ContentBean> articleIdList = contentBiz.queryIdsByCategoryIdForParser(column.getCategoryId(), null, null,orderby,order); Map<Object, Object> contentModelMap = new HashMap<Object, Object>(); ContentModelEntity contentModel = null; for (int artId = 0; artId < articleIdList.size();) { if(articleIdList.get(artId).getArticleId() != Integer.parseInt(article.getId())){ artId++; continue; } String articleColumnPath = articleIdList.get(artId).getCategoryPath(); String columnContentModelId = articleIdList.get(artId).getMdiyModelId(); Map<String, Object> parserParams = new HashMap<String, Object>(); parserParams.put(ParserUtil.COLUMN, articleIdList.get(artId)); if ( StringUtils.isNotBlank(columnContentModelId)) { if (contentModelMap.containsKey(columnContentModelId)) { parserParams.put(ParserUtil.TABLE_NAME, contentModel.getCmTableName()); } else { contentModel = (ContentModelEntity) SpringUtil.getBean(IContentModelBiz.class) .getEntity(Integer.parseInt(columnContentModelId)); // key contentModelMap.put(columnContentModelId, contentModel.getCmTableName()); parserParams.put(ParserUtil.TABLE_NAME, contentModel.getCmTableName()); } } if (artId > 0) { ContentBean preCaBean = articleIdList.get(artId - 1); if(articleColumnPath.contains(preCaBean.getCategoryId()+"")){ page.setPreId(preCaBean.getArticleId()); } } if (artId + 1 < articleIdList.size()) { ContentBean nextCaBean = articleIdList.get(artId + 1); if(articleColumnPath.contains(nextCaBean.getCategoryId()+"")){ page.setNextId(nextCaBean.getArticleId()); } } break; } try { content = CmsParserUtil.generate(column.getCategoryUrl(), map, isMobileDevice(req)); } catch (TemplateNotFoundException e) { e.printStackTrace(); } catch (MalformedTemplateNameException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } this.outString(resp, content); } // /** // * // * // * @param request // * id // * @param response // */ // @RequestMapping(value = "search") // @ResponseBody // public void search(HttpServletRequest request, HttpServletResponse response) { // Map<String, Object> map = new HashMap<>(); // Map<String, String[]> field = request.getParameterMap(); // Map<String, String> basicField = getMapByProperties(net.mingsoft.mdiy.constant.Const.BASIC_FIELD); // Map<String, Object> articleFieldName = new HashMap<String, Object>(); // Map<String, String> diyFieldName = new HashMap<String, String>(); // CategoryEntity column = null; // // ModelEntity contentModel = null; // // List<DiyModelMap> fieldValueList = new ArrayList<DiyModelMap>(); // // int typeId = 0; // String categoryIds = BasicUtil.getString("categoryId"); // if(!StringUtil.isBlank(categoryIds) && !categoryIds.contains(",")){ // typeId = Integer.parseInt(categoryIds); // List filedStr = new ArrayList<>(); // if(typeId>0){ // column = (CategoryEntity) categoryBiz.getEntity(Integer.parseInt(typeId+"")); // if (column != null&&ObjectUtil.isNotNull(column.getMdiyModelId())) { // contentModel = (ModelEntity) modelBiz.getEntity(Integer.parseInt(column.getMdiyModelId())); // if (contentModel != null) { // Map<String,String> fieldMap = contentModel.getFieldMap(); // for (String s : fieldMap.keySet()) { // filedStr.add(fieldMap.get(s)); // map.put(ParserUtil.TABLE_NAME, contentModel.getModelTableName()); // map.put(ParserUtil.COLUMN, column); //// map.put(ParserUtil.TYPE_ID, typeId); // if (field != null) { // for (Map.Entry<String, String[]> entry : field.entrySet()) { // if (entry != null) { // String value = entry.getValue()[0]; // get // if (ObjectUtil.isNull(value)) { // continue; // if (request.getMethod().equals(RequestMethod.GET)) { // get // try { // value = new String(value.getBytes("ISO-8859-1"), Const.UTF8); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // if (ObjectUtil.isNotNull(basicField.get(entry.getKey())) && ObjectUtil.isNotNull(value)) { // articleFieldName.put(entry.getKey(), value); // } else { // if (!StringUtil.isBlank(value)) { // diyFieldName.put(entry.getKey(), value); // if(filedStr.contains(entry.getKey())){ // DiyModelMap diyMap = new DiyModelMap(); // diyMap.setKey(entry.getKey()); // diyMap.setValue(value); // fieldValueList.add(diyMap); // if(fieldValueList.size()>0){ // map.put("diyModel", fieldValueList); // //where // Map whereMap = ObjectUtil.isNotNull(contentModel)? // this.searchMap(articleFieldName, diyFieldName, JSONArray.parseArray(contentModel.getModelField())): // new HashMap(); // int count = contentBiz.getSearchCount(contentModel, whereMap, BasicUtil.getAppId(), categoryIds); // PageBean page = new PageBean(); // int size = BasicUtil.getInt(ParserUtil.SIZE,10); // try { // size = TagParser.getPageSize(ParserUtil.read(SEARCH+ParserUtil.HTM_SUFFIX,false )); // } catch (TemplateNotFoundException e1) { // e1.printStackTrace(); // } catch (MalformedTemplateNameException e1) { // e1.printStackTrace(); // } catch (ParseException e1) { // e1.printStackTrace(); // } catch (IOException e1) { // e1.printStackTrace(); // int total = PageUtil.totalPage(count, size); // int pageNo = BasicUtil.getInt(ParserUtil.PAGE_NO, 1); // if(pageNo >= total && total!=0) { // pageNo = total; // page.setTotal(total); // page.setSize(size); // page.setPageNo(pageNo); // String str = ParserUtil.PAGE_NO+","+ParserUtil.SIZE; // String url = BasicUtil.getUrl()+request.getServletPath() +"?" + BasicUtil.assemblyRequestUrlParams(str.split(",")); // String pageNoStr = "&"+ParserUtil.SIZE+"="+size+"&"+ParserUtil.PAGE_NO+"="; // String nextUrl = url + pageNoStr+((pageNo+1 > total)?total:pageNo+1); // String indexUrl = url + pageNoStr + 1; // String lastUrl = url + pageNoStr + total; // String preUrl = url + pageNoStr + ((pageNo==1) ? 1:pageNo-1); // page.setIndexUrl(indexUrl); // page.setNextUrl(nextUrl); // page.setPreUrl(preUrl); // page.setLastUrl(lastUrl); // map.put(ParserUtil.URL, BasicUtil.getUrl()); // Map<String, Object> searchMap = BasicUtil.assemblyRequestMap(); // searchMap.put(ParserUtil.PAGE_NO, pageNo); // map.put(SEARCH, searchMap); // map.put(ParserUtil.PAGE, page); // map.put(ParserUtil.IS_DO,false); // map.put(ParserUtil.MODEL_NAME, "mcms"); // String content = ""; // try { // content = CmsParserUtil.generate(SEARCH+ParserUtil.HTM_SUFFIX,map, isMobileDevice(request)); // } catch (TemplateNotFoundException e) { // e.printStackTrace(); // } catch (MalformedTemplateNameException e) { // e.printStackTrace(); // } catch (ParseException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // this.outString(response, content); /** * where Map key: value:List list[0]: * list[1]: list[2]: list[3]: * * @param articleField * * @param diyFieldName * * @param fields * * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) private Map<String, List> searchMap(Map<String, Object> articleField, Map<String, String> diyFieldName, List fields) { Map<String, List> map = new HashMap<String, List>(); for (Iterator iter = articleField.keySet().iterator(); iter.hasNext();) { String key = iter.next().toString(); String fieldValue = articleField.get(key).toString(); List list = new ArrayList(); List listValue = new ArrayList(); list.add(false); // true: list.add(true); list.add(true); listValue.add(articleField.get(key)); list.add(listValue); map.put(key, list); } for (Iterator iter = diyFieldName.keySet().iterator(); iter.hasNext();) { String key = iter.next().toString(); String fieldValue = diyFieldName.get(key); Map field = get(key, fields); if (field != null) { List list = new ArrayList(); list.add(0, true); List listValue = new ArrayList(); if ("int".equals(field.get("javaType") ) || "float".equals(field.get("javaType") )|| "Double".equals(field.get("javaType")) ) { if (diyFieldName.get(key).toString().indexOf("-") > 0) { String[] values = fieldValue.toString().split("-"); // false: list.add(false); // false: list.add(false); listValue.add(values[0]); listValue.add(values[1]); } else { // false:2 list.add(false); // true:3 list.add(true); listValue.add(fieldValue); } } else { // true:2 list.add(true); list.add(false); listValue.add(fieldValue); } list.add(listValue); map.put(key, list); } } return map; } private Map get(String key, List<Map> fields) { for (Map field : fields) { if(key.equals(field.get("key"))){ return field; } } return null; } /** * * @author * @date 201935 */ public class DiyModelMap { String key; Object value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } } }