answer
stringlengths
17
10.2M
package eu.modernmt.processing.tags.cli; import eu.modernmt.io.*; import eu.modernmt.model.*; import eu.modernmt.processing.tags.projection.TagProjector; import org.apache.commons.io.IOUtils; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.regex.Matcher; public class XMLProjectorTestMain { private static final TagProjector projector = new TagProjector(); public static void main(String[] args) throws Throwable { if (args.length != 3) throw new IllegalArgumentException("USAGE: source_file target_file alignment_file"); File source = new File(args[0]); File target = new File(args[1]); File alignment = new File(args[2]); UnixLineWriter output = new UnixLineWriter(System.out, UTF8Charset.get()); ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); ArrayList<Future<Translation>> translations = new ArrayList<>(); try (TranslationProvider provider = new TranslationProvider(source, target, alignment)) { Translation translation; while ((translation = provider.next()) != null) { final Translation t = translation; Future<Translation> future = executor.submit(() -> projector.project(t)); translations.add(future); } for (Future<Translation> future : translations) { String serialized = serialize(future.get()); output.writeLine(serialized); } } finally { executor.shutdownNow(); } output.flush(); } private static String serialize(Sentence sentence) { StringBuilder result = new StringBuilder(); boolean first = true; for (Token token : sentence) { if (!first) result.append(' '); first = false; result.append(token.getPlaceholder()); } return result.toString(); } private static class TranslationProvider implements Closeable { private final LineReader sources; private final LineReader targets; private final LineReader alignments; public TranslationProvider(File source, File target, File alignment) throws FileNotFoundException { boolean success = false; try { this.sources = new UnixLineReader(new FileInputStream(source), UTF8Charset.get()); this.targets = new UnixLineReader(new FileInputStream(target), UTF8Charset.get()); this.alignments = new UnixLineReader(new FileInputStream(alignment), UTF8Charset.get()); success = true; } finally { if (!success) close(); } } public Translation next() throws IOException { String sourceLine = this.sources.readLine(); String targetLine = this.targets.readLine(); String alignmentLine = this.alignments.readLine(); if (sourceLine == null && targetLine == null && alignmentLine == null) return null; if (sourceLine == null || targetLine == null || alignmentLine == null) throw new IOException("files not parallel"); Sentence sentence = parseSentence(sourceLine); Word[] targetWords = TokensOutputStream.deserializeWords(targetLine); Alignment alignment = parseAlignment(alignmentLine); return new Translation(targetWords, sentence, alignment); } public static Sentence parseSentence(String string) { ArrayList<Word> words = new ArrayList<>(); ArrayList<Tag> tags = new ArrayList<>(); Matcher m = XMLTag.TagRegex.matcher(string); int last = 0; while (m.find()) { int start = m.start(); int end = m.end(); Tag tag = XMLTag.fromText(string.substring(start, end)); if (start > last) { words.addAll(Arrays.asList( TokensOutputStream.deserializeWords(string.substring(last, start).trim()) )); } tag.setPosition(words.size()); tags.add(tag); last = end; } if (last < string.length() - 1) { words.addAll(Arrays.asList( TokensOutputStream.deserializeWords(string.substring(last)) )); } return new Sentence(words.toArray(new Word[0]), tags.toArray(new Tag[0])); } public static Alignment parseAlignment(String string) { string = string.trim(); if (string.isEmpty()) return new Alignment(new int[0], new int[0]); String[] parts = string.split("\\s+"); int[] sourceIndexes = new int[parts.length]; int[] targetIndexes = new int[parts.length]; for (int i = 0; i < parts.length; ++i) { String[] st = parts[i].split("-", 2); sourceIndexes[i] = Integer.parseInt(st[0]); targetIndexes[i] = Integer.parseInt(st[1]); } return new Alignment(sourceIndexes, targetIndexes); } @Override public void close() { IOUtils.closeQuietly(sources); IOUtils.closeQuietly(targets); IOUtils.closeQuietly(alignments); } } }
package com.db.net.soap; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import org.w3c.dom.Element; import com.db.logging.Logger; import com.db.logging.LoggerManager; import com.db.net.http.HttpBodyPartHeader; import com.db.net.http.HttpHeader; import com.db.net.http.HttpWebConnection; import com.db.net.wsdl.Wsdl; import com.db.net.wsdl.WsdlMessage; import com.db.net.wsdl.WsdlMessagePart; import com.db.net.wsdl.WsdlPortType; import com.db.net.wsdl.WsdlPortTypeOperation; import com.db.xml.AbstractXmlSerializer; import com.db.xml.ElementReader; import com.db.xml.XmlCoder; /** * This class represents a SOAP message. * * FUTURE CODE: We want to split some of the functionality for this * message up into separate classes (i.e. request/result/fault). The * fault implementation is also incomplete, lacking code to handle * a fault detail if one exists. * * @author Dave Longley */ public class SoapMessage extends AbstractXmlSerializer { /** * The xml schema for a soap message (the xsd). */ public static final String XSD_NAMESPACE = "http: /** * The xml schema instance for a soap message. */ public static final String XSI_NAMESPACE = "http: /** * The soap namespace. */ public static final String SOAP_NAMESPACE = "http://schemas.xmlsoap.org/wsdl/soap/"; /** * The encoding schema. */ public static final String ENCODING_SCHEMA = "http://schemas.xmlsoap.org/soap/encoding/"; /** * The envelope schema. */ public static final String ENVELOPE_SCHEMA = "http://schemas.xmlsoap.org/soap/envelope/"; /** * The WSDL for the web service. */ protected Wsdl mWsdl; /** * The port type for the web service. */ protected WsdlPortType mPortType; /** * The port type operation for the method. */ protected WsdlPortTypeOperation mPortTypeOperation; /** * The name of the method to execute. */ protected String mMethod; /** * The parameters for the method to execute. */ protected Object[] mParams; /** * The results of the executed method. */ protected Object[] mResults; /** * The address of the client for this soap message. */ protected String mClientIP; /** * The fault code for this soap message, if any. A fault code * can be any of the following: * * VersionMismatch.* * MustUnderstand.* * Client.* * Server.* */ protected String mFaultCode; /** * The fault string for this soap message, if any. This is a human * readable string that provides a short explanation for the fault. */ protected String mFaultString; /** * The fault actor for this soap message, if any. The fault actor specifies * who caused the fault to happen within the soap message path. The fault * actor is a URI identifying the source of the fault. */ protected String mFaultActor; /** * An http web connection for reading or writing attachments. */ protected HttpWebConnection mAttachmentWebConnection; /** * The http header for this soap message, if any. */ protected HttpHeader mHttpHeader; /** * A soap fault: when a version mismatch occurs. */ protected final static String FAULT_VERSION_MISMATCH = "VersionMismatch"; /** * A soap fault: when something must be understood but is not. */ protected final static String FAULT_MUST_UNDERSTAND = "MustUnderstand"; /** * A soap fault: when a soap client faults. */ protected final static String FAULT_CLIENT = "Client"; /** * A soap fault: when a soap server faults. */ protected final static String FAULT_SERVER = "Server"; /** * XML serializer options. */ protected int mXmlOptions; /** * An XML serializer option for converting to/from a soap request. */ protected final static int SOAP_REQUEST = 1; /** * An XML serializer option for converting to/from a soap response. */ protected final static int SOAP_RESPONSE = 2; /** * An XML serializer option for converting to/from a soap fault. */ protected final static int SOAP_FAULT = 4; /** * Creates a new soap message. * * @param wsdl the wsdl for the web service this soap message will be used * with. * @param portType the name of the port type to use. */ public SoapMessage(Wsdl wsdl, String portType) { // store the wsdl and port type mWsdl = wsdl; mPortType = mWsdl.getPortTypes().getPortType(portType); mPortTypeOperation = null; if(mPortType == null) { throw new IllegalArgumentException( "Port Type not valid for given Wsdl!"); } // default to a soap request setXmlSerializerOptions(SOAP_REQUEST); // set default client IP address mClientIP = "0.0.0.0"; // set default fault string and actor to blank setFaultString(""); setFaultActor(""); } protected void findPortTypeOperation(String method) throws IllegalArgumentException { // get the port type operation mPortTypeOperation = mPortType.getOperations().getOperation(method); if(mPortTypeOperation == null) { throw new IllegalArgumentException( "Method is not valid for the given Wsdl Port Type!"); } } /** * Gets the WsdlMessage for a SOAP request. * * @return the WsdlMessage for a SOAP request. */ protected WsdlMessage getRequestMessage() { WsdlMessage rval = null; // get the message name String messageName = ""; if(getPortTypeOperation().usesOnlyInputMessage()) { messageName = getPortTypeOperation().getInputMessageName(); } else if(getPortTypeOperation().usesOnlyOutputMessage()) { messageName = getPortTypeOperation().getOutputMessageName(); } else { if(getPortTypeOperation().isInputFirst()) { messageName = getPortTypeOperation().getInputMessageName(); } else { messageName = getPortTypeOperation().getOutputMessageName(); } } // get the wsdl message rval = mWsdl.getMessages().getMessage(messageName); return rval; } /** * Gets the WsdlMessage for a SOAP response. * * @return the WsdlMessage for a SOAP response. */ protected WsdlMessage getResponseMessage() { WsdlMessage rval = null; // get the message name String messageName = ""; if(getPortTypeOperation().usesOnlyInputMessage()) { messageName = getPortTypeOperation().getInputMessageName(); } else if(getPortTypeOperation().usesOnlyOutputMessage()) { messageName = getPortTypeOperation().getOutputMessageName(); } else { if(getPortTypeOperation().isInputFirst()) { messageName = getPortTypeOperation().getOutputMessageName(); } else { messageName = getPortTypeOperation().getInputMessageName(); } } // get the wsdl message rval = mWsdl.getMessages().getMessage(messageName); return rval; } /** * Converts a soap fault from an XML element reader pointing to the * soap message body. * * @param reader the element reader. */ protected void convertSoapFaultFromXml(ElementReader reader) { // get fault code, fault string, and fault actor ElementReader r = null; r = reader.getFirstElementReader("faultcode"); if(r != null) { String[] split = r.getStringValue().split(":"); if(split.length > 1) { setFaultCode(split[1]); } } r = reader.getFirstElementReader("faultstring"); if(r != null) { setFaultString(r.getStringValue()); } r = reader.getFirstElementReader("faultactor"); if(r != null) { setFaultActor(r.getStringValue()); } } /** * Converts a soap request from an XML element reader pointing to the * soap message body. * * @param reader the element reader. */ protected void convertSoapRequestFromXml(ElementReader reader) { // get the request message WsdlMessage message = getRequestMessage(); // build a parameters array Object[] params = new Object[message.getParts().size()]; if(params.length > 0) { // iterate through the parts of the message int count = 0; for(Iterator i = reader.getElementReaders().iterator(); i.hasNext(); count++) { ElementReader partReader = (ElementReader)i.next(); // get the appropriate message part WsdlMessagePart part = message.getParts().getPart( partReader.getTagName()); // get the parameter value String value = partReader.getStringValue(); getLogger().debug(getClass(), "soap method parameter found."); getLogger().debugData(getClass(), "soap method parameter found" + ",name=" + part.getName() + ",value=" + value + ",type=" + part.getType()); // parse the object params[count] = Wsdl.parseObject(value, part.getType()); } getLogger().debug(getClass(), "number of soap method parameters read: " + count); } // set the parameters setParameters(params); } /** * Converts a soap response from an XML element reader pointing to the * soap message body. * * @param reader the element reader. */ protected void convertSoapResponseFromXml(ElementReader reader) { // get the response message WsdlMessage message = getResponseMessage(); // build a results array Object[] results = new Object[message.getParts().size()]; if(results.length > 0) { // iterate through the parts of the message int count = 0; for(Iterator i = reader.getElementReaders().iterator(); i.hasNext(); count++) { ElementReader partReader = (ElementReader)i.next(); // get the appropriate message part WsdlMessagePart part = message.getParts().getPart( partReader.getTagName()); // get the parameter value String value = partReader.getStringValue(); getLogger().debug(getClass(), "soap method result found."); getLogger().debugData(getClass(), "soap method result found" + ",name=" + part.getName() + ",value=" + value + ",type=" + part.getType()); // parse the object results[count] = Wsdl.parseObject(value, part.getType()); } getLogger().debug(getClass(), "number of soap method results read: " + count); } // set the results setResults(results); } /** * Gets the current port type operation. * * @return the current port type operation. */ protected WsdlPortTypeOperation getPortTypeOperation() { return mPortTypeOperation; } /** * Gets the WSDL for this soap message. * * @return the WSDL for this soap message. */ public Wsdl getWsdl() { return mWsdl; } /** * Gets the port type for this soap message. * * @return the port type for this soap message. */ public WsdlPortType getPortType() { return mPortType; } /** * Sets the method for this soap message. * * @param method the method. */ public void setMethod(String method) { // try to find the operation for the given method findPortTypeOperation(method); // store method mMethod = method; } /** * Gets the method. * * @return the method. */ public String getMethod() { return mMethod; } /** * Sets the parameters for the method. * * @param params the parameters for the method. */ public void setParameters(Object[] params) { mParams = params; if(mParams == null) { mParams = new Object[0]; } } /** * Gets the parameters for the method. * * @return the parameters for the method. */ public Object[] getParameters() { if(mParams == null) { mParams = new Object[0]; } return mParams; } /** * Sets the results. * * @param results the results. */ public void setResults(Object[] results) { mResults = results; if(mResults == null) { mResults = new Object[0]; } } /** * Gets the results. * * @return the results. */ public Object[] getResults() { if(mResults == null) { mResults = new Object[0]; } return mResults; } /** * Sets the fault code. Whenever a fault code is set, the serializer * type will be set to SOAP_FAULT. The only acceptable strings are: * * VersionMismatch.* * MustUnderstand.* * Client.* * Server.* * * @param faultCode the fault code. */ public void setFaultCode(String faultCode) { // FUTURE CODE: this code needs to actually check qualified names, etc // for now, it sets only the most generic types and cuts off sub types if(faultCode.startsWith("VersionMismatch")) { setXmlSerializerOptions(SOAP_FAULT); mFaultCode = FAULT_VERSION_MISMATCH; } else if(faultCode.startsWith("MustUnderstand")) { setXmlSerializerOptions(SOAP_FAULT); mFaultCode = FAULT_MUST_UNDERSTAND; } else if(faultCode.startsWith("Client")) { setXmlSerializerOptions(SOAP_FAULT); mFaultCode = FAULT_CLIENT; } else if(faultCode.startsWith("Server")) { setXmlSerializerOptions(SOAP_FAULT); mFaultCode = FAULT_SERVER; } } /** * Gets the fault code. * * @return the fault code or null if none is set. */ public String getFaultCode() { return mFaultCode; } /** * Sets the fault string. This is a human readable string that provides a * short explanation for the fault. * * @param faultString the fault string. */ public void setFaultString(String faultString) { mFaultString = faultString; } /** * Gets the fault string. This is a human readable string that provides a * short explanation for the fault. * * @return the fault string. */ public String getFaultString() { return mFaultString; } /** * Sets the fault actor. The fault actor specifies who caused the * fault to happen within the soap message path. The fault actor is * a URI identifying the source of the fault (i.e. the destination of * the soap message). It need not always be present unless the application * raising the fault is not the destination. * * @param faultActor the fault actor (the URI for the source of the fault). */ public void setFaultActor(String faultActor) { mFaultActor = faultActor; } /** * Gets the fault actor. The fault actor specifies who caused the * fault to happen within the soap message path. The fault actor is * a URI identifying the source of the fault (i.e. the destination of * the soap message). It need not always be present unless the application * raising the fault is not the destination. * * @return the fault actor (the URI for the source of the fault). */ public String getFaultActor() { return mFaultActor; } /** * Sets the client IP. * * @param clientIP the client's IP. */ public void setClientIP(String clientIP) { mClientIP = clientIP; } /** * Gets the client IP. * * @return the client IP. */ public String getClientIP() { return mClientIP; } /** * Sets the http header for this soap message. * * @param header the http header for this soap message. */ public void setHttpHeader(HttpHeader header) { mHttpHeader = header; } /** * Gets the http header for this soap message. * * @return the http header for this soap message. */ public HttpHeader getHttpHeader() { return mHttpHeader; } /** * Sets the http web connection to read or write soap attachments with. * * @param hwc the http web connection to read or write soap attachments with. */ public void setAttachmentWebConnection(HttpWebConnection hwc) { mAttachmentWebConnection = hwc; } /** * Gets the http web connection to read or write soap attachments with. * * @return the http web connection to read or write soap attachments with. */ public HttpWebConnection getAttachmentWebConnection() { return mAttachmentWebConnection; } /** * Sends an attachment for this soap message. * * @param header the http body part header for the attachment. * @param is the input stream to read the attachment from. * @param lastAttachment true if this is the last attachment, false if not. * * @return true if the attachment was written, false if not. */ public boolean sendAttachment( HttpBodyPartHeader header, InputStream is, boolean lastAttachment) { boolean rval = false; // get attachment connection HttpWebConnection hwc = getAttachmentWebConnection(); if(hwc != null) { // send the header if(hwc.sendHeader(header)) { // send the body rval = hwc.sendBodyPartBody(is, getHttpHeader(), header, lastAttachment); } } return rval; } /** * Receives an attachment for this soap message if there is one * to be received. * * @param header the http body part header for the attachment. * @param os the output stream to write the attachment to. * * @return true if an attachment was received, false if not. */ public boolean receiveAttachment(HttpBodyPartHeader header, OutputStream os) { boolean rval = false; // get attachment connection HttpWebConnection hwc = getAttachmentWebConnection(); if(hwc != null && hasMoreAttachments()) { // receive the header if(hwc.receiveHeader(header)) { // receive the body rval = hwc.receiveBodyPartBody(os, getHttpHeader(), header); } } return rval; } /** * Returns true if there are more attachments to be received, false if not. * * @return true if there are more attachments to be received, false if not. */ public boolean hasMoreAttachments() { boolean rval = false; // get attachment connection HttpWebConnection hwc = getAttachmentWebConnection(); if(hwc != null) { String endBoundary = getHttpHeader().getEndBoundary(); // see if there is a last read boundary or if the last read // boundary is not the end boundary if(hwc.getLastReadBoundary() == null || !hwc.getLastReadBoundary().equals(endBoundary)) { rval = true; } } return rval; } /** * Returns true if this soap message is a soap request. * * @return true if this soap message is a soap request, false if not. */ public boolean isRequest() { return (getXmlSerializerOptions() == SOAP_REQUEST); } /** * Returns true if this soap message is a soap response. * * @return true if this soap message is a soap response, false if not. */ public boolean isResponse() { return (getXmlSerializerOptions() == SOAP_RESPONSE); } /** * Returns true if this soap message is a soap fault. * * @return true if this soap message is a soap fault, false if not. */ public boolean isFault() { return (getXmlSerializerOptions() == SOAP_FAULT); } /** * This method takes options that are used to configure * how to convert to and from xml. * * @param options the configuration options. * * @return true if options successfully set, false if not. */ public boolean setXmlSerializerOptions(int options) { boolean rval = false; if(options == SOAP_REQUEST || options == SOAP_RESPONSE || options == SOAP_FAULT) { mXmlOptions = options; rval = true; } return rval; } /** * This method gets the options that are used to configure * how to convert to and from xml. * * @return the configuration options. */ public int getXmlSerializerOptions() { return mXmlOptions; } /** * Returns the root tag name for this serializer. * * @return the root tag name for this serializer. */ public String getRootTag() { // this is according to the set schema (env) return "Envelope"; } /** * This method takes the object representation and creates an * XML-based representation of the object. * * @param indentLevel the number of spaces to place before the text * after each new line. * * @return the xml-based representation of the object. */ public String convertToXml(int indentLevel) { // FUTURE CODE: the current implementation makes some assumptions about // soap encoding and so forth -- the same ones made by the Wsdl class StringBuffer xml = new StringBuffer(); if(indentLevel == 0) { xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); } xml.append("<soap:Envelope xmlns:soap=\"" + ENVELOPE_SCHEMA + "\" "); xml.append("xmlns:xsd=\"" + XSD_NAMESPACE + "\" "); xml.append("xmlns:xsi=\"" + XSI_NAMESPACE + "\" "); xml.append("xmlns:enc=\"" + ENCODING_SCHEMA + "\" "); xml.append("xmlns:tns=\"" + getWsdl().getTargetNamespace() + "\" "); xml.append("soap:encodingStyle=\"" + ENCODING_SCHEMA +"\">"); // add the envelope's body xml.append("<soap:Body>"); if(isRequest()) { // get the request message WsdlMessage message = getRequestMessage(); xml.append("<tns:" + getPortTypeOperation().getName() + ">"); // convert the parameters int count = 0; for(Iterator i = message.getParts().iterator(); i.hasNext(); count++) { WsdlMessagePart part = (WsdlMessagePart)i.next(); xml.append("<" + part.getName() + ">"); xml.append(XmlCoder.encode("" + getParameters()[count])); xml.append("</" + part.getName() + ">"); } xml.append("</tns:" + getPortTypeOperation().getName() + ">"); } else if(isResponse()) { // get the response message WsdlMessage message = getResponseMessage(); xml.append("<tns:" + message.getName() + ">"); // convert the results int count = 0; for(Iterator i = message.getParts().iterator(); i.hasNext(); count++) { WsdlMessagePart part = (WsdlMessagePart)i.next(); xml.append("<" + part.getName() + ">"); xml.append(XmlCoder.encode("" + getResults()[count])); xml.append("</" + part.getName() + ">"); } xml.append("</tns:" + message.getName() + ">"); } else if(isFault()) { // convert the fault xml.append("<soap:Fault>"); xml.append("<faultcode>soap:" + XmlCoder.encode(getFaultCode()) + "</faultcode>"); xml.append("<faultstring>" + XmlCoder.encode(getFaultString()) + "</faultstring>"); xml.append("<faultactor>" + XmlCoder.encode(getFaultActor()) + "</faultactor>"); xml.append("</soap:Fault>"); } xml.append("</soap:Body>"); xml.append("</soap:Envelope>"); return xml.toString(); } /** * This method takes a parsed DOM XML element and converts it * back into this object's representation. * * @param element the parsed element that contains this objects information. * * @return true if successful, false otherwise. */ public boolean convertFromXml(Element element) { boolean rval = false; // FUTURE CODE: the current implementation makes some assumptions about // soap encoding and so forth -- the same ones made by the Wsdl class ElementReader er = new ElementReader(element); // iterate through the envelope elements Iterator ei = er.getElementReadersNS(ENVELOPE_SCHEMA).iterator(); while(ei.hasNext()) { getLogger().detail(getClass(), "found soap envelope elements..."); // get the envelope prefix String envPrefix = er.getPrefix(ENVELOPE_SCHEMA, false); getLogger().detail(getClass(), "soap envelope prefix=" + envPrefix); ElementReader envelopeER = (ElementReader)ei.next(); if(envelopeER.getTagName().equals(envPrefix + ":Body")) { getLogger().detail(getClass(), "got soap envelope body..."); // go through all of the body (method/response) elements Iterator bi = envelopeER.getElementReaders().iterator(); while(bi.hasNext() && !rval) { ElementReader bodyReader = (ElementReader)bi.next(); String name[] = bodyReader.getTagName().split(":"); if(name.length > 1) { // see if this is a soap fault if(name[1].equals("Fault")) { // convert soap fault convertSoapFaultFromXml(bodyReader); } else { getLogger().debug(getClass(), "got soap envelope method/response," + "method/response=" + name[1]); // get the incoming message if(isRequest()) { // set the method setMethod(name[1]); // convert soap request convertSoapRequestFromXml(bodyReader); } else if(isResponse()) { // convert soap response convertSoapResponseFromXml(bodyReader); } } rval = true; } } } } return rval; } /** * Gets the logger. * * @return the logger. */ public Logger getLogger() { return LoggerManager.getLogger("dbnet"); } }
package naftoreiclag.villagefive.util; import com.jme3.math.Vector3f; import com.jme3.scene.Mesh; import com.jme3.scene.VertexBuffer.Type; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.List; import org.lwjgl.BufferUtils; public class ModelBuilder { private int appendX = 0; private int appendY = 0; private int appendZ = 0; public void setAppendOrigin(int x, int y, int z) { this.appendX = x; this.appendY = y; this.appendZ = z; } public void resetAppendOrigin() { this.appendX = 0; this.appendY = 0; this.appendZ = 0; } private boolean combineNormals = true; // Where the data is stored to be baked private List<Vertex> vertices = new ArrayList<Vertex>(); private List<Triangle> triangles = new ArrayList<Triangle>(); // Add a triangle with respects to the user-set origin public void addTriangle(Vertex a, Vertex b, Vertex c) { if(appendX == 0 && appendY == 0 && appendZ == 0) { addTriangleNoAppend(a, b, c); } else { addTriangleNoAppend(a.clone(appendX, appendY, appendZ), b.clone(appendX, appendY, appendZ), c.clone(appendX, appendY, appendZ)); } } // Add a triangle without appending anything private void addTriangleNoAppend(Vertex a, Vertex b, Vertex c) { // Find appropriate indices for these, re-using old ones if possible int ai = -1; int bi = -1; int ci = -1; for(int index = 0; index < vertices.size(); ++ index) { Vertex compare = vertices.get(index); if(combineNormals) { if(compare.samePos(a)) { System.out.println("smooth"); Vector3f combined = compare.normal.add(a.normal).normalizeLocal(); compare.normal = combined; a.normal = combined; } if(compare.samePos(b)) { Vector3f combined = compare.normal.add(b.normal).normalizeLocal(); compare.normal = combined; b.normal = combined; } if(compare.samePos(c)) { Vector3f combined = compare.normal.add(c.normal).normalizeLocal(); compare.normal = combined; c.normal = combined; } } if(compare.same(a)) { ai = index; } if(compare.same(b)) { bi = index; } if(compare.same(c)) { ci = index; } if(ai != -1 && bi != -1 && ci != -1) { break; } } if(ai == -1) { ai = vertices.size(); vertices.add(a); } if(bi == -1) { bi = vertices.size(); vertices.add(b); } if(ci == -1) { ci = vertices.size(); vertices.add(c); } // Add this to our triangles triangles.add(new Triangle(ai, bi, ci)); } // Add a triangle with respects to the user-set origin public void addTriangle( float x1, float y1, float z1, Vector3f normal1, float texX1, float texY1, float x2, float y2, float z2, Vector3f normal2, float texX2, float texY2, float x3, float y3, float z3, Vector3f normal3, float texX3, float texY3) { // Make vertexes from this Vertex a = new Vertex(x1 + appendX, y1 + appendY, z1 + appendZ, normal1, texX1, texY1); Vertex b = new Vertex(x2 + appendX, y2 + appendY, z2 + appendZ, normal2, texX2, texY2); Vertex c = new Vertex(x3 + appendX, y3 + appendY, z3 + appendZ, normal3, texX3, texY3); this.addTriangleNoAppend(a, b, c); } // Add a quad with respects to the user-set origin. Note: this just adds two triangles at once public void addQuad(Vertex a, Vertex b, Vertex c, Vertex d) { // 1 2 // 4 3 this.addTriangle(a, b, c); this.addTriangle(a, c, d); } // Add a quad with respects to the user-set origin. Note: this just adds two triangles at once public void addQuad( float x1, float y1, float z1, Vector3f normal1, float texX1, float texY1, float x2, float y2, float z2, Vector3f normal2, float texX2, float texY2, float x3, float y3, float z3, Vector3f normal3, float texX3, float texY3, float x4, float y4, float z4, Vector3f normal4, float texX4, float texY4) { // 1 2 // 4 3 this.addTriangle(x1, y1, z1, normal1, texX1, texY1, x2, y2, z2, normal2, texX2, texY2, x3, y3, z3, normal3, texX3, texY3); this.addTriangle(x1, y1, z1, normal1, texX1, texY1, x3, y3, z3, normal3, texX3, texY3, x4, y4, z4, normal4, texX4, texY4); } // Bakes the data into a usable model. Note: You can bake this more than once if you really want to. public Mesh bake() { return bake(1.0f); } public Mesh bake(float scale) { FloatBuffer v = BufferUtils.createFloatBuffer(vertices.size() * 3); FloatBuffer n = BufferUtils.createFloatBuffer(vertices.size() * 3); FloatBuffer t = BufferUtils.createFloatBuffer(vertices.size() * 2); for(Vertex vert : vertices) { v.put(vert.x * scale).put(vert.y * scale).put(vert.z * scale); n.put(vert.normal.x).put(vert.normal.y).put(vert.normal.z); t.put(vert.texX).put(vert.texY); } IntBuffer i = BufferUtils.createIntBuffer(triangles.size() * 3); for(Triangle tri : triangles) { // Note: I reversed the direction here to accommodate for JME. i.put(tri.a).put(tri.b).put(tri.c); } System.out.println("Model Built!"); System.out.println("Polys: " + triangles.size()); System.out.println("Vertices: " + (triangles.size() * 3)); System.out.println("Output Verts: " + vertices.size()); /* v.flip(); n.flip(); t.flip(); i.flip(); */ Mesh mesh = new Mesh(); mesh.setBuffer(Type.Position, 3, v); mesh.setBuffer(Type.Normal, 3, n); mesh.setBuffer(Type.TexCoord, 2, t); mesh.setBuffer(Type.Index, 3, i); mesh.updateBound(); return mesh; } // Class for storing a single vertex's data public static class Vertex { public float x; public float y; public float z; public Vector3f normal; public float texX; public float texY; public Vertex(float x, float y, float z, Vector3f normal, float texX, float texY) { this.x = x; this.y = y; this.z = z; this.normal = normal; this.texX = texX; this.texY = texY; } // Clone and add values to location public Vertex clone(float x, float y, float z) { return new Vertex(this.x + x, this.y + y, this.z + z, normal.clone(), texX, texY); } // If two vectors are the same private boolean compareVectors(Vector3f a, Vector3f b) { //return true; return a == b || (a.x == b.x && a.y == b.y && a.z == b.z); } // Returns if this has the same position, no regards to tex or normals public boolean samePos(Vertex other) { // In case this is literally the same object if(this == other) { return true; } // Functionally the same return other.x == this.x && other.y == this.y && other.z == this.z; } // Returns if this is exactly the same as another vertex public boolean same(Vertex other) { // In case this is literally the same object if(this == other) { return true; } // Functionally the same return other.x == this.x && other.y == this.y && other.z == this.z && compareVectors(other.normal, this.normal) && other.texX == this.texX && other.texY == this.texY; } } // Private class for storing a tuple of integers private class Triangle { private int a; private int b; private int c; public Triangle(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } }
package rest; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import tm.RotondAndesException; import tm.RotondAndesTM; import vos.Registro; @Path(URLS.REGISTRO) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class RegistroServices extends BaseServices implements CRUDRest<Registro>, URLS { @GET @Override public Response getAll() { RotondAndesTM tm = new RotondAndesTM(getPath()); List<Registro> videos; try { videos = tm.getAllResgistro(); } catch (Exception e) { return Response.status(500).entity(doErrorMessage(e)).build(); } return Response.status(200).entity(videos).build(); } @GET @Path("{" + REGISTROID + ": \\d+}") @Override public Response get(@PathParam(REGISTROID) long id) { RotondAndesTM tm = new RotondAndesTM(getPath()); try { Registro v = tm.getRegistro(id); System.out.println(v); return Response.status(200).entity(v).build(); } catch (RotondAndesException ex) { return Response.status(404).entity(doErrorMessage(ex)).build(); } catch (Exception e) { return Response.status(500).entity(doErrorMessage(e)).build(); } } @POST @Override public Response add(Registro data) { RotondAndesTM tm = new RotondAndesTM(getPath()); try { integridad(data); tm.addRegistro(data); } catch (RotondAndesException ex) { return Response.status(404).entity(doErrorMessage(ex)).build(); } catch (Exception e) { return Response.status(500).entity(doErrorMessage(e)).build(); } return Response.status(200).entity(data).build(); } @PUT @Override public Response update(Registro data) { RotondAndesTM tm = new RotondAndesTM(getPath()); try { integridad(data); tm.updateRegistro(data); } catch (RotondAndesException ex) { return Response.status(404).entity(doErrorMessage(ex)).build(); } catch (Exception e) { return Response.status(500).entity(doErrorMessage(e)).build(); } return Response.status(200).entity(data).build(); } @DELETE @Override public Response delete(Registro data) { RotondAndesTM tm = new RotondAndesTM(getPath()); try { tm.deleteRegistro(data); } catch (RotondAndesException ex) { return Response.status(404).entity(doErrorMessage(ex)).build(); } catch (Exception e) { return Response.status(500).entity(doErrorMessage(e)).build(); } return Response.status(200).entity(data).build(); } @Path("{" + REGISTROID + ": \\d+}/" + CLIENTE) public ClienteModificationServices getCliente(@PathParam(REGISTROID) Long id) { RotondAndesTM tm = new RotondAndesTM(getPath()); try { if (tm.getRegistro(id).getPermisos() != 3) throw new RotondAndesException("no tiene los permisos necesarios"); return new ClienteModificationServices(context); } catch (RotondAndesException ex) { throw new WebApplicationException(Response.status(404).entity(doErrorMessage(ex)).build()); } catch (Exception e) { throw new WebApplicationException(Response.status(500).entity(doErrorMessage(e)).build()); } } @Path("{" + REGISTROID + ": \\d+}/" + ZONA) public ZonaModificationServices getZona(@PathParam(REGISTROID) Long id) { RotondAndesTM tm = new RotondAndesTM(getPath()); try { if (tm.getRegistro(id).getPermisos() != 3) throw new RotondAndesException("no tiene los permisos necesarios"); return new ZonaModificationServices(context); } catch (RotondAndesException ex) { throw new WebApplicationException(Response.status(404).entity(doErrorMessage(ex)).build()); } catch (Exception e) { throw new WebApplicationException(Response.status(500).entity(doErrorMessage(e)).build()); } } @Path("{" + REGISTROID + ": \\d+}/" + RESTAURANTE) public RestauranteModificationServices getRestaurante(@PathParam(REGISTROID) Long id) { RotondAndesTM tm = new RotondAndesTM(getPath()); try { if (tm.getRegistro(id).getPermisos() != 3) throw new RotondAndesException("No tiene los permisos necesarios"); return new RestauranteModificationServices(context); } catch (RotondAndesException ex) { throw new WebApplicationException(Response.status(404).entity(doErrorMessage(ex)).build()); } catch (Exception e) { throw new WebApplicationException(Response.status(500).entity(doErrorMessage(e)).build()); } } @Path("{" + REGISTROID + ": \\d+}/" + RESERVA) public ReservaModificationServices getReservas(@PathParam(REGISTROID) Long id) { RotondAndesTM tm = new RotondAndesTM(getPath()); try { if (tm.getRegistro(id).getPermisos() != 3) throw new RotondAndesException("No tiene los permisos necesarios"); return new ReservaModificationServices(context); } catch (RotondAndesException ex) { throw new WebApplicationException(Response.status(404).entity(doErrorMessage(ex)).build()); } catch (Exception e) { throw new WebApplicationException(Response.status(500).entity(doErrorMessage(e)).build()); } } @Path("{" + REGISTROID + ": \\d+}/" + ESPACIO) public EspacioModificationServices getEspacio(@PathParam(REGISTROID) Long id) { RotondAndesTM tm = new RotondAndesTM(getPath()); try { if (tm.getRegistro(id).getPermisos() != 3) throw new RotondAndesException("No tiene los permisos necesarios"); return new EspacioModificationServices(context); } catch (RotondAndesException ex) { throw new WebApplicationException(Response.status(404).entity(doErrorMessage(ex)).build()); } catch (Exception e) { throw new WebApplicationException(Response.status(500).entity(doErrorMessage(e)).build()); } } @Path("{" + REGISTROID + ": \\d+}/" + REPRESENTANTE) public RepresentateModificationServices getRepresentante(@PathParam(REGISTROID) Long id) { RotondAndesTM tm = new RotondAndesTM(getPath()); try { if (tm.getRegistro(id).getPermisos() != 3) throw new RotondAndesException("No tiene los permisos necesarios"); return new RepresentateModificationServices(context); } catch (RotondAndesException ex) { throw new WebApplicationException(Response.status(404).entity(doErrorMessage(ex)).build()); } catch (Exception e) { throw new WebApplicationException(Response.status(500).entity(doErrorMessage(e)).build()); } } @Override public void integridad(Registro data) throws RotondAndesException { if (data.getCodigo() == null) throw new RotondAndesException("el codigo no puede ser null"); if (data.getUsuario() == null) throw new RotondAndesException("el usuario no puede ser null"); if (data.getContrasena() == null) throw new RotondAndesException("la contrasenia no piede ser null"); if (data.getPermisos() == null) throw new RotondAndesException("el permiso no puede se null"); if (data.getUsuario().equals("")) throw new RotondAndesException("no puede agregar un usuario vacio"); if (data.getUsuario().contains(" ")) throw new RotondAndesException("un usuario no puede tener espacios"); if (data.getUsuario().length() > 100) throw new RotondAndesException("la cadena ususrio supera el limite permitido de caracteres"); if (data.getContrasena().equals("")) throw new RotondAndesException("no puede agregar un usuario vacio"); if (data.getContrasena().length() > 100) throw new RotondAndesException("la cadena ususrio supera el limite permitido de caracteres"); if (data.getPermisos() <= 0 || data.getPermisos() > 3) throw new RotondAndesException("el permiso no es valido"); } }
package org.lunatecs316.frc2014.lib; import edu.wpi.first.wpilibj.Joystick; /** * Wrapper class for the Xbox Controller * @author domenicpaul */ public class XboxController extends Joystick { public static final Button kButtonA = new Button(1); public static final Button kButtonB = new Button(2); public static final Button kButtonX = new Button(3); public static final Button kButtonY = new Button(4); public static final Button kLeftBumper = new Button(5); public static final Button kRightBumper = new Button(6); public static class Button { private int number; public Button(int number) { this.number = number; } public int getNumber() { return number; } } private boolean[] previous = { false, false, false, false, false, false }; public XboxController(final int port) { super(port); } public double getLeftX() { return getX(); } public double getLeftY() { return getY(); } public double getRightX() { return getRawAxis(4); } public double getRightY() { return getRawAxis(5); } public boolean getButtonA() { boolean current = getRawButton(1); previous[0] = current; return current; } public boolean getButtonB() { boolean current = getRawButton(2); previous[1] = current; return current; } public boolean getButtonX() { boolean current = getRawButton(3); previous[2] = current; return current; } public boolean getButtonY() { boolean current = getRawButton(4); previous[3] = current; return current; } public boolean getLeftBumper() { boolean current = getRawButton(5); previous[4] = current; return current; } public boolean getRightBumper() { boolean current = getRawButton(6); previous[5] = current; return current; } public boolean getButton(Button button) { boolean current = getRawButton(button.getNumber()); previous[button.getNumber()-1] = current; return current; } public boolean getButtonPressed(Button button) { int number = button.getNumber(); boolean current = getRawButton(number); boolean result = current && !previous[number-1]; previous[number-1] = current; return result; } public boolean getButtonHeld(Button button) { int number = button.getNumber(); boolean current = getRawButton(number); boolean result = current && previous[number-1]; previous[number-1] = current; return result; } public boolean getButtonReleased(Button button) { int number = button.getNumber(); boolean current = getRawButton(number); boolean result = !current && previous[number-1]; previous[number-1] = current; return result; } }
package org.opencms.ui.components; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_CREATED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_EXPIRED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_MODIFIED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_DATE_RELEASED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_INSIDE_PROJECT; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_IS_FOLDER; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_NAVIGATION_TEXT; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_PERMISSIONS; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_PROJECT; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_RESOURCE_NAME; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_RESOURCE_TYPE; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_SIZE; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_STATE; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_STATE_NAME; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_TITLE; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_TYPE_ICON; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_USER_CREATED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_USER_LOCKED; import static org.opencms.ui.components.CmsResourceTableProperty.PROPERTY_USER_MODIFIED; import org.opencms.db.CmsResourceState; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.file.types.I_CmsResourceType; import org.opencms.i18n.CmsMessages; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.ui.A_CmsCustomComponent; import org.opencms.ui.A_CmsUI; import org.opencms.ui.CmsVaadinUtils; import org.opencms.util.CmsStringUtil; import org.opencms.workplace.CmsWorkplace; import org.opencms.workplace.CmsWorkplaceMessages; import org.opencms.workplace.explorer.CmsExplorerTypeSettings; import org.opencms.workplace.explorer.CmsResourceUtil; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Set; import org.apache.commons.logging.Log; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.vaadin.data.Item; import com.vaadin.data.util.IndexedContainer; import com.vaadin.event.dd.DropHandler; import com.vaadin.server.ThemeResource; import com.vaadin.ui.Image; import com.vaadin.ui.Table; import com.vaadin.ui.Table.RowHeaderMode; import com.vaadin.ui.Table.TableDragMode; /** * Generic table for displaying lists of resources.<p> */ public class CmsResourceTable extends A_CmsCustomComponent { /** * Helper class for easily configuring a set of columns to display, together with their visibility / collapsed status.<p> */ public class ColumnBuilder { /** The column entries configured so far. */ private List<ColumnEntry> m_columnEntries = Lists.newArrayList(); /** * Sets up the table and its container using the columns configured so far.<p> */ public void buildColumns() { List<CmsResourceTableProperty> visible = Lists.newArrayList(); List<CmsResourceTableProperty> collapsed = Lists.newArrayList(); for (ColumnEntry entry : m_columnEntries) { CmsResourceTableProperty prop = entry.getColumn(); m_container.addContainerProperty(prop, prop.getColumnType(), prop.getDefaultValue()); if (entry.isCollapsed()) { collapsed.add(entry.getColumn()); } if (entry.isVisible()) { visible.add(entry.getColumn()); } } m_fileTable.setVisibleColumns(visible.toArray(new Object[0])); setCollapsedColumns(collapsed.toArray(new Object[0])); for (CmsResourceTableProperty visibleProp : visible) { String headerKey = visibleProp.getHeaderKey(); if (!CmsStringUtil.isEmptyOrWhitespaceOnly(headerKey)) { m_fileTable.setColumnHeader(visibleProp, CmsVaadinUtils.getMessageText(headerKey)); } else { m_fileTable.setColumnHeader(visibleProp, ""); } m_fileTable.setColumnCollapsible(visibleProp, visibleProp.isCollapsible()); if (visibleProp.getColumnWidth() > 0) { m_fileTable.setColumnWidth(visibleProp, visibleProp.getColumnWidth()); } if (visibleProp.getExpandRatio() > 0) { m_fileTable.setColumnExpandRatio(visibleProp, visibleProp.getExpandRatio()); } } } /** * Adds a new column.<p> * * @param prop the column * * @return this object */ public ColumnBuilder column(CmsResourceTableProperty prop) { column(prop, 0); return this; } /** * Adds a new column.<p< * * @param prop the column * @param flags the flags for the column * * @return this object */ public ColumnBuilder column(CmsResourceTableProperty prop, int flags) { ColumnEntry entry = new ColumnEntry(); entry.setColumn(prop); entry.setFlags(flags); m_columnEntries.add(entry); return this; } } /** * Contains the data for the given column, along with some flags to control visibility/collapsed status.<p> * */ public static class ColumnEntry { /** The column. */ private CmsResourceTableProperty m_column; /** The flags. */ private int m_flags; /** * Returns the column.<p> * * @return the column */ public CmsResourceTableProperty getColumn() { return m_column; } /** * Returns the collapsed.<p> * * @return the collapsed */ public boolean isCollapsed() { return (m_flags & COLLAPSED) != 0; } /** * Returns the visible.<p> * * @return the visible */ public boolean isVisible() { return 0 == (m_flags & INVISIBLE); } /** * Sets the column.<p> * * @param column the column to set */ public void setColumn(CmsResourceTableProperty column) { m_column = column; } /** * Sets the flags.<p> * * @param flags the flags to set */ public void setFlags(int flags) { m_flags = flags; } } /** * Extending the indexed container to make the number of un-filtered items available.<p> */ protected static class ItemContainer extends IndexedContainer { /** The serial version id. */ private static final long serialVersionUID = -2033722658471550506L; /** * Returns the number of items in the container, not considering any filters.<p> * * @return the number of items */ protected int getItemCount() { return getAllItemIds().size(); } } /** Flag to mark columns as initially collapsed.*/ public static final int COLLAPSED = 1; /** Flag to mark columns as invisible. */ public static final int INVISIBLE = 2; /** Serial version id. */ private static final long serialVersionUID = 1L; /** The logger instance for this class. */ private static final Log LOG = CmsLog.getLog(CmsResourceTable.class); /** The resource data container. */ protected ItemContainer m_container = new ItemContainer(); /** The table used to display the resource data. */ protected Table m_fileTable = new Table(); /** * Creates a new instance.<p> * * This constructor does *not* set up the columns of the table; use the ColumnBuilder inner class for this. */ public CmsResourceTable() { m_fileTable.setContainerDataSource(m_container); setCompositionRoot(m_fileTable); m_fileTable.setRowHeaderMode(RowHeaderMode.HIDDEN); } /** * Static helper method to initialize the 'standard' properties of a data item from a given resource.<p> * @param resourceItem the resource item to fill * @param cms the CMS context * @param resource the resource * @param messages the message bundle * @param locale the locale */ public static void fillItemDefault( Item resourceItem, CmsObject cms, CmsResource resource, CmsMessages messages, Locale locale) { if (resource == null) { LOG.error("Error rendering item for 'null' resource"); return; } if (resourceItem == null) { LOG.error("Error rendering 'null' item for resource " + resource.getRootPath()); return; } if (cms == null) { cms = A_CmsUI.getCmsObject(); LOG.warn("CmsObject was 'null', using thread local CmsObject"); } CmsResourceUtil resUtil = new CmsResourceUtil(cms, resource); I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(resource); CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(type.getTypeName()); if (settings == null) { LOG.error("Could not read explorer type settings for resource type " + type.getTypeName()); return; } if (resourceItem.getItemProperty(PROPERTY_TYPE_ICON) != null) { resourceItem.getItemProperty(PROPERTY_TYPE_ICON).setValue( new CmsResourceIcon( resUtil, CmsWorkplace.getResourceUri(CmsWorkplace.RES_PATH_FILETYPES + settings.getBigIconIfAvailable()), resource.getState())); } else { LOG.error("Error redering item, property " + PROPERTY_TYPE_ICON.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_PROJECT) != null) { Image projectFlag = null; switch (resUtil.getProjectState().getMode()) { case 1: projectFlag = new Image( resUtil.getLockedInProjectName(), new ThemeResource(OpenCmsTheme.PROJECT_CURRENT_PATH)); break; case 2: projectFlag = new Image( resUtil.getLockedInProjectName(), new ThemeResource(OpenCmsTheme.PROJECT_OTHER_PATH)); break; case 5: projectFlag = new Image( resUtil.getLockedInProjectName(), new ThemeResource(OpenCmsTheme.PROJECT_PUBLISH_PATH)); break; default: } resourceItem.getItemProperty(PROPERTY_PROJECT).setValue(projectFlag); } else { LOG.error("Error redering item, property " + PROPERTY_PROJECT.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_INSIDE_PROJECT) != null) { resourceItem.getItemProperty(PROPERTY_INSIDE_PROJECT).setValue(Boolean.valueOf(resUtil.isInsideProject())); } else { LOG.error("Error redering item, property " + PROPERTY_INSIDE_PROJECT.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_RESOURCE_NAME) != null) { resourceItem.getItemProperty(PROPERTY_RESOURCE_NAME).setValue(resource.getName()); } else { LOG.error("Error redering item, property " + PROPERTY_RESOURCE_NAME.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_TITLE) != null) { resourceItem.getItemProperty(PROPERTY_TITLE).setValue(resUtil.getTitle()); } else { LOG.error("Error redering item, property " + PROPERTY_TITLE.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_NAVIGATION_TEXT) != null) { resourceItem.getItemProperty(PROPERTY_NAVIGATION_TEXT).setValue(resUtil.getNavText()); } else { LOG.error("Error redering item, property " + PROPERTY_NAVIGATION_TEXT.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_RESOURCE_TYPE) != null) { resourceItem.getItemProperty(PROPERTY_RESOURCE_TYPE).setValue( CmsWorkplaceMessages.getResourceTypeName(locale, type.getTypeName())); } else { LOG.error("Error redering item, property " + PROPERTY_RESOURCE_TYPE.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_IS_FOLDER) != null) { resourceItem.getItemProperty(PROPERTY_IS_FOLDER).setValue(Boolean.valueOf(resource.isFolder())); } else { LOG.error("Error redering item, property " + PROPERTY_IS_FOLDER.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_SIZE) != null) { if (resource.isFile()) { resourceItem.getItemProperty(PROPERTY_SIZE).setValue(Integer.valueOf(resource.getLength())); } } else { LOG.error("Error redering item, property " + PROPERTY_SIZE.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_PERMISSIONS) != null) { resourceItem.getItemProperty(PROPERTY_PERMISSIONS).setValue(resUtil.getPermissionString()); } else { LOG.error("Error redering item, property " + PROPERTY_PERMISSIONS.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_DATE_MODIFIED) != null) { resourceItem.getItemProperty(PROPERTY_DATE_MODIFIED).setValue( messages.getDateTime(resource.getDateLastModified())); } else { LOG.error("Error redering item, property " + PROPERTY_DATE_MODIFIED.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_USER_MODIFIED) != null) { resourceItem.getItemProperty(PROPERTY_USER_MODIFIED).setValue(resUtil.getUserLastModified()); } else { LOG.error("Error redering item, property " + PROPERTY_USER_MODIFIED.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_DATE_CREATED) != null) { resourceItem.getItemProperty(PROPERTY_DATE_CREATED).setValue( messages.getDateTime(resource.getDateCreated())); } else { LOG.error("Error redering item, property " + PROPERTY_DATE_CREATED.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_USER_CREATED) != null) { resourceItem.getItemProperty(PROPERTY_USER_CREATED).setValue(resUtil.getUserCreated()); } else { LOG.error("Error redering item, property " + PROPERTY_USER_CREATED.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_DATE_RELEASED) != null) { resourceItem.getItemProperty(PROPERTY_DATE_RELEASED).setValue(resUtil.getDateReleased()); } else { LOG.error("Error redering item, property " + PROPERTY_DATE_RELEASED.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_DATE_EXPIRED) != null) { resourceItem.getItemProperty(PROPERTY_DATE_EXPIRED).setValue(resUtil.getDateExpired()); } else { LOG.error("Error redering item, property " + PROPERTY_DATE_EXPIRED.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_STATE_NAME) != null) { resourceItem.getItemProperty(PROPERTY_STATE_NAME).setValue(resUtil.getStateName()); } else { LOG.error("Error redering item, property " + PROPERTY_STATE_NAME.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_STATE) != null) { resourceItem.getItemProperty(PROPERTY_STATE).setValue(resource.getState()); } else { LOG.error("Error redering item, property " + PROPERTY_STATE.getId() + " is null"); } if (resourceItem.getItemProperty(PROPERTY_USER_LOCKED) != null) { resourceItem.getItemProperty(PROPERTY_USER_LOCKED).setValue(resUtil.getLockedByName()); } else { LOG.error("Error redering item, property " + PROPERTY_USER_LOCKED.getId() + " is null"); } } /** * Gets the CSS style name for the given resource state.<p> * * @param state the resource state * @return the CSS style name */ public static String getStateStyle(CmsResourceState state) { String stateStyle = ""; if (state != null) { if (state.isDeleted()) { stateStyle = OpenCmsTheme.STATE_DELETED; } else if (state.isNew()) { stateStyle = OpenCmsTheme.STATE_NEW; } else if (state.isChanged()) { stateStyle = OpenCmsTheme.STATE_CHANGED; } } return stateStyle; } /** * Clears the value selection.<p> */ public void clearSelection() { m_fileTable.setValue(Collections.emptySet()); } /** * Fills the resource table.<p> * * @param cms the current CMS context * @param resources the resources which should be displayed in the table */ public void fillTable(CmsObject cms, List<CmsResource> resources) { Locale wpLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); m_container.removeAllItems(); m_container.removeAllContainerFilters(); for (CmsResource resource : resources) { fillItem(cms, resource, wpLocale); } m_fileTable.sort(); clearSelection(); } /** * Returns the number of currently visible items.<p> * * @return the number of currentliy visible items */ public int getItemCount() { return m_container.getItemCount(); } /** * Returns if the column with the given property id is visible and not collapsed.<p> * * @param propertyId the property id * * @return <code>true</code> if the column is visible */ public boolean isColumnVisible(CmsResourceTableProperty propertyId) { return Arrays.asList(m_fileTable.getVisibleColumns()).contains(propertyId) && !m_fileTable.isColumnCollapsed(propertyId); } /** * Selects all resources.<p> */ public void selectAll() { m_fileTable.setValue(m_fileTable.getItemIds()); } /** * Sets the list of collapsed columns.<p> * * @param collapsedColumns the list of collapsed columns */ public void setCollapsedColumns(Object... collapsedColumns) { Set<Object> collapsedSet = Sets.newHashSet(); for (Object collapsed : collapsedColumns) { collapsedSet.add(collapsed); } for (Object key : m_fileTable.getVisibleColumns()) { m_fileTable.setColumnCollapsed(key, collapsedSet.contains(key)); } } /** * Sets the table drag mode.<p> * * @param dragMode the drag mode */ public void setDragMode(TableDragMode dragMode) { m_fileTable.setDragMode(dragMode); } /** * Sets the table drop handler.<p> * * @param handler the drop handler */ public void setDropHandler(DropHandler handler) { m_fileTable.setDropHandler(handler); } /** * Fills the file item data.<p> * * @param cms the cms context * @param resource the resource * @param locale the workplace locale */ protected void fillItem(CmsObject cms, CmsResource resource, Locale locale) { Item resourceItem = m_container.getItem(resource.getStructureId()); if (resourceItem == null) { resourceItem = m_container.addItem(resource.getStructureId()); } fillItemDefault(resourceItem, cms, resource, CmsVaadinUtils.getWpMessagesForCurrentLocale(), locale); } }
package org.opencms.workplace; import org.opencms.i18n.A_CmsMessageBundle; import org.opencms.i18n.CmsMessages; import org.opencms.i18n.CmsMultiMessages; import org.opencms.i18n.I_CmsMessageBundle; import org.opencms.main.OpenCms; import org.opencms.util.CmsStringUtil; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; /** * Provides access to the localized messages for the OpenCms workplace.<p> * * The workplace messages are collected from the workplace resource bundles of all installed modules, * plus all the OpenCms core packages.<p> * * To be recognized as a workplace module resource bundle, * the workplace property file must follow the naming convention <code>${module_package_name}.workplace${locale}.properties</code>, * or <code>${module_package_name}.messages${locale}.properties</code> * for example like <code>com.mycompany.module.workplace_en.properties</code> or * <code>com.mycompany.module.messages_en.properties</code>.<p> * * Workplace messages are cached for faster lookup. If a localized key is contained in more then one module, * it will be used only from the module where it was first found in. The module order is undefined. It is therefore * recommended to ensure the uniqueness of all module keys by placing a special prefix in front of all keys of a module.<p> * * @since 6.0.0 */ public class CmsWorkplaceMessages extends CmsMultiMessages { /** The title key prefix used for the "new resource" dialog. */ public static final String GUI_NEW_RESOURCE_TITLE_PREFIX = "title.new"; /** Constant for the <code>".messages"</code> prefix. */ public static final String PREFIX_BUNDLE_MESSAGES = ".messages"; /** Constant for the <code>".workplace"</code> prefix. */ public static final String PREFIX_BUNDLE_WORKPLACE = ".workplace"; /** Constant for the multi bundle name. */ public static final String WORKPLACE_BUNDLE_NAME = CmsWorkplaceMessages.class.getName(); /** * Constructor for creating a new messages object * initialized with the provided locale.<p> * * @param locale the locale to initialize */ public CmsWorkplaceMessages(Locale locale) { super(locale); setBundleName(WORKPLACE_BUNDLE_NAME); addMessages(collectModuleMessages(locale)); } /** * Returns the title for the "new resource" dialog.<p> * * It will look up a key with the prefix {@link #GUI_NEW_RESOURCE_TITLE_PREFIX} * and the given name appended (converted to lower case).<p> * * If this key is not found, the value of * {@link org.opencms.workplace.explorer.Messages#GUI_TITLE_NEWFILEOTHER_0} will be returned.<p> * * @param wp an instance of a {@link CmsWorkplace} to resolve the key name with * @param name the type to generate the title for * * @return the title for the "new resource" dialog */ public static String getNewResourceTitle(CmsWorkplace wp, String name) { // try to find the localized key String title = wp.key(GUI_NEW_RESOURCE_TITLE_PREFIX + name.toLowerCase()); if (CmsMessages.isUnknownKey(title)) { // still unknown - use default title title = wp.key(org.opencms.workplace.explorer.Messages.GUI_TITLE_NEWFILEOTHER_0); } return title; } /** * Returns the description of the given resource type name.<p> * * If this key is not found, the value of the name input will be returned.<p> * * @param wp an instance of a {@link CmsWorkplace} to resolve the key name with * @param name the resource type name to generate the nice name for * * @return the description of the given resource type name */ public static String getResourceTypeDescription(CmsWorkplace wp, String name) { // try to find the localized key String key = OpenCms.getWorkplaceManager().getExplorerTypeSetting(name).getInfo(); return wp.keyDefault(key, name); } /** * Returns the description of the given resource type name.<p> * * If this key is not found, the value of the name input will be returned.<p> * * @param locale the right locale to use * @param name the resource type name to generate the nice name for * * @return the description of the given resource type name */ public static String getResourceTypeDescription(Locale locale, String name) { // try to find the localized key String key = OpenCms.getWorkplaceManager().getExplorerTypeSetting(name).getInfo(); if (CmsStringUtil.isEmptyOrWhitespaceOnly(key)) { return ""; } return OpenCms.getWorkplaceManager().getMessages(locale).keyDefault(key, name); } /** * Returns the localized name of the given resource type name.<p> * * If this key is not found, the value of the name input will be returned.<p> * * @param wp an instance of a {@link CmsWorkplace} to resolve the key name with * @param name the resource type name to generate the nice name for * * @return the localized name of the given resource type name */ public static String getResourceTypeName(CmsWorkplace wp, String name) { // try to find the localized key String key = OpenCms.getWorkplaceManager().getExplorerTypeSetting(name).getKey(); return wp.keyDefault(key, name); } /** * Returns the localized name of the given resource type name.<p> * * If this key is not found, the value of the name input will be returned.<p> * * @param locale the right locale to use * @param name the resource type name to generate the nice name for * * @return the localized name of the given resource type name */ public static String getResourceTypeName(Locale locale, String name) { // try to find the localized key String key = OpenCms.getWorkplaceManager().getExplorerTypeSetting(name).getKey(); return OpenCms.getWorkplaceManager().getMessages(locale).keyDefault(key, name); } /** * Gathers all localization files for the workplace from the different modules.<p> * * For a module named "my.module.name" the locale file must be named * "my.module.name.workplace" or "my.module.name.messages" and * be located in the classpath so that the resource loader can find it.<p> * * @param locale the selected locale * * @return an initialized set of module messages */ private static List<CmsMessages> collectModuleMessages(Locale locale) { // create a new list and add the base bundle ArrayList<CmsMessages> result = new ArrayList<CmsMessages>(); //////////// iterate over all registered modules //////////////// Set<String> names = OpenCms.getModuleManager().getModuleNames(); if (names != null) { // iterate all module names Iterator<String> i = names.iterator(); while (i.hasNext()) { String modName = i.next(); //////////// collect the workplace.properties //////////////// // this should result in a name like "my.module.name.workplace" String bundleName = modName + PREFIX_BUNDLE_WORKPLACE; // try to load a bundle with the module names CmsMessages msg = new CmsMessages(bundleName, locale); // bundle was loaded, add to list of bundles if (msg.isInitialized()) { result.add(msg); } //////////// collect the messages.properties //////////////// // this should result in a name like "my.module.name.messages" bundleName = modName + PREFIX_BUNDLE_MESSAGES; // try to load a bundle with the module names msg = new CmsMessages(bundleName, locale); // bundle was loaded, add to list of bundles if (msg.isInitialized()) { result.add(msg); } } } //////////// collect additional core packages //////////////// I_CmsMessageBundle[] coreMsgs = A_CmsMessageBundle.getOpenCmsMessageBundles(); for (int i = 0; i < coreMsgs.length; i++) { I_CmsMessageBundle bundle = coreMsgs[i]; result.add(bundle.getBundle(locale)); } return result; } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof CmsWorkplaceMessages) { // workplace messages are equal if the locale is equal (since all bundles are the same) CmsMessages other = (CmsMessages)obj; return other.getLocale().equals(getLocale()); } return false; } /** * @see org.opencms.i18n.CmsMessages#hashCode() */ @Override public int hashCode() { return getLocale().hashCode(); } }
package org.pentaho.di.trans.steps.abort; import java.util.List; import java.util.Map; import org.pentaho.di.core.CheckResult; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Counter; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.repository.Repository; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.w3c.dom.Node; /** * Meta data for the abort step. * * @author sboden */ public class AbortMeta extends BaseStepMeta implements StepMetaInterface { /** * Threshold to abort. */ private String rowThreshold; /** * Message to put in log when aborting. */ private String message; /** * Always log rows. */ private boolean alwaysLogRows; public void getFields(RowMetaInterface inputRowMeta, String name, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space) throws KettleStepException { // Default: no values are added to the row in the step } public void check(List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepinfo, RowMetaInterface prev, String input[], String output[], RowMetaInterface info) { // See if we have input streams leading to this step! if (input.length == 0) { CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_WARNING, Messages.getString("AbortMeta.CheckResult.NoInputReceivedError"), stepinfo); //$NON-NLS-1$ remarks.add(cr); } } public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { return new Abort(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public StepDataInterface getStepData() { return new AbortData(); } public void loadXML(Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleXMLException { readData(stepnode); } public void setDefault() { rowThreshold = "0"; message = ""; alwaysLogRows = true; } public String getXML() { StringBuilder retval = new StringBuilder(200); retval.append(" ").append(XMLHandler.addTagValue("row_threshold", rowThreshold)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("message", message)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("always_log_rows", alwaysLogRows)); //$NON-NLS-1$ //$NON-NLS-2$ return retval.toString(); } private void readData(Node stepnode) throws KettleXMLException { try { rowThreshold = XMLHandler.getTagValue(stepnode, "row_threshold"); //$NON-NLS-1$ message = XMLHandler.getTagValue(stepnode, "message"); //$NON-NLS-1$ alwaysLogRows = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "always_log_rows")); //$NON-NLS-1$ //$NON-NLS-2$ } catch(Exception e) { throw new KettleXMLException(Messages.getString("AbortMeta.Exception.UnexpectedErrorInReadingStepInfoFromRepository"), e); //$NON-NLS-1$ } } public void readRep(Repository rep, long id_step, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleException { try { rowThreshold = rep.getStepAttributeString(id_step, "row_threshold"); //$NON-NLS-1$ message = rep.getStepAttributeString(id_step, "message"); //$NON-NLS-1$ alwaysLogRows = rep.getStepAttributeBoolean(id_step, "always_log_rows"); //$NON-NLS-1$ } catch(Exception e) { throw new KettleException(Messages.getString("AbortMeta.Exception.UnexpectedErrorInReadingStepInfoFromRepository"), e); //$NON-NLS-1$ } } public void saveRep(Repository rep, long id_transformation, long id_step) throws KettleException { try { rep.saveStepAttribute(id_transformation, id_step, "row_threshold", rowThreshold); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, "message", message); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, "always_log_rows", alwaysLogRows); //$NON-NLS-1$ } catch(Exception e) { throw new KettleException(Messages.getString("AbortMeta.Exception.UnableToSaveStepInfoToRepository")+id_step, e); //$NON-NLS-1$ } } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getRowThreshold() { return rowThreshold; } public void setRowThreshold(String rowThreshold) { this.rowThreshold = rowThreshold; } public boolean isAlwaysLogRows() { return alwaysLogRows; } public void setAlwaysLogRows(boolean alwaysLogRows) { this.alwaysLogRows = alwaysLogRows; } }
package org.pentaho.ui.xul.swing.tags; import java.awt.Dimension; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; import javax.swing.text.PlainDocument; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.components.XulTextbox; import org.pentaho.ui.xul.dom.Element; import org.pentaho.ui.xul.swing.SwingElement; import org.pentaho.ui.xul.util.TextType; /** * @author nbaker * */ public class SwingTextbox extends SwingElement implements XulTextbox { private JTextField textField; private boolean multiline = false; private JTextArea textArea; boolean disabled = false; private String value = ""; private JScrollPane scrollPane; private static final Log logger = LogFactory.getLog(SwingTextbox.class); private boolean readonly = false; private TextType type = TextType.NORMAL; private JTextComponent textComp = null; private String onInput; private int min = -1; private int max = -1; private int maxlength = -1; private String oldValue; public SwingTextbox(Element self, XulComponent parent, XulDomContainer domContainer, String tagName) { super("textbox"); managedObject = null; } public String getValue() { if (managedObject != null) { return textComp.getText(); } else { logger.error("Attempt to get Textbox's value before it's instantiated"); return null; } } public void setValue(String text) { String oldVal = this.value; if (managedObject != null) { textComp.setText(text); } this.value = text; if (text != null || oldVal != null) { this.changeSupport.firePropertyChange("value", oldVal, text); } } public void layout() { } public int getMaxlength() { return maxlength; } public boolean isDisabled() { return this.disabled; } public void setDisabled(boolean dis) { this.disabled = dis; if (managedObject != null) { textComp.setEnabled(!dis); } } public void setMaxlength(int length) { maxlength = length; } public boolean isMultiline() { return multiline; } public void setMultiline(boolean multi) { this.multiline = multi; } public boolean isReadonly() { return readonly; } public void setReadonly(boolean readOnly) { this.readonly = readOnly; } public String getType() { if (type == null) { return null; } return type.toString(); } public void setType(String type) { if (type == null) { return; } setType(TextType.valueOf(type.toUpperCase())); } public void setType(TextType type) { this.type = type; } public void selectAll() { textComp.selectAll(); } public void setFocus() { } public Object getTextControl() { return managedObject; } @Override public Object getManagedObject() { if (managedObject == null) { switch (this.type) { case PASSWORD: JPasswordField pass = new JPasswordField((value != null) ? value : ""); pass.setPreferredSize(new Dimension(150, 20)); pass.setMinimumSize(new Dimension(pass.getPreferredSize().width, pass.getPreferredSize().height)); pass.setEditable(!readonly); textComp = pass; managedObject = pass; break; case NUMERIC: default: //regular text if (this.multiline) { textArea = new JTextArea((value != null) ? value : ""); scrollPane = new JScrollPane(textArea); textComp = textArea; managedObject = scrollPane; textArea.setEditable(!readonly); this.scrollPane.setMinimumSize(new Dimension(this.width, this.height)); //this.scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); } else { textField = new JTextField((value != null) ? value : ""); textField.setPreferredSize(new Dimension(150, textField.getPreferredSize().height)); textField.setMinimumSize(new Dimension(textField.getPreferredSize().width, textField.getPreferredSize().height)); textField.setEditable(!readonly); managedObject = textField; textComp = textField; } //constrin Numeric only here if (this.type == TextType.NUMERIC) { textComp.setDocument(new NumericDocument(min, max)); } textComp.setEnabled(!disabled); break; } textComp.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) {oldValue = textComp.getText();} public void keyReleased(KeyEvent e) { if(!oldValue.equals(textComp.getText())){ SwingTextbox.this.changeSupport.firePropertyChange("value", "", SwingTextbox.this.getValue()); oldValue = textComp.getText(); } else { logger.debug("Special key pressed, ignoring"); } } public void keyTyped(KeyEvent e) { } }); // Why do we need this here if we setup oninput in the setOninput // textComp.addKeyListener(new KeyAdapter() { // public void keyReleased(KeyEvent e) { // invoke(onInput); } return managedObject; } public void setOninput(final String method) { if (textComp != null) { textComp.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { invoke(method); } }); } else { //Not instantiated, save for later onInput = method; } } public String getMin() { return "" + min; } public void setMin(String min) { this.min = Integer.parseInt(min); } public String getMax() { return "" + max; } public void setMax(String max) { this.max = Integer.parseInt(max); } @SuppressWarnings("serial") private class NumericDocument extends PlainDocument { private int min; private int max; public NumericDocument(int min, int max) { super(); this.min = min; this.max = max; } @Override public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (str == null) { return; } if (!validString(str)) { logger.error("Textbox input not a valid number: " + str); return; } //if not special chars, evaluate number for range if (str.charAt(str.length() - 1) != '.' && str.charAt(str.length() - 1) != '-') { if (max > -1 && Double.parseDouble(super.getText(0, super.getLength()) + str) > max) { logger.error(String.format("Textbox Greater [%f]less than max: %d", Float.parseFloat(super.getText(0, super .getLength()) + str), max)); return; } } //everything checks out insert string super.insertString(offs, str, a); } private boolean validString(String str) { return StringUtils.isNumeric(str.replace(".", "").replace("-", "")) || str.equals("-") || str.equals("."); } } }
package org.pentaho.ui.xul.swing.tags; import java.awt.Component; import java.awt.Dimension; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import javax.swing.text.JTextComponent; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.components.XulTextbox; import org.pentaho.ui.xul.dom.Element; import org.pentaho.ui.xul.swing.SwingElement; import org.pentaho.ui.xul.util.TextType; /** * @author nbaker * */ public class SwingTextbox extends SwingElement implements XulTextbox { private JTextField textField; private boolean multiline = false; private JTextArea textArea; boolean disabled = false; private String value = ""; private JScrollPane scrollPane; private static final Log logger = LogFactory.getLog(SwingTextbox.class); private boolean readonly = false; private TextType type = TextType.NORMAL; private JTextComponent textComp = null; private String onInput; public SwingTextbox(Element self, XulComponent parent, XulDomContainer domContainer, String tagName) { super("textbox"); managedObject = null; } public String getValue(){ if(managedObject != null){ return textComp.getText(); } else { logger.error("Attempt to get Textbox's value before it's instantiated"); return null; } } public void setValue(String text){ if(managedObject != null){ textComp.setText(text); } String oldVal = getText(); this.value = text; changeSupport.firePropertyChange("value", oldVal, text); } public void layout(){ } public int getMaxlength() { return 0; } public boolean isDisabled() { return this.disabled; } public void setDisabled(boolean dis) { this.disabled = dis; if(managedObject != null){ textComp.setEnabled(!dis); } } public void setMaxlength(int length) { } public boolean isMultiline() { return multiline; } public void setMultiline(boolean multi) { this.multiline = multi; } public boolean isReadonly() { return readonly; } public void setReadonly(boolean readOnly) { this.readonly = readOnly; } public String getType() { if (type == null){ return null; } return type.toString(); } public void setType(String type) { if (type == null){ return; } setType(TextType.valueOf(type.toUpperCase())); } public void setType(TextType type) { this.type = type; } public void selectAll() { textComp.selectAll(); } public void setFocus() { } public Object getTextControl() { return managedObject; } @Override public Object getManagedObject() { if(managedObject == null){ switch(this.type){ case PASSWORD: JPasswordField pass = new JPasswordField((value != null) ? value : ""); pass.setPreferredSize(new Dimension(200,20)); pass.setEditable(!readonly); textComp = pass; managedObject = pass; break; default: //regular text if(this.multiline){ textArea = new JTextArea((value != null) ? value : ""); scrollPane = new JScrollPane(textArea); textComp = textArea; managedObject = scrollPane; textArea.setEditable(!readonly); this.scrollPane.setMinimumSize(new Dimension(this.width, this.height)); this.scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); break; } else { textField = new JTextField((value != null) ? value : ""); textField.setPreferredSize(new Dimension(200,20)); textField.setEditable(!readonly); managedObject = textField; textComp = textField; break; } } textComp.addKeyListener(new KeyListener(){ public void keyPressed(KeyEvent e) {} public void keyReleased(KeyEvent e) { String newVal = SwingTextbox.this.getValue(); SwingTextbox.this.changeSupport.firePropertyChange("value", "", SwingTextbox.this.getValue()); } public void keyTyped(KeyEvent e) {} }); textComp.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { invoke(onInput); } }); } return managedObject; } public void setOninput(final String method) { if(textComp != null){ textComp.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { invoke(method); } }); } else { //Not instantiated, save for later onInput = method; } } }
package pitt.search.semanticvectors; import java.lang.IllegalArgumentException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.Enumeration; import java.util.logging.Logger; import pitt.search.semanticvectors.LuceneUtils; import pitt.search.semanticvectors.VectorSearcher; import pitt.search.semanticvectors.VectorStore; import pitt.search.semanticvectors.vectors.BinaryVectorUtils; import pitt.search.semanticvectors.vectors.IncompatibleVectorsException; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorType; import pitt.search.semanticvectors.vectors.VectorUtils; /** * Class for searching vector stores using different scoring functions. * Each VectorSearcher implements a particular scoring function which is * normally query dependent, so each query needs its own VectorSearcher. */ abstract public class VectorSearcher { private static final Logger logger = Logger.getLogger(VectorSearcher.class.getCanonicalName()); private VectorStore searchVecStore; private LuceneUtils luceneUtils; /** * Expand search space for dual-predicate searches */ public static VectorStore expandSearchSpace(VectorStore searchVecStore) { VectorStoreRAM nusearchspace = new VectorStoreRAM(searchVecStore.getVectorType(), searchVecStore.getDimension()); Enumeration<ObjectVector> allVectors = searchVecStore.getAllVectors(); ArrayList<ObjectVector> storeVectors = new ArrayList<ObjectVector>(); while (allVectors.hasMoreElements()) { ObjectVector nextObjectVector = allVectors.nextElement(); nusearchspace.putVector(nextObjectVector.getObject(), nextObjectVector.getVector()); storeVectors.add(nextObjectVector); } for (int x=0; x < storeVectors.size()-1; x++) for (int y=x; y < storeVectors.size(); y++) { Vector vec1 = storeVectors.get(x).getVector().copy(); Vector vec2 = storeVectors.get(y).getVector().copy(); String obj1 = storeVectors.get(x).getObject().toString(); String obj2 = storeVectors.get(y).getObject().toString(); vec1.release(vec2); nusearchspace.putVector(obj2+":"+obj1, vec1); if (nusearchspace.getVectorType().equals(VectorType.COMPLEX)) { vec2.release(storeVectors.get(x).getVector().copy()); nusearchspace.putVector(obj1+":"+obj2, vec2); } } System.err.println("Expanding search space from "+storeVectors.size()+" to "+nusearchspace.getNumVectors()); return nusearchspace; } /** * This needs to be filled in for each subclass. It takes an individual * vector and assigns it a relevance score for this VectorSearcher. */ public abstract double getScore(Vector testVector); /** * Performs basic initialization; subclasses should normally call super() to use this. * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) */ public VectorSearcher(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils) { this.searchVecStore = searchVecStore; this.luceneUtils = luceneUtils; if (Flags.expandsearchspace) searchVecStore = expandSearchSpace(searchVecStore); } /** * This nearest neighbor search is implemented in the abstract * VectorSearcher class itself: this enables all subclasses to reuse * the search whatever scoring method they implement. Since query * expressions are built into the VectorSearcher, * getNearestNeighbors no longer takes a query vector as an * argument. * @param numResults the number of results / length of the result list. */ public LinkedList<SearchResult> getNearestNeighbors(int numResults) { LinkedList<SearchResult> results = new LinkedList<SearchResult>(); double score = -1; double threshold = Flags.searchresultsminscore; if (Flags.stdev) threshold = 0; //Counters for statistics to calculate standard deviation double sum=0, sumsquared=0; int count=0; Enumeration<ObjectVector> vecEnum = searchVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Test this element. ObjectVector testElement = vecEnum.nextElement(); score = getScore(testElement.getVector()); // This is a way of using the Lucene Index to get term and // document frequency information to reweight all results. It // seems to be good at moving excessively common terms further // down the results. Note that using this means that scores // returned are no longer just cosine similarities. if (this.luceneUtils != null && Flags.usetermweightsinsearch) { score = score * luceneUtils.getGlobalTermWeightFromString((String) testElement.getObject()); } if (Flags.stdev) { count++; sum += score; sumsquared += Math.pow(score, 2); } if (score > threshold) { boolean added = false; for (int i = 0; i < results.size(); ++i) { // Add to list if this is right place. if (score > results.get(i).getScore() && added == false) { results.add(i, new SearchResult(score, testElement)); added = true; } } // Prune list if there are already numResults. if (results.size() > numResults) { results.removeLast(); threshold = results.getLast().getScore(); } else { if (added == false) { results.add(new SearchResult(score, testElement)); } } } } if (Flags.stdev) results = transformToStats(results, count, sum, sumsquared); return results; } /** * This search is implemented in the abstract * VectorSearcher class itself: this enables all subclasses to reuse * the search whatever scoring method they implement. Since query * expressions are built into the VectorSearcher, * getAllAboveThreshold does not takes a query vector as an * argument. * * This will retrieve all the results above the threshold score passed * as a parameter. It is more computationally convenient than getNearestNeighbor * when large numbers of results are anticipated * * @param numResults the number of results / length of the result list. */ public LinkedList<SearchResult> getAllAboveThreshold(float threshold) { LinkedList<SearchResult> results = new LinkedList<SearchResult>(); double score; Enumeration<ObjectVector> vecEnum = null; vecEnum = searchVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Test this element. ObjectVector testElement = vecEnum.nextElement(); if (testElement == null) score = Float.MIN_VALUE; else { Vector testVector = testElement.getVector(); score = getScore(testVector); } if (score > threshold) { results.add(new SearchResult(score, testElement));} } return results; } /** * Class for searching a vector store using cosine similarity. * Takes a sum of positive query terms and optionally negates some terms. */ static public class VectorSearcherCosine extends VectorSearcher { Vector queryVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherCosine( VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.queryVector = CompoundVectorBuilder.getQueryVector( queryVecStore, luceneUtils, queryTerms); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryVector Vector representing query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherCosine( VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, Vector queryVector) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.queryVector = queryVector; Vector testVector = searchVecStore.getAllVectors().nextElement().getVector(); IncompatibleVectorsException.checkVectorsCompatible(queryVector, testVector); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } @Override public double getScore(Vector testVector) { return this.queryVector.measureOverlap(testVector); } } /** * Class for searching a vector store using the bound product of a series two vectors. */ static public class VectorSearcherBoundProduct extends VectorSearcher { Vector queryVector; public VectorSearcherBoundProduct(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String term1, String term2) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.queryVector = CompoundVectorBuilder.getBoundProductQueryVectorFromString(queryVecStore, term1); queryVector.release(CompoundVectorBuilder.getBoundProductQueryVectorFromString(boundVecStore, term2)); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } public VectorSearcherBoundProduct(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String term1) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.queryVector = CompoundVectorBuilder.getBoundProductQueryVectorFromString(queryVecStore, boundVecStore, term1); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryVector Vector representing query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherBoundProduct(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, Vector queryVector) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.queryVector = queryVector; Vector testVector = searchVecStore.getAllVectors().nextElement().getVector(); IncompatibleVectorsException.checkVectorsCompatible(queryVector, testVector); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } @Override public double getScore(Vector testVector) { return this.queryVector.measureOverlap(testVector); } } /** * Class for searching a vector store using the bound product of a series two vectors. */ static public class VectorSearcherBoundProductSubSpace extends VectorSearcher { ArrayList<Vector> disjunctSpace; VectorType vectorType; public VectorSearcherBoundProductSubSpace(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String term1, String term2) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); disjunctSpace = new ArrayList<Vector>(); vectorType = queryVecStore.getVectorType(); Vector queryVector = queryVecStore.getVector(term1).copy(); if (queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } this.disjunctSpace = CompoundVectorBuilder.getBoundProductQuerySubSpaceFromString( boundVecStore, queryVector, term2); } @Override public double getScore(Vector testVector) { if (!vectorType.equals(VectorType.BINARY)) return VectorUtils.compareWithProjection(testVector, disjunctSpace); else return BinaryVectorUtils.compareWithProjection(testVector, disjunctSpace); } } /** * Class for searching a vector store using quantum disjunction similarity. */ static public class VectorSearcherSubspaceSim extends VectorSearcher { private ArrayList<Vector> disjunctSpace; private VectorType vectorType; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherSubspaceSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.disjunctSpace = new ArrayList<Vector>(); this.vectorType = queryVecStore.getVectorType(); for (int i = 0; i < queryTerms.length; ++i) { System.out.println("\t" + queryTerms[i]); // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); Vector tmpVector = CompoundVectorBuilder.getQueryVector( queryVecStore, luceneUtils, tmpTerms); if (tmpVector != null) { this.disjunctSpace.add(tmpVector); } } if (this.disjunctSpace.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } if (!vectorType.equals(VectorType.BINARY)) VectorUtils.orthogonalizeVectors(this.disjunctSpace); else BinaryVectorUtils.orthogonalizeVectors(this.disjunctSpace); } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ @Override public double getScore(Vector testVector) { if (!vectorType.equals(VectorType.BINARY)) return VectorUtils.compareWithProjection(testVector, disjunctSpace); else return BinaryVectorUtils.compareWithProjection(testVector, disjunctSpace); } } /** * Class for searching a vector store using minimum distance similarity. */ static public class VectorSearcherMaxSim extends VectorSearcher { private ArrayList<Vector> disjunctVectors; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMaxSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.disjunctVectors = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); Vector tmpVector = CompoundVectorBuilder.getQueryVector( queryVecStore, luceneUtils, tmpTerms); if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } if (this.disjunctVectors.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ @Override public double getScore(Vector testVector) { double score = -1; double max_score = -1; for (int i = 0; i < disjunctVectors.size(); ++i) { score = this.disjunctVectors.get(i).measureOverlap(testVector); if (score > max_score) { max_score = score; } } return max_score; } } /** * Class for searching a permuted vector store using cosine similarity. * Uses implementation of rotation for permutation proposed by Sahlgren et al 2008 * Should find the term that appears frequently in the position p relative to the * index term (i.e. sat +1 would find a term occurring frequently immediately after "sat" */ static public class VectorSearcherPerm extends VectorSearcher { Vector theAvg; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "?" appears, terms best fitting into this position will be returned */ public VectorSearcherPerm(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws IllegalArgumentException, ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); try { theAvg = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(queryVecStore, luceneUtils, queryTerms); } catch (IllegalArgumentException e) { logger.info("Couldn't create permutation VectorSearcher ..."); throw e; } if (theAvg.isZeroVector()) { throw new ZeroVectorException("Permutation query vector is zero ... no results."); } } @Override public double getScore(Vector testVector) { return theAvg.measureOverlap(testVector); } } /** * Test searcher for finding a is to b as c is to ? * * Doesn't do well yet! * * @author dwiddows */ static public class AnalogySearcher extends VectorSearcher { Vector queryVector; public AnalogySearcher( VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTriple) { super(queryVecStore, searchVecStore, luceneUtils); Vector term0 = CompoundVectorBuilder.getQueryVectorFromString(queryVecStore, luceneUtils, queryTriple[0]); Vector term1 = CompoundVectorBuilder.getQueryVectorFromString(queryVecStore, luceneUtils, queryTriple[1]); Vector term2 = CompoundVectorBuilder.getQueryVectorFromString(queryVecStore, luceneUtils, queryTriple[2]); Vector relationVec = term0.copy(); relationVec.bind(term1); this.queryVector = term2.copy(); this.queryVector.release(relationVec); } @Override public double getScore(Vector testVector) { return queryVector.measureOverlap(testVector); } } /** * Class for searching a permuted vector store using cosine similarity. * Uses implementation of rotation for permutation proposed by Sahlgren et al 2008 * Should find the term that appears frequently in the position p relative to the * index term (i.e. sat +1 would find a term occurring frequently immediately after "sat" * This is a variant that takes into account different results obtained when using either * permuted or random index vectors as the cue terms, by taking the mean of the results * obtained with each of these options. */ static public class BalancedVectorSearcherPerm extends VectorSearcher { Vector oneDirection; Vector otherDirection; VectorStore searchVecStore, queryVecStore; LuceneUtils luceneUtils; String[] queryTerms; /** * @param queryVecStore Vector store to use for query generation (this is also reversed). * @param searchVecStore The vector store to search (this is also reversed). * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "?" appears, terms best fitting into this position will be returned */ public BalancedVectorSearcherPerm(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, String[] queryTerms) throws IllegalArgumentException, ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils); this.queryVecStore = queryVecStore; this.searchVecStore = searchVecStore; this.luceneUtils = luceneUtils; try { oneDirection = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(queryVecStore,luceneUtils,queryTerms); otherDirection = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(searchVecStore,luceneUtils,queryTerms); } catch (IllegalArgumentException e) { logger.info("Couldn't create balanced permutation VectorSearcher ..."); throw e; } if (oneDirection.isZeroVector()) { throw new ZeroVectorException("Permutation query vector is zero ... no results."); } } /** * This overides the nearest neighbor class implemented in the abstract * {@code VectorSearcher} class. * * WARNING: This implementation fails to respect flags used by the * {@code VectorSearcher.getNearestNeighbors} method. * * @param numResults the number of results / length of the result list. */ @Override public LinkedList<SearchResult> getNearestNeighbors(int numResults) { LinkedList<SearchResult> results = new LinkedList<SearchResult>(); double score, score1, score2 = -1; double threshold = Flags.searchresultsminscore; if (Flags.stdev) threshold = 0; //Counters for statistics to calculate standard deviation double sum=0, sumsquared=0; int count=0; Enumeration<ObjectVector> vecEnum = searchVecStore.getAllVectors(); Enumeration<ObjectVector> vecEnum2 = queryVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Test this element. ObjectVector testElement = vecEnum.nextElement(); ObjectVector testElement2 = vecEnum2.nextElement(); score1 = getScore(testElement.getVector()); score2 = getScore2(testElement2.getVector()); score = Math.max(score1,score2); // This is a way of using the Lucene Index to get term and // document frequency information to reweight all results. It // seems to be good at moving excessively common terms further // down the results. Note that using this means that scores // returned are no longer just cosine similarities. if ((this.luceneUtils != null) && Flags.usetermweightsinsearch) { score = score * luceneUtils.getGlobalTermWeightFromString((String) testElement.getObject()); } if (Flags.stdev) { count++; sum += score; sumsquared += Math.pow(score, 2); } if (score > threshold) { boolean added = false; for (int i = 0; i < results.size(); ++i) { // Add to list if this is right place. if (score > results.get(i).getScore() && added == false) { results.add(i, new SearchResult(score, testElement)); added = true; } } // Prune list if there are already numResults. if (results.size() > numResults) { results.removeLast(); threshold = results.getLast().getScore(); } else { if (added == false) { results.add(new SearchResult(score, testElement)); } } } } if (Flags.stdev) results = transformToStats(results, count, sum, sumsquared); return results; } @Override public double getScore(Vector testVector) { testVector.normalize(); return oneDirection.measureOverlap(testVector); } public double getScore2(Vector testVector) { testVector.normalize(); return (otherDirection.measureOverlap(testVector)); } } /** * calculates approximation of standard deviation (using a somewhat imprecise single-pass algorithm) * and recasts top scores as number of standard deviations from the mean (for a single search) * * @return list of results with scores as number of standard deviations from mean */ public static LinkedList<SearchResult> transformToStats( LinkedList<SearchResult> rawResults,int count, double sum, double sumsq) { LinkedList<SearchResult> transformedResults = new LinkedList<SearchResult>(); double variancesquared = sumsq - (Math.pow(sum,2)/count); double stdev = Math.sqrt(variancesquared/(count)); double mean = sum/count; Iterator<SearchResult> iterator = rawResults.iterator(); while (iterator.hasNext()) { SearchResult temp = iterator.next(); double score = temp.getScore(); score = new Double((score-mean)/stdev).floatValue(); if (score > Flags.searchresultsminscore) transformedResults.add(new SearchResult(score, temp.getObjectVector())); } return transformedResults; } }
package com.rho.db; import com.xruby.runtime.builtin.*; import com.xruby.runtime.lang.*; import com.rho.*; import com.rho.file.*; import java.util.Enumeration; import java.util.Vector; import java.util.Hashtable; public class DBAdapter extends RubyBasic { private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() : new RhoLogger("DbAdapter"); //private static DBAdapter m_Instance; private IDBStorage m_dbStorage; private boolean m_bIsOpen = false; private String m_strDBPath, m_strDBVerPath; private String m_strDbPartition; private DBAttrManager m_attrMgr = new DBAttrManager(); static Hashtable/*Ptr<String,CDBAdapter*>*/ m_mapDBPartitions = new Hashtable(); Mutex m_mxDB = new Mutex(); int m_nTransactionCounter=0; boolean m_bUIWaitDB = false; static String USER_PARTITION_NAME(){return "user";} static Hashtable/*Ptr<String,CDBAdapter*>&*/ getDBPartitions(){ return m_mapDBPartitions; } String m_strClientInfoInsert = ""; Object[] m_dataClientInfo = null; DBAdapter(RubyClass c) { super(c); try{ m_dbStorage = RhoClassFactory.createDBStorage(); }catch(Exception exc){ LOG.ERROR("createDBStorage failed.", exc); } } /* public static DBAdapter getInstance(){ if ( m_Instance == null ) m_Instance = new DBAdapter(RubyRuntime.DatabaseClass); return m_Instance; }*/ private void setDbPartition(String strPartition) { m_strDbPartition = strPartition; } public void close() { try{ m_dbStorage.close(); m_dbStorage = null; }catch(Exception exc) { LOG.ERROR("DB close failed.", exc); } } public DBAttrManager getAttrMgr() { return m_attrMgr; } public void executeBatchSQL(String strStatement)throws DBException{ LOG.TRACE("executeBatchSQL: " + strStatement); m_dbStorage.executeBatchSQL(strStatement); } public IDBResult executeSQL(String strStatement, Object[] values)throws DBException{ LOG.TRACE("executeSQL: " + strStatement); IDBResult res = null; Lock(); try{ res = m_dbStorage.executeSQL(strStatement,values,false); }finally { Unlock(); } return res; } public IDBResult executeSQL(String strStatement)throws DBException{ return executeSQL(strStatement,null); } public IDBResult executeSQL(String strStatement, Object arg1)throws DBException{ Object[] values = {arg1}; return executeSQL(strStatement,values); } public IDBResult executeSQL(String strStatement, int arg1)throws DBException{ Object[] values = { new Integer(arg1)}; return executeSQL(strStatement,values); } public IDBResult executeSQL(String strStatement, int arg1, int arg2)throws DBException{ Object[] values = { new Integer(arg1), new Integer(arg2)}; return executeSQL(strStatement,values); } public IDBResult executeSQL(String strStatement, long arg1)throws DBException{ Object[] values = { new Long(arg1)}; return executeSQL(strStatement,values); } public IDBResult executeSQL(String strStatement, Object arg1, Object arg2)throws DBException{ Object[] values = {arg1,arg2}; return executeSQL(strStatement,values); } public IDBResult executeSQL(String strStatement, Object arg1, Object arg2, Object arg3)throws DBException{ Object[] values = {arg1,arg2,arg3}; return executeSQL(strStatement,values); } public IDBResult executeSQL(String strStatement, Object arg1, Object arg2, Object arg3, Object arg4)throws DBException{ Object[] values = {arg1,arg2,arg3,arg4}; return executeSQL(strStatement,values); } public IDBResult executeSQL(String strStatement, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5)throws DBException{ Object[] values = {arg1,arg2,arg3,arg4,arg5}; return executeSQL(strStatement,values); } public IDBResult executeSQL(String strStatement, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6)throws DBException{ Object[] values = {arg1,arg2,arg3,arg4,arg5,arg6}; return executeSQL(strStatement,values); } public IDBResult executeSQLReportNonUnique(String strStatement, Object arg1, Object arg2, Object arg3, Object arg4)throws DBException{ //LOG.TRACE("executeSQLReportNonUnique: " + strStatement); Object[] values = {arg1,arg2,arg3,arg4}; IDBResult res = null; Lock(); try{ res = m_dbStorage.executeSQL(strStatement,values, true); }finally { Unlock(); } return res; } public IDBResult executeSQLReportNonUnique(String strStatement, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7)throws DBException{ //LOG.TRACE("executeSQLReportNonUnique: " + strStatement); Object[] values = {arg1,arg2,arg3,arg4, arg5, arg6, arg7}; IDBResult res = null; Lock(); try{ res = m_dbStorage.executeSQL(strStatement,values, true); }finally { Unlock(); } return res; } public IDBResult executeSQLReportNonUniqueEx(String strStatement, Vector vecValues)throws DBException{ //LOG.TRACE("executeSQLReportNonUnique: " + strStatement); Object[] values = new Object[vecValues.size()]; for (int i = 0; i < vecValues.size(); i++ ) values[i] = vecValues.elementAt(i); IDBResult res = null; Lock(); try{ res = m_dbStorage.executeSQL(strStatement,values, true); }finally { Unlock(); } return res; } public IDBResult executeSQLEx(String strStatement, Vector vecValues)throws DBException{ Object[] values = new Object[vecValues.size()]; for (int i = 0; i < vecValues.size(); i++ ) values[i] = vecValues.elementAt(i); return executeSQL(strStatement,values); } public IDBResult executeSQL(String strStatement, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7)throws DBException{ Object[] values = {arg1,arg2,arg3,arg4,arg5,arg6,arg7}; return executeSQL(strStatement,values); } public boolean isUIWaitDB(){ return m_bUIWaitDB; } public void Lock() { if ( RhoRuby.isMainRubyThread() ) m_bUIWaitDB = true; m_mxDB.Lock(); if ( RhoRuby.isMainRubyThread() ) m_bUIWaitDB = false; } public void Unlock(){ m_mxDB.Unlock(); } public boolean isInsideTransaction(){ return m_nTransactionCounter>0; } //public static IDBResult createResult(){ // return getInstance().m_dbStorage.createResult(); public static String makeBlobFolderName()throws Exception{ String fName = RhoClassFactory.createFile().getDirPath("db/db-files"); return fName; } RubyString[] getOrigColNames(IDBResult rows) { RubyString[] colNames = new RubyString[rows.getColCount()]; for ( int nCol = 0; nCol < rows.getColCount(); nCol ++ ) colNames[nCol] = ObjectFactory.createString(rows.getOrigColName(nCol)); return colNames; } private String getNameNoExt(String strPath){ int nDot = strPath.lastIndexOf('.'); String strDbName = ""; if ( nDot > 0 ) strDbName = strPath.substring(0, nDot); else strDbName = strPath; return strDbName; } public String getDBPath(){ return getNameNoExt(m_strDBPath); } private void initFilePaths(String strDBName)throws Exception { if ( strDBName.charAt(0) == '/' || strDBName.charAt(0) == '\\' ) strDBName = strDBName.substring(1); int nSlash = strDBName.lastIndexOf('/'); if ( nSlash < 0 ) nSlash = strDBName.lastIndexOf('\\'); String strDBDir = ""; if ( nSlash > 0 ) strDBDir = strDBName.substring(0, nSlash); String strPath = RhoClassFactory.createFile().getDirPath(strDBDir); m_strDBPath = strPath + strDBName.substring(nSlash+1); m_strDBVerPath = strPath + getNameNoExt(strDBName.substring(nSlash+1)) + ".version"; } private String getSqlScript() { return RhoFile.readStringFromJarFile("apps/db/syncdb.schema", this); } public void startTransaction()throws DBException { Lock(); m_nTransactionCounter++; if (m_nTransactionCounter == 1) m_dbStorage.startTransaction(); } public void commit()throws DBException { m_nTransactionCounter if (m_nTransactionCounter == 0) { m_dbStorage.onBeforeCommit(); //getAttrMgr().save(this); m_dbStorage.commit(); } Unlock(); } public void rollback()throws DBException { m_nTransactionCounter if (m_nTransactionCounter == 0) m_dbStorage.rollback(); Unlock(); } public void endTransaction()throws DBException { commit(); } class DBVersion { String m_strRhoVer = ""; String m_strAppVer = ""; DBVersion(){} DBVersion( String strRhoVer, String strAppVer ) { m_strRhoVer = strRhoVer; m_strAppVer = strAppVer; } }; /*private void testError()throws Exception { throw new net.rim.device.api.io.file.FileIOException(net.rim.device.api.io.file.FileIOException.FILESYSTEM_FULL); }*/ DBVersion readDBVersion()throws Exception { String strFullVer = ""; IRAFile file = null; try { file = RhoClassFactory.createRAFile(); try{ file.open(m_strDBVerPath); }catch(j2me.io.FileNotFoundException exc) { //file not exist return new DBVersion(); } byte buf[] = new byte[20]; // testError(); int len = file.read(buf, 0, buf.length); if ( len > 0 ) strFullVer = new String(buf,0,len); if ( strFullVer.length() == 0 ) return new DBVersion(); int nSep = strFullVer.indexOf(';'); if ( nSep == -1 ) return new DBVersion(strFullVer, ""); return new DBVersion(strFullVer.substring(0,nSep), strFullVer.substring(nSep+1) ); } catch (Exception e) { LOG.ERROR("readDBVersion failed.", e); throw e; }finally { if (file!=null) try{ file.close(); }catch(Exception exc){} } } void writeDBVersion(DBVersion ver)throws Exception { IRAFile file = null; try{ file = RhoClassFactory.createRAFile(); file.open(m_strDBVerPath, "rw"); String strFullVer = ver.m_strRhoVer + ";" + ver.m_strAppVer; byte[] buf = strFullVer.getBytes(); file.write(buf, 0, buf.length); }catch (Exception e) { LOG.ERROR("writeDBVersion failed.", e); throw e; }finally { if (file!=null) try{ file.close(); }catch(Exception exc){} } } boolean migrateDB(DBVersion dbVer, String strRhoDBVer, String strAppDBVer ) { LOG.INFO( "Try migrate database from " + (dbVer != null ? dbVer.m_strRhoVer:"") + " to " + (strRhoDBVer !=null ? strRhoDBVer:"") ); if ( dbVer != null && strRhoDBVer != null && (dbVer.m_strRhoVer.startsWith("1.4")||dbVer.m_strRhoVer.startsWith("1.4")) && (strRhoDBVer.startsWith("1.5")||strRhoDBVer.startsWith("1.4")) ) { LOG.INFO( "No migration required from " + (dbVer != null ? dbVer.m_strRhoVer:"") + " to " + (strRhoDBVer !=null ? strRhoDBVer:"") ); try{ writeDBVersion( new DBVersion(strRhoDBVer, strAppDBVer) ); }catch(Exception e) { LOG.ERROR("migrateDB failed.", e); } return true; } //1.2.x -> 1.5.x,1.4.x if ( dbVer != null && strRhoDBVer != null && (dbVer.m_strRhoVer.startsWith("1.2")||dbVer.m_strRhoVer.startsWith("1.4")) && (strRhoDBVer.startsWith("1.5")||strRhoDBVer.startsWith("1.4")) ) { //sources //priority INTEGER, ADD //backend_refresh_time int default 0, ADD LOG.INFO("Migrate database from " + dbVer.m_strRhoVer + " to " + strRhoDBVer); IDBStorage db = null; try{ db = RhoClassFactory.createDBStorage(); db.open( m_strDBPath, getSqlScript() ); db.executeSQL( "ALTER TABLE sources ADD priority INTEGER", null, false); db.executeSQL( "ALTER TABLE sources ADD backend_refresh_time int default 0", null, false); { Vector/*<int>*/ vecSrcIds = new Vector(); IDBResult res2 = db.executeSQL( "SELECT source_id FROM sources", null, false ); for ( ; !res2.isEnd(); res2.next() ) vecSrcIds.addElement( new Integer(res2.getIntByIdx(0)) ); for( int i = 0; i < vecSrcIds.size(); i++) { Object[] values = {vecSrcIds.elementAt(i), vecSrcIds.elementAt(i)}; db.executeSQL( "UPDATE sources SET priority=? where source_id=?", values, false ); } } db.close(); db = null; writeDBVersion( new DBVersion(strRhoDBVer, strAppDBVer) ); return true; }catch(Exception e) { LOG.ERROR("migrateDB failed.", e); if (db!=null) { try{db.close();}catch(DBException exc) { LOG.ERROR("migrateDB : close db after error failed.", e); } db = null; } } } return false; } void checkDBVersion()throws Exception { String strRhoDBVer = RhoSupport.getRhoDBVersion(); String strAppDBVer = RhoConf.getInstance().getString("app_db_version"); DBVersion dbVer = readDBVersion(); boolean bRhoReset = false; boolean bAppReset = false; if ( strRhoDBVer != null && strRhoDBVer.length() > 0 ) { if ( dbVer == null || dbVer.m_strRhoVer == null || !dbVer.m_strRhoVer.equalsIgnoreCase(strRhoDBVer) ) bRhoReset = true; } if ( strAppDBVer != null && strAppDBVer.length() > 0 ) { if ( dbVer == null || dbVer.m_strAppVer == null || !dbVer.m_strAppVer.equalsIgnoreCase(strAppDBVer) ) bAppReset = true; } if ( bRhoReset && !bAppReset ) bRhoReset = !migrateDB(dbVer, strRhoDBVer, strAppDBVer); else if ( Capabilities.USE_SQLITE ) { IFileAccess fs = RhoClassFactory.createFileAccess(); String dbName = getNameNoExt(m_strDBPath); String dbNameScript = dbName + ".script"; String dbNameData = dbName + ".data"; String dbNameJournal = dbName + ".journal"; String dbNameProperties = dbName + ".properties"; if ( fs.exists(dbNameScript) ) { LOG.INFO("Remove hsqldb and use sqlite for Blackberry>=5."); fs.delete(dbNameScript); fs.delete(dbNameData); fs.delete(dbNameJournal); fs.delete(dbNameProperties); bRhoReset = true; } } if ( bRhoReset || bAppReset ) { IDBStorage db = null; try { db = RhoClassFactory.createDBStorage(); if ( db.isDbFileExists(m_strDBPath) ) { db.open( m_strDBPath, "" ); IDBResult res = db.executeSQL("SELECT * FROM client_info", null, false); if ( !res.isOneEnd() ) { m_strClientInfoInsert = createInsertStatement(res, "client_info"); m_dataClientInfo = res.getCurData(); } } }catch(Exception exc) { LOG.ERROR("Copy client_info table failed.", exc); }catch(Throwable e) { LOG.ERROR("Copy client_info table crashed.", e); }finally { if (db != null ) try{ db.close(); }catch(Exception e){} } m_dbStorage.deleteAllFiles(m_strDBPath); String fName = makeBlobFolderName(); RhoClassFactory.createFile().delete(fName); DBAdapter.makeBlobFolderName(); //Create folder back writeDBVersion(new DBVersion(strRhoDBVer, strAppDBVer) ); if ( RhoConf.getInstance().isExist("bulksync_state") && RhoConf.getInstance().getInt("bulksync_state") != 0) RhoConf.getInstance().setInt("bulksync_state", 0, true); } } static Vector m_dbAdapters = new Vector(); public static DBAdapter findDBAdapterByBaseName(String strBaseName) { for ( int i = 0; i < m_dbAdapters.size(); i++ ) { DBAdapter item = (DBAdapter)m_dbAdapters.elementAt(i); FilePath oPath = new FilePath(item.getDBPath()); if ( oPath.getBaseName().compareTo(strBaseName) == 0 ) return item; } return null; } public static void startAllDBTransaction()throws DBException { for ( int i = 0; i < m_dbAdapters.size(); i++ ) { DBAdapter item = (DBAdapter)m_dbAdapters.elementAt(i); item.startTransaction(); } } public static void commitAllDBTransaction()throws DBException { for ( int i = 0; i < m_dbAdapters.size(); i++ ) { DBAdapter item = (DBAdapter)m_dbAdapters.elementAt(i); item.commit(); } } private void openDB(String strDBName, boolean bTemp)throws Exception { if ( m_bIsOpen ) return; initFilePaths(strDBName); if ( !bTemp ) checkDBVersion(); m_dbStorage.open(m_strDBPath, getSqlScript() ); //executeSQL("CREATE INDEX by_src ON object_values (source_id)", null); m_bIsOpen = true; //getAttrMgr().load(this); m_dbStorage.setDbCallback(new DBCallback(this)); m_dbAdapters.addElement(this); //copy client_info table if ( !bTemp && m_strClientInfoInsert != null && m_strClientInfoInsert.length() > 0 && m_dataClientInfo != null ) { LOG.INFO("Copy client_info table from old database"); m_dbStorage.executeSQL(m_strClientInfoInsert, m_dataClientInfo, false ); IDBResult res = executeSQL( "SELECT client_id FROM client_info" ); if ( !res.isOneEnd() && res.getStringByIdx(0).length() > 0 ) { LOG.INFO("Set reset=1 in client_info"); executeSQL( "UPDATE client_info SET reset=1" ); } } } private String createInsertStatement(IDBResult res, String tableName) { String strInsert = "INSERT INTO "; strInsert += tableName; strInsert += "("; String strQuest = ") VALUES("; for (int i = 0; i < res.getColCount(); i++ ) { if ( i > 0 ) { strInsert += ","; strQuest += ","; } strInsert += res.getColName(i); strQuest += "?"; } strInsert += strQuest + ")"; return strInsert; } private boolean destroyTableName(String tableName, Vector arIncludeTables, Vector arExcludeTables ) { int i; for (i = 0; i < (int)arExcludeTables.size(); i++ ) { if ( ((String)arExcludeTables.elementAt(i)).equalsIgnoreCase(tableName) ) return false; } for (i = 0; i < (int)arIncludeTables.size(); i++ ) { if ( ((String)arIncludeTables.elementAt(i)).equalsIgnoreCase(tableName) ) return true; } return arIncludeTables.size()==0; } public boolean isTableExist(String strTableName)throws DBException { return m_dbStorage.isTableExists(strTableName); } private RubyValue rb_destroy_tables(RubyValue vInclude, RubyValue vExclude) { if ( !m_bIsOpen ) return RubyConstant.QNIL; IDBStorage db = null; try{ //getAttrMgr().reset(this); Vector vecIncludes = RhoRuby.makeVectorStringFromArray(vInclude); Vector vecExcludes = RhoRuby.makeVectorStringFromArray(vExclude); String dbName = getNameNoExt(m_strDBPath); String dbNewName = dbName + "new"; IFileAccess fs = RhoClassFactory.createFileAccess(); String dbNameData = dbName + ".data"; String dbNewNameData = dbNewName + ".data"; String dbNameScript = dbName + ".script"; String dbNewNameScript = dbNewName + ".script"; String dbNameJournal = dbName + ".journal"; String dbNameJournal2 = dbName + ".data-journal"; String dbNewNameJournal = dbNewName + ".journal"; String dbNewNameJournal2 = dbNewName + ".data-journal"; String dbNewNameProps = dbNewName + ".properties"; //LOG.TRACE("DBAdapter: " + dbNewNameDate + ": " + (fs.exists(dbNewNameData) ? "" : "not ") + "exists"); fs.delete(dbNewNameData); //LOG.TRACE("DBAdapter: " + dbNewNameScript + ": " + (fs.exists(dbNewNameScript) ? "" : "not ") + "exists"); fs.delete(dbNewNameScript); //LOG.TRACE("DBAdapter: " + dbNewNameJournal + ": " + (fs.exists(dbNewNameJournal) ? "" : "not ") + "exists"); fs.delete(dbNewNameJournal); fs.delete(dbNewNameJournal2); fs.delete(dbNewNameProps); LOG.TRACE("1. Size of " + dbNameData + ": " + fs.size(dbNameData)); db = RhoClassFactory.createDBStorage(); db.open( dbNewName, getSqlScript() ); String[] vecTables = m_dbStorage.getAllTableNames(); //IDBResult res; db.startTransaction(); for ( int i = 0; i< vecTables.length; i++ ) { String tableName = vecTables[i]; if ( destroyTableName( tableName, vecIncludes, vecExcludes ) ) continue; copyTable(tableName, this.m_dbStorage, db ); } db.commit(); db.close(); m_dbStorage.close(); m_dbStorage = null; m_bIsOpen = false; LOG.TRACE("2. Size of " + dbNewNameData + ": " + fs.size(dbNewNameData)); fs.delete(dbNewNameProps); fs.delete(dbNameJournal); fs.delete(dbNameJournal2); String fName = makeBlobFolderName(); RhoClassFactory.createFile().delete(fName); DBAdapter.makeBlobFolderName(); //Create folder back fs.renameOverwrite(dbNewNameData, dbNameData); if ( !Capabilities.USE_SQLITE ) fs.renameOverwrite(dbNewNameScript, dbNameScript); LOG.TRACE("3. Size of " + dbNameData + ": " + fs.size(dbNameData)); m_dbStorage = RhoClassFactory.createDBStorage(); m_dbStorage.open(m_strDBPath, getSqlScript() ); m_bIsOpen = true; //getAttrMgr().load(this); m_dbStorage.setDbCallback(new DBCallback(this)); }catch(Exception e) { LOG.ERROR("execute failed.", e); if ( !m_bIsOpen ) { LOG.ERROR("destroy_table error.Try to open old DB."); try{ m_dbStorage.open(m_strDBPath, getSqlScript() ); m_bIsOpen = true; }catch(Exception exc) { LOG.ERROR("destroy_table open old table failed.", exc); } } try { if ( db != null) db.close(); } catch (DBException e1) { LOG.ERROR("closing of DB caused exception: " + e1.getMessage()); } throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } return RubyConstant.QNIL; } private void copyTable(String tableName, IDBStorage dbFrom, IDBStorage dbTo)throws DBException { IDBResult res = dbFrom.executeSQL("SELECT * from " + tableName, null, false); String strInsert = ""; for ( ; !res.isEnd(); res.next() ) { if ( strInsert.length() == 0 ) strInsert = createInsertStatement(res, tableName); dbTo.executeSQL(strInsert, res.getCurData(), false ); } } public void updateAllAttribChanges()throws DBException { //Check for attrib = object IDBResult res = executeSQL("SELECT object, source_id, update_type " + "FROM changed_values where attrib = 'object' and sent=0" ); if ( res.isEnd() ) return; startTransaction(); Vector/*<String>*/ arObj = new Vector(), arUpdateType = new Vector(); Vector/*<int>*/ arSrcID = new Vector(); for( ; !res.isEnd(); res.next() ) { arObj.addElement(res.getStringByIdx(0)); arSrcID.addElement(new Integer(res.getIntByIdx(1))); arUpdateType.addElement(res.getStringByIdx(2)); } for( int i = 0; i < (int)arObj.size(); i++ ) { IDBResult resSrc = executeSQL("SELECT name, schema FROM sources where source_id=?", arSrcID.elementAt(i) ); boolean bSchemaSource = false; String strTableName = "object_values"; if ( !resSrc.isOneEnd() ) { bSchemaSource = resSrc.getStringByIdx(1).length() > 0; if ( bSchemaSource ) strTableName = resSrc.getStringByIdx(0); } if (bSchemaSource) { IDBResult res2 = executeSQL( "SELECT * FROM " + strTableName + " where object=?", arObj.elementAt(i) ); for( int j = 0; j < res2.getColCount(); j ++) { String strAttrib = res2.getColName(j); String value = res2.getStringByIdx(j); String attribType = getAttrMgr().isBlobAttr((Integer)arSrcID.elementAt(i), strAttrib) ? "blob.file" : ""; executeSQLReportNonUnique("INSERT INTO changed_values (source_id,object,attrib,value,update_type,attrib_type,sent) VALUES(?,?,?,?,?,?,?)", arSrcID.elementAt(i), arObj.elementAt(i), strAttrib, value, arUpdateType.elementAt(i), attribType, new Integer(0) ); } }else { IDBResult res2 = executeSQL( "SELECT attrib, value FROM " + strTableName + " where object=? and source_id=?", arObj.elementAt(i), arSrcID.elementAt(i) ); for( ; !res2.isEnd(); res2.next() ) { String strAttrib = res2.getStringByIdx(0); String value = res2.getStringByIdx(1); String attribType = getAttrMgr().isBlobAttr((Integer)arSrcID.elementAt(i), strAttrib) ? "blob.file" : ""; executeSQLReportNonUnique("INSERT INTO changed_values (source_id,object,attrib,value,update_type,attrib_type,sent) VALUES(?,?,?,?,?,?,?)", arSrcID.elementAt(i), arObj.elementAt(i), strAttrib, value, arUpdateType.elementAt(i), attribType, new Integer(0) ); } } } executeSQL("DELETE FROM changed_values WHERE attrib='object'"); endTransaction(); } void copyChangedValues(DBAdapter db)throws DBException { updateAllAttribChanges(); copyTable("changed_values", m_dbStorage, db.m_dbStorage ); { Vector/*<int>*/ arOldSrcs = new Vector(); { IDBResult resSrc = db.executeSQL( "SELECT DISTINCT(source_id) FROM changed_values" ); for ( ; !resSrc.isEnd(); resSrc.next() ) arOldSrcs.addElement( new Integer(resSrc.getIntByIdx(0)) ); } for( int i = 0; i < arOldSrcs.size(); i++) { int nOldSrcID = ((Integer)arOldSrcs.elementAt(i)).intValue(); IDBResult res = executeSQL("SELECT name from sources WHERE source_id=?", nOldSrcID); if ( !res.isOneEnd() ) { String strSrcName = res.getStringByIdx(0); IDBResult res2 = db.executeSQL("SELECT source_id from sources WHERE name=?", strSrcName ); if ( !res2.isOneEnd() ) { if ( nOldSrcID != res2.getIntByIdx(0) ) { db.executeSQL("UPDATE changed_values SET source_id=? WHERE source_id=?", res2.getIntByIdx(0), nOldSrcID); } continue; } } //source not exist in new partition, remove this changes db.executeSQL("DELETE FROM changed_values WHERE source_id=?", nOldSrcID); } } } public void setBulkSyncDB(String fDbName, String fScriptName) { DBAdapter db = null; try{ db = (DBAdapter)alloc(null); db.openDB(fDbName, true); db.m_dbStorage.createTriggers(); db.setDbPartition(m_strDbPartition); db.startTransaction(); copyTable("client_info", m_dbStorage, db.m_dbStorage ); copyChangedValues(db); /* //update User partition if ( m_strDbPartition.compareTo(USER_PARTITION_NAME()) == 0 ) { //copy all NOT user sources from current db to bulk db startTransaction(); executeSQL("DELETE FROM sources WHERE partition=?", m_strDbPartition); copyTable("sources", m_dbStorage, db.m_dbStorage ); rollback(); }else { //remove all m_strDbPartition sources from user db //copy all sources from bulk db to user db DBAdapter dbUser = getDB(USER_PARTITION_NAME()); dbUser.startTransaction(); dbUser.executeSQL("DELETE FROM sources WHERE partition=?", m_strDbPartition); copyTable("sources", db.m_dbStorage, dbUser.m_dbStorage ); dbUser.endTransaction(); }*/ getDBPartitions().put(m_strDbPartition, db); com.rho.sync.SyncThread.getSyncEngine().applyChangedValues(db); getDBPartitions().put(m_strDbPartition, this); db.endTransaction(); db.close(); m_dbStorage.close(); m_dbStorage = null; m_bIsOpen = false; String dbName = getNameNoExt(m_strDBPath); IFileAccess fs = RhoClassFactory.createFileAccess(); String dbNameData = dbName + ".data"; String dbNameScript = dbName + ".script"; String dbNameJournal = dbName + ".journal"; String dbNameJournal2 = dbName + ".data-journal"; String dbNewNameProps = getNameNoExt(fDbName) + ".properties"; fs.delete(dbNameJournal); fs.delete(dbNameJournal2); fs.delete(dbNewNameProps); String fName = makeBlobFolderName(); RhoClassFactory.createFile().delete(fName); DBAdapter.makeBlobFolderName(); //Create folder back fs.renameOverwrite(fDbName, dbNameData); if ( !Capabilities.USE_SQLITE ) fs.renameOverwrite(fScriptName, dbNameScript); m_dbStorage = RhoClassFactory.createDBStorage(); m_dbStorage.open(m_strDBPath, getSqlScript() ); m_bIsOpen = true; //getAttrMgr().load(this); m_dbStorage.setDbCallback(new DBCallback(this)); }catch(Exception e) { LOG.ERROR("execute failed.", e); if ( !m_bIsOpen ) { LOG.ERROR("destroy_table error.Try to open old DB."); try{ m_dbStorage.open(m_strDBPath, getSqlScript() ); m_bIsOpen = true; }catch(Exception exc) { LOG.ERROR("destroy_table open old table failed.", exc); } } if ( db != null) db.close(); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } } /* public RubyValue rb_execute(RubyValue v) { RubyArray res = new RubyArray(); try{ IDBResult rows = executeSQL(v.toStr(), null); RubyString[] colNames = getColNames(rows); for( ; !rows.isEnd(); rows.next() ) { RubyHash row = ObjectFactory.createHash(); for ( int nCol = 0; nCol < rows.getColCount(); nCol ++ ) row.add( colNames[nCol], rows.getRubyValueByIdx(nCol) ); res.add( row ); } }catch(Exception e) { LOG.ERROR("execute failed.", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } return res; }*/ public RubyValue rb_execute(RubyValue v, RubyValue batch, RubyValue arg) { RubyArray res = new RubyArray(); try{ String strSql = v.toStr(); if ( batch == RubyConstant.QTRUE ) { //LOG.INFO("batch execute:" + strSql); executeBatchSQL( strSql ); } else { Object[] values = null; if ( arg != null ) { RubyArray args1 = arg.toAry(); RubyArray args = args1; if ( args.size() > 0 && args.get(0) instanceof RubyArray ) args = (RubyArray)args.get(0); values = new Object[args.size()]; for ( int i = 0; i < args.size(); i++ ) { RubyValue val = args.get(i); if ( val == RubyConstant.QNIL ) values[i] = null; else if ( val instanceof RubyInteger ) values[i] = new Long( ((RubyInteger)val).toLong() ); else if ( val instanceof RubyFloat ) values[i] = new Double( ((RubyFloat)val).toFloat() ); else if ( val instanceof RubyString ) values[i] = new String( ((RubyString)val).toStr() ); else if ( val == RubyConstant.QTRUE ) values[i] = new String( "true" ); else if ( val == RubyConstant.QFALSE ) values[i] = new String( "false" ); else values[i] = val.toStr(); } } IDBResult rows = executeSQL( strSql, values); RubyString[] colNames = null; for( ; !rows.isEnd(); rows.next() ) { RubyHash row = ObjectFactory.createHash(); for ( int nCol = 0; nCol < rows.getColCount(); nCol ++ ) { if ( colNames == null ) colNames = getOrigColNames(rows); row.add( colNames[nCol], rows.getRubyValueByIdx(nCol) ); } res.add( row ); } } }catch(Exception e) { LOG.ERROR("execute failed.", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } return res; } //@RubyAllocMethod private static RubyValue alloc(RubyValue receiver) { return new DBAdapter((RubyClass) receiver); } public static void closeAll() { Enumeration enumDBs = m_mapDBPartitions.elements(); while (enumDBs.hasMoreElements()) { DBAdapter db = (DBAdapter)enumDBs.nextElement(); db.close(); } } public static void initAttrManager()throws DBException { Enumeration enumDBs = m_mapDBPartitions.elements(); while (enumDBs.hasMoreElements()) { DBAdapter db = (DBAdapter)enumDBs.nextElement(); db.getAttrMgr().loadBlobAttrs(db); if ( !db.getAttrMgr().hasBlobAttrs() ) db.m_dbStorage.setDbCallback(null); } } public static DBAdapter getUserDB() { return (DBAdapter)getDBPartitions().get(USER_PARTITION_NAME()); } public static DBAdapter getDB(String szPartition) { return (DBAdapter)getDBPartitions().get(szPartition); } public static Vector/*<String>*/ getDBAllPartitionNames() { Vector/*<String>*/ vecNames = new Vector(); Enumeration enumDBs = m_mapDBPartitions.keys(); while (enumDBs.hasMoreElements()) { vecNames.addElement(enumDBs.nextElement()); } return vecNames; } public static boolean isAnyInsideTransaction() { Enumeration enumDBs = m_mapDBPartitions.elements(); while (enumDBs.hasMoreElements()) { DBAdapter db = (DBAdapter)enumDBs.nextElement(); if ( db.isInsideTransaction() ) return true; } return false; } public static void initMethods(RubyClass klass) { klass.defineAllocMethod(new RubyNoArgMethod(){ protected RubyValue run(RubyValue receiver, RubyBlock block ) { return DBAdapter.alloc(receiver);} }); klass.defineMethod( "initialize", new RubyTwoArgMethod() { protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyValue arg2, RubyBlock block ) { try { String szDbName = arg1.toStr(); String szDbPartition = arg2.toStr(); ((DBAdapter)receiver).openDB(szDbName, false); ((DBAdapter)receiver).setDbPartition(szDbPartition); DBAdapter.getDBPartitions().put(szDbPartition, receiver); return receiver; }catch(Exception e) { LOG.ERROR("initialize failed.", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } } }); /*klass.defineMethod( "close", new RubyNoArgMethod(){ protected RubyValue run(RubyValue receiver, RubyBlock block ){ return ((DBAdapter)receiver).rb_close();} });*/ klass.defineMethod( "execute", new RubyVarArgMethod(){ protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block ){ return ((DBAdapter)receiver).rb_execute(args.get(0), args.get(1), (args.size() > 2 ? args.get(2):null));} }); klass.defineMethod( "start_transaction", new RubyNoArgMethod(){ protected RubyValue run(RubyValue receiver, RubyBlock block ) { try{ ((DBAdapter)receiver).startTransaction(); return ObjectFactory.createInteger(0); }catch( Exception e ){ LOG.ERROR("start_transaction failed.", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } } }); klass.defineMethod( "commit", new RubyNoArgMethod(){ protected RubyValue run(RubyValue receiver, RubyBlock block ) { try{ ((DBAdapter)receiver).commit(); return ObjectFactory.createInteger(0); }catch( Exception e ){ LOG.ERROR("commit failed.", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } } }); klass.defineMethod( "rollback", new RubyNoArgMethod(){ protected RubyValue run(RubyValue receiver, RubyBlock block ) { try{ ((DBAdapter)receiver).rollback(); return ObjectFactory.createInteger(0); }catch( Exception e ){ LOG.ERROR("rollback failed.", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } } }); klass.defineMethod( "destroy_tables", new RubyTwoArgMethod(){ protected RubyValue run(RubyValue receiver, RubyValue arg, RubyValue arg1, RubyBlock block ){ return ((DBAdapter)receiver).rb_destroy_tables(arg, arg1);} }); klass.defineMethod("is_ui_waitfordb", new RubyNoArgMethod() { protected RubyValue run(RubyValue receiver, RubyBlock block) { try{ boolean bRes = ((DBAdapter)receiver).isUIWaitDB(); return ObjectFactory.createBoolean(bRes); }catch(Exception e) { LOG.ERROR("is_ui_waitfordb failed", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } } }); klass.defineMethod("lock_db", new RubyNoArgMethod() { protected RubyValue run(RubyValue receiver, RubyBlock block) { try{ DBAdapter db = (DBAdapter)receiver; //db.setUnlockDB(true); db.Lock(); }catch(Exception e) { LOG.ERROR("lock_db failed", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } return RubyConstant.QNIL; } }); klass.defineMethod("unlock_db", new RubyNoArgMethod() { protected RubyValue run(RubyValue receiver, RubyBlock block) { try{ DBAdapter db = (DBAdapter)receiver; db.Unlock(); }catch(Exception e) { LOG.ERROR("unlock_db failed", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } return RubyConstant.QNIL; } }); klass.defineMethod( "table_exist?", new RubyOneArgMethod(){ protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block ) { try{ DBAdapter db = (DBAdapter)receiver; boolean bExists = db.isTableExist(arg.toStr()); return ObjectFactory.createBoolean(bExists); }catch(Exception e) { LOG.ERROR("unlock_db failed", e); throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage())); } } }); } public static class DBCallback implements IDBCallback { private DBAdapter m_db; DBCallback(DBAdapter db){ m_db = db; } /*public void OnDeleteAll() { OnDeleteAllFromTable("object_values"); } public void OnDeleteAllFromTable(String tableName) { if ( !tableName.equals("object_values") ) return; try{ String fName = DBAdapter.makeBlobFolderName(); RhoClassFactory.createFile().delete(fName); DBAdapter.makeBlobFolderName(); //Create folder back }catch(Exception exc){ LOG.ERROR("DBCallback.OnDeleteAllFromTable: Error delete files from table: " + tableName, exc); } }*/ /* public void onAfterInsert(String tableName, IDBResult rows2Insert) { try { if ( !tableName.equalsIgnoreCase("object_values") ) return; for( ; !rows2Insert.isEnd(); rows2Insert.next() ) { //Object[] data = rows2Insert.getCurData(); Integer nSrcID = new Integer(rows2Insert.getIntByIdx(0)); String attrib = rows2Insert.getStringByIdx(1); m_db.getAttrMgr().add(nSrcID, attrib); } }catch(DBException exc) { LOG.ERROR("onAfterInsert failed.", exc); } }*/ public void onBeforeUpdate(String tableName, IDBResult rows2Delete, int[] cols) { try { processDelete(tableName, rows2Delete, cols); }catch(DBException exc) { LOG.ERROR("onAfterInsert failed.", exc); } } public void onBeforeDelete(String tableName, IDBResult rows2Delete) { try { processDelete(tableName, rows2Delete, null); }catch(DBException exc) { LOG.ERROR("onAfterInsert failed.", exc); } } private boolean isChangedCol(int[] cols, int iCol) { if (cols==null) return true; for ( int i = 0; i < cols.length; i++ ) { if ( cols[i] == iCol ) return true; } return false; } private void processDelete(String tableName, IDBResult rows2Delete, int[] cols) throws DBException { if ( tableName.equalsIgnoreCase("changed_values") || tableName.equalsIgnoreCase("sources") || tableName.equalsIgnoreCase("client_info")) return; boolean bProcessTable = tableName.equalsIgnoreCase("object_values"); boolean bSchemaSrc = false; Integer nSrcID = null; if ( !bProcessTable ) { nSrcID = m_db.getAttrMgr().getSrcIDHasBlobsByName(tableName); bProcessTable = nSrcID != null; bSchemaSrc = bProcessTable; } if ( !bProcessTable) return; if ( !bSchemaSrc && !isChangedCol(cols, 3))//value return; for( ; !rows2Delete.isEnd(); rows2Delete.next() ) { if ( !bSchemaSrc ) { nSrcID = new Integer(rows2Delete.getIntByIdx(0)); String attrib = rows2Delete.getStringByIdx(1); String value = rows2Delete.getStringByIdx(3); //if (cols == null) //delete // m_db.getAttrMgr().remove(nSrcID, attrib); if ( m_db.getAttrMgr().isBlobAttr(nSrcID, attrib) ) processBlobDelete(nSrcID, attrib, value); }else { Object[] data = rows2Delete.getCurData(); for ( int i = 0; i < rows2Delete.getColCount(); i++ ) { if (!isChangedCol(cols, i)) continue; String attrib = rows2Delete.getColName(i); if ( !(data[i] instanceof String) ) continue; String value = (String)data[i]; if ( m_db.getAttrMgr().isBlobAttr(nSrcID, attrib) ) processBlobDelete(nSrcID, attrib, value); } } } } private void processBlobDelete(Integer nSrcID, String attrib, String value) { if ( value == null || value.length() == 0 ) return; try{ String strFilePath = RhodesApp.getInstance().resolveDBFilesPath(value); SimpleFile oFile = RhoClassFactory.createFile(); oFile.delete(strFilePath); }catch(Exception exc){ LOG.ERROR("DBCallback.OnDeleteFromTable: Error delete file: " + value, exc); } } } }
package oap.util; import lombok.EqualsAndHashCode; import lombok.ToString; import oap.util.function.Try; import java.io.Serializable; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; @EqualsAndHashCode @ToString public final class Result<S, F> implements Serializable { public final S successValue; public final F failureValue; private final boolean success; Result( S successValue, F failureValue, boolean success ) { this.successValue = successValue; this.failureValue = failureValue; this.success = success; } public static <S, F> Result<S, F> success( S value ) { return new Result<>( value, null, true ); } public static <S, F> Result<S, F> failure( F value ) { return new Result<>( null, value, false ); } public static <S> Result<S, Throwable> catching( Try.ThrowingSupplier<S> supplier ) { try { return success( supplier.get() ); } catch( Throwable e ) { return failure( e ); } } @Deprecated( forRemoval = true ) public static <S> Result<S, Throwable> trying( oap.util.Try.ThrowingSupplier<S> supplier ) { return catching( supplier::get ); } /** * @see #catchingInterruptible(Try.ThrowingSupplier) * reason: "blocking" is not actual semantics but usecase */ @Deprecated public static <S> Result<S, Throwable> blockingTrying( oap.util.Try.ThrowingSupplier<S> supplier ) throws InterruptedException { return tryingInterruptible( supplier ); } @Deprecated public static <S> Result<S, Throwable> tryingInterruptible( oap.util.Try.ThrowingSupplier<S> supplier ) throws InterruptedException { return catchingInterruptible( supplier::get ); } public static <S> Result<S, Throwable> catchingInterruptible( Try.ThrowingSupplier<S> supplier ) throws InterruptedException { try { return success( supplier.get() ); } catch( InterruptedException e ) { throw e; } catch( Throwable e ) { return failure( e ); } } public <NS, NF> Result<NS, NF> map( Function<S, Result<NS, NF>> onSuccess, Function<F, Result<NS, NF>> onFailure ) { if( success ) return onSuccess.apply( successValue ); else return onFailure.apply( failureValue ); } public Optional<Result<S, F>> filter( Predicate<S> predicate ) { return success && predicate.test( successValue ) ? Optional.of( this ) : Optional.empty(); } public <R> Result<R, F> mapSuccess( Function<? super S, ? extends R> mapper ) { return success ? success( mapper.apply( successValue ) ) : failure( failureValue ); } public <F2> Result<S, F2> mapFailure( Function<? super F, ? extends F2> mapper ) { return success ? success( successValue ) : failure( mapper.apply( failureValue ) ); } public boolean isSuccess() { return success; } public Result<S, F> ifSuccess( Consumer<S> consumer ) { if( success ) consumer.accept( successValue ); return this; } public Result<S, F> ifFailure( Consumer<F> consumer ) { if( !success ) consumer.accept( failureValue ); return this; } public void ifSuccessOrElse( Consumer<S> onSuccess, Consumer<F> onFailure ) { ifSuccess( onSuccess ).ifFailure( onFailure ); } public S getSuccessValue() { return successValue; } public F getFailureValue() { return failureValue; } public Optional<S> toOptional() { return isSuccess() ? Optional.of( successValue ) : Optional.empty(); } public <X extends Throwable> S orElseThrow( Function<F, ? extends X> f ) throws X { if( success ) return successValue; else throw f.apply( failureValue ); } public S orElse( S value ) { return success ? successValue : value; } }
package org.eigenbase.javac; import net.janino.*; import org.eigenbase.util.*; import java.io.*; public class JaninoCompiler implements JavaCompiler { private JaninoCompilerArgs args = new JaninoCompilerArgs(); // REVIEW jvs 28-June-2004: pool this instance? Is it thread-safe? private JavaSourceClassLoader classLoader; public JaninoCompiler() { args = new JaninoCompilerArgs(); } // implement JavaCompiler public void compile() { // REVIEW jvs 29-Sept-2004: we used to delegate to // ClassLoader.getSystemClassLoader(), but for some reason that didn't // work when run from ant's junit task without forking. Should // probably take it as a parameter, but how should we decide what to // use? // TODO jvs 10-Nov-2004: provide a means to request // DebuggingInformation.ALL assert(args.destdir != null); assert(args.fullClassName != null); // TODO jvs 28-June-2004: with some glue code, we could probably get // Janino to compile directly from the generated string source instead // of from a file. (It's possible to do that with the SimpleCompiler // class, but then we don't avoid the bytecode storage.) classLoader = new JavaSourceClassLoader( getClass().getClassLoader(), new File[] { new File(args.destdir) }, null, DebuggingInformation.NONE); try { classLoader.loadClass(args.fullClassName); } catch (ClassNotFoundException ex) { throw Util.newInternal(ex, "while compiling " + args.fullClassName); } } // implement JavaCompiler public JavaCompilerArgs getArgs() { return args; } // implement JavaCompiler public ClassLoader getClassLoader() { return classLoader; } private static class JaninoCompilerArgs extends JavaCompilerArgs { String destdir; String fullClassName; public JaninoCompilerArgs() { } public void setDestdir(String destdir) { super.setDestdir(destdir); this.destdir = destdir; } // NOTE jvs 28-June-2004: these go along with TODO above /* String source; public void setSource(String source, String fileName) { this.source = source; addFile(fileName); } */ public void setFullClassName(String fullClassName) { this.fullClassName = fullClassName; } } } // End JaninoCompiler.java
package cpw.mods.fml.common; import java.io.File; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import com.google.common.base.Function; import com.google.common.base.Strings; import com.google.common.base.Throwables; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.Mod.Metadata; import cpw.mods.fml.common.discovery.ASMDataTable; import cpw.mods.fml.common.discovery.ASMDataTable.ASMData; import cpw.mods.fml.common.event.FMLConstructionEvent; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartedEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.event.FMLServerStoppingEvent; import cpw.mods.fml.common.event.FMLStateEvent; import cpw.mods.fml.common.network.FMLNetworkHandler; import cpw.mods.fml.common.versioning.ArtifactVersion; import cpw.mods.fml.common.versioning.DefaultArtifactVersion; public class FMLModContainer implements ModContainer { private Mod modDescriptor; private Object modInstance; private File source; private ModMetadata modMetadata; private String className; private Map<String, Object> descriptor; private boolean enabled = true; private String internalVersion; private boolean overridesMetadata; private EventBus eventBus; private LoadController controller; private Multimap<Class<? extends Annotation>, Object> annotations; private DefaultArtifactVersion processedVersion; private boolean isNetworkMod; private static final BiMap<Class<? extends FMLStateEvent>, Class<? extends Annotation>> modAnnotationTypes = ImmutableBiMap.<Class<? extends FMLStateEvent>, Class<? extends Annotation>>builder() .put(FMLPreInitializationEvent.class, Mod.PreInit.class) .put(FMLInitializationEvent.class, Mod.Init.class) .put(FMLPostInitializationEvent.class, Mod.PostInit.class) .put(FMLServerStartingEvent.class, Mod.ServerStarting.class) .put(FMLServerStartedEvent.class, Mod.ServerStarted.class) .put(FMLServerStoppingEvent.class, Mod.ServerStopping.class) .build(); private static final BiMap<Class<? extends Annotation>, Class<? extends FMLStateEvent>> modTypeAnnotations = modAnnotationTypes.inverse(); private String annotationDependencies; public FMLModContainer(String className, File modSource, Map<String,Object> modDescriptor) { this.className = className; this.source = modSource; this.descriptor = modDescriptor; } @Override public String getModId() { return (String) descriptor.get("modid"); } @Override public String getName() { return modMetadata.name; } @Override public String getVersion() { return internalVersion; } @Override public File getSource() { return source; } @Override public ModMetadata getMetadata() { return modMetadata; } @Override public void bindMetadata(MetadataCollection mc) { modMetadata = mc.getMetadataForId(getModId(), descriptor); if (descriptor.containsKey("usesMetadata")) { overridesMetadata = !((Boolean)descriptor.get("usesMetadata")).booleanValue(); } if (overridesMetadata || !modMetadata.useDependencyInformation) { Set<ArtifactVersion> requirements = Sets.newHashSet(); List<ArtifactVersion> dependencies = Lists.newArrayList(); List<ArtifactVersion> dependants = Lists.newArrayList(); annotationDependencies = (String) descriptor.get("dependencies"); Loader.instance().computeDependencies(annotationDependencies, requirements, dependencies, dependants); modMetadata.requiredMods = requirements; modMetadata.dependencies = dependencies; modMetadata.dependants = dependants; FMLLog.finest("Parsed dependency info : %s %s %s", requirements, dependencies, dependants); } else { FMLLog.finest("Using mcmod dependency info : %s %s %s", modMetadata.requiredMods, modMetadata.dependencies, modMetadata.dependants); } if (Strings.isNullOrEmpty(modMetadata.name)) { FMLLog.info("Mod %s is missing the required element 'name'. Substituting %s", getModId(), getModId()); modMetadata.name = getModId(); } internalVersion = (String) descriptor.get("version"); if (Strings.isNullOrEmpty(internalVersion) && !Strings.isNullOrEmpty(modMetadata.version)) { FMLLog.warning("Mod %s is missing the required element 'version'. Falling back to metadata version %s", getModId(), modMetadata.version); modMetadata.version = internalVersion; } if (Strings.isNullOrEmpty(internalVersion)) { FMLLog.warning("Mod %s is missing the required element 'version' and no fallback can be found. Substituting '1.0'.", getModId()); modMetadata.version = internalVersion = "1.0"; } } @Override public void setEnabledState(boolean enabled) { this.enabled = enabled; } @Override public Set<ArtifactVersion> getRequirements() { return modMetadata.requiredMods; } @Override public List<ArtifactVersion> getDependencies() { return modMetadata.dependencies; } @Override public List<ArtifactVersion> getDependants() { return modMetadata.dependants; } @Override public String getSortingRules() { return ((overridesMetadata || !modMetadata.useDependencyInformation) ? Strings.nullToEmpty(annotationDependencies) : modMetadata.printableSortingRules()); } @Override public boolean matches(Object mod) { return mod == modInstance; } @Override public Object getMod() { return modInstance; } @Override public boolean registerBus(EventBus bus, LoadController controller) { if (this.enabled) { FMLLog.fine("Enabling mod %s", getModId()); this.eventBus = bus; this.controller = controller; eventBus.register(this); return true; } else { return false; } } private Multimap<Class<? extends Annotation>, Object> gatherAnnotations(Class<?> clazz) throws Exception { Multimap<Class<? extends Annotation>,Object> anns = ArrayListMultimap.create(); for (Method m : clazz.getDeclaredMethods()) { for (Annotation a : m.getAnnotations()) { if (modTypeAnnotations.containsKey(a.annotationType())) { Class<?>[] paramTypes = new Class[] { modTypeAnnotations.get(a.annotationType()) }; if (Arrays.equals(m.getParameterTypes(), paramTypes)) { m.setAccessible(true); anns.put(a.annotationType(), m); } else { FMLLog.severe("The mod %s appears to have an invalid method annotation %s. This annotation can only apply to methods with argument types %s -it will not be called", getModId(), a.annotationType().getSimpleName(), Arrays.toString(paramTypes)); } } } } return anns; } private void processFieldAnnotations(ASMDataTable asmDataTable) throws Exception { SetMultimap<String, ASMData> annotations = asmDataTable.getAnnotationsFor(this); parseSimpleFieldAnnotation(annotations, Instance.class.getName(), new Function<ModContainer, Object>() { public Object apply(ModContainer mc) { return mc.getMod(); } }); parseSimpleFieldAnnotation(annotations, Metadata.class.getName(), new Function<ModContainer, Object>() { public Object apply(ModContainer mc) { return mc.getMetadata(); } }); //TODO // for (Object o : annotations.get(Block.class)) // Field f = (Field) o; // f.set(modInstance, GameRegistry.buildBlock(this, f.getType(), f.getAnnotation(Block.class))); } private void parseSimpleFieldAnnotation(SetMultimap<String, ASMData> annotations, String annotationClassName, Function<ModContainer, Object> retreiver) throws IllegalAccessException { String[] annName = annotationClassName.split("\\."); String annotationName = annName[annName.length - 1]; for (ASMData targets : annotations.get(annotationClassName)) { String targetMod = (String) targets.getAnnotationInfo().get("value"); Field f = null; Object injectedMod = null; ModContainer mc = this; boolean isStatic = false; Class<?> clz = modInstance.getClass(); if (!Strings.isNullOrEmpty(targetMod)) { if (Loader.isModLoaded(targetMod)) { mc = Loader.instance().getIndexedModList().get(targetMod); } else { mc = null; } } if (mc != null) { try { clz = Class.forName(targets.getClassName(), true, Loader.instance().getModClassLoader()); f = clz.getDeclaredField(targets.getObjectName()); f.setAccessible(true); isStatic = Modifier.isStatic(f.getModifiers()); injectedMod = retreiver.apply(mc); } catch (Exception e) { Throwables.propagateIfPossible(e); FMLLog.log(Level.WARNING, e, "Attempting to load @%s in class %s for %s and failing", annotationName, targets.getClassName(), mc.getModId()); } } if (f != null) { Object target = null; if (!isStatic) { target = modInstance; if (!modInstance.getClass().equals(clz)) { FMLLog.warning("Unable to inject @%s in non-static field %s.%s for %s as it is NOT the primary mod instance", annotationName, targets.getClassName(), targets.getObjectName(), mc.getModId()); continue; } } f.set(target, injectedMod); } } } @Subscribe public void constructMod(FMLConstructionEvent event) { try { ModClassLoader modClassLoader = event.getModClassLoader(); modClassLoader.addFile(source); Class<?> clazz = Class.forName(className, true, modClassLoader); ASMDataTable asmHarvestedAnnotations = event.getASMHarvestedData(); // TODO asmHarvestedAnnotations.getAnnotationsFor(this); annotations = gatherAnnotations(clazz); isNetworkMod = FMLNetworkHandler.instance().registerNetworkMod(this, clazz, event.getASMHarvestedData()); modInstance = clazz.newInstance(); ProxyInjector.inject(this, event.getASMHarvestedData(), FMLCommonHandler.instance().getSide()); processFieldAnnotations(event.getASMHarvestedData()); } catch (Throwable e) { controller.errorOccurred(this, e); Throwables.propagateIfPossible(e); } } @Subscribe public void handleModStateEvent(FMLStateEvent event) { Class<? extends Annotation> annotation = modAnnotationTypes.get(event.getClass()); if (annotation == null) { return; } try { for (Object o : annotations.get(annotation)) { Method m = (Method) o; m.invoke(modInstance, event); } } catch (Throwable t) { controller.errorOccurred(this, t); Throwables.propagateIfPossible(t); } } @Override public ArtifactVersion getProcessedVersion() { if (processedVersion == null) { processedVersion = new DefaultArtifactVersion(getModId(), getVersion()); } return processedVersion; } @Override public boolean isImmutable() { return false; } @Override public boolean isNetworkMod() { return isNetworkMod; } @Override public String getDisplayVersion() { return modMetadata.version; } }
package ifc.configuration.backend; import com.sun.star.configuration.backend.XLayer; import lib.MultiMethodTest; import util.XLayerHandlerImpl; public class _XLayer extends MultiMethodTest { public XLayer oObj; public void _readData() { boolean res = false; log.println("Checking for Exception in case of nul argument"); try { oObj.readData(null); } catch (com.sun.star.lang.NullPointerException e) { log.println("Expected Exception res = true; } catch (com.sun.star.lang.WrappedTargetException e) { log.println("Unexpected Exception ("+e+") -- FAILED"); } catch (com.sun.star.configuration.backend.MalformedDataException e) { log.println("Unexpected Exception ("+e+") -- FAILED"); } log.println("checking read data with own XLayerHandler implementation"); try { XLayerHandlerImpl xLayerHandler = new XLayerHandlerImpl(); oObj.readData(xLayerHandler); String implCalled = xLayerHandler.getCalls(); log.println(implCalled); int sl = implCalled.indexOf("startLayer"); if (sl < 0) { log.println("startLayer wasn't called -- FAILED"); res &= false; } else { log.println("startLayer was called res &= true; } int el = implCalled.indexOf("endLayer"); if (el < 0) { log.println("endLayer wasn't called -- FAILED"); res &= false; } else { log.println("endLayer was called res &= true; } } catch (com.sun.star.lang.NullPointerException e) { log.println("Unexpected Exception ("+e+") -- FAILED"); res &= false; } catch (com.sun.star.lang.WrappedTargetException e) { log.println("Unexpected Exception ("+e+") -- FAILED"); res &= false; } catch (com.sun.star.configuration.backend.MalformedDataException e) { log.println("Unexpected Exception ("+e+") -- FAILED"); res &= false; } tRes.tested("readData()",res); } }
package railo.commons.io; import java.io.IOException; import java.io.InputStream; import railo.commons.io.res.Resource; import railo.commons.lang.StringUtil; public class FileRotation { public static void checkFile(Resource res, long maxFileSize, int maxFiles, byte[] header) throws IOException { boolean writeHeader=false; // create file if(!res.exists()) { res.createFile(true); writeHeader=true; } else if(res.length()==0) { writeHeader=true; } // create new file else if(res.length()>maxFileSize) { Resource parent = res.getParentResource(); String name = res.getName(); int lenMaxFileSize=(""+maxFiles).length(); for(int i=maxFiles;i>0;i Resource to=parent.getRealResource(name+"."+StringUtil.addZeros(i, lenMaxFileSize)+".bak"); Resource from=parent.getRealResource(name+"."+StringUtil.addZeros(i-1,lenMaxFileSize)+".bak"); if(from.exists()) { if(to.exists())to.delete(); from.renameTo(to); } } res.renameTo(parent.getRealResource(name+"."+StringUtil.addZeros(1,lenMaxFileSize)+".bak")); res=parent.getRealResource(name);//new File(parent,name); res.createNewFile(); writeHeader=true; } else if(header!=null && header.length>0) { byte[] buffer = new byte[header.length]; int len; InputStream in = null; try{ in = res.getInputStream(); boolean headerOK = true; len = in.read(buffer); if(len==header.length){ for(int i=0;i<header.length;i++) { if(header[i]!=buffer[i]){ headerOK=false; break; } } } else headerOK=false; if(!headerOK)writeHeader=true; } finally { IOUtil.closeEL(in); } } if(writeHeader) { if(header==null)header=new byte[0]; IOUtil.write(res, header,false); } } }
package com.neverwinterdp.vm; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.ApplicationConstants; import com.beust.jcommander.DynamicParameter; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParametersDelegate; import com.neverwinterdp.registry.RegistryConfig; import com.neverwinterdp.util.text.StringUtil; public class VMConfig { public enum ClusterEnvironment { YARN, YARN_MINICLUSTER, JVM; public static ClusterEnvironment fromString(String code) { for(ClusterEnvironment output : ClusterEnvironment.values()) { if(output.toString().equalsIgnoreCase(code)) return output; } return null; } } @Parameter(names = "--description", description = "Description") private String description; @Parameter(names = {"--name", "--vm-id"} , required=true, description = "The registry partition or table") private String vmId; @Parameter(names = "--role", description = "The VM roles") private List<String> roles = new ArrayList<String>(); @Parameter(names = "--cpu-cores", description = "The request number of cpu cores") private int requestCpuCores = 1; @Parameter(names = "--memory", description = "The request amount of memory in MB") private int requestMemory = 256; @Parameter(names = "--dfs-app-home", description = "DFS App Home") private String dfsAppHome; @Parameter(names = "--local-app-home", description = "Local App Home") private String localAppHome = null; @Parameter(names = "--local-log-dir", description = "Local Log Dir") private String localLogDir = "/opt/hadoop/vm-logs"; @Parameter(names = "--log4j-config-url", description = "Log4j Config Url") private String log4jConfigUrl = "classpath:vm-log4j.properties"; @Parameter(names = "--enable-gc-log", description = "Enable GC Log") private boolean enableGCLog = true; @Parameter(names = "--profiler-opts", description = "Options for profiler such yourkit") private String profilerOpts ; @DynamicParameter(names = "--vm-resource:", description = "The resources for the vm") private Map<String, String> vmResources = new LinkedHashMap<String, String>(); @ParametersDelegate private RegistryConfig registryConfig = new RegistryConfig(); @Parameter( names = "--self-registration", description = "Self create the registation entry in the registry, for master node") private boolean selfRegistration = false; @Parameter(names = "--vm-application", description = "The vm application class") private String vmApplication; @DynamicParameter(names = "--prop:", description = "The application configuration properties") private Map<String, String> properties = new HashMap<String, String>(); @DynamicParameter(names = "--hadoop:", description = "The application configuration properties") private HadoopProperties hadoopProperties = new HadoopProperties(); @Parameter(names = "--environment", description = "Environement YARN, YARN_MINICLUSTER, JVM") private ClusterEnvironment clusterEnvironment = ClusterEnvironment.JVM; public VMConfig() {} public VMConfig(String[] args) { new JCommander(this, args); } public String getVmId() { return vmId; } public VMConfig setVmId(String vmId) { this.vmId = vmId; return this; } public List<String> getRoles() { return roles; } public VMConfig setRoles(List<String> roles) { this.roles = roles; return this; } public VMConfig addRoles(String ... role) { if(roles == null) roles = StringUtil.toList(role); else StringUtil.addList(roles, role); return this; } public int getRequestCpuCores() { return requestCpuCores; } public VMConfig setRequestCpuCores(int requestCpuCores) { this.requestCpuCores = requestCpuCores; return this; } public int getRequestMemory() { return requestMemory; } public VMConfig setRequestMemory(int requestMemory) { this.requestMemory = requestMemory; return this; } public String getDfsAppHome() { return dfsAppHome; } public void setDfsAppHome(String dfsAppHome) { this.dfsAppHome = dfsAppHome; } public String getLocalAppHome() { return localAppHome; } public VMConfig setLocalAppHome(String localAppHome) { this.localAppHome = localAppHome; return this; } public String getLocalLogDir() { return localLogDir; } public VMConfig setLocalLogDir(String localLogDir) { this.localLogDir = localLogDir; return this; } public String getLog4jConfigUrl() { return log4jConfigUrl; } public VMConfig setLog4jConfigUrl(String url) { if(url != null && url.length() > 0) log4jConfigUrl = url; return this; } public boolean isEnableGCLog() { return enableGCLog; } public VMConfig setEnableGCLog(boolean enableGCLog) { this.enableGCLog = enableGCLog; return this; } public String getProfilerOpts() { return profilerOpts; } public VMConfig setProfilerOpts(String profilerOpts) { this.profilerOpts = profilerOpts; return this; } public Map<String, String> getVmResources() { return vmResources; } public void setVmResources(Map<String, String> vmResources) { this.vmResources = vmResources; } public void addVMResource(String name, String resource) { vmResources.put(name, resource); } public RegistryConfig getRegistryConfig() { return registryConfig;} public VMConfig setRegistryConfig(RegistryConfig registryConfig) { this.registryConfig = registryConfig; return this; } public boolean isSelfRegistration() { return selfRegistration; } public VMConfig setSelfRegistration(boolean selfRegistration) { this.selfRegistration = selfRegistration; return this; } public String getVmApplication() { return vmApplication;} public VMConfig setVmApplication(String vmApplication) { this.vmApplication = vmApplication; return this; } public Map<String, String> getProperties() { return properties;} public VMConfig setProperties(Map<String, String> appProperties) { this.properties = appProperties; return this; } public VMConfig addProperty(String name, String value) { properties.put(name, value); return this; } public String getProperty(String name) { return properties.get(name); } public String getProperty(String name, String defaultValue) { String value = properties.get(name); if(value == null) return defaultValue; return value ; } public int getPropertyAsInt(String name, int defaultVal) { String val = properties.get(name); return val == null ? defaultVal : Integer.parseInt(val); } public VMConfig addProperty(String name, int value) { return addProperty(name, Integer.toString(value)); } public long getPropertyAsLong(String name, long defaultVal) { String val = properties.get(name); return val == null ? defaultVal : Long.parseLong(val); } public VMConfig addProperty(String name, long value) { return addProperty(name, Long.toString(value)); } public boolean getPropertyAsBoolean(String name, boolean defaultVal) { String val = properties.get(name); return val == null ? defaultVal : Boolean.parseBoolean(val); } public VMConfig addProperty(String name, boolean value) { return addProperty(name, Boolean.toString(value)); } public HadoopProperties getHadoopProperties() { return hadoopProperties; } public VMConfig setHadoopProperties(HadoopProperties hadoopProperties) { this.hadoopProperties = hadoopProperties; return this; } public VMConfig addHadoopProperty(String name, String value) { hadoopProperties.put(name, value); return this; } public VMConfig addHadoopProperty(Map<String, String> conf) { Iterator<Map.Entry<String, String>> i = conf.entrySet().iterator(); while(i.hasNext()) { Map.Entry<String, String> entry = i.next(); String key = entry.getKey(); String value = conf.get(key); if(value.length() == 0) continue; else if(value.indexOf(' ') > 0) continue; hadoopProperties.put(key, value); } return this; } public void overrideHadoopConfiguration(Configuration aconf) { hadoopProperties.overrideConfiguration(aconf); } public String getDescription() { return description; } public VMConfig setDescription(String description) { this.description = description; return this; } public ClusterEnvironment getClusterEnvironment() { return this.clusterEnvironment; } public VMConfig setClusterEnvironment(ClusterEnvironment env) { this.clusterEnvironment = env; return this; } public String buildCommand() { StringBuilder b = new StringBuilder() ; b.append("java ").append(" -Xms128m -Xmx" + requestMemory + "m "); addJVMOptions(b); b.append(" ").append(VM.class.getName()).append(" ") ; addParameters(b); System.out.println("Command: " + b.toString()); return b.toString() ; } private void addJVMOptions(StringBuilder b) { b.append(" -server -Djava.awt.headless=true "); b.append(" -XX:+UseConcMarkSweepGC "); b.append(" -XX:+CMSClassUnloadingEnabled"); if(enableGCLog) { String logFile = localLogDir + "/" + vmId + "-gc.log"; b.append(" -Xloggc:" + logFile + " -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps"); } b.append(" -agentpath:/opt/yourkit/bin/linux-x86-64/libyjpagent.so=disablestacktelemetry,disableexceptiontelemetry,delay=10000 "); } private void addParameters(StringBuilder b) { if(vmId != null) { b.append(" --vm-id ").append(vmId) ; } if(roles != null && roles.size() > 0) { b.append(" --role "); for(String role : roles) { b.append(role).append(" "); } } b.append(" --cpu-cores ").append(requestCpuCores) ; b.append(" --memory ").append(requestMemory) ; if(dfsAppHome != null) { b.append(" --dfs-app-home ").append(dfsAppHome) ; } if(localAppHome != null) { b.append(" --local-app-home ").append(localAppHome) ; } for(Map.Entry<String, String> entry : vmResources.entrySet()) { b.append(" --vm-resource:").append(entry.getKey()).append("=").append(entry.getValue()) ; } b.append(" --vm-application ").append(vmApplication); if(selfRegistration) { b.append(" --self-registration ") ; } b.append(" --registry-connect ").append(registryConfig.getConnect()) ; b.append(" --registry-db-domain ").append(registryConfig.getDbDomain()) ; b.append(" --registry-implementation ").append(registryConfig.getRegistryImplementation()) ; b.append(" --environment ").append(clusterEnvironment) ; b.append(" --log4j-config-url ").append(log4jConfigUrl) ; for(Map.Entry<String, String> entry : properties.entrySet()) { b.append(" --prop:").append(entry.getKey()).append("=").append(entry.getValue()) ; } for(Map.Entry<String, String> entry : hadoopProperties.entrySet()) { b.append(" --hadoop:").append(entry.getKey()).append("=").append(entry.getValue()) ; } } static public void overrideHadoopConfiguration(Map<String, String> props, Configuration aconf) { HadoopProperties hprops = new HadoopProperties() ; hprops.putAll(props); hprops.overrideConfiguration(aconf); } }
package bullybot.classfiles; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import bullybot.classfiles.util.Functions; public class Settings { private String filePath; private String pugChannel = "pugs"; private String mumble = "N/A"; private Integer afkTime = 120; private Integer dcTime = 120; private Integer finishTime = 60; private Integer minNumberOfGames = 5; private boolean randomizeCaptains = true; public Settings(String id){ this.filePath = String.format("%s/%s/%s", "app_data", id, "settings.cfg"); if(!new File(filePath).exists()){ createSettingsFile(); } loadSettingsFile(); } private void loadSettingsFile() { try{ FileInputStream is = new FileInputStream(filePath); Properties p = new Properties(); p.load(is); mumble = p.getProperty("mumble", mumble); pugChannel = p.getProperty("pugchannel", pugChannel); minNumberOfGames = Integer.valueOf(p.getProperty("mingames", minNumberOfGames.toString())); afkTime = Integer.valueOf(p.getProperty("afktime", afkTime.toString())); dcTime = Integer.valueOf(p.getProperty("dctime", dcTime.toString())); finishTime = Integer.valueOf(p.getProperty("finishtime", finishTime.toString())); randomizeCaptains = Boolean.valueOf(p.getProperty("randomizecaptains", String.valueOf(randomizeCaptains))); is.close(); }catch(IOException ex){ ex.printStackTrace(); } } private void createSettingsFile() { Functions.createFile(filePath); try{ FileOutputStream os = new FileOutputStream(filePath); Properties p = new Properties(); p.setProperty("mumble", mumble); p.setProperty("pugchannel", pugChannel); p.setProperty("mingames", minNumberOfGames.toString()); p.setProperty("afktime", afkTime.toString()); p.setProperty("dctime", dcTime.toString()); p.setProperty("finishtime", finishTime.toString()); p.setProperty("randomizecaptains", String.valueOf(randomizeCaptains)); p.store(os, null); os.close(); }catch(IOException ex){ ex.printStackTrace(); } } public String pugChannel(){ return pugChannel; } public Integer afkTime(){ return afkTime; } public Integer dcTime(){ return dcTime; } public Integer finishTime(){ return finishTime; } public boolean randomizeCaptains(){ return randomizeCaptains; } public String mumble(){ return mumble; } }
package Model; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * * @author Ruben */ public class Opleiding implements Entiteit{ private int ID; private String naam; private int contact_id; public Opleiding() {}; public Opleiding(int ID, int contact_id, String naam) { this.ID = ID; this.naam = naam; this.contact_id = contact_id; } public int getOpleidingID() { return ID; } public String getOpleidingNaam() { return naam; } public String InsertOpleiding() { return "INSERT INTO Opleiding VALUES('" + this.getOpleidingID() + "', '" + this.getOpleidingNaam() + "');"; } @Override public String getInsertSQL() { return "INSERT INTO Opleiding (naam) VALUES (?);"; } @Override public PreparedStatement getInsertStatement(PreparedStatement stmt, Connection con) throws SQLException { stmt.setString(1, this.naam); return stmt; } @Override public String getUpdateSQL() { return "UPDATE Opleiding SET naam = ? WHERE opleiding_id = ?"; } @Override public PreparedStatement getUpdateStatement(PreparedStatement stmt, Connection con) throws SQLException { stmt.setString(1, this.naam); stmt.setInt(2, this.ID); return stmt; } @Override public String getDeleteSQL() { return "DELETE from Opleiding WHERE opleiding_id = ?"; } @Override public PreparedStatement getDeleteStatement(PreparedStatement stmt, Connection con, int keyValue) throws SQLException { stmt.setInt(1, keyValue); return stmt; } @Override public String getSelectSQL(String columnName) { String SQL = ""; if (columnName.isEmpty()) { SQL = "SELECT * FROM Opleiding"; } else { SQL = "SELECT * FROM Opleiding WHERE " + columnName + " LIKE ?"; } return SQL; } @Override public PreparedStatement getSelectStatement(PreparedStatement stmt, String columnInput) throws SQLException { stmt.setString(1, "%" + columnInput + "%"); return stmt; } }
package sandbox; import com.almasb.fxgl.app.GameApplication; import com.almasb.fxgl.app.GameSettings; import com.almasb.fxgl.texture.ImagesKt; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import static com.almasb.fxgl.dsl.FXGL.*; /** * This is a sample class for testing image rescaling. */ public class ImageSample extends GameApplication { @Override protected void initSettings(GameSettings settings) { settings.setWidth(800); settings.setHeight(800); settings.setTitle("ImageSample"); } @Override protected void initGame() { Image background = image("background.png"); Image backgroundResized = ImagesKt.resize(background, 400, 300); addUINode(new ImageView(backgroundResized)); // 64x64 Image original = image("brick.png"); for (int i = 16; i > 0; i Image processed = ImagesKt.resize(original, 16 * i, 16 * i); addUINode(new ImageView(processed), 5 * i * i, 0.3 * i * i * i); } } public static void main(String[] args) { launch(args); } }
package org.jcoderz.commons.types; import junit.framework.TestCase; import org.jcoderz.commons.ArgumentMaxLengthViolationException; import org.jcoderz.commons.ArgumentMaxValueViolationException; import org.jcoderz.commons.ArgumentMinLengthViolationException; import org.jcoderz.commons.ArgumentMinValueViolationException; import org.jcoderz.commons.config.ConfigurationKey; import org.jcoderz.commons.test.RestrictedLong; /** * Test the generated Strong Types. * @author Andreas Mandel */ public class StrongTypesTest extends TestCase { private static final int LONG_STRING_LENGTH = 2048; private static final String LONG_STRING; static { final StringBuffer sb = new StringBuffer(); for (int i = 0; i < LONG_STRING_LENGTH; i++) { sb.append(' '); } LONG_STRING = sb.toString(); } /** * Testing the max length restriction in generated String types. */ public void testToLong () { try { final ConfigurationKey key = ConfigurationKey.fromString(LONG_STRING.substring(0, ConfigurationKey.MAX_LENGTH + 1)); fail("Expected exception!"); } catch (ArgumentMaxLengthViolationException ex) { // expected; } } /** * Testing the min length restriction in generated String types. */ public void testToShort () { try { final ConfigurationKey key = ConfigurationKey.fromString(""); fail("Expected exception!"); } catch (ArgumentMinLengthViolationException ex) { // expected; } } /** * Testing the max value restriction in generated Long types. */ public void testToHigh () { try { final RestrictedLong lg = RestrictedLong.fromLong(RestrictedLong.MAX_VALUE + 1); fail("Expected exception!"); } catch (ArgumentMaxValueViolationException ex) { // expected; } } /** * Testing the min value restriction in generated Long types. */ public void testToLow () { try { final RestrictedLong lg = RestrictedLong.fromLong(RestrictedLong.MIN_VALUE - 1); fail("Expected exception!"); } catch (ArgumentMinValueViolationException ex) { // expected; } } /** * Test method for comparison. */ public void testComparison () { assertEquals("Comparing equal values", 0, RestrictedLong.fromString("15") .compareTo(RestrictedLong.fromString("15"))); assertTrue("Comparing different values", RestrictedLong.fromString("15") .compareTo(RestrictedLong.fromString("21")) < 0); assertTrue("Comparing different values", RestrictedLong.fromString("21") .compareTo(RestrictedLong.fromString("15")) > 0); } /** Test for enumeration implements tag. */ public void testImplementsTaggedColor () { assertTrue("TaggedColor should implement Tagger interface", TestTaggerInterface.class.isAssignableFrom(TaggedColor.class)); } /** Test for restricted string implements tag. */ public void testImplementsTaggedFooString () { assertTrue("TaggedFooString should implement Tagger interface", TestTaggerInterface.class.isAssignableFrom(TaggedFooString.class)); } /** Test for value objects implements tag. */ public void testImplementsTaggedValueObject () { assertTrue( "TaggedSampleValueObject should implement Tagger interface", TestTaggerInterface.class.isAssignableFrom( TaggedSampleValueObject.class)); assertTrue( "TaggedPlainSampleValueObject should implement Tagger interface", TestTaggerInterface.class.isAssignableFrom( TaggedPlainSampleValueObject.class)); assertTrue( "TaggedSerializableSampleValueObject " + "should implement Tagger interface", TestTaggerInterface.class.isAssignableFrom( TaggedSerializableSampleValueObject.class)); } }
package org.traccar.protocol; import org.junit.Test; import org.traccar.ProtocolTest; public class Gps103ProtocolDecoderTest extends ProtocolTest { @Test public void testDecode() throws Exception { Gps103ProtocolDecoder decoder = new Gps103ProtocolDecoder(new Gps103Protocol()); verifyNull(decoder, text( "imei:868683027825532,OBD,170613203014,,,,0,0,0.00%,0,0.00%,0,0.00,,,,;")); verifyAttributes(decoder, text( "imei:862106025092216,OBD,170612165656,196043,,145803.9,,000,0.0%,+,0.0%,00000,12.6,,,,;")); verifyAttributes(decoder, text( "imei:862106025092216,OBD,170605095949,195874,,370.8,808,066,30.0%,+87,13.0%,02444,14.3,,,,;")); verifyPosition(decoder, text( "imei:353451044508750,DTC,0809231929,,F,055403.000,A,2233.1870,N,11354.3067,E,0.00,30.1,,1,0,10.5%,P0021,;")); verifyPosition(decoder, text( "imei:353451044508750,oil1,0809231929,,F,055403.000,A,2233.1870,N,11354.3067,E,0.00,,,,51.6,41.7,;")); verifyPosition(decoder, text( "imei:353451044508750,oil2,0809231929,,F,055403.000,A,2233.1870,N,11354.3067,E,0.00,,,,51.6,41.7,;")); verifyPosition(decoder, text( "imei:353451044508750,oil 51.67,0809231929,,F,055403.000,A,2233.1870,N,11354.3067,E,0.00,,;")); verifyPosition(decoder, text( "imei:353451044508750,T:+28.0,0809231929,,F,055403.000,A,2233.1870,N,11354.3067,E,0.00,,;")); verifyPosition(decoder, text( "imei:353451044508750,bonnet alarm,0809231929,,F,055403.000,A,2233.1870,N,11354.3067,E,0.00,,;")); verifyPosition(decoder, text( "imei:353451044508750,footbrake alarm,0809231929,,F,055403.000,A,2233.1870,N,11354.3067,E,0.00,,;")); verifyPosition(decoder, text( "imei:862106021237716,ac alarm,1611291645,,F,204457.000,A,1010.2783,N,06441.0274,W,0.00,,;")); verifyAttributes(decoder, text( "imei:359710049057798,OBD,161003192752,1785,,,0,54,96.47%,75,20.00%,1892,0.00,P0134,P0571,,;")); verifyAttributes(decoder, text( "imei:359710049090138,OBD,160629022949,51442,0.00,15.88,5632,122,40.39%,95,0.00%,2101,13.80,,,,;")); verifyPosition(decoder, text( "imei:359710049090138,tracker,160629022948,,F,182949.000,A,4043.8839,N,11328.8029,W,65.26,271.82,,1,0,31.37%,51442,;")); verifyAttributes(decoder, text( "imei:359710049042014,001,160615040011,,F,040011.000,A,2833.0957,N,07711.9465,E,0.01,215.33,,0,,,,;")); verifyAttributes(decoder, text( "imei:359710049028435,OBD,160316053657,70430,,,0,49,60.00%,46,19.22%,859,0.00,U1108,,,;")); verifyPosition(decoder, text( "359769031878322imei:359769031878322,tracker,1602160718,2,F,221811.000,A,1655.2193,S,14546.6722,E,0.00,,")); verifyNull(decoder, text( "imei:865328021049167,OBD,141118115036,,,0.0,,000,0.0%,+,0.0%,00000,,,,,")); verifyAttributes(decoder, text( "imei:359710049032874,OBD,160208152900,13555,,,45,0,24.71%,35,13.73%,1230,14.13,U1108,,,")); verifyAttributes(decoder, text( "imei:359710049064398,OBD,160101035156,17887,0.00,17.06,0,0,0.00%,0,0.00%,16383,10.82,,,,")); verifyPosition(decoder, text( "imei:868683020235846,rfid,160202091347,49121185,F,011344.000,A,0447.7273,N,07538.9934,W,0.00,0,,0,0,0.00%,,")); verifyNotNull(decoder, text( "imei:359710049075097,help me,,,L,,,113b,,558f,,,,,0,0,,,")); verifyNotNull(decoder, text( "imei:359710041100000,tracker,000000000,,L,,,fa8,,c9af,,,,,0,0,0.00%,,")); verifyNotNull(decoder, text( "imei:863070016871385,tracker,0000000119,,L,,,0FB6,,CB5D,,,")); verifyPosition(decoder, text( "imei:359710045559474,tracker,151030080103,,F,000101.000,A,5443.3834,N,02512.9071,E,0.00,0;"), position("2015-10-30 00:01:01.000", true, 54.72306, 25.21512)); verifyPosition(decoder, text( "imei:359710049092324,tracker,151027025958,,F,235957.000,A,2429.5156,N,04424.5828,E,0.01,27.91,,0,0,,,;"), position("2015-10-26 23:59:57.000", true, 24.49193, 44.40971)); verifyPosition(decoder, text( "imei:865328021058861,tracker,151027041419,,F,011531.000,A,6020.2979,N,02506.1940,E,0.49,113.30,,0,0,0.0%,,;"), position("2015-10-27 01:15:31.000", true, 60.33830, 25.10323)); // Log on request verifyNull(decoder, text( "##,imei:359586015829802,A")); // Heartbeat package verifyNull(decoder, text( "359586015829802")); // No GPS signal verifyNull(decoder, text( "imei:359586015829802,tracker,000000000,13554900601,L,;")); verifyPosition(decoder, text( "imei:869039001186913,tracker,1308282156,0,F,215630.000,A,5602.11015,N,9246.30767,E,1.4,,175.9,")); verifyPosition(decoder, text( "imei:359710040656622,tracker,13/02/27 23:40,,F,125952.000,A,3450.9430,S,13828.6753,E,0.00,0")); verifyPosition(decoder, text( "imei:359710040565419,tracker,13/05/25 14:23,,F,062209.000,A,0626.0411,N,10149.3904,E,0.00,0")); verifyPosition(decoder, text( "imei:353451047570260,tracker,1302110948,,F,144807.000,A,0805.6615,S,07859.9763,W,0.00,,")); verifyPosition(decoder, text( "imei:359587016817564,tracker,1301251602,,F,080251.000,A,3223.5832,N,11058.9449,W,0.03,")); verifyPosition(decoder, text( "imei:359587016817564,tracker,1301251602,,F,080251.000,A,3223.5832,N,11058.9449,W,,")); verifyPosition(decoder, text( "imei:012497000208821,tracker,1301080525,,F,212511.000,A,2228.5279,S,06855.6328,W,18.62,268.98,")); verifyPosition(decoder, text( "imei:012497000208821,tracker,1301072224,,F,142411.077,A,2227.0739,S,06855.2912,,0,0,")); verifyPosition(decoder, text( "imei:012497000431811,tracker,1210260609,,F,220925.000,A,0845.5500,N,07024.7673,W,0.00,,")); verifyPosition(decoder, text( "imei:100000000000000,help me,1004171910,,F,010203.000,A,0102.0003,N,00102.0003,E,1.02,")); verifyPosition(decoder, text( "imei:353451040164707,tracker,1105182344,+36304665439,F,214418.000,A,4804.2222,N,01916.7593,E,0.37,")); verifyPosition(decoder, text( "imei:353451042861763,tracker,1106132241,,F,144114.000,A,2301.9052,S,04909.3676,W,0.13,")); verifyPosition(decoder, text( "imei:359587010124900,tracker,0809231929,13554900601,F,112909.397,A,2234.4669,N,11354.3287,E,0.11,321.53,")); verifyPosition(decoder, text( "imei:353451049926460,tracker,1208042043,123456 99008026,F,124336.000,A,3509.8668,N,03322.7636,E,0.00,,")); // SOS alarm verifyPosition(decoder, text( "imei:359586015829802,help me,0809231429,13554900601,F,062947.294,A,2234.4026,N,11354.3277,E,0.00,")); // Low battery alarm verifyPosition(decoder, text( "imei:359586015829802,low battery,0809231429,13554900601,F,062947.294,A,2234.4026,N,11354.3277,E,0.00,")); // Geo-fence alarm verifyPosition(decoder, text( "imei:359586015829802,stockade,0809231429,13554900601,F,062947.294,A,2234.4026,N,11354.3277,E,0.00,")); // Move alarm verifyPosition(decoder, text( "imei:359586015829802,move,0809231429,13554900601,F,062947.294,A,2234.4026,N,11354.3277,E,0.00,")); // Over speed alarm verifyPosition(decoder, text( "imei:359586015829802,speed,0809231429,13554900601,F,062947.294,A,2234.4026,N,11354.3277,E,0.00,")); verifyPosition(decoder, text( "imei:863070010423167,tracker,1211051840,,F,104000.000,A,2220.6483,N,11407.6377,,0,0,")); verifyPosition(decoder, text( "imei:863070010423167,tracker,1211051951,63360926,F,115123.000,A,2220.6322,N,11407.5313,E,0.00,,")); verifyPosition(decoder, text( "imei:863070010423167,tracker,1211060621,,F,062152.000,A,2220.6914,N,11407.5506,E,15.85,347.84,")); verifyPosition(decoder, text( "imei:863070012698733,tracker,1303092334,,F,193427.000,A,5139.0369,N,03907.2791,E,0.00,,")); verifyPosition(decoder, text( "imei:869039001186913,tracker,130925065533,0,F,065533.000,A,5604.11015,N,9232.12238,E,0.0,,329.0,")); verifyPosition(decoder, text( "imei:359710041641581,acc alarm,1402231159,,F,065907.000,A,2456.2591,N,06708.8335,E,7.53,76.10,,1,0,0.03%,,")); verifyPosition(decoder, text( "imei:359710041641581,acc alarm,1402231159,,F,065907.000,A,2456.2591,N,06708.8335,E,7.53,76.10,,1,0,0.03%,,")); verifyPosition(decoder, text( "imei:313009071131684,tracker,1403211928,,F,112817.000,A,0610.1133,N,00116.5840,E,0.00,,,0,0,0.0,0.0,")); verifyPosition(decoder, text( "imei:866989771979791,tracker,140527055653,,F,215653.00,A,5050.33113,N,00336.98783,E,0.066,0")); verifyPosition(decoder, text( "imei:353552045375005,tracker,150401165832,61.0,F,31.0,A,1050.73696,N,10636.49489,E,8.0,,22.0,")); verifyPosition(decoder, text( "imei:353552045403597,tracker,150420050648,53.0,F,0.0,A,N,5306.64155,E,00700.77848,0.0,,1.0,;")); verifyPosition(decoder, text( "imei:353552045403597,tracker,150420051153,53.0,F,0.0,A,5306.64155,N,00700.77848,E,0.0,,1.0,;")); verifyPosition(decoder, text( "imei:359710047424644,tracker,150506224036,,F,154037.000,A,0335.2785,N,09841.1543,E,3.03,337.54,,0,0,45.16%,,;")); verifyPosition(decoder, text( "imei:865328023776874,acc off,150619152221,,F,072218.000,A,5439.8489,N,02518.5945,E,0.00,,,1,1,0.0,0.0,23.0,;")); } }
package org.traccar.protocol; import org.junit.Test; import org.traccar.ProtocolTest; public class HuabaoProtocolDecoderTest extends ProtocolTest { @Test public void testDecode() throws Exception { HuabaoProtocolDecoder decoder = new HuabaoProtocolDecoder(new HuabaoProtocol()); verifyPosition(decoder, binary( "7e0200002c00160128561400020000000000040001005de1f7065c6cef00000000000017011710044201040000a9002a02000030011b3101030c7e")); verifyPosition(decoder, binary( "7e0200002c00160128561400030000000000040007005de13c065c6cdb00160000000017011710054201040000a9002a02000030011b310104e47e")); verifyNothing(decoder, binary( "7e0100002d0141305678720024002c012f373031313142534a2d41362d424400000000000000000000003035363738373201d4c14238383838386d7e")); verifyNothing(decoder, binary( "7E0100002D013511221122000500000000373031303748422D52303347424400000000000000000000003233363631303402CBD5424136383630387E")); verifyNothing(decoder, binary( "7e0100002d007089994489002800000000000000000048422d523033474244000000000000000000000031393036373531024142433030303030d17e")); verifyNothing(decoder, binary( "7E0102000E013511221122000661757468656E7469636174696F6E3F7E")); verifyPosition(decoder, binary( "7E02000032013511221122000700000000000C000301578CC006CA3A5C00470000000014072317201501040000000030011631010BD07E")); verifyNothing(decoder, binary( "7E010200100940278494700084323031313131303831313333323139369F7E")); verifyNothing(decoder, binary( "7e010000190940278494700012000000000000000000000000000000000000094027849470000a7e")); verifyPosition(decoder, binary( "7e0200002e094027587492000a000000010000000a03083db7001329f3000000140000130412164952010400000012360a0002341502cb0c20085c107e")); verifyPosition(decoder, binary( "7e020000220014012499170007000000000000400e012af16f02cbd2ba000000000000150101194257010400000077a97e")); } }
package test.jamocha.filter; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static test.jamocha.util.CounterColumnMatcherMockup.counterColumnMatcherMockup; import org.jamocha.dn.memory.SlotType; import org.jamocha.dn.memory.Template; import org.jamocha.dn.memory.javaimpl.SlotAddress; import org.jamocha.filter.FilterFunctionCompare; import org.jamocha.filter.FilterTranslator; import org.jamocha.filter.Function; import org.jamocha.filter.FunctionDictionary; import org.jamocha.filter.Path; import org.jamocha.filter.PathFilter; import org.jamocha.filter.PathFilter.PathFilterElement; import org.jamocha.filter.Predicate; import org.junit.BeforeClass; import org.junit.Test; import test.jamocha.util.FunctionBuilder; import test.jamocha.util.PredicateBuilder; public class FilterEqualsInFunctionTest { @BeforeClass public static void setUpBeforeClass() throws Exception { FunctionDictionary.load(); } @Test public void testFunctionWithArgumentsCompositeEqualsInFunctionTrueEquality() { final Path p1 = new Path(Template.DOUBLE); final Path p2 = new Path(Template.DOUBLE); final Path p3 = new Path(Template.DOUBLE); final SlotAddress a1 = new SlotAddress(0); final SlotAddress a2 = new SlotAddress(0); final SlotAddress a3 = new SlotAddress(0); final Function<?> plus = FunctionDictionary.lookup("+", SlotType.DOUBLE, SlotType.DOUBLE); final Function<?> minus = FunctionDictionary.lookup("-", SlotType.DOUBLE, SlotType.DOUBLE); final Predicate equals = FunctionDictionary.lookupPredicate("=", SlotType.DOUBLE, SlotType.DOUBLE); PathFilterElement f, g; f = new PredicateBuilder(equals) .addFunction( new FunctionBuilder(plus).addPath(p1, a1).addPath(p2, a2).build()) .addFunction( new FunctionBuilder(minus).addDouble(1337.).addPath(p3, a3).build()) .buildPFE(); g = new PredicateBuilder(equals) .addFunction( new FunctionBuilder(plus).addPath(p1, a1).addPath(p2, a2).build()) .addFunction( new FunctionBuilder(minus).addDouble(1337.).addPath(p3, a3).build()) .buildPFE(); final PathFilter pf = new PathFilter(f), pg = new PathFilter(g); assertTrue(FilterFunctionCompare.equals( FilterTranslator.translate(pf, counterColumnMatcherMockup), FilterTranslator.translate(pf, counterColumnMatcherMockup))); assertTrue(FilterFunctionCompare.equals( FilterTranslator.translate(pg, counterColumnMatcherMockup), FilterTranslator.translate(pg, counterColumnMatcherMockup))); assertTrue(FilterFunctionCompare.equals( FilterTranslator.translate(pf, counterColumnMatcherMockup), FilterTranslator.translate(pg, counterColumnMatcherMockup))); } @Test public void testEqualsInFunctionFalseDifferentSlotAddress() { final Path p1 = new Path(new Template(SlotType.DOUBLE, SlotType.DOUBLE)); final Path p2 = new Path(Template.DOUBLE); final Path p3 = new Path(Template.DOUBLE); final SlotAddress a1 = new SlotAddress(0); final SlotAddress a2 = new SlotAddress(0); final SlotAddress a3 = new SlotAddress(0); final SlotAddress a4 = new SlotAddress(1); final Function<?> plus = FunctionDictionary.lookup("+", SlotType.DOUBLE, SlotType.DOUBLE); final Function<?> minus = FunctionDictionary.lookup("-", SlotType.DOUBLE, SlotType.DOUBLE); final Predicate equals = FunctionDictionary.lookupPredicate("=", SlotType.DOUBLE, SlotType.DOUBLE); PathFilterElement f, g; f = new PredicateBuilder(equals) .addFunction( new FunctionBuilder(plus).addPath(p1, a1).addPath(p2, a2).build()) .addFunction( new FunctionBuilder(minus).addDouble(1337.).addPath(p3, a3).build()) .buildPFE(); g = new PredicateBuilder(equals) .addFunction( new FunctionBuilder(plus).addPath(p1, a4).addPath(p2, a2).build()) .addFunction( new FunctionBuilder(minus).addDouble(1337.).addPath(p3, a3).build()) .buildPFE(); final PathFilter pf = new PathFilter(f), pg = new PathFilter(g); assertTrue(FilterFunctionCompare.equals( FilterTranslator.translate(pf, counterColumnMatcherMockup), FilterTranslator.translate(pf, counterColumnMatcherMockup))); assertTrue(FilterFunctionCompare.equals( FilterTranslator.translate(pg, counterColumnMatcherMockup), FilterTranslator.translate(pg, counterColumnMatcherMockup))); assertFalse(FilterFunctionCompare.equals( FilterTranslator.translate(pf, counterColumnMatcherMockup), FilterTranslator.translate(pg, counterColumnMatcherMockup))); assertFalse(FilterFunctionCompare.equals( FilterTranslator.translate(pg, counterColumnMatcherMockup), FilterTranslator.translate(pf, counterColumnMatcherMockup))); } @Test public void testFunctionWithArgumentsCompositeEqualsInFunctionTrueNormalize() { final Path p1 = new Path(Template.DOUBLE); final Path p2 = new Path(Template.DOUBLE); final Path p3 = new Path(Template.DOUBLE); final SlotAddress a1 = new SlotAddress(0); final SlotAddress a2 = new SlotAddress(0); final SlotAddress a3 = new SlotAddress(0); final Function<?> plus = FunctionDictionary.lookup("+", SlotType.DOUBLE, SlotType.DOUBLE); final Function<?> minus = FunctionDictionary.lookup("-", SlotType.DOUBLE, SlotType.DOUBLE); final Predicate equals = FunctionDictionary.lookupPredicate("=", SlotType.DOUBLE, SlotType.DOUBLE); PathFilterElement f, g; PathFilter pf, pg; f = new PredicateBuilder(equals) .addFunction( new FunctionBuilder(plus).addPath(p1, a1).addPath(p2, a2).build()) .addFunction( new FunctionBuilder(minus).addDouble(1337.).addPath(p3, a3).build()) .buildPFE(); g = new PredicateBuilder(equals) .addFunction( new FunctionBuilder(minus).addDouble(1337.).addPath(p3, a3).build()) .addFunction( new FunctionBuilder(plus).addPath(p1, a1).addPath(p2, a2).build()) .buildPFE(); pf = new PathFilter(f); pg = new PathFilter(g); assertTrue(FilterFunctionCompare.equals(FilterTranslator.translate(pf, counterColumnMatcherMockup), FilterTranslator.translate(pg, counterColumnMatcherMockup).getNormalisedVersion())); assertTrue(FilterFunctionCompare.equals(FilterTranslator.translate(pg, counterColumnMatcherMockup), FilterTranslator.translate(pf, counterColumnMatcherMockup).getNormalisedVersion())); g = new PredicateBuilder(equals) .addFunction( new FunctionBuilder(minus).addDouble(1337.).addPath(p3, a3).build()) .addFunction( new FunctionBuilder(plus).addPath(p2, a2).addPath(p1, a1).build()) .buildPFE(); pg = new PathFilter(g); assertTrue(FilterFunctionCompare.equals(FilterTranslator.translate(pf, counterColumnMatcherMockup), FilterTranslator.translate(pg, counterColumnMatcherMockup).getNormalisedVersion())); assertTrue(FilterFunctionCompare.equals(FilterTranslator.translate(pg, counterColumnMatcherMockup), FilterTranslator.translate(pf, counterColumnMatcherMockup).getNormalisedVersion())); } @Test public void testFunctionWithArgumentsCompositeEqualsInFunctionTrueDifferentPath() { final Path p1 = new Path(Template.DOUBLE); final Path p2 = new Path(Template.DOUBLE); final Path p3 = new Path(Template.DOUBLE); final Path p4 = new Path(Template.DOUBLE); final SlotAddress a1 = new SlotAddress(0); final SlotAddress a2 = new SlotAddress(0); final SlotAddress a3 = new SlotAddress(0); final Function<?> plus = FunctionDictionary.lookup("+", SlotType.DOUBLE, SlotType.DOUBLE); final Function<?> minus = FunctionDictionary.lookup("-", SlotType.DOUBLE, SlotType.DOUBLE); final Predicate equals = FunctionDictionary.lookupPredicate("=", SlotType.DOUBLE, SlotType.DOUBLE); PathFilterElement f, g; PathFilter pf, pg; f = new PredicateBuilder(equals) .addFunction( new FunctionBuilder(plus).addPath(p1, a1).addPath(p2, a2).build()) .addFunction( new FunctionBuilder(minus).addDouble(1337.).addPath(p3, a3).build()) .buildPFE(); g = new PredicateBuilder(equals) .addFunction( new FunctionBuilder(plus).addPath(p4, a1).addPath(p2, a2).build()) .addFunction( new FunctionBuilder(minus).addDouble(1337.).addPath(p3, a3).build()) .buildPFE(); pf = new PathFilter(f); pg = new PathFilter(g); assertTrue(FilterFunctionCompare.equals( FilterTranslator.translate(pf, counterColumnMatcherMockup), FilterTranslator.translate(pg, counterColumnMatcherMockup))); assertTrue(FilterFunctionCompare.equals( FilterTranslator.translate(pg, counterColumnMatcherMockup), FilterTranslator.translate(pf, counterColumnMatcherMockup))); } @Test public void testFilterEqualsInFunction() { final Path p1 = new Path(new Template(SlotType.STRING, SlotType.LONG)); final Path p2 = new Path(Template.LONG); final Path p3 = new Path(Template.LONG); final SlotAddress a1 = new SlotAddress(0); final SlotAddress a3 = new SlotAddress(0); final SlotAddress a4 = new SlotAddress(0); final SlotAddress a5 = new SlotAddress(1); PathFilterElement f, g, h, i, j, k, l; final Function<?> plusL = FunctionDictionary.lookup("+", SlotType.LONG, SlotType.LONG); final Predicate lessL = FunctionDictionary.lookupPredicate("<", SlotType.LONG, SlotType.LONG); final Predicate eqS = FunctionDictionary.lookupPredicate("=", SlotType.STRING, SlotType.STRING); f = new PredicateBuilder(eqS).addString("Max Mustermann").addPath(p1, a1).buildPFE(); g = new PredicateBuilder(lessL).addLong(18L).addPath(p1, a5).buildPFE(); h = new PredicateBuilder(lessL) .addLong(50000) .addFunction( new FunctionBuilder(plusL).addPath(p2, a3).addPath(p3, a4).build()) .buildPFE(); i = new PredicateBuilder(eqS).addString("Max Mustermann").addPath(p1, a1).buildPFE(); j = new PredicateBuilder(lessL).addLong(18L).addPath(p1, a5).buildPFE(); k = new PredicateBuilder(lessL) .addLong(50000) .addFunction( new FunctionBuilder(plusL).addPath(p2, a3).addPath(p3, a4).build()) .buildPFE(); PathFilter a, b; a = new PathFilter(f, g, h); b = new PathFilter(f, g, h); assertTrue(FilterFunctionCompare.equals( FilterTranslator.translate(a, counterColumnMatcherMockup), FilterTranslator.translate(b, counterColumnMatcherMockup))); assertTrue(FilterFunctionCompare.equals( FilterTranslator.translate(b, counterColumnMatcherMockup), FilterTranslator.translate(a, counterColumnMatcherMockup))); b = new PathFilter(i, j, k); assertTrue(FilterFunctionCompare.equals( FilterTranslator.translate(a, counterColumnMatcherMockup), FilterTranslator.translate(b, counterColumnMatcherMockup))); assertTrue(FilterFunctionCompare.equals( FilterTranslator.translate(b, counterColumnMatcherMockup), FilterTranslator.translate(a, counterColumnMatcherMockup))); b = new PathFilter(f, j, h); assertTrue(FilterFunctionCompare.equals( FilterTranslator.translate(a, counterColumnMatcherMockup), FilterTranslator.translate(b, counterColumnMatcherMockup))); assertTrue(FilterFunctionCompare.equals( FilterTranslator.translate(b, counterColumnMatcherMockup), FilterTranslator.translate(a, counterColumnMatcherMockup))); l = new PredicateBuilder(lessL).addLong(17L).addPath(p1, a5).buildPFE(); b = new PathFilter(f, l, h); assertFalse(FilterFunctionCompare.equals( FilterTranslator.translate(a, counterColumnMatcherMockup), FilterTranslator.translate(b, counterColumnMatcherMockup))); assertFalse(FilterFunctionCompare.equals( FilterTranslator.translate(b, counterColumnMatcherMockup), FilterTranslator.translate(a, counterColumnMatcherMockup))); b = new PathFilter(f, l, h); assertFalse(FilterFunctionCompare.equals( FilterTranslator.translate(a, counterColumnMatcherMockup), FilterTranslator.translate(b, counterColumnMatcherMockup))); assertFalse(FilterFunctionCompare.equals( FilterTranslator.translate(b, counterColumnMatcherMockup), FilterTranslator.translate(a, counterColumnMatcherMockup))); } }
package org.fandev.icons; import com.intellij.openapi.util.IconLoader; import consulo.annotation.DeprecationInfo; import consulo.ui.image.Image; /** * @author Dror Bereznitsky * @date Jan 10, 2009 3:56:47 PM */ @Deprecated @DeprecationInfo("See consulo.fantom.FantomIcons") public interface Icons { Image POD = IconLoader.getIcon("/icons/structure/pod.png"); Image CLASS = IconLoader.getIcon("/icons/structure/class.png"); Image ABSTRACT_CLASS = IconLoader.getIcon("/icons/structure/abstract-class.png"); Image MIXIN = IconLoader.getIcon("/icons/structure/mixin.png"); Image ENUM = IconLoader.getIcon("/icons/structure/enum.png"); Image METHOD = IconLoader.getIcon("/icons/structure/method.png"); Image FIELD = IconLoader.getIcon("/icons/structure/field.png"); }
package bookmarks; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.mock.http.MockHttpOutputMessage; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; /** * @author Josh Long */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration public class BookmarkRestControllerTest { private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); private MockMvc mockMvc; private String userName = "bdussault"; private HttpMessageConverter mappingJackson2HttpMessageConverter; private Account account; private List<Bookmark> bookmarkList = new ArrayList<>(); @Autowired private BookmarkRepository bookmarkRepository; @Autowired private WebApplicationContext webApplicationContext; @Autowired private AccountRepository accountRepository; @Autowired void setConverters(HttpMessageConverter<?>[] converters) { this.mappingJackson2HttpMessageConverter = Arrays.asList(converters).stream().filter( hmc -> hmc instanceof MappingJackson2HttpMessageConverter).findAny().get(); Assert.assertNotNull("the JSON message converter must not be null", this.mappingJackson2HttpMessageConverter); } @Before public void setup() throws Exception { this.mockMvc = webAppContextSetup(webApplicationContext).build(); this.bookmarkRepository.deleteAllInBatch(); this.accountRepository.deleteAllInBatch(); this.account = accountRepository.save(new Account(userName, "password")); this.bookmarkList.add(bookmarkRepository.save(new Bookmark(account, "http://bookmark.com/1/" + userName, "A description"))); this.bookmarkList.add(bookmarkRepository.save(new Bookmark(account, "http://bookmark.com/2/" + userName, "A description"))); } @Test public void userNotFound() throws Exception { Assert.assertTrue(false); mockMvc.perform(post("/george/bookmarks/") .content(this.json(new Bookmark())) .contentType(contentType)) .andExpect(status().isNotFound()); } @Test public void readSingleBookmark() throws Exception { mockMvc.perform(get("/" + userName + "/bookmarks/" + this.bookmarkList.get(0).getId())) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$.id", is(this.bookmarkList.get(0).getId().intValue()))) .andExpect(jsonPath("$.uri", is("http://bookmark.com/1/" + userName))) .andExpect(jsonPath("$.description", is("A description"))); } @Test public void readBookmarks() throws Exception { mockMvc.perform(get("/" + userName + "/bookmarks")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$", hasSize(2))) .andExpect(jsonPath("$[0].id", is(this.bookmarkList.get(0).getId().intValue()))) .andExpect(jsonPath("$[0].uri", is("http://bookmark.com/1/" + userName))) .andExpect(jsonPath("$[0].description", is("A description"))) .andExpect(jsonPath("$[1].id", is(this.bookmarkList.get(1).getId().intValue()))) .andExpect(jsonPath("$[1].uri", is("http://bookmark.com/2/" + userName))) .andExpect(jsonPath("$[1].description", is("A description"))); } @Test public void createBookmark() throws Exception { String bookmarkJson = json(new Bookmark( this.account, "http://spring.io", "a bookmark to the best resource for Spring news and information")); this.mockMvc.perform(post("/" + userName + "/bookmarks") .contentType(contentType) .content(bookmarkJson)) .andExpect(status().isCreated()); } protected String json(Object o) throws IOException { MockHttpOutputMessage mockHttpOutputMessage = new MockHttpOutputMessage(); this.mappingJackson2HttpMessageConverter.write( o, MediaType.APPLICATION_JSON, mockHttpOutputMessage); return mockHttpOutputMessage.getBodyAsString(); } }
package com.rexsl.w3c; import com.rexsl.test.AssertionPolicy; import com.rexsl.test.TestResponse; import com.ymock.util.Logger; /** * Retry policy of assertion. * * @author Yegor Bugayenko (yegor@rexsl.com) * @version $Id$ */ final class RetryPolicy implements AssertionPolicy { /** * XPath to look for. */ private final transient String xpath; /** * Was it an invalid XML response? */ private transient boolean invalid; /** * Public ctor. * @param addr The XPath addr to check */ public RetryPolicy(final String addr) { this.xpath = addr; } /** * {@inheritDoc} */ @Override public void assertThat(final TestResponse response) { this.invalid = response.nodes(this.xpath).isEmpty(); if (this.invalid) { throw new AssertionError("invalid XML from W3C server"); } } /** * {@inheritDoc} */ @Override public boolean again(final int attempt) { Logger.warn( this, "#again(#%d): W3C XML response is broken", attempt ); return this.invalid; } }
package rhogenwizard.editors; import java.io.DataInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.EditorPart; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.progress.UIJob; import rhogenwizard.OSHelper; import rhogenwizard.rhohub.TokenChecker; import rhogenwizard.sdk.task.JobNotificationMonitor; import rhogenwizard.sdk.task.liveupdate.DiscoverTask; import rhogenwizard.sdk.task.liveupdate.LUDevice; import rhogenwizard.sdk.task.liveupdate.LiveUpdateTask; import rhogenwizard.sdk.task.liveupdate.PrintSubnetsTask; class NetworkListener { private String m_networkAddess = null; public NetworkListener(String address) { m_networkAddess = address; } public boolean waitServer() { try { URL url; URLConnection urlConn; DataInputStream dis; url = new URL(m_networkAddess); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setUseCaches(false); dis = new DataInputStream(urlConn.getInputStream()); String s; byte[] data = new byte[100]; dis.read(data); return true; } catch (MalformedURLException mue) { } catch (IOException ioe) { } return false; } } class LiveUpdateObserver extends Observable { public void notifyUi(Object arg) { this.setChanged(); this.notifyObservers(arg); } } class CancelLiveUpdateUIJob extends UIJob { private Button m_enableBtn = null; public CancelLiveUpdateUIJob(Button enableBtn) { super("Update UI"); m_enableBtn = enableBtn; } @Override public IStatus runInUIThread(IProgressMonitor monitor) { Job[] runningJobs = Job.getJobManager().find(null); for (Job job : runningJobs) { if (job.getName().equals(LiveUpdateEditor.liveUpdateJobName)) { job.cancel(); break; } } if (!m_enableBtn.isDisposed()) m_enableBtn.setEnabled(true); return Status.OK_STATUS; } } class CloseEditorUIJob extends UIJob { private IEditorPart m_editor = null; public CloseEditorUIJob(IEditorPart editor) { super("Update UI"); m_editor = editor; } @Override public IStatus runInUIThread(IProgressMonitor monitor) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } m_editor.getEditorSite().getPage().closeEditor(m_editor, false); return Status.OK_STATUS; } } class TableItemUpdateUIJob extends UIJob { private int m_showIndex = 0; private TableItem m_item = null; public TableItemUpdateUIJob(TableItem item, int showIndex) { super("Update UI"); m_showIndex = showIndex; m_item = item; } @Override public IStatus runInUIThread(IProgressMonitor monitor) { if (!m_item.isDisposed()) m_item.setText(1, LiveUpdateEditor.discoverStatus[m_showIndex]); return Status.OK_STATUS; } } class DevicesTableFillUIJob extends UIJob { private Table m_table = null; private IProject m_project = null; public DevicesTableFillUIJob(IProject project, Table table) { super("Update UI"); m_table = table; m_project = project; } @Override public IStatus runInUIThread(IProgressMonitor monitor) { if (m_table.isDisposed()) return Status.OK_STATUS; m_table.removeAll(); IPath path = m_project.getLocation(); path = path.append(LUDevice.configFileName); try { List<LUDevice> devices = LUDevice.load(path); if (devices != null && devices.size() != 0) { for (LUDevice itemDev : devices) { TableItem item = new TableItem(m_table, SWT.NONE); item.setText(0, itemDev.Name); item.setText(1, itemDev.URI); item.setText(2, itemDev.Application); item.setText(3, itemDev.Platfrom); } } } catch (FileNotFoundException e) { e.printStackTrace(); } return Status.OK_STATUS; } } class SearchProgressMonitor implements Runnable { private static final int updateUiSleep = 1000; private TableItem m_item = null; private IProject m_project = null; private String m_subnetMask = null; public SearchProgressMonitor(IProject project, String subnetMask, TableItem item) { m_item = item; m_project = project; m_subnetMask = subnetMask; } @Override public void run() { try { new TableItemUpdateUIJob(m_item, LiveUpdateEditor.searchId).schedule(); DiscoverTask task = new DiscoverTask(m_project.getLocation().toOSString(), m_subnetMask); Job taskJob = task.makeJob("Discover devices in " + m_subnetMask + " subnet"); taskJob.schedule(); int searchIdx = 0; int maxSearchAnimSteps = 2; while(true) { if(searchIdx >= maxSearchAnimSteps) searchIdx = 0; else searchIdx++; new TableItemUpdateUIJob(m_item, LiveUpdateEditor.searchId + searchIdx).schedule(); if (taskJob.getResult() != null) break; if (m_item.isDisposed()) { taskJob.cancel(); break; } Thread.sleep(updateUiSleep); } if (task.isOk()) { new TableItemUpdateUIJob(m_item, LiveUpdateEditor.foundId).schedule(); } else { new TableItemUpdateUIJob(m_item, LiveUpdateEditor.notFoundId).schedule(); } LiveUpdateEditor.eventHandler.notifyUi("update"); } catch (InterruptedException e) { e.printStackTrace(); } } } class DiscoverSubnet implements Runnable { private List<String> m_subnets = null; private String m_pathToProject = null; public DiscoverSubnet(IProject project) { m_pathToProject = project.getLocation().toOSString(); } @Override public void run() { PrintSubnetsTask task = new PrintSubnetsTask(m_pathToProject); task.run(); if (task.isOk()) { m_subnets = task.getSubnets(); } } public List<String> getSubnets() { return m_subnets; } } class LUJobNotifications implements JobNotificationMonitor { IProject m_project = null; final Button m_btn; class StopUiJob extends UIJob { public StopUiJob(String name) { super(name); } @Override public IStatus runInUIThread(IProgressMonitor monitor) { try { m_project.setSessionProperty(LiveUpdateEditor.isLiveUpdateEnableTag, true); if (!m_btn.isDisposed()) { m_btn.setEnabled(true); m_btn.setText(LiveUpdateEditor.switchLUButtonText[LiveUpdateEditor.liveUpdateEnableId]); } } catch (CoreException e) { e.printStackTrace(); } return Status.OK_STATUS; } } class OnStartUiJob extends UIJob { public OnStartUiJob(String name) { super(name); } @Override public IStatus runInUIThread(IProgressMonitor monitor) { try { m_project.setSessionProperty(LiveUpdateEditor.isLiveUpdateEnableTag, m_btn.getEnabled()); } catch (CoreException e) { e.printStackTrace(); } return Status.OK_STATUS; } } public LUJobNotifications(IProject project, final Button btn) { m_project = project; m_btn = btn; } @Override public void onJobStop() { LiveUpdateTask task = new LiveUpdateTask(m_project.getLocation(), false); task.run(); if (task.isOk()) { new StopUiJob("update ui").schedule(); } } @Override public void onJobStart() { try { OnStartUiJob job = new OnStartUiJob("update ui"); job.schedule(); job.join(); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void onJobFinished() { } } public class LiveUpdateEditor extends EditorPart implements Observer { public static QualifiedName isLiveUpdateEnableTag = new QualifiedName(null, "is-live-update-ebnable"); public static String[] discoverStatus = {"Found", "Not Found", "Empty", "Search.", "Search..", "Search..."}; public static String[] switchLUButtonText = {"Enable live update", "Disable live update"}; private static final String webrickCommandLineTag = "http://127.0.0.1:3000/auto_update_pid"; //"dev:webserver:privateStart"; public static final String liveUpdateJobName = "live update is running"; public static LiveUpdateObserver eventHandler = new LiveUpdateObserver(); private static Thread webrickWatcherThread = null; public static int liveUpdateEnableId = 0; public static int liveUpdateDisableId = 1; public static int foundId = 0; public static int notFoundId = 1; public static int emptyId = 2; public static int searchId = 3; private static GridData textAligment = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); private IProject m_project = null; private Table m_devicesTable = null; private Job m_liveUpdateTaskJob = null; @Override public void doSave(IProgressMonitor monitor) { } @Override public void doSaveAs() { } @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { if (input instanceof FileEditorInput) { FileEditorInput fileInput = (FileEditorInput)input; m_project = (IProject)fileInput.getFile().getParent(); } setSite(site); setInput(input); eventHandler.addObserver(this); } @Override public boolean isDirty() { return false; } @Override public boolean isSaveAsAllowed() { return false; } @Override public void setFocus() { } @Override public void createPartControl(Composite parent) { if (m_project == null) return; Composite area = parent; Composite container = new Composite(area, SWT.NONE); container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); container.setLayoutData(new GridData(GridData.FILL_BOTH)); container.setLayout(new GridLayout(2, false)); // row 0 createTitleLabel(container, "Common:"); // row 1 new Label(container, SWT.NONE).setText(""); createLUSwitchButton(container); // row 2 new Label(container, SWT.NONE).setText("Subnets: "); new Label(container, SWT.NONE).setText("(for discover make double click on the item of the table)"); // row 3 new Label(container, SWT.NONE).setText(""); createSubnetsTable(container); // row 4 createTitleLabel(container, "Found devices:"); // row 5 new Label(container, SWT.NONE).setText(""); createDevicesTable(container); } private void createLUSwitchButton(Composite container) { try { final Boolean isEnable = (Boolean)m_project.getSessionProperty(isLiveUpdateEnableTag); final Button liveUpdateSwitchButton = new Button(container, SWT.PUSH); LiveUpdateTask task = new LiveUpdateTask(m_project.getLocation(), true); m_liveUpdateTaskJob = task.makeJob(liveUpdateJobName, new LUJobNotifications(m_project, liveUpdateSwitchButton)); liveUpdateSwitchButton.setText(switchLUButtonText[liveUpdateEnableId]); liveUpdateSwitchButton.setLayoutData(textAligment); liveUpdateSwitchButton.setEnabled(isEnable != null ? isEnable.booleanValue() : true); liveUpdateSwitchButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if (!TokenChecker.processToken(m_project)) { return; } final Button enableBtn = (Button)e.widget; enableBtn.setEnabled(false); m_liveUpdateTaskJob.schedule(); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); webrickWatcherThread = new Thread(new Runnable() { @Override public void run() { try { NetworkListener listener = new NetworkListener(webrickCommandLineTag); while(true) { while(!listener.waitServer()) { Thread.sleep(1000); } while(listener.waitServer()) { Thread.sleep(1000); } CancelLiveUpdateUIJob job = new CancelLiveUpdateUIJob(liveUpdateSwitchButton); job.schedule(); job.join(); } } catch (InterruptedException e) { } } }); webrickWatcherThread.start(); } catch (CoreException e2) { e2.printStackTrace(); } } @Override public void dispose() { if (webrickWatcherThread != null) { webrickWatcherThread.interrupt(); webrickWatcherThread = null; } super.dispose(); } private void createDevicesTable(Composite container) { Composite tblContainer = new Composite(container, SWT.NONE); tblContainer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); tblContainer.setLayout(new FillLayout()); m_devicesTable = new Table(tblContainer, SWT.SINGLE | SWT.FULL_SELECTION); m_devicesTable.setHeaderVisible(true); m_devicesTable.setLinesVisible(true); TableColumn columnSubnetIp = new TableColumn(m_devicesTable, SWT.NONE); columnSubnetIp.setText("Device name"); columnSubnetIp.setWidth(100); final TableColumn column2 = new TableColumn(m_devicesTable, SWT.CENTER); column2.setText("URI"); column2.setWidth(200); final TableColumn column3 = new TableColumn(m_devicesTable, SWT.CENTER); column3.setText("Application name"); column3.setWidth(200); final TableColumn column4 = new TableColumn(m_devicesTable, SWT.CENTER); column4.setText("Device platform"); column4.setWidth(200); fillDevicesTable(container, m_devicesTable); } private void fillDevicesTable(Composite container, Table table) { new DevicesTableFillUIJob(m_project, table).schedule(); } private void createSubnetsTable(Composite container) { Composite tblContainer = new Composite(container, SWT.NONE); tblContainer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); tblContainer.setLayout(new FillLayout()); final Table subnetTable = new Table(tblContainer, SWT.SINGLE | SWT.FULL_SELECTION); subnetTable.setHeaderVisible(true); subnetTable.setLinesVisible(true); TableColumn columnSubnetIp = new TableColumn(subnetTable, SWT.NONE); columnSubnetIp.setText("Subnet"); columnSubnetIp.setWidth(100); final TableColumn column2 = new TableColumn(subnetTable, SWT.CENTER); column2.setText("Status"); column2.setWidth(300); fillSubnetsTable(container, subnetTable); subnetTable.addListener(SWT.MouseDoubleClick, new Listener() { @Override public void handleEvent(Event event) { dblClickHandler((TableItem)subnetTable.getSelection()[0]); } }); } private void createTitleLabel(Composite container, String title) { new Label(container, SWT.NONE).setText(title); new Label(container, SWT.NONE).setText(""); } private void dblClickHandler(TableItem item) { new Thread(new SearchProgressMonitor(m_project, item.getText(0), item)).start(); } private void fillSubnetsTable(Composite container, Table table) { table.clearAll(); DiscoverSubnet discoverJob = new DiscoverSubnet(m_project); BusyIndicator.showWhile(container.getShell().getDisplay(), discoverJob); if (discoverJob.getSubnets() != null) { for (String itemName : discoverJob.getSubnets()) { TableItem item = new TableItem(table, SWT.NONE); item.setText(itemName); item.setText(1, discoverStatus[emptyId]); } } } @Override public void update(Observable o, Object arg) { fillDevicesTable(null, m_devicesTable); } }
package org.fxmisc.richtext; import static org.fxmisc.richtext.TwoDimensional.Bias.*; import java.util.Iterator; import java.util.Objects; import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.UnaryOperator; import java.util.stream.Stream; import java.util.stream.StreamSupport; public interface StyleSpans<S> extends Iterable<StyleSpan<S>>, TwoDimensional { static <S> StyleSpans<S> singleton(S style, int length) { return singleton(new StyleSpan<>(style, length)); } static <S> StyleSpans<S> singleton(StyleSpan<S> span) { return new SingletonSpans<>(span); } int length(); int getSpanCount(); StyleSpan<S> getStyleSpan(int index); /** * Two {@code StyleSpans} objects are considered equal if they contain equal * number of {@code StyleSpan}s and the {@code StyleSpan}s are pairwise * equal. */ @Override public boolean equals(Object other); @Override default Iterator<StyleSpan<S>> iterator() { return new Iterator<StyleSpan<S>>() { private int nextToReturn = 0; private final int spanCount = getSpanCount(); @Override public boolean hasNext() { return nextToReturn < spanCount; } @Override public StyleSpan<S> next() { return getStyleSpan(nextToReturn++); } }; } default StyleSpans<S> append(S style, int length) { return append(new StyleSpan<>(style, length)); } default StyleSpans<S> append(StyleSpan<S> span) { if(span.getLength() == 0) { return this; } else if(length() == 0) { return singleton(span); } int lastIdx = getSpanCount() - 1; StyleSpan<S> myLastSpan = getStyleSpan(lastIdx); if(Objects.equals(myLastSpan.getStyle(), span.getStyle())) { StyleSpan<S> newLastSpan = new StyleSpan<>(span.getStyle(), myLastSpan.getLength() + span.getLength()); return new UpdatedSpans<>(this, lastIdx, newLastSpan); } else { return new AppendedSpans<>(this, span); } } default StyleSpans<S> prepend(S style, int length) { return prepend(new StyleSpan<>(style, length)); } default StyleSpans<S> prepend(StyleSpan<S> span) { if(span.getLength() == 0) { return this; } else if(length() == 0) { return singleton(span); } StyleSpan<S> myFirstSpan = getStyleSpan(0); if(Objects.equals(span.getStyle(), myFirstSpan.getStyle())) { StyleSpan<S> newFirstSpan = new StyleSpan<>(span.getStyle(), span.getLength() + myFirstSpan.getLength()); return new UpdatedSpans<>(this, 0, newFirstSpan); } else { return new PrependedSpans<>(this, span); } } default StyleSpans<S> subView(int from, int to) { Position start = offsetToPosition(from, Forward); Position end = to > from ? start.offsetBy(to - from, Backward) : start; return subView(start, end); } default StyleSpans<S> subView(Position from, Position to) { return new SubSpans<>(this, from, to); } default StyleSpans<S> concat(StyleSpans<S> that) { if(that.length() == 0) { return this; } else if(this.length() == 0) { return that; } int n1 = this.getSpanCount(); int n2 = that.getSpanCount(); StyleSpan<S> myLast = this.getStyleSpan(n1 - 1); StyleSpan<S> theirFirst = that.getStyleSpan(0); StyleSpansBuilder<S> builder; if(Objects.equals(myLast.getStyle(), theirFirst.getStyle())) { builder = new StyleSpansBuilder<>(n1 + n2 - 1); for(int i = 0; i < n1 - 1; ++i) { builder.add(this.getStyleSpan(i)); } builder.add(myLast.getStyle(), myLast.getLength() + theirFirst.getLength()); for(int i = 1; i < n2; ++i) { builder.add(that.getStyleSpan(i)); } } else { builder = new StyleSpansBuilder<>(n1 + n2); builder.addAll(this, n1); builder.addAll(that, n2); } return builder.create(); } /** * Returns a new {@code StyleSpans} object that has the same total length * as this StyleSpans and style of every span is mapped by the given * function. Adjacent style spans whose style mapped to the same value are * merged into one. As a consequence, the returned StyleSpans might have * fewer style spans than this StyleSpans. * @param mapper function to calculate new style * @return StyleSpans with replaced styles. */ default StyleSpans<S> mapStyles(UnaryOperator<S> mapper) { int n = getSpanCount(); StyleSpansBuilder<S> builder = new StyleSpansBuilder<>(n); StyleSpan<S> firstSpan = getStyleSpan(0); // there should always be at least one span int prevLen = firstSpan.getLength(); S prevStyle = mapper.apply(firstSpan.getStyle()); for(int i = 1; i < n; ++i) { StyleSpan<S> span = getStyleSpan(i); S style = mapper.apply(span.getStyle()); if(Objects.equals(prevStyle, style)) { prevLen += span.getLength(); } else { builder.add(prevStyle, prevLen); prevLen = span.getLength(); prevStyle = style; } } builder.add(prevStyle, prevLen); return builder.create(); } default Stream<S> styleStream() { return stream().map(span -> span.getStyle()); } default Stream<StyleSpan<S>> stream() { Spliterator<StyleSpan<S>> spliterator = new Spliterator<StyleSpan<S>>() { private final Iterator<StyleSpan<S>> iterator = iterator(); @Override public boolean tryAdvance(Consumer<? super StyleSpan<S>> action) { if(iterator.hasNext()) { action.accept(iterator.next()); return true; } else { return false; } } @Override public Spliterator<StyleSpan<S>> trySplit() { return null; } @Override public long estimateSize() { return getSpanCount(); } @Override public int characteristics() { return Spliterator.IMMUTABLE | Spliterator.SIZED; } }; return StreamSupport.stream(spliterator, false); } }
package com.rultor.life; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.model.DeleteMessageRequest; import com.amazonaws.services.sqs.model.Message; import com.amazonaws.services.sqs.model.ReceiveMessageRequest; import com.amazonaws.services.sqs.model.ReceiveMessageResult; import com.jcabi.aspects.Loggable; import com.jcabi.aspects.Tv; import com.jcabi.log.Logger; import com.jcabi.log.VerboseThreads; import com.rultor.aws.SQSClient; import com.rultor.spi.ACL; import com.rultor.spi.Arguments; import com.rultor.spi.Repo; import com.rultor.spi.SpecException; import com.rultor.spi.Stand; import com.rultor.spi.User; import com.rultor.spi.Users; import com.rultor.spi.Work; import java.io.Closeable; import java.io.IOException; import java.io.StringReader; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.json.Json; import javax.json.JsonObject; import lombok.EqualsAndHashCode; import org.apache.commons.lang3.exception.ExceptionUtils; /** * Sensor to pulses in SQS queue. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @checkstyle ClassDataAbstractionCoupling (500 lines) */ @Loggable(Loggable.DEBUG) @EqualsAndHashCode(of = { "users", "client" }) @SuppressWarnings("PMD.DoNotUseThreads") public final class SQSPulseSensor implements Runnable, Closeable { /** * How many threads to use. */ private static final int THREADS = Runtime.getRuntime().availableProcessors() * Tv.FIVE; /** * Executor service. */ private final transient ScheduledExecutorService service = Executors.newScheduledThreadPool( SQSPulseSensor.THREADS, new VerboseThreads() ); /** * Users. */ private final transient Users users; /** * Repository for ACL instantiation. */ private final transient Repo repo; /** * Quartz queue client. */ private final transient SQSClient client; /** * Public ctor. * @param usr Users * @param rpo Repo * @param clnt SQS client for quartz queue */ protected SQSPulseSensor(final Users usr, final Repo rpo, final SQSClient clnt) { this.users = usr; this.repo = rpo; this.client = clnt; for (int thread = 0; thread < SQSPulseSensor.THREADS; ++thread) { this.service.scheduleWithFixedDelay( this, TimeUnit.SECONDS.toMillis(1), 1, TimeUnit.MILLISECONDS ); } } /** * {@inheritDoc} */ @Override @SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops", "PMD.AvoidCatchingGenericException" }) public void run() { final AmazonSQS aws = this.client.get(); final ReceiveMessageResult result = aws.receiveMessage( new ReceiveMessageRequest() .withQueueUrl(this.client.url()) .withWaitTimeSeconds(Tv.TWENTY) .withVisibilityTimeout(Tv.FIVE) .withMaxNumberOfMessages(Tv.TEN) ); for (Message msg : result.getMessages()) { try { this.post(msg.getBody()); } catch (SecurityException ex) { Logger.info(this, ExceptionUtils.getRootCauseMessage(ex)); } catch (Exception ex) { Logger.warn(this, ExceptionUtils.getRootCauseMessage(ex)); } finally { aws.deleteMessage( new DeleteMessageRequest() .withQueueUrl(this.client.url()) .withReceiptHandle(msg.getReceiptHandle()) ); } } } /** * {@inheritDoc} */ @Override public void close() throws IOException { this.service.shutdown(); } /** * Post this JSON to the right stand. * @param json JSON to process */ private void post(final String json) { final JsonObject object = Json.createReader( new StringReader(json) ).readObject(); final Stand stand = this.users.stand(object.getString("stand")); final String key = object.getString("key"); if (!this.acl(stand).canPost(key)) { throw new SecurityException( String.format( "access denied to `%s` for '%s'", stand.name(), key ) ); } final JsonObject work = object.getJsonObject("work"); stand.post( String.format( "%s:%s:%s", work.getString("owner"), work.getString("unit"), work.getString("started") ), object.getString("xembly") ); } /** * Get ACL of a stand. * @param stand The stand * @return ACL */ private ACL acl(final Stand stand) { try { return ACL.class.cast( new Repo.Cached(this.repo, new User.Nobody(), stand.acl()) .get() .instantiate(this.users, new Arguments(new Work.None())) ); } catch (SpecException ex) { throw new IllegalStateException(ex); } } }
package transform; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Script { public List<String> m_warnings = new ArrayList<>(); private List<String> m_operations = new ArrayList<>(); // Temporary state, held only during a single MOVE resolution private List<String> head = new ArrayList<>(); private List<String> tail = new ArrayList<>(); private List<String> fromDiff; private List<String> toDiff; @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("# Generated: " + ZonedDateTime.now( ZoneOffset.UTC ) + " (UTC)\n#\n"); sb.append("# WARNINGS:\n#\n"); for (String s : m_warnings) { sb.append(s); sb.append("\n"); } if (m_warnings.isEmpty()) sb.append("# I got 99 problems, but your changes ain't one.\n"); sb.append("\n# SCRIPT:\n\nMODE FRAMED\n\n"); for (String s : m_operations) { sb.append(s); sb.append("\n"); } return sb.toString(); } public void resolveMove(String fromPath, String toPath) { List<String> from = Arrays.asList(fromPath.split(",")); List<String> to = Arrays.asList(toPath.split(",")); // make: // from = head + fromDiff + tail // to = head + toDiff + tail head = new ArrayList<>(); tail = new ArrayList<>(); fromDiff = new ArrayList<>(); toDiff = new ArrayList<>(); int i = 0; while ( from.get(i).equals(to.get(i)) ) head.add( from.get(i++) ); i = 0; while ( from.get( from.size()-i-1 ).equals(to.get( to.size()-i-1 )) ) { tail.add(0, from.get(from.size() - i - 1)); ++i; } fromDiff = from.subList( head.size(), from.size()-tail.size() ); toDiff = to.subList( head.size(), to.size()-tail.size() ); //System.err.println("head: " + head + " tail: " + tail + "\n\tfromDiff: " + fromDiff + "\n\ttoDiff: " + toDiff); List<String> operations = generatePivotPointMoves(); if (!operations.isEmpty()) { m_operations.add("# Resulting from observed grammar diff:\n# " + fromPath + "\n# -> " + toPath); m_operations.addAll(operations); m_operations.add(""); // empty line } } /** * Lists ("_list") forms pivots points of sorts in the transformation. In the diffing part of the path, * each list must be matched up to its transformed equivalence. If the number of "_list"s diff, the change * can't be resolved with any certainty (Which list should be collapsed?). */ private List<String> generatePivotPointMoves() { List<String> resultingOperations = new ArrayList<>(); boolean done; // Generate a move sequence for each _list pivot point do { done = true; int fromIndex = 0, toIndex = 0; while (fromIndex < fromDiff.size() && toIndex < toDiff.size()) { if (fromDiff.get(fromIndex).equals("_list") && toDiff.get(toIndex).equals("_list")) { List<String> sourceList = new ArrayList<>(); sourceList.addAll(head); sourceList.addAll(fromDiff.subList(0, fromIndex)); List<String> targetList = new ArrayList<>(); targetList.addAll(head); targetList.addAll(toDiff.subList(0, toIndex)); // Issue a command to make this move resultingOperations.addAll(generateMoveSequence(sourceList, targetList, 0, 0)); // Keep looking head.addAll(toDiff.subList(0, toIndex+1)); toDiff = toDiff.subList(toIndex+1, toDiff.size()); fromDiff = fromDiff.subList(fromIndex+1, fromDiff.size()); done = false; break; } if (!fromDiff.get(fromIndex).equals("_list")) ++fromIndex; if (!toDiff.get(toIndex).equals("_list")) ++toIndex; } } while (!done); //System.err.println("Remaining: " + fromDiff + " / " + toDiff); // Generate a move sequence for the remainder [last pivotpoint] -> end of toPath List<String> sourceList = new ArrayList<>(); sourceList.addAll(head); sourceList.addAll(fromDiff); List<String> targetList = new ArrayList<>(); targetList.addAll(head); targetList.addAll(toDiff); resultingOperations.addAll(generateMoveSequence(sourceList, targetList, 0, 0)); return resultingOperations; } private List<String> generateMoveSequence(List<String> sourcePath, List<String> targetPath, int startIndex, int indentation) { List<String> resultingOperations = new ArrayList<>(); for (int i = startIndex; i < Integer.min(sourcePath.size(), targetPath.size()); ++i) { if (sourcePath.get(i).equals("_list") && targetPath.get(i).equals("_list")) { List<String> newSourcePath = new ArrayList<>(); newSourcePath.addAll(sourcePath.subList(0, i)); newSourcePath.add("it"+indentation); newSourcePath.addAll(sourcePath.subList(i+1, sourcePath.size())); List<String> newTargetPath = new ArrayList<>(); newTargetPath.addAll(targetPath.subList(0, i)); newTargetPath.add("it"+indentation); newTargetPath.addAll(targetPath.subList(i+1, targetPath.size())); String tabs = ""; for (int j = 0; j < indentation; ++j) tabs += " "; String tabsP1 = ""; for (int j = 0; j < indentation+1; ++j) tabsP1 += " "; resultingOperations.add(tabs + "FOREACH it" + indentation + " : " + String.join(",", sourcePath.subList(0, i))); resultingOperations.add(tabs + "{"); List<String> nestedOps = generateMoveSequence(newSourcePath, newTargetPath, startIndex+1, indentation+1); resultingOperations.addAll(nestedOps); if (nestedOps.isEmpty()) resultingOperations.add(tabsP1 + "MOVE " + String.join(",",newSourcePath) + "\n" + tabsP1 + "-> " + String.join(",",newTargetPath)); resultingOperations.add(tabs + "}"); break; } } return resultingOperations; } }
package net.md_5.bungee; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.TimerTask; import net.md_5.bungee.api.ProxyServer; public class Metrics extends TimerTask { /** * The current revision number */ private final static int REVISION = 5; /** * The base url of the metrics domain */ private static final String BASE_URL = "http://mcstats.org"; /** * The url used to report a server's status */ private static final String REPORT_URL = "/report/%s"; /** * Interval of time to ping (in minutes) */ final static int PING_INTERVAL = 10; boolean firstPost = true; @Override public void run() { try { // We use the inverse of firstPost because if it is the first time we are posting, // it is not a interval ping, so it evaluates to FALSE // Each time thereafter it will evaluate to TRUE, i.e PING! postPlugin( !firstPost ); // After the first post we set firstPost to false // Each post thereafter will be a ping firstPost = false; } catch ( IOException ex ) { // ProxyServer.getInstance().getLogger().info( "[Metrics] " + ex.getMessage() ); } } /** * Generic method that posts a plugin to the metrics website */ private void postPlugin(boolean isPing) throws IOException { // Construct the post data final StringBuilder data = new StringBuilder(); data.append( encode( "guid" ) ).append( '=' ).append( encode( BungeeCord.getInstance().config.getUuid() ) ); encodeDataPair( data, "version", ProxyServer.getInstance().getVersion() ); encodeDataPair( data, "server", "0" ); encodeDataPair( data, "players", Integer.toString( ProxyServer.getInstance().getOnlineCount() ) ); encodeDataPair( data, "revision", String.valueOf( REVISION ) ); // If we're pinging, append it if ( isPing ) { encodeDataPair( data, "ping", "true" ); } // Create the url URL url = new URL( BASE_URL + String.format( REPORT_URL, encode( "BungeeCord" ) ) ); // Connect to the website URLConnection connection; connection = url.openConnection(); connection.setDoOutput( true ); final BufferedReader reader; final String response; try ( OutputStreamWriter writer = new OutputStreamWriter( connection.getOutputStream() ) ) { writer.write( data.toString() ); writer.flush(); reader = new BufferedReader( new InputStreamReader( connection.getInputStream() ) ); response = reader.readLine(); } reader.close(); if ( response == null || response.startsWith( "ERR" ) ) { throw new IOException( response ); //Throw the exception } } /** * <p>Encode a key/value data pair to be used in a HTTP post request. This * INCLUDES a & so the first key/value pair MUST be included manually, * e.g:</p> * <code> * StringBuffer data = new StringBuffer(); * data.append(encode("guid")).append('=').append(encode(guid)); * encodeDataPair(data, "version", description.getVersion()); * </code> * * @param buffer the StringBuilder to append the data pair onto * @param key the key value * @param value the value */ private static void encodeDataPair(final StringBuilder buffer, final String key, final String value) throws UnsupportedEncodingException { buffer.append( '&' ).append( encode( key ) ).append( '=' ).append( encode( value ) ); } /** * Encode text as UTF-8 * * @param text the text to encode * @return the encoded text, as UTF-8 */ private static String encode(final String text) throws UnsupportedEncodingException { return URLEncoder.encode( text, "UTF-8" ); } }
package FlightScheduler; // INPUT.JAVA // Input reader for Lab 4b airport and flight data // To read all the information necessary for this lab: // (1) Create an object (say, "input") of type Input. // (2) Call input.readAirports(<airportFileName>) // (3) Call input.readFlights(<flightFileName>) // Note that you *must* do (3) after (2). // If all goes well, you will then have access to // * input.airports -- an array of Airport objects // * input.flights -- an array of Flight objects import java.util.*; class Input { // Airport information class Airport { public String name; // name of airport (3-letter code) public int offset; // offset of local time from GMT (in minutes) public int id; // convenient integer identifier } // Flight information // NB: all times are GMT, in minutes since midnight class Flight { public String name; // flight name public Airport startAirport, endAirport; // flight termini public int startTime, endTime; // departure and arrival times } // array of all airports read from input public Airport airports[]; // array of all flights read from input public Flight flights[]; // mapping from airport codes (strings) to Airport objects public HashMap<String,Airport> airportMap; // constructor public Input() { airportMap = new HashMap<String,Airport>(); } // readAirports() // Read the airport file public void readAirports(String filename) { FileParser fp = new FileParser(filename); // hold the airports as they are read ArrayList<Airport> aplist = new ArrayList<Airport>(); while (!fp.isEof()) { Airport ap = new Airport(); ap.name = fp.readWord(); ap.offset = (fp.readInt() / 100) * 60; if (!fp.isEof()) { // crete mapping from names to objects airportMap.put(ap.name, ap); aplist.add(ap); } } airports = new Airport [aplist.size()]; aplist.toArray(airports); } // read the flight file public void readFlights(String filename) { FileParser fp = new FileParser(filename); // hold the flights as they are read ArrayList<Flight> fllist = new ArrayList<Flight>(); // read the flights and store their times in GMT while (!fp.isEof()) { Flight fl = new Flight(); String airline; int flightno; airline = fp.readWord(); flightno = fp.readInt(); fl.name = airline + "-" + flightno; if (fp.isEof()) break; String code; int tm; String ampm; code = fp.readWord(); fl.startAirport = airportMap.get(code); tm = fp.readInt(); ampm = fp.readWord(); fl.startTime = toTime(tm, ampm, fl.startAirport.offset); code = fp.readWord(); fl.endAirport = airportMap.get(code); tm = fp.readInt(); ampm = fp.readWord(); fl.endTime = toTime(tm, ampm, fl.endAirport.offset); fllist.add(fl); } flights = new Flight [fllist.size()]; fllist.toArray(flights); } // toTime() // convert raw time value and AM/PM in local time, to minutes // since midnight in GMT, using supplied offset from GMT. int toTime(int timeRaw, String ampm, int offset) { int hour = (timeRaw / 100) % 12; int minute = timeRaw % 100; boolean isPM = (ampm.charAt(0) == 'P'); int minutes = hour * 60 + minute; if (isPM) minutes += 12 * 60; int finalTime = (minutes - offset + 24 * 60) % (24 * 60); return finalTime; } }
package com.m12y.ld29; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; public class Floor { final Body body; public Floor(World world, ArrayList<Vector2> vertices) { BodyDef bodyDef = new BodyDef(); bodyDef.position.set(new Vector2(0, 0)); body = world.createBody(bodyDef); for (int i = 0; i < vertices.size(); i++) { ChainShape shape = new ChainShape(); shape.createChain(new Vector2[]{vertices.get(i), vertices.get((i+1)%vertices.size())}); shape.setPrevVertex(vertices.get((i-1+vertices.size())%vertices.size())); shape.setNextVertex(vertices.get((i+2)%vertices.size())); Fixture fixture = body.createFixture(shape, 0); fixture.setUserData("floor"); shape.dispose(); } } public static ArrayList<Vector2> corner(float x, float y, float r, int quadrant) { ArrayList<Vector2> vertices = new ArrayList<Vector2>(); float a; float b; switch (quadrant) { case 1: a = x-r; b = y-r; break; case 2: a = x+r; b = y-r; break; case 3: a = x+r; b = y+r; break; case 4: a = x-r; b = y+r; break; default: throw new RuntimeException("that ain't a quadrant i've heard of"); } for (float t = (quadrant-1) * MathUtils.PI/2; t < quadrant * MathUtils.PI/2; t += 0.05f/r) { vertices.add(new Vector2(a + r * MathUtils.cos(t), b + r * MathUtils.sin(t))); } return vertices; } public static ArrayList<Vector2> outerCorner(float x, float y, float r, int quadrant) { ArrayList<Vector2> vertices = new ArrayList<Vector2>(); float a; float b; switch (quadrant) { case 1: a = x-r; b = y-r; break; case 2: a = x+r; b = y-r; break; case 3: a = x+r; b = y+r; break; case 4: a = x-r; b = y+r; break; default: throw new RuntimeException("that ain't a quadrant i've heard of"); } for (float t = quadrant * MathUtils.PI/2; t > (quadrant-1) * MathUtils.PI/2; t -= 0.05f) { vertices.add(new Vector2(a + r * MathUtils.cos(t), b + r * MathUtils.sin(t))); } return vertices; } public static ArrayList<Vector2> floor() { ArrayList<Vector2> vertices = new ArrayList<Vector2>(); // Start vertices.add(new Vector2(0, 0)); // Big stairs vertices.add(new Vector2(5, 0)); vertices.add(new Vector2(5, 2)); vertices.add(new Vector2(7, 2)); vertices.add(new Vector2(7, 4)); vertices.add(new Vector2(9, 4)); // Pit vertices.add(new Vector2(9, -6)); vertices.add(new Vector2(8, -6)); // Underground corner vertices.addAll(corner(8, -4, 1, 1)); vertices.add(new Vector2(5, -4)); vertices.add(new Vector2(5, -10)); vertices.add(new Vector2(11, -10)); // Other side of pit vertices.add(new Vector2(11, 5)); vertices.add(new Vector2(13, 5)); vertices.add(new Vector2(13, 0)); // First corner vertices.addAll(corner(17, 0, 1, 4)); vertices.add(new Vector2(17, 4)); vertices.add(new Vector2(15, 4)); // Top right staircase vertices.add(new Vector2(15, 12)); vertices.add(new Vector2(14, 12)); vertices.add(new Vector2(14, 13)); vertices.add(new Vector2(13, 13)); vertices.add(new Vector2(13, 14)); // Top blocker vertices.add(new Vector2(1, 14)); vertices.add(new Vector2(1, 10)); vertices.add(new Vector2(-4, 10)); vertices.addAll(outerCorner(-4, 8, 1, 4)); vertices.add(new Vector2(-9, 8)); vertices.addAll(corner(-9, 0, 3, 3)); // End area vertices.add(new Vector2(-1, 0)); vertices.add(new Vector2(-1, 4)); vertices.add(new Vector2(-6, 4)); vertices.add(new Vector2(-6, 5)); vertices.add(new Vector2(0, 5)); return vertices; } public static ArrayList<Vector2> floater1() { ArrayList<Vector2> vertices = new ArrayList<Vector2>(); vertices.add(new Vector2(11, 11)); vertices.add(new Vector2(12, 11)); vertices.add(new Vector2(12, 10)); vertices.add(new Vector2(13, 10)); vertices.add(new Vector2(13, 9)); vertices.add(new Vector2(11, 9)); return vertices; } public static ArrayList<Vector2> floater2() { ArrayList<Vector2> vertices = new ArrayList<Vector2>(); vertices.add(new Vector2(5, 11)); vertices.add(new Vector2(8, 11)); vertices.add(new Vector2(8, 10)); vertices.add(new Vector2(5, 10)); return vertices; } public static void draw(ShapeRenderer shapeRenderer) { shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); shapeRenderer.setColor(LD29.WHITE); shapeRenderer.rect(0, 0, 5, 10); shapeRenderer.rect(5, 2, 2, 8); shapeRenderer.rect(7, 4, 4, 6); shapeRenderer.rect(11, 5, 4, 4); shapeRenderer.rect(13, 0, 2, 12); shapeRenderer.rect(15, 0, 1, 4); shapeRenderer.rect(16, 1, 1, 3); shapeRenderer.arc(16, 1, 1, 269, 91, 20); shapeRenderer.rect(9, -6, 2, 11); shapeRenderer.rect(5, -10, 6, 4); shapeRenderer.rect(5, -6, 2, 2); shapeRenderer.rect(7, -6, 1, 1); shapeRenderer.arc(7, -5, 1, -1, 92, 20); shapeRenderer.rect(12, 10, 2, 3); shapeRenderer.rect(1, 11, 12, 3); shapeRenderer.rect(1, 10, 4, 1); shapeRenderer.rect(8, 10, 3, 1); shapeRenderer.rect(-2, 5, 2, 5); shapeRenderer.rect(-4, 5, 2, 5); shapeRenderer.arc(-6, 3, 3, 180, 92, 20); shapeRenderer.rect(-9, 3, 2, 5); shapeRenderer.rect(-7, 3, 1, 2); shapeRenderer.rect(-7, 5, 3, 3); shapeRenderer.rect(-6, 0, 5, 4); shapeRenderer.rect(-5, 8, 1, 1); shapeRenderer.setColor(LD29.BLACK); shapeRenderer.arc(-5, 9, 1, 269, 92, 20); shapeRenderer.end(); } }
package water.api; import water.Key; import water.rapids.Session; import java.util.HashMap; public class InitIDHandler extends Handler { // For now, only 1 active Rapids session-per-cloud. Needs to be per-session // id... but clients then need to announce which session with each rapids call static HashMap<String, Session> SESSIONS = new HashMap<>(); @SuppressWarnings("unused") // called through reflection by RequestServer public InitIDV3 issue(int version, InitIDV3 p) { p.session_key = "_sid" + Key.make().toString().substring(0,5); return p; } @SuppressWarnings("unused") // called through reflection by RequestServer public InitIDV3 endSession(int version, InitIDV3 p) { if( SESSIONS.get(p.session_key) != null ) { try { SESSIONS.get(p.session_key).end(null); SESSIONS.remove(p.session_key); } catch( Throwable ex ) { throw SESSIONS.get(p.session_key).endQuietly(ex); } } return p; } }
package water.rapids; import water.*; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.Vec; import water.util.ArrayUtils; import water.util.Log; import water.util.Pair; import water.util.PrettyPrint; import java.util.Arrays; import java.util.Hashtable; class RadixCount extends MRTask<RadixCount> { public static class Long2DArray extends Iced { Long2DArray(int len) { _val = new long[len][]; } long _val[][]; } Long2DArray _counts; int _biggestBit; int _col; boolean _isLeft; // used to determine the unique DKV names since DF._key is null now and before only an RTMP name anyway RadixCount(boolean isLeft, int biggestBit, int col) { _isLeft = isLeft; _biggestBit = biggestBit; _col = col; } // make a unique deterministic key as a function of frame, column and node // make it homed to the owning node static Key getKey(boolean isLeft, int col, H2ONode node) { Key ans = Key.make("__radix_order__MSBNodeCounts_col" + col + "_node" + node.index() + (isLeft ? "_LEFT" : "_RIGHT")); // Each node's contents is different so the node number needs to be in the key // TO DO: need the biggestBit in here too, that the MSB is offset from //Log.info(ans.toString()); return ans; } @Override protected void setupLocal() { _counts = new Long2DArray(_fr.anyVec().nChunks()); } @Override public void map( Chunk chk ) { long tmp[] = _counts._val[chk.cidx()] = new long[256]; int shift = _biggestBit-8; if (shift<0) shift = 0; // TO DO: assert chk instanceof integer or enum; -- but how? // alternatively: chk.getClass().equals(C8Chunk.class) for (int r=0; r<chk._len; r++) { tmp[(int) (chk.at8(r) >> shift & 0xFFL)]++; // forget the L => wrong answer with no type warning from IntelliJ // TO DO - use _mem directly. Hist the compressed bytes and then shift the histogram afterwards when reducing. } } @Override protected void closeLocal() { //Log.info("Putting MSB counts for column " + _col + " over my chunks (node " + H2O.SELF + ") for frame " + _frameKey); //Log.info("Putting"); DKV.put(getKey(_isLeft, _col, H2O.SELF), _counts); // just the MSB counts per chunk on this node. Most of this spine will be empty here. TO DO: could condense to just the chunks on this node but for now, leave sparse. // We'll use this sparse spine right now on this node and the reduce happens on _o and _x later //super.postLocal(); } } class SplitByMSBLocal extends MRTask<SplitByMSBLocal> { private transient long _counts[][]; transient long _o[][][]; // transient ok because there is no reduce here between nodes, and important to save shipping back to caller. transient byte _x[][][]; boolean _isLeft; int _biggestBit, _batchSize, _bytesUsed[], _keySize; int[]_col; Key _linkTwoMRTask; static Hashtable<Key,SplitByMSBLocal> MOVESHASH = new Hashtable<>(); SplitByMSBLocal(boolean isLeft, int biggestBit, int keySize, int batchSize, int bytesUsed[], int[] col, Key linkTwoMRTask) { _isLeft = isLeft; _biggestBit = biggestBit; _batchSize=batchSize; _bytesUsed = bytesUsed; _col = col; _keySize = keySize; // ArrayUtils.sum(_bytesUsed) -1; _linkTwoMRTask = linkTwoMRTask; //setProfile(true); } @Override protected void setupLocal() { // First cumulate MSB count histograms across the chunks in this node // Log.info("Getting RadixCounts for column " + _col[0] + " from myself (node " + H2O.SELF + ") for Frame " + _frameKey ); // Log.info("Getting"); _counts = ((RadixCount.Long2DArray)DKV.getGet(RadixCount.getKey(_isLeft, _col[0], H2O.SELF)))._val; // get the sparse spine for this node, created and DKV-put above // try { // Thread.sleep(10000); // } catch (InterruptedException e) { // e.printStackTrace(); long _MSBhist[] = new long[256]; // total across nodes but retain original spine as we need that below int nc = _fr.anyVec().nChunks(); for (int c = 0; c < nc; c++) { if (_counts[c]!=null) { for (int h = 0; h < 256; h++) { _MSBhist[h] += _counts[c][h]; } } } if (ArrayUtils.maxValue(_MSBhist) > Math.max(1000, _fr.numRows() / 20 / H2O.CLOUD.size())) { // TO DO: better test of a good even split Log.warn("RadixOrder(): load balancing on this node not optimal (max value should be <= " + (Math.max(1000, _fr.numRows() / 20 / H2O.CLOUD.size())) + " " + Arrays.toString(_MSBhist) + ")"); } /*System.out.println("_MSBhist on this node (biggestBit==" + _biggestBit + ") ..."); for (int m=1; m<16; m+=2) { // print MSB 0-5, 16-21, etc to get a feel for distribution without wrapping line width when large numbers System.out.print(String.format("%3d",m*16) + ": "); for (int n=0; n<6; n++) System.out.print(String.format("%9d",_MSBhist[m*16 + n]) + " "); System.out.println(" ..."); }*/ // shared between threads on the same node, all mappers write into distinct locations (no conflicts, no need to atomic updates, etc.) System.out.print("Allocating _o and _x buckets on this node with known size up front ... "); long t0 = System.nanoTime(); _o = new long[256][][]; _x = new byte[256][][]; // for each bucket, there might be > 2^31 bytes, so an extra dimension for that for (int msb = 0; msb < 256; msb++) { if (_MSBhist[msb] == 0) continue; int nbatch = (int) (_MSBhist[msb]-1)/_batchSize +1; // at least one batch int lastSize = (int) (_MSBhist[msb] - (nbatch-1) * _batchSize); // the size of the last batch (could be batchSize) assert nbatch == 1; // Prevent large testing for now. TO DO: test nbatch>0 by reducing batchSize very small and comparing results with non-batched assert lastSize > 0; _o[msb] = new long[nbatch][]; _x[msb] = new byte[nbatch][]; int b; for (b = 0; b < nbatch-1; b++) { _o[msb][b] = new long[_batchSize]; // TO DO?: use MemoryManager.malloc8() _x[msb][b] = new byte[_batchSize * _keySize]; } _o[msb][b] = new long[lastSize]; _x[msb][b] = new byte[lastSize * _keySize]; } System.out.println("done in " + (System.nanoTime() - t0 / 1e9)); // TO DO: otherwise, expand width. Once too wide (and interestingly large width may not be a problem since small buckets won't impact cache), // start rolling up bins (maybe into pairs or even quads) // System.out.print("Columwise cumulate of chunk level MSB hists ... "); for (int msb = 0; msb < 256; msb++) { long rollSum = 0; // each of the 256 columns starts at 0 for the 0th chunk. This 0 offsets into x[MSBvalue][batch div][mod] and o[MSBvalue][batch div][mod] for (int c = 0; c < nc; c++) { if (_counts[c] == null) continue; long tmp = _counts[c][msb]; _counts[c][msb] = rollSum; //Warning: modify the POJO DKV cache, but that's fine since this node won't ask for the original DKV.get() version again rollSum += tmp; } } MOVESHASH.put(_linkTwoMRTask, this); // System.out.println("done"); // NB: no radix skipping in this version (unlike data.table we'll use biggestBit and assume further bits are used). } @Override public void map(Chunk chk[]) { // System.out.println("Starting MoveByFirstByte.map() for chunk " + chk[0].cidx()); long myCounts[] = _counts[chk[0].cidx()]; //cumulative offsets into o and x if (myCounts == null) { System.out.println("myCounts empty for chunk " + chk[0].cidx()); return; // TODO delete ... || _o==null || _x==null) return; } //int leftAlign = (8-(_biggestBit % 8)) % 8; // only the first column is left aligned, currently. But they all could be for better splitting. // Loop through this chunk and write the byte key and the source row into the local MSB buckets long t0 = System.nanoTime(); for (int r=0; r<chk[0]._len; r++) { // tight, branch free and cache efficient (surprisingly) long thisx = chk[0].at8(r); // - _colMin[0]) << leftAlign; (don't subtract colMin because it unlikely helps compression and makes joining 2 compressed keys more difficult and expensive). int shift = _biggestBit-8; if (shift<0) shift = 0; int MSBvalue = (int) (thisx >> shift & 0xFFL); long target = myCounts[MSBvalue]++; int batch = (int) (target / _batchSize); int offset = (int) (target % _batchSize); if (_o[MSBvalue] == null) throw new RuntimeException("Internal error: o_[MSBvalue] is null. Should never happen."); _o[MSBvalue][batch][offset] = (long) r + chk[0].start(); // move i and the index. byte this_x[] = _x[MSBvalue][batch]; offset *= _keySize; //can't overflow because batchsize was chosen above to be maxByteSize/max(keysize,8) for (int i = _bytesUsed[0] - 1; i >= 0; i--) { // a loop because I don't believe System.arraycopy() can copy parts of (byte[])long to byte[] this_x[offset + i] = (byte) (thisx & 0xFF); thisx >>= 8; } for (int c=1; c<chk.length; c++) { // TO DO: left align subsequent offset += _bytesUsed[c-1]-1; // advance offset by the previous field width thisx = chk[c].at8(r); // TO DO : compress with a scale factor such as dates stored as ms since epoch / 3600000L for (int i = _bytesUsed[c] - 1; i >= 0; i this_x[offset + i] = (byte) (thisx & 0xFF); thisx >>= 8; } } } // System.out.println(System.currentTimeMillis() + " MoveByFirstByte.map() into MSB buckets for chunk " + chk[0].cidx() + " took : " + (System.nanoTime() - t0) / 1e9); } static H2ONode ownerOfMSB(int MSBvalue) { // TO DO: this isn't properly working for efficiency. This value should pick the value of where it is, somehow. // Why not getSortedOXHeader(MSBvalue).home_node() ? //int blocksize = (int) Math.ceil(256. / H2O.CLOUD.size()); //H2ONode node = H2O.CLOUD._memary[MSBvalue / blocksize]; H2ONode node = H2O.CLOUD._memary[MSBvalue % H2O.CLOUD.size()]; // spread it around more. return node; } public static Key getNodeOXbatchKey(boolean isLeft, int MSBvalue, int node, int batch) { Key ans = Key.make("__radix_order__NodeOXbatch_MSB" + MSBvalue + "_node" + node + "_batch" + batch + (isLeft ? "_LEFT" : "_RIGHT"), (byte) 1, Key.HIDDEN_USER_KEY, false, SplitByMSBLocal.ownerOfMSB(MSBvalue)); return ans; } public static Key getSortedOXbatchKey(boolean isLeft, int MSBvalue, int batch) { Key ans = Key.make("__radix_order__SortedOXbatch_MSB" + MSBvalue + "_batch" + batch + (isLeft ? "_LEFT" : "_RIGHT"), (byte) 1, Key.HIDDEN_USER_KEY, false, SplitByMSBLocal.ownerOfMSB(MSBvalue)); return ans; } public static class OXbatch extends Iced { OXbatch(long[] o, byte[] x) { _o = o; _x = x; } long[/*batchSize or lastSize*/] _o; byte[/*batchSize or lastSize*/] _x; } public static Key getMSBNodeHeaderKey(boolean isLeft, int MSBvalue, int node) { Key ans = Key.make("__radix_order__OXNodeHeader_MSB" + MSBvalue + "_node" + node + (isLeft ? "_LEFT" : "_RIGHT"), (byte) 1, Key.HIDDEN_USER_KEY, false, SplitByMSBLocal.ownerOfMSB(MSBvalue)); return ans; } public static class MSBNodeHeader extends Iced { MSBNodeHeader(int MSBnodeChunkCounts[/*chunks*/]) { _MSBnodeChunkCounts = MSBnodeChunkCounts;} int _MSBnodeChunkCounts[]; // a vector of the number of contributions from each chunk. Since each chunk is length int, this must less than that, so int } // Push o/x in chunks to owning nodes void SendSplitMSB() { long t0 = System.nanoTime(); Futures fs = new Futures(); // System.out.println(System.currentTimeMillis() + " Starting MoveByFirstByte.PushFirstByteBatches() ... "); int nc = _fr.anyVec().nChunks(); long forLoopTime = 0, DKVputTime = 0, sumSize = 0; // The map() above ran above for each chunk on this node. Although this data was written to _o and _x in the order of chunk number (because we // calculated those offsets in order in the prior step), the chunk numbers will likely have gaps because chunks are distributed across nodes // not using a modulo approach but something like chunk1 on node1, chunk2 on node2, etc then modulo after that. Also, as tables undergo // changes as a result of user action, their distribution of chunks to nodes could change or be changed (e.g. 'Thomas' rebalance()') for various reasons. // When the helper node (i.e the node doing all the A's) gets the A's from this node, it must stack all this nodes' A's with the A's from the other // nodes in chunk order in order to maintain the original order of the A's within the global table. // To to do that, this node must tell the helper node where the boundaries are in _o and _x. That's what the first for loop below does. // The helper node doesn't need to be sent the corresponding chunk numbers. He already knows them from the Vec header which he already has locally. // TODO: perhaps write to o_ and x_ in batches in the first place, and just send more and smaller objects via the DKV. This makes the stitching much easier // on the helper node too, as it doesn't need to worry about batch boundaries in the source data. Then it might be easier to parallelize that helper part. // The thinking was that if each chunk generated 256 objects, that would flood the DKV with keys? // TODO: send nChunks * 256. Currently we do nNodes * 256. Or avoid DKV altogether if possible. for (int msb =0; msb <_o.length /*256*/; ++msb) { // TODO this can be done in parallel, surely // "I'll send you a long vector of _o and _x (batched if very long) along with where the boundaries are." // "You don't need to know the chunk numbers of these boundaries, because you know the node of each chunk from your local Vec header" long t00 = System.nanoTime(); if(_o[msb] == null) continue; int numChunks = 0; // how many of the chunks on this node had some rows with this MSB for (int c=0; c<nc; c++) { if (_counts[c] != null && _counts[c][msb] > 0) numChunks++; } int MSBnodeChunkCounts[] = new int[numChunks]; // make dense. And by construction (i.e. cumulative counts) these chunks contributed in order int j=0; long lastCount = 0; // _counts are cumulative at this stage so need to undo for (int c=0; c<nc; c++) { if (_counts[c] != null && _counts[c][msb] > 0) { MSBnodeChunkCounts[j] = (int)(_counts[c][msb] - lastCount); // _counts is long so it can be accumulated in-place I think. TO DO: check lastCount = _counts[c][msb]; j++; } } forLoopTime += System.nanoTime() - t00; //assert _MSBhist[msb] == ArrayUtils.sum(MSBnodeChunkCounts); MSBNodeHeader msbh = new MSBNodeHeader(MSBnodeChunkCounts); //Log.info("Putting MSB node headers for Frame " + _frameKey + " for MSB " + msb); //Log.info("Putting msb " + msb + " on node " + H2O.SELF.index()); DKV.put(getMSBNodeHeaderKey(_isLeft, msb, H2O.SELF.index()), msbh, fs, true); for (int b=0;b<_o[msb].length; ++b) { OXbatch ox = new OXbatch(_o[msb][b], _x[msb][b]); // this does not copy in Java, just references //Log.info("Putting OX batch for Frame " + _frameKey + " for batch " + b + " for MSB " + msb); //Log.info("Putting"); sumSize += _o[msb][b].length * 8 + _x[msb][b].length * _keySize + 64; t00 = System.nanoTime(); DKV.put(getNodeOXbatchKey(_isLeft, msb, H2O.SELF.index(), b), ox, fs, true); // TODO: send to particular node long thist = System.nanoTime() - t00; // System.out.println("This DKV put took : " + thist / 1e9); // TODO: adding fs (does it need ,fs,true?) above didn't appear to make it go in parallel. Apx 200 prints of 0.07 = 14s total DKVputTime += thist; } } System.out.println("this node took : " + (System.nanoTime() - t0) / 1e9); System.out.println(" Finding the chunk boundaries in split OX took " + forLoopTime / 1e9); System.out.println(" DKV.put " + PrettyPrint.bytes(sumSize) + " in " + DKVputTime / 1e9 + ". Overall rate: " + String.format("%.3f", sumSize / (DKVputTime/1e9) / (1024*1024*1024)) + " GByte/sec [10Gbit = 1.25GByte/sec]"); } } class SendSplitMSB extends MRTask<SendSplitMSB> { Key _linkTwoMRTask; SendSplitMSB(Key linkTwoMRTask) { _linkTwoMRTask = linkTwoMRTask; } @Override public void setupLocal() { SplitByMSBLocal.MOVESHASH.get(_linkTwoMRTask).SendSplitMSB(); SplitByMSBLocal.MOVESHASH.remove(_linkTwoMRTask); } } // It is intended that several of these SingleThreadRadixOrder run on the same node, to utilize the cores available. // The initial MSB needs to split by num nodes * cpus per node; e.g. 256 is pretty good for 10 nodes of 32 cores. Later, use 9 bits, or a few more bits accordingly. // Its this 256 * 4kB = 1MB that needs to be < cache per core for cache write efficiency in MoveByFirstByte(). 10 bits (1024 threads) would be 4MB which still < L2 // Since o[] and x[] are arrays here (not Vecs) it's harder to see how to parallelize inside this function. Therefore avoid that issue by using more threads in calling split. // General principle here is that several parallel, tight, branch free loops, faster than one heavy DKV pass per row class SingleThreadRadixOrder extends DTask<SingleThreadRadixOrder> { //long _nGroup[]; int _MSBvalue; // only needed to be able to return the number of groups back to the caller RadixOrder int _keySize, _batchSize; long _numRows; Frame _fr; boolean _isLeft; private transient long _o[/*batch*/][]; private transient byte _x[/*batch*/][]; private transient long _otmp[][]; private transient byte _xtmp[][]; // TEMPs private transient long counts[][]; private transient byte keytmp[]; //public long _groupSizes[][]; // outputs ... // o and x are changed in-place always // iff _groupsToo==true then the following are allocated and returned //int _MSBvalue; // Most Significant Byte value this node is working on //long _nGroup[/*MSBvalue*/]; // number of groups found (could easily be > BATCHLONG). Each group has its size stored in _groupSize. //long _groupSize[/*MSBvalue*/][/*_nGroup div BATCHLONG*/][/*mod*/]; // Now taken out ... boolean groupsToo, long groupSize[][][], long nGroup[], int MSBvalue //long _len; //int _byte; SingleThreadRadixOrder(Frame fr, boolean isLeft, int batchSize, int keySize, /*long nGroup[],*/ int MSBvalue) { _fr = fr; _isLeft = isLeft; _batchSize = batchSize; _keySize = keySize; //_nGroup = nGroup; _MSBvalue = MSBvalue; } @Override protected void compute2() { keytmp = new byte[_keySize]; counts = new long[_keySize][256]; SplitByMSBLocal.MSBNodeHeader[] MSBnodeHeader = new SplitByMSBLocal.MSBNodeHeader[H2O.CLOUD.size()]; _numRows =0; for (int n=0; n<H2O.CLOUD.size(); n++) { // Log.info("Getting MSB " + MSBvalue + " Node Header from node " + n + "/" + H2O.CLOUD.size() + " for Frame " + _fr._key); // Log.info("Getting"); MSBnodeHeader[n] = DKV.getGet(SplitByMSBLocal.getMSBNodeHeaderKey(_isLeft, _MSBvalue, n)); if (MSBnodeHeader[n]==null) continue; _numRows += ArrayUtils.sum(MSBnodeHeader[n]._MSBnodeChunkCounts); // This numRows is split into nbatch batches on that node. // This header has the counts of each chunk (the ordered chunk numbers on that node) } if (_numRows == 0) { tryComplete(); return; } // Allocate final _o and _x for this MSB which is gathered together on this node from the other nodes. int nbatch = (int) (_numRows -1) / _batchSize +1; // at least one batch. TO DO: as Arno suggested, wrap up into class for fixed width batching (to save espc overhead) int lastSize = (int) (_numRows - (nbatch-1) * _batchSize); // the size of the last batch (could be batchSize, too if happens to be exact multiple of batchSize) _o = new long[nbatch][]; _x = new byte[nbatch][]; int b; for (b = 0; b < nbatch-1; b++) { _o[b] = new long[_batchSize]; // TO DO?: use MemoryManager.malloc8() _x[b] = new byte[_batchSize * _keySize]; } _o[b] = new long[lastSize]; _x[b] = new byte[lastSize * _keySize]; SplitByMSBLocal.OXbatch ox[/*node*/] = new SplitByMSBLocal.OXbatch[H2O.CLOUD.size()]; int oxBatchNum[/*node*/] = new int[H2O.CLOUD.size()]; // which batch of OX are we on from that node? Initialized to 0. for (int node=0; node<H2O.CLOUD.size(); node++) { //TO DO: why is this serial? Relying on // Log.info("Getting OX MSB " + MSBvalue + " batch 0 from node " + node + "/" + H2O.CLOUD.size() + " for Frame " + _fr._key); // Log.info("Getting"); Key k = SplitByMSBLocal.getNodeOXbatchKey(_isLeft, _MSBvalue, node, /*batch=*/0); assert k.home(); ox[node] = DKV.getGet(k); // get the first batch for each node for this MSB } int oxOffset[] = new int[H2O.CLOUD.size()]; int oxChunkIdx[] = new int[H2O.CLOUD.size()]; // that node has n chunks and which of those are we currently on? int targetBatch = 0, targetOffset = 0, targetBatchRemaining = _batchSize; for (int c=0; c<_fr.anyVec().nChunks(); c++) { int fromNode = _fr.anyVec().chunkKey(c).home_node().index(); // each chunk in the column may be on different nodes // See long comment at the top of SendSplitMSB. One line from there repeated here : // " When the helper node (i.e. this one, now) (i.e the node doing all the A's) gets the A's from that node, it must stack all the nodes' A's // with the A's from the other nodes in chunk order in order to maintain the original order of the A's within the global table. " // TODO: We could process these in node order and or/in parallel if we cumulated the counts first to know the offsets - should be doable and high value if (MSBnodeHeader[fromNode] == null) continue; int numRowsToCopy = MSBnodeHeader[fromNode]._MSBnodeChunkCounts[oxChunkIdx[fromNode]++]; // magically this works, given the outer for loop through global chunk // _MSBnodeChunkCounts is a vector of the number of contributions from each Vec chunk. Since each chunk is length int, this must less than that, so int // The set of data corresponding to the Vec chunk contributions is stored packed in batched vectors _o and _x. int sourceBatchRemaining = _batchSize - oxOffset[fromNode]; // at most batchSize remaining. No need to actually put the number of rows left in here while (numRowsToCopy > 0) { // No need for class now, as this is a bit different to the other batch copier. Two isn't too bad. int thisCopy = Math.min(numRowsToCopy, Math.min(sourceBatchRemaining, targetBatchRemaining)); System.arraycopy(ox[fromNode]._o, oxOffset[fromNode], _o[targetBatch], targetOffset, thisCopy); System.arraycopy(ox[fromNode]._x, oxOffset[fromNode]*_keySize, _x[targetBatch], targetOffset*_keySize, thisCopy*_keySize); numRowsToCopy -= thisCopy; oxOffset[fromNode] += thisCopy; sourceBatchRemaining -= thisCopy; targetOffset += thisCopy; targetBatchRemaining -= thisCopy; if (sourceBatchRemaining == 0) { // delete and free node's OX batch. Have moved all its contents into _o and _x. Remove so as to avoid mistakenly picking it up in future and to free up memory as early as possible. DKV.remove(SplitByMSBLocal.getNodeOXbatchKey(_isLeft, _MSBvalue, fromNode, oxBatchNum[fromNode])); // fetched the next batch : ox[fromNode] = DKV.getGet(SplitByMSBLocal.getNodeOXbatchKey(_isLeft, _MSBvalue, fromNode, ++oxBatchNum[fromNode])); if (ox[fromNode] == null) { // if the last chunksworth fills a batchsize exactly, the getGet above will have returned null. // TODO: Check will Cliff that a known fetch of a non-existent key is ok e.g. won't cause a delay/block? If ok, leave as good check. assert oxBatchNum[fromNode]==MSBnodeHeader[fromNode]._MSBnodeChunkCounts.length; assert ArrayUtils.sum(MSBnodeHeader[fromNode]._MSBnodeChunkCounts) % _batchSize == 0; } oxOffset[fromNode] = 0; sourceBatchRemaining = _batchSize; } if (targetBatchRemaining == 0) { targetBatch++; targetOffset = 0; targetBatchRemaining = _batchSize; } } } // Now remove the last batch on each node from DKV. Have used it all now (moved into _o and _x). Remove as early as possible to save memory. for (int node = 0; node < H2O.CLOUD.size(); node++) { if (MSBnodeHeader[node] == null) continue; // no contributions from that node long nodeNumRows = ArrayUtils.sum(MSBnodeHeader[node]._MSBnodeChunkCounts); assert nodeNumRows >= 1; if (nodeNumRows % _batchSize == 0) { // already should have been removed above in 'if (sourceBatchRemaining == 0)' assert ox[node] == null; } else { assert ox[node] != null; assert oxBatchNum[node] == (nodeNumRows-1) / _batchSize; DKV.remove(SplitByMSBLocal.getNodeOXbatchKey(_isLeft, _MSBvalue, node, oxBatchNum[node])); } } // We now have _o and _x collated from all the contributing nodes, in the correct original order. _xtmp = new byte[_x.length][]; _otmp = new long[_o.length][]; assert _x.length == _o.length; // i.e. aligned batch size between x and o (think 20 bytes keys and 8 bytes of long in o) for (int i=0; i<_x.length; i++) { // Seems like no deep clone available in Java. Maybe System.arraycopy but maybe that needs target to be allocated first _xtmp[i] = Arrays.copyOf(_x[i], _x[i].length); _otmp[i] = Arrays.copyOf(_o[i], _o[i].length); } // TO DO: a way to share this working memory between threads. // Just create enough for the 4 threads active at any one time. Not 256 allocations and releases. // We need o[] and x[] in full for the result. But this way we don't need full size xtmp[] and otmp[] at any single time. // Currently Java will allocate and free these xtmp and otmp and maybe it does good enough job reusing heap that we don't need to explicitly optimize this reuse. // Perhaps iterating this task through the largest bins first will help java reuse heap. //_groupSizes = new long[256][]; //_groups = groups; //_nGroup = nGroup; //_whichGroup = whichGroup; //_groups[_whichGroup] = new long[(int)Math.min(MAXVECLONG, len) ]; // at most len groups (i.e. all groups are 1 row) assert(_o != null); assert(_numRows > 0); // The main work. Radix sort this batch ... run(0, _numRows, _keySize-1); // if keySize is 6 bytes, first byte is byte 5 // don't need to clear these now using private transient // _counts = null; // keytmp = null; //_nGroup = null; // tell the world how many batches and rows for this MSB OXHeader msbh = new OXHeader(_o.length, _numRows, _batchSize); // Log.info("Putting MSB header for Frame " + _fr._key + " for MSB " + _MSBvalue); // Log.info("Putting"); Futures fs = new Futures(); DKV.put(getSortedOXHeaderKey(_isLeft, _MSBvalue), msbh, fs, true); for (b=0; b<_o.length; b++) { SplitByMSBLocal.OXbatch tmp = new SplitByMSBLocal.OXbatch(_o[b], _x[b]); // Log.info("Putting OX header for Frame " + _fr._key + " for MSB " + _MSBvalue); // Log.info("Putting"); DKV.put(SplitByMSBLocal.getSortedOXbatchKey(_isLeft, _MSBvalue, b), tmp, fs, true); // the OXbatchKey's on this node will be reused for the new keys } fs.blockForPending(); tryComplete(); } public static Key getSortedOXHeaderKey(boolean isLeft, int MSBvalue) { // This guy has merges together data from all nodes and its data is not "from" any particular node. Therefore node number should not be in the key. Key ans = Key.make("__radix_order__SortedOXHeader_MSB" + MSBvalue + (isLeft ? "_LEFT" : "_RIGHT")); // If we don't say this it's random ... (byte) 1 /*replica factor*/, (byte) 31 /*hidden user-key*/, true, H2O.SELF); //if (MSBvalue==73) Log.info(ans.toString()); return ans; } public static class OXHeader extends Iced { OXHeader(int batches, long numRows, int batchSize) { _nBatch = batches; _numRows = numRows; _batchSize = batchSize; } int _nBatch; long _numRows; int _batchSize; } int keycmp(byte x[], int xi, byte y[], int yi) { // Same return value as strcmp in C. <0 => xi<yi xi *= _keySize; yi *= _keySize; int len = _keySize; while (len > 1 && x[xi] == y[yi]) { xi++; yi++; len return ((x[xi] & 0xFF) - (y[yi] & 0xFF)); // 0xFF for getting back from -1 to 255 } public void insert(long start, int len) // only for small len so len can be type int /* orders both x and o by reference in-place. Fast for small vectors, low overhead. don't be tempted to binsearch backwards here because have to shift anyway */ { int batch0 = (int) (start / _batchSize); int batch1 = (int) (start+len-1) / _batchSize; long origstart = start; // just for when straddle batch boundaries int len0 = 0; // same // _nGroup[_MSBvalue]++; // TODO: reinstate. This is at least 1 group (if all keys in this len items are equal) byte _xbatch[]; long _obatch[]; if (batch1 != batch0) { // small len straddles a batch boundary. Unlikely very often since len<=200 assert batch0 == batch1-1; len0 = _batchSize - (int)(start % _batchSize); // copy two halves to contiguous temp memory, do the below, then split it back to the two halves afterwards. // Straddles batches very rarely (at most once per batch) so no speed impact at all. _xbatch = new byte[len * _keySize]; System.arraycopy(_xbatch, 0, _x[batch0], (int)((start % _batchSize)*_keySize), len0*_keySize); System.arraycopy(_xbatch, len0*_keySize, _x[batch1], 0, (len-len0)*_keySize); _obatch = new long[len]; System.arraycopy(_obatch, 0, _o[batch0], (int)(start % _batchSize), len0); System.arraycopy(_obatch, len0, _o[batch1], 0, len-len0); start = 0; } else { _xbatch = _x[batch0]; // taking this outside the loop does indeed make quite a big different (hotspot isn't catching this, then) _obatch = _o[batch0]; } int offset = (int) (start % _batchSize); for (int i=1; i<len; i++) { int cmp = keycmp(_xbatch, offset+i, _xbatch, offset+i-1); // TO DO: we don't need to compare the whole key here. Set cmpLen < keySize if (cmp < 0) { System.arraycopy(_xbatch, (offset+i)*_keySize, keytmp, 0, _keySize); int j = i - 1; long otmp = _obatch[offset+i]; do { System.arraycopy(_xbatch, (offset+j)*_keySize, _xbatch, (offset+j+1)*_keySize, _keySize); _obatch[offset+j+1] = _obatch[offset+j]; j } while (j >= 0 && (cmp = keycmp(keytmp, 0, _xbatch, offset+j))<0); System.arraycopy(keytmp, 0, _xbatch, (offset+j+1)*_keySize, _keySize); _obatch[offset + j + 1] = otmp; } //if (cmp>0) _nGroup[_MSBvalue]++; //TODO: reinstate _nGroup. Saves sweep afterwards. Possible now that we don't maintain the group sizes in this deep pass, unlike data.table // saves call to push() and hop to _groups // _nGroup == nrow afterwards tells us if the keys are unique. // Sadly, it seems _nGroup += (cmp==0) isn't possible in Java even with explicit cast of boolean to int, so branch needed } if (batch1 != batch0) { // Put the sorted data back into original two places straddling the boundary System.arraycopy(_x[batch0], (int)(origstart % _batchSize) *_keySize, _xbatch, 0, len0*_keySize); System.arraycopy(_x[batch1], 0, _xbatch, len0*_keySize, (len-len0)*_keySize); System.arraycopy(_o[batch0], (int)(origstart % _batchSize), _obatch, 0, len0); System.arraycopy(_o[batch1], 0, _obatch, len0, len-len0); } } public void run(long start, long len, int Byte) { // System.out.println("run " + start + " " + len + " " + Byte); if (len < 200) { // N_SMALL=200 is guess based on limited testing. Needs calibrate(). // Was 50 based on sum(1:50)=1275 worst -vs- 256 cummulate + 256 memset + allowance since reverse order is unlikely. insert(start, (int)len); // when nalast==0, iinsert will be called only from within iradix. // TO DO: inside insert it doesn't need to compare the bytes so far as they're known equal, so pass Byte (NB: not Byte-1) through to insert() // TO DO: Maybe transposing keys to be a set of _keySize byte columns might in fact be quicker - no harm trying. What about long and varying length string keys? return; } int batch0 = (int) (start / _batchSize); int batch1 = (int) (start+len-1) / _batchSize; // could well span more than one boundary when very large number of rows. // assert batch0==0; // assert batch0==batch1; // Count across batches of 2Bn is now done. Wish we had 64bit indexing in Java. long thisHist[] = counts[Byte]; // thisHist reused and carefully set back to 0 below so we don't need to clear it now int idx = (int)(start%_batchSize)*_keySize + _keySize-Byte-1; int bin=-1; // the last bin incremented. Just to see if there is only one bin with a count. int nbatch = batch1-batch0+1; // number of batches this span of len covers. Usually 1. Minimum 1. int thisLen = (int)Math.min(len, _batchSize - start%_batchSize); for (int b=0; b<nbatch; b++) { byte _xbatch[] = _x[batch0+b]; // taking this outside the loop below does indeed make quite a big different (hotspot isn't catching this, then) for (int i = 0; i < thisLen; i++) { bin = 0xff & _xbatch[idx]; thisHist[bin]++; idx += _keySize; // maybe TO DO: shorten key by 1 byte on each iteration, so we only need to thisx && 0xFF. No, because we need for construction of final table key columns. } idx = _keySize-Byte-1; thisLen = (b==nbatch-2/*next iteration will be last batch*/ ? (int)(start+len-1)%_batchSize : _batchSize); // thisLen will be set to _batchSize for the middle batches when nbatch>=3 } if (thisHist[bin] == len) { // one bin has count len and the rest zero => next byte quick thisHist[bin] = 0; // important, clear for reuse if (Byte == 0) ; // TODO: reinstate _nGroup[_MSBvalue]++; else run(start, len, Byte - 1); return; } long rollSum = 0; for (int c = 0; c < 256; c++) { long tmp = thisHist[c]; if (tmp == 0) continue; // important to skip zeros for logic below to undo cumulate. Worth the branch to save a deeply iterative memset back to zero thisHist[c] = rollSum; rollSum += tmp; } // Sigh. Now deal with batches here as well because Java doesn't have 64bit indexing. int oidx = (int)(start%_batchSize); int xidx = oidx*_keySize + _keySize-Byte-1; thisLen = (int)Math.min(len, _batchSize - start%_batchSize); for (int b=0; b<nbatch; b++) { long _obatch[] = _o[batch0+b]; // taking these outside the loop below does indeed make quite a big different (hotspot isn't catching this, then) byte _xbatch[] = _x[batch0+b]; for (int i = 0; i < thisLen; i++) { long target = thisHist[0xff & _xbatch[xidx]]++; // now always write to the beginning of _otmp and _xtmp just to reuse the first hot pages _otmp[(int)(target/_batchSize)][(int)(target%_batchSize)] = _obatch[oidx+i]; // this must be kept in 8 bytes longs System.arraycopy(_xbatch, (oidx+i)*_keySize, _xtmp[(int)(target/_batchSize)], (int)(target%_batchSize)*_keySize, _keySize ); xidx += _keySize; // Maybe TO DO: this can be variable byte width and smaller widths as descend through bytes (TO DO: reverse byte order so always doing &0xFF) } xidx = _keySize-Byte-1; oidx = 0; thisLen = (b==nbatch-2/*next iteration will be last batch*/ ? (int)(start+len-1)%_batchSize : _batchSize); } // now copy _otmp and _xtmp back over _o and _x from the start position, allowing for boundaries // _o, _x, _otmp and _xtmp all have the same _batchsize // Would be really nice if Java had 64bit indexing to save programmer time. long numRowsToCopy = len; int sourceBatch = 0, sourceOffset = 0; int targetBatch = (int)(start / _batchSize), targetOffset = (int)(start % _batchSize); int targetBatchRemaining = _batchSize - targetOffset; // 'remaining' means of the the full batch, not of the numRowsToCopy int sourceBatchRemaining = _batchSize - sourceOffset; // at most batchSize remaining. No need to actually put the number of rows left in here int thisCopy; while (numRowsToCopy > 0) { // TO DO: put this into class as well, to ArrayCopy into batched thisCopy = (int)Math.min(numRowsToCopy, Math.min(sourceBatchRemaining, targetBatchRemaining)); System.arraycopy(_otmp[sourceBatch], sourceOffset, _o[targetBatch], targetOffset, thisCopy); System.arraycopy(_xtmp[sourceBatch], sourceOffset*_keySize, _x[targetBatch], targetOffset*_keySize, thisCopy*_keySize); numRowsToCopy -= thisCopy; // sourceBatch no change sourceOffset += thisCopy; sourceBatchRemaining -= thisCopy; targetOffset += thisCopy; targetBatchRemaining -= thisCopy; if (sourceBatchRemaining == 0) { sourceBatch++; sourceOffset = 0; sourceBatchRemaining = _batchSize; } if (targetBatchRemaining == 0) { targetBatch++; targetOffset = 0; targetBatchRemaining = _batchSize; } // 'source' and 'target' deliberately the same length variable names and long lines deliberately used so we // can easy match them up vertically to ensure they are the same } long itmp = 0; for (int i=0; i<256; i++) { if (thisHist[i]==0) continue; long thisgrpn = thisHist[i] - itmp; if (thisgrpn == 1 || Byte == 0) { //TODO reinstate _nGroup[_MSBvalue]++; } else { run(start+itmp, thisgrpn, Byte-1); } itmp = thisHist[i]; thisHist[i] = 0; // important, to save clearing counts on next iteration } } } public class RadixOrder { int _biggestBit[]; int _bytesUsed[]; //long[][][] _o; //byte[][][] _x; RadixOrder(Frame DF, boolean isLeft, int whichCols[]) { //System.out.println("Calling RadixCount ..."); long t0 = System.nanoTime(); _biggestBit = new int[whichCols.length]; // currently only biggestBit[0] is used _bytesUsed = new int[whichCols.length]; //long colMin[] = new long[whichCols.length]; for (int i = 0; i < whichCols.length; i++) { Vec col = DF.vec(whichCols[i]); //long range = (long) (col.max() - col.min()); //assert range >= 1; // otherwise log(0)==-Inf next line _biggestBit[i] = 1 + (int) Math.floor(Math.log(col.max()) / Math.log(2)); // number of bits starting from 1 easier to think about (for me) _bytesUsed[i] = (int) Math.ceil(_biggestBit[i] / 8.0); //colMin[i] = (long) col.min(); // TO DO: non-int/enum } if (_biggestBit[0] < 8) Log.warn("biggest bit should be >= 8 otherwise need to dip into next column (TODO)"); // TODO: feeed back to R warnings() int keySize = ArrayUtils.sum(_bytesUsed); // The MSB is stored (seemingly wastefully on first glance) because we need it when aligning two keys in Merge() int batchSize = 256*1024*1024 / Math.max(keySize, 8) / 2 ; // 256MB is the DKV limit. / 2 because we fit o and x together in one OXBatch. // The Math.max ensures that batches of o and x are aligned, even for wide keys. To save % and / in deep iteration; e.g. in insert(). System.out.println("Time to use rollup stats to determine biggestBit: " + (System.nanoTime() - t0) / 1e9); t0 = System.nanoTime(); new RadixCount(isLeft, _biggestBit[0], whichCols[0]).doAll(DF.vec(whichCols[0])); System.out.println("Time of MSB count MRTask left local on each node (no reduce): " + (System.nanoTime() - t0) / 1e9); // NOT TO DO: we do need the full allocation of x[] and o[]. We need o[] anyway. x[] will be compressed and dense. // o is the full ordering vector of the right size // x is the byte key aligned with o // o AND x are what bmerge() needs. Pushing x to each node as well as o avoids inter-node comms. // System.out.println("Starting MSB hist reduce across nodes and SplitByMSBLocal MRTask ..."); // Workaround for incorrectly blocking closeLocal() in MRTask is to do a double MRTask and pass a key between them to pass output // from first on that node to second on that node. // TODO: fix closeLocal() blocking issue and revert to simpler usage of closeLocal() t0 = System.nanoTime(); Key linkTwoMRTask = Key.make(); SplitByMSBLocal tmp = new SplitByMSBLocal(isLeft, _biggestBit[0], keySize, batchSize, _bytesUsed, whichCols, linkTwoMRTask).doAll(DF.vecs(whichCols)); // postLocal needs DKV.put() System.out.println("SplitByMSBLocal MRTask (all local per node, no network) took : " + (System.nanoTime() - t0) / 1e9); System.out.print(tmp.profString()); System.out.print("Starting SendSplitMSB ... "); t0 = System.nanoTime(); new SendSplitMSB(linkTwoMRTask).doAllNodes(); System.out.println("SendSplitMSB across all nodes took : " + (System.nanoTime() - t0) / 1e9); //long nGroup[] = new long[257]; // one extra for later to make undo of cumulate easier when finding groups. TO DO: let grouper do that and simplify here to 256 // dispatch in parallel RPC[] radixOrders = new RPC[256]; System.out.print("Sending SingleThreadRadixOrder async RPC calls ... "); t0 = System.nanoTime(); for (int i = 0; i < 256; i++) { //System.out.print(i+" "); radixOrders[i] = new RPC<>(SplitByMSBLocal.ownerOfMSB(i), new SingleThreadRadixOrder(DF, isLeft, batchSize, keySize, /*nGroup,*/ i)).call(); } System.out.println("took : " + (System.nanoTime() - t0) / 1e9); System.out.print("Waiting for RPC SingleThreadRadixOrder to finish ... "); t0 = System.nanoTime(); int i=0; for (RPC rpc : radixOrders) { //TODO: Use a queue to make this fully async // System.out.print(i+" "); rpc.get(); //SingleThreadRadixOrder radixOrder = (SingleThreadRadixOrder)rpc.get(); // TODO: make sure all transient here i++; } System.out.println("took " + (System.nanoTime() - t0) / 1e9); // serial, do one at a time // for (int i = 0; i < 256; i++) { // H2ONode node = MoveByFirstByte.ownerOfMSB(i); // SingleThreadRadixOrder radixOrder = new RPC<>(node, new SingleThreadRadixOrder(DF, batchSize, keySize, nGroup, i)).call().get(); // _o[i] = radixOrder._o; // _x[i] = radixOrder._x; // If sum(nGroup) == nrow then the index is unique. // 1) useful to know if an index is unique or not (when joining to it we know multiples can't be returned so can allocate more efficiently) // 2) If all groups are size 1 there's no need to actually allocate an all-1 group size vector (perhaps user was checking for uniqueness by counting group sizes) // 3) some nodes may have unique input and others may contain dups; e.g., in the case of looking for rare dups. So only a few threads may have found dups. // 4) can sweep again in parallel and cache-efficient finding the groups, and allocate known size up front to hold the group sizes. // 5) can return to Flow early with the group count. User may now realise they selected wrong columns and cancel early. } }
package mil.emp3.api; import junit.framework.TestCase; import org.mockito.internal.matchers.Contains; import java.net.URI; import mil.emp3.api.exceptions.EMP_Exception; import mil.emp3.mirrorcache.MirrorCacheClient; import mil.emp3.mirrorcache.MirrorCacheException; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mock; public class MirrorCacheTest extends TestCase { }
package io.github.ihongs; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import java.util.TimeZone; import java.util.Locale; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.function.Supplier; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * * * <p> * Servlet , * ; * Core , , * , * getInstance . * Core Core.getInstance() * </p> * * <p> * : , . * THREAD_CORE ThreadLocal, * , * ; * GLOBAL_CORE , , * Cleanable,Singleton . * </p> * * <h3>:</h3> * <pre> * ENVIR (0 cmd, 1 web) * DEBUG (0 , 1 , 2 , 4 8 ; 3 ) * BASE_HREF (WEBContextPath) * BASE_PATH (WEBRealPath(/)) * CORE_PATH (WEBWEB-INF) * CONF_PATH * DATA_PATH * SERVER_ID ID ( Core.getUniqueId()) * : Servlet/Filter/Cmdlet . * </pre> * * <h3>:</h3> * <pre> * 0x24 * 0x25 * 0x26 * 0x27 * 0x28 * </pre> * * @author Hongs */ public class Core extends HashMap<String, Object> implements AutoCloseable { /** * * * @param <T> * @param klass [.].class * @return */ public <T> T get(Class<T> klass) { String name = klass.getName( ); Core core = Core.GLOBAL_CORE; if (this.containsKey(name)) { return (T)this.got(name); } if (core.containsKey(name)) { return (T)core.got(name); } T inst = newInstance (klass); if (inst instanceof Singleton) { this.put( name, inst ); } else { core.put( name, inst ); } return inst; } /** * * * @param name [.] * @return */ public Object get(String name) { Core core = Core.GLOBAL_CORE; if (this.containsKey(name)) { return this.got(name); } if (core.containsKey(name)) { return core.got(name); } Object inst =newInstance(name); if (inst instanceof Singleton) { this.put( name, inst ); } else { core.put( name, inst ); } return inst; } /** * get * * @param name * @return , */ public Object got(String name) { return super.get(name); } /** * get(Object), got(String),get(String|Class) * * @param name * @return , * @throws UnsupportedOperationException * @deprecated */ @Override public Object get(Object name) { throw new UnsupportedOperationException( "May cause an error on 'get(Object)', use 'got(String)' or 'get(String|Class)'"); } public void clean() { if (this.isEmpty()) { return; } Iterator i = this.entrySet().iterator(); while ( i.hasNext( ) ) { Entry e = (Entry)i.next(); Object o = e . getValue(); try { if (o instanceof Cleanable) { Cleanable c = (Cleanable) o; if (c.cleanable ()) { if (o instanceof AutoCloseable ) { ((AutoCloseable) c ).close( ); } i.remove(); } } } catch ( Throwable x ) { x.printStackTrace ( System.err ); } } } @Override public void clear() { if (this.isEmpty()) { return; } /** * ConcurrentModificationException, * . */ Object[] a = this.values().toArray(); for (int i = 0; i < a.length; i ++ ) { Object o = a [i]; try { if (o instanceof AutoCloseable ) { ((AutoCloseable) o ).close( ); } } catch ( Throwable x ) { x.printStackTrace ( System.err ); } } super.clear(); } @Override public void close() { clear(); } @Override protected void finalize() throws Throwable { try { close(); } finally { super.finalize(); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); for(Map.Entry<String, Object> et : entrySet()) { sb.append('['); int ln = sb.length(); Object ob = et.getValue(); if (ob instanceof AutoCloseable) { sb.append('A'); } if (ob instanceof Cleanable) { sb.append('C'); } if (ob instanceof Globalize) { sb.append('G'); } if (ob instanceof Singleton) { sb.append('S'); } if (ln < sb.length() ) { sb.append(']'); } else { sb.setLength(ln - 1); } sb.append(et.getKey()).append(", "); } int sl = sb.length(); if (sl > 0 ) { sb.setLength(sl-2); } return sb.toString(); } / /** * (0 Cmd , 1 Web ) */ public static byte ENVIR; /** * (0 , 1 , 2 , 4 Trace, 8 Debug) * : , 0 */ public static byte DEBUG; public static String SERVER_ID = "0" ; /** * WEB, : , */ public static String BASE_HREF = null; /** * WEB, : , */ public static String BASE_PATH = null; public static String CORE_PATH = null; public static String CONF_PATH; public static String DATA_PATH; public static final String CONF_PACK = "io/github/ihongs/config" ; public static final long STARTS_TIME = System.currentTimeMillis(); public static final Globalize GLOBAL_CORE = new Globalize(); public static ThreadLocal<Core> THREAD_CORE = new ThreadLocal() { @Override protected Core initialValue() { return new Core(); } @Override public void remove() { try { ( (Core) get()).close(); } catch (Throwable ex) { throw new Error(ex); } super.remove(); } }; public static InheritableThreadLocal< Long > ACTION_TIME = new InheritableThreadLocal(); public static InheritableThreadLocal<String> ACTION_ZONE = new InheritableThreadLocal(); public static InheritableThreadLocal<String> ACTION_LANG = new InheritableThreadLocal(); public static InheritableThreadLocal<String> ACTION_NAME = new InheritableThreadLocal(); public static InheritableThreadLocal<String> CLIENT_ADDR = new InheritableThreadLocal(); /** * * @return */ public static Core getInstance() { return THREAD_CORE.get(); } /** * * * @param <T> * @param clas * @return */ public static <T>T getInstance(Class<T> clas) { return getInstance().get(clas); } /** * * * @param name * @return */ public static Object getInstance(String name) { return getInstance().get(name); } public static <T>T newInstance(Class<T> klass) { try { Method method = klass.getMethod("getInstance", new Class[] {}); try { return (T) method.invoke(null, new Object[] {}); } catch (IllegalAccessException ex) { throw new HongsError(0x27, "Can not build "+klass.getName(), ex); } catch (IllegalArgumentException ex) { throw new HongsError(0x27, "Can not build "+klass.getName(), ex); } catch (InvocationTargetException ex) { Throwable ta = ex.getCause(); if (ta instanceof StackOverflowError) { throw ( StackOverflowError ) ta ; } throw new HongsError(0x27, "Can not build "+klass.getName(), ta); } } catch (NoSuchMethodException ez) { try { return klass.newInstance(); } catch (IllegalAccessException ex) { throw new HongsError(0x28, "Can not build "+klass.getName(), ex); } catch (InstantiationException ex) { Throwable ta = ex.getCause(); if (ta instanceof StackOverflowError) { throw ( StackOverflowError ) ta ; } throw new HongsError(0x28, "Can not build "+klass.getName(), ex); } } catch (SecurityException se) { throw new HongsError(0x26, "Can not build "+klass.getName(), se); } } public static Object newInstance(String name) { Class klass; try { klass = Class.forName( name ); } catch (ClassNotFoundException ex) { throw new HongsError(0x25, "Can not find class by name '" + name + "'."); } return newInstance(klass); } /** * * * 3612(ID), * "2059/01/01 00:00:00". * : 0~9A~Z * * @param svid ID * @return */ public static String newIdentity(String svid) { long n; n = System.currentTimeMillis( ); String time = String.format("%8s", Long.toString(n, 36)); n = Thread.currentThread().getId(); String trid = String.format("%4s", Long.toString(n, 36)); n = (long) ( Math.random() * 1679615); //36^4-1 String rand = String.format("%4s", Long.toString(n, 36)); if (time.length() > 8) time = time.substring(time.length() - 8); if (trid.length() > 4) trid = trid.substring(trid.length() - 4); if (rand.length() > 4) rand = rand.substring(rand.length() - 4); return new StringBuilder() .append(time).append(trid) .append(rand).append(svid) .toString().toUpperCase( ) .replace ( ' ' , '0' ); } /** * * * ID(Core.SERVER_ID) * * @return */ public static String newIdentity() { return Core.newIdentity(Core.SERVER_ID); } /** * * @return */ public static Locale getLocality() { Core core = Core.getInstance(); String name = Locale.class.getName(); Locale inst = (Locale)core.got(name); if (null != inst) { return inst; } String[] lang = Core.ACTION_LANG.get().split("_",2); if (2 <= lang.length) { inst = new Locale(lang[0],lang[1]); } else { inst = new Locale(lang[0]); } core.put(name, inst); return inst; } /** * * @return */ public static TimeZone getTimezone() { Core core = Core.getInstance(); String name = TimeZone.class.getName(); TimeZone inst = (TimeZone)core.got(name); if (null != inst) { return inst; } inst = TimeZone.getTimeZone(Core.ACTION_ZONE.get()); core.put(name, inst); return inst; } / static public interface Singleton {} static public interface Cleanable { public boolean cleanable (); } static public class Globalize extends Core { final private ReadWriteLock LOCK = new ReentrantReadWriteLock(); @Override public <T>T get(Class<T> cls) { String key = cls.getName( ); LOCK.readLock( ).lock(); try { if (super.containsKey(key)) { return (T) super.got(key); } } finally { LOCK.readLock( ).unlock(); } LOCK.writeLock().lock(); try { T obj = newInstance(cls); super.put( key, obj ); return obj; } finally { LOCK.writeLock().unlock(); } } @Override public Object get(String key) { LOCK.readLock( ).lock(); try { if (super.containsKey(key)) { return super.got(key); } } finally { LOCK.readLock( ).unlock(); } LOCK.writeLock().lock(); try { Object obj = newInstance(key); super.put( key, obj ); return obj; } finally { LOCK.writeLock().unlock(); } } @Override public Object got(String key) { LOCK.readLock( ).lock(); try { return super.got(key); } finally { LOCK.readLock( ).unlock(); } } @Override public Object put(String key, Object obj) { LOCK.writeLock().lock(); try { return super.put(key,obj); } finally { LOCK.writeLock().unlock(); } } /** * , * @param <T> * @param key * @param fun * @return put , */ public <T>T set(String key, Supplier<T> fun) { LOCK.writeLock().lock(); try { T obj = fun . get ( ); super.put( key, obj ); return obj ; } finally { LOCK.writeLock().unlock(); } } @Override public void clear() { LOCK.writeLock().lock(); try { super.clear(); } finally { LOCK.writeLock().unlock(); } } @Override public void clean() { LOCK.writeLock().lock(); try { super.clean(); } finally { LOCK.writeLock().unlock(); } } } }
package com.ebay.web.cors; import java.io.IOException; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class CORSFilterTest { private CORSConfiguration corsConfiguration; /** * Setup the intial configuration mock. * * @throws ServletException */ @Before public void setup() throws ServletException { corsConfiguration = new CORSConfiguration(); Set<String> allowedHttpHeaders = new HashSet<String>(); corsConfiguration.setAllowedHttpHeaders(allowedHttpHeaders); Set<String> allowedOrigins = new HashSet<String>(); allowedOrigins.add(TestConfigs.HTTPS_WWW_APACHE_ORG); corsConfiguration.setAllowedOrigins(allowedOrigins); Set<String> exposedHeaders = new HashSet<String>(); corsConfiguration.setExposedHeaders(exposedHeaders); corsConfiguration.setSupportsCredentials(true); } @Test public void testDoFilterSimple() throws IOException, ServletException { HttpServletRequest request = EasyMock .createMock(HttpServletRequest.class); EasyMock.expect(request.getHeader(CORSFilter.REQUEST_HEADER_ORIGIN)) .andReturn(TestConfigs.HTTPS_WWW_APACHE_ORG).anyTimes(); EasyMock.expect(request.getMethod()).andReturn("POST").anyTimes(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST, true); EasyMock.expectLastCall(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_ORIGIN, TestConfigs.HTTPS_WWW_APACHE_ORG); EasyMock.expectLastCall(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE, CORSRequestType.SIMPLE.getType()); EasyMock.expectLastCall(); EasyMock.replay(request); HttpServletResponse response = EasyMock .createNiceMock(HttpServletResponse.class); EasyMock.replay(response); FilterChain filterChain = EasyMock.createNiceMock(FilterChain.class); CORSFilter corsFilter = new CORSFilter(); corsFilter.init(TestConfigs.getFilterConfig()); corsFilter.doFilter(request, response, filterChain); corsFilter.destroy(); // If we don't get an exception at this point, then all mocked objects // worked as expected. } @Test public void testDoFilterPreflight() throws IOException, ServletException { HttpServletRequest request = EasyMock .createMock(HttpServletRequest.class); EasyMock.expect(request.getHeader(CORSFilter.REQUEST_HEADER_ORIGIN)) .andReturn(TestConfigs.HTTPS_WWW_APACHE_ORG).anyTimes(); EasyMock.expect(request.getMethod()).andReturn("OPTIONS").anyTimes(); EasyMock.expect( request.getHeader(CORSFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD)) .andReturn("OPTIONS").anyTimes(); EasyMock.expect( request.getHeader(CORSFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS)) .andReturn("Content-Type").anyTimes(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST, true); EasyMock.expectLastCall(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_ORIGIN, TestConfigs.HTTPS_WWW_APACHE_ORG); EasyMock.expectLastCall(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE, CORSRequestType.PRE_FLIGHT.getType()); EasyMock.expectLastCall(); EasyMock.replay(request); HttpServletResponse response = EasyMock .createNiceMock(HttpServletResponse.class); EasyMock.replay(response); FilterChain filterChain = EasyMock.createNiceMock(FilterChain.class); CORSFilter corsFilter = new CORSFilter(corsConfiguration); corsFilter.doFilter(request, response, filterChain); // If we don't get an exception at this point, then all mocked objects // worked as expected. } @Test public void testDoFilterNotCORS() throws IOException, ServletException { HttpServletRequest request = EasyMock .createMock(HttpServletRequest.class); EasyMock.expect(request.getHeader(CORSFilter.REQUEST_HEADER_ORIGIN)) .andReturn(null).anyTimes(); EasyMock.expect(request.getMethod()).andReturn("POST").anyTimes(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST, false); EasyMock.expectLastCall(); EasyMock.replay(request); HttpServletResponse response = EasyMock .createNiceMock(HttpServletResponse.class); EasyMock.replay(response); FilterChain filterChain = EasyMock.createNiceMock(FilterChain.class); CORSFilter corsFilter = new CORSFilter(corsConfiguration); corsFilter.doFilter(request, response, filterChain); // If we don't get an exception at this point, then all mocked objects // worked as expected. } @Test(expected = ServletException.class) public void testDoFilterInvalidCORSOriginNotAllowed() throws IOException, ServletException { HttpServletRequest request = EasyMock .createMock(HttpServletRequest.class); EasyMock.expect(request.getHeader(CORSFilter.REQUEST_HEADER_ORIGIN)) .andReturn("www.google.com").anyTimes(); EasyMock.expect(request.getMethod()).andReturn("OPTIONS").anyTimes(); EasyMock.expect( request.getHeader(CORSFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD)) .andReturn("OPTIONS").anyTimes(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST, true); EasyMock.expectLastCall(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_ORIGIN, TestConfigs.HTTPS_WWW_APACHE_ORG); EasyMock.expectLastCall(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE, CORSRequestType.INVALID_CORS.getType()); EasyMock.expectLastCall(); EasyMock.replay(request); HttpServletResponse response = EasyMock .createNiceMock(HttpServletResponse.class); EasyMock.replay(response); FilterChain filterChain = EasyMock.createNiceMock(FilterChain.class); CORSConfiguration corsConfiguration = CORSConfiguration .loadFromFilterConfig(TestConfigs.getFilterConfig()); CORSFilter corsFilter = new CORSFilter(corsConfiguration); corsFilter.doFilter(request, response, filterChain); // If we don't get an exception at this point, then all mocked objects // worked as expected. } @Test(expected = ServletException.class) public void testDoFilterNullRequestNullResponse() throws IOException, ServletException { FilterChain filterChain = EasyMock.createNiceMock(FilterChain.class); CORSFilter corsFilter = new CORSFilter(corsConfiguration); corsFilter.doFilter(null, null, filterChain); } @Test(expected = ServletException.class) public void testDoFilterNullRequestResponse() throws IOException, ServletException { FilterChain filterChain = EasyMock.createNiceMock(FilterChain.class); HttpServletResponse response = EasyMock .createMock(HttpServletResponse.class); CORSFilter corsFilter = new CORSFilter(corsConfiguration); corsFilter.doFilter(null, response, filterChain); } @Test(expected = ServletException.class) public void testDoFilterRequestNullResponse() throws IOException, ServletException { FilterChain filterChain = EasyMock.createNiceMock(FilterChain.class); HttpServletRequest request = EasyMock .createMock(HttpServletRequest.class); CORSFilter corsFilter = new CORSFilter(corsConfiguration); corsFilter.doFilter(request, null, filterChain); } @Test public void testDoFilterSimpleCustomHandlers() throws IOException, ServletException { HttpServletRequest request = EasyMock .createMock(HttpServletRequest.class); EasyMock.expect(request.getHeader(CORSFilter.REQUEST_HEADER_ORIGIN)) .andReturn(TestConfigs.HTTPS_WWW_APACHE_ORG).anyTimes(); EasyMock.expect(request.getMethod()).andReturn("POST").anyTimes(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST, true); EasyMock.expectLastCall(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_ORIGIN, TestConfigs.HTTPS_WWW_APACHE_ORG); EasyMock.expectLastCall(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE, CORSRequestType.SIMPLE.getType()); EasyMock.expectLastCall(); EasyMock.replay(request); HttpServletResponse response = EasyMock .createNiceMock(HttpServletResponse.class); EasyMock.replay(response); FilterChain filterChain = EasyMock.createNiceMock(FilterChain.class); CORSFilter corsFilter = new CORSFilter(corsConfiguration); corsFilter.setCorsConfiguration(corsConfiguration); corsFilter.doFilter(request, response, filterChain); corsFilter.destroy(); // If we don't get an exception at this point, then all mocked objects // worked as expected. } /** * Should load the default config and configure default handlers. And, not * throw IOException. * * @throws IOException */ public void testDefaultConstructor() throws IOException { new CORSFilter(); } @Test public void testInit() throws IOException, ServletException { HttpServletRequest request = EasyMock .createMock(HttpServletRequest.class); EasyMock.expect(request.getHeader(CORSFilter.REQUEST_HEADER_ORIGIN)) .andReturn(TestConfigs.HTTPS_WWW_APACHE_ORG).anyTimes(); EasyMock.expect(request.getMethod()).andReturn("POST").anyTimes(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST, true); EasyMock.expectLastCall(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_ORIGIN, TestConfigs.HTTPS_WWW_APACHE_ORG); EasyMock.expectLastCall(); request.setAttribute(CORSFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE, CORSRequestType.SIMPLE.getType()); EasyMock.expectLastCall(); EasyMock.replay(request); HttpServletResponse response = EasyMock .createNiceMock(HttpServletResponse.class); EasyMock.replay(response); FilterChain filterChain = EasyMock.createNiceMock(FilterChain.class); CORSFilter corsFilter = new CORSFilter(); corsFilter.init(TestConfigs.getFilterConfig()); corsFilter.doFilter(request, response, filterChain); corsFilter.destroy(); // If we don't get an exception at this point, then all mocked objects // worked as expected. } @Test(expected = ServletException.class) public void testInitInvalidFilterConfig() throws IOException, ServletException { CORSFilter corsFilter = new CORSFilter(); corsFilter.init(TestConfigs.getFilterConfigInvalidMaxPreflightAge()); // If we don't get an exception at this point, then all mocked objects // worked as expected. } @Test public void testDestroy() { // Nothing to test. // NO-OP } @Test public void testJoin() { Set<String> elements = new LinkedHashSet<String>(); String separator = ","; elements.add("world"); elements.add("peace"); String join = CORSFilter.join(elements, separator); Assert.assertTrue("world,peace".equals(join)); } @Test public void testJoinSingleElement() { Set<String> elements = new LinkedHashSet<String>(); String separator = ","; elements.add("world"); String join = CORSFilter.join(elements, separator); Assert.assertTrue("world".equals(join)); } @Test public void testJoinSepNull() { Set<String> elements = new LinkedHashSet<String>(); String separator = null; elements.add("world"); elements.add("peace"); String join = CORSFilter.join(elements, separator); Assert.assertTrue("world,peace".equals(join)); } @Test public void testJoinElementsNull() { Set<String> elements = null; String separator = ","; String join = CORSFilter.join(elements, separator); Assert.assertNull(join); } @Test public void testJoinOneNullElement() { Set<String> elements = new LinkedHashSet<String>(); String separator = ","; elements.add(null); elements.add("peace"); String join = CORSFilter.join(elements, separator); Assert.assertTrue(",peace".equals(join)); } @Test public void testJoinAllNullElements() { Set<String> elements = new LinkedHashSet<String>(); String separator = ","; elements.add(null); elements.add(null); String join = CORSFilter.join(elements, separator); Assert.assertTrue("".equals(join)); } @Test public void testJoinAllEmptyElements() { Set<String> elements = new LinkedHashSet<String>(); String separator = ","; elements.add(""); elements.add(""); String join = CORSFilter.join(elements, separator); Assert.assertTrue("".equals(join)); } @Test public void testJoinPipeSeparator() { Set<String> elements = new LinkedHashSet<String>(); String separator = "|"; elements.add("world"); elements.add("peace"); String join = CORSFilter.join(elements, separator); Assert.assertTrue("world|peace".equals(join)); } }
package com.tinkerpop.pipes; import com.tinkerpop.blueprints.pgm.Edge; import com.tinkerpop.blueprints.pgm.Graph; import com.tinkerpop.blueprints.pgm.Vertex; import com.tinkerpop.blueprints.pgm.impls.tg.TinkerEdge; import com.tinkerpop.blueprints.pgm.impls.tg.TinkerGraphFactory; import com.tinkerpop.blueprints.pgm.impls.tg.TinkerVertex; import com.tinkerpop.pipes.filter.ComparisonFilterPipe; import com.tinkerpop.pipes.pgm.EdgeVertexPipe; import com.tinkerpop.pipes.pgm.LabelFilterPipe; import com.tinkerpop.pipes.pgm.PropertyPipe; import com.tinkerpop.pipes.pgm.VertexEdgePipe; import junit.framework.TestCase; import java.util.*; public class PipelineTest extends TestCase { public void testOneStagePipeline() { System.out.println("one stage"); Graph graph = TinkerGraphFactory.createTinkerGraph(); Vertex marko = graph.getVertex("1"); Pipe vep = new VertexEdgePipe(VertexEdgePipe.Step.OUT_EDGES); Pipe<Vertex, Edge> pipeline = new Pipeline<Vertex, Edge>(Arrays.asList(vep)); pipeline.setStarts(Arrays.asList(marko).iterator()); assertTrue(pipeline.hasNext()); int counter = 0; Iterator<Vertex> expectedEnds = Arrays.asList( graph.getVertex("2"), graph.getVertex("3"), graph.getVertex("4")).iterator(); Iterator<String> expectedPaths = Arrays.asList( "[v[1], e[7][1-knows->2]]", "[v[1], e[9][1-created->3]]", "[v[1], e[8][1-knows->4]]").iterator(); pipeline.enablePath(); while (pipeline.hasNext()) { Edge e = pipeline.next(); assertEquals(expectedEnds.next(), e.getInVertex()); List path = pipeline.getPath(); System.out.println(path); assertEquals(expectedPaths.next(), path.toString()); counter++; } assertEquals(3, counter); } public void testThreeStagePipeline() { Graph graph = TinkerGraphFactory.createTinkerGraph(); Vertex marko = graph.getVertex("1"); Pipe vep = new VertexEdgePipe(VertexEdgePipe.Step.OUT_EDGES); Pipe lfp = new LabelFilterPipe("created", ComparisonFilterPipe.Filter.NOT_EQUAL); Pipe evp = new EdgeVertexPipe(EdgeVertexPipe.Step.IN_VERTEX); Pipe<Vertex, Vertex> pipeline = new Pipeline<Vertex, Vertex>(Arrays.asList(vep, lfp, evp)); pipeline.setStarts(Arrays.asList(marko).iterator()); assertTrue(pipeline.hasNext()); int counter = 0; pipeline.enablePath(); while (pipeline.hasNext()) { assertEquals(pipeline.next().getId(), "3"); List path = pipeline.getPath(); if (counter == 0) { System.out.println(path); assertEquals(path, Arrays.asList(graph.getVertex("1"), graph.getEdge(9), graph.getVertex(3))); } counter++; } assertEquals(1, counter); vep = new VertexEdgePipe(VertexEdgePipe.Step.OUT_EDGES); lfp = new LabelFilterPipe("created", ComparisonFilterPipe.Filter.EQUAL); evp = new EdgeVertexPipe(EdgeVertexPipe.Step.IN_VERTEX); pipeline = new Pipeline<Vertex, Vertex>(vep, lfp, evp); pipeline.setStarts(Arrays.asList(marko).iterator()); assertTrue(pipeline.hasNext()); counter = 0; while (pipeline.hasNext()) { Vertex v = pipeline.next(); assertTrue(v.getId().equals("4") || v.getId().equals("2")); counter++; } assertEquals(2, counter); try { pipeline.next(); assertTrue(false); } catch (NoSuchElementException e) { assertFalse(false); } } public void testPipelineResuse() { Graph graph = TinkerGraphFactory.createTinkerGraph(); Vertex marko = graph.getVertex("1"); Pipe vep = new VertexEdgePipe(VertexEdgePipe.Step.OUT_EDGES); Pipe evp = new EdgeVertexPipe(EdgeVertexPipe.Step.IN_VERTEX); Pipe<Vertex, Vertex> pipeline = new Pipeline<Vertex, Vertex>(Arrays.asList(vep, evp)); pipeline.setStarts(Arrays.asList(marko).iterator()); assertTrue(pipeline.hasNext()); int counter = 0; if (pipeline.hasNext()) { counter++; pipeline.next(); } assertEquals(1, counter); pipeline.setStarts(Arrays.asList(marko).iterator()); assertTrue(pipeline.hasNext()); counter = 0; while (pipeline.hasNext()) { counter++; pipeline.next(); } assertEquals(5, counter); try { pipeline.next(); assertTrue(false); } catch (NoSuchElementException e) { assertFalse(false); } } public void testTwoSimilarConstructions() { List<String> names = Arrays.asList("marko", "peter", "josh"); IdentityPipe<String> pipe1 = new IdentityPipe<String>(); IdentityPipe<String> pipe2 = new IdentityPipe<String>(); Pipeline<String, String> pipeline = new Pipeline<String, String>(pipe1, pipe2); pipeline.setStarts(names); int counter = 0; for (String name : pipeline) { counter++; assertTrue(name.equals("marko") || name.equals("peter") || name.equals("josh")); } assertEquals(counter, 3); pipe1 = new IdentityPipe<String>(); pipe2 = new IdentityPipe<String>(); pipeline = new Pipeline<String, String>(); pipeline.setStartPipe(pipe1); pipeline.setEndPipe(pipe2); // when only setting starts and ends, the intermediate pipes must be chained manually. pipe2.setStarts((Iterator<String>) pipe1); pipeline.setStarts(names); counter = 0; for (String name : pipeline) { counter++; assertTrue(name.equals("marko") || name.equals("peter") || name.equals("josh")); } assertEquals(counter, 3); } public void testPipelinePathConstruction() { Graph graph = TinkerGraphFactory.createTinkerGraph(); Vertex marko = graph.getVertex("1"); Pipe pipe1 = new VertexEdgePipe(VertexEdgePipe.Step.OUT_EDGES); Pipe pipe2 = new EdgeVertexPipe(EdgeVertexPipe.Step.IN_VERTEX); Pipe pipe3 = new PropertyPipe<Vertex, String>("name"); Pipe<Vertex, String> pipeline = new Pipeline<Vertex, String>(Arrays.asList(pipe1, pipe2, pipe3)); pipeline.setStarts(Arrays.asList(marko).iterator()); pipeline.enablePath(); for (String name : pipeline) { List path = pipeline.getPath(); assertEquals(path.get(0), marko); assertEquals(path.get(1).getClass(), TinkerEdge.class); assertEquals(path.get(2).getClass(), TinkerVertex.class); assertEquals(path.get(3).getClass(), String.class); if (name.equals("vadas")) { assertEquals(path.get(1), graph.getEdge(7)); assertEquals(path.get(2), graph.getVertex(2)); assertEquals(path.get(3), "vadas"); } else if (name.equals("lop")) { assertEquals(path.get(1), graph.getEdge(9)); assertEquals(path.get(2), graph.getVertex(3)); assertEquals(path.get(3), "lop"); } else if (name.equals("josh")) { assertEquals(path.get(1), graph.getEdge(8)); assertEquals(path.get(2), graph.getVertex(4)); assertEquals(path.get(3), "josh"); } else { assertFalse(true); } //System.out.println(name); //System.out.println(pipeline.getPath()); } } }
package de.ailis.usb4java.test; import static org.junit.Assume.assumeTrue; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; /** * USB-related assumptions. * * @author Klaus Reimer (k@ailis.de) */ public class UsbAssume { /** If USB tests are to be executed. */ private static Boolean usbTests; /** If TCK tests are to be executed. */ private static Boolean tckTests; /** * Assume that USB tests are enabled. Call this in the first line of * tests method or preparation methods when you want to ignore the * tests when the system is not able to run the tests anyway. * * USB tests can be controlled with the system property USB_TESTS. When * set to true then USB tests are always run, if set to false then they * are never run. If this property is not set then the command-line tool * lsusb is called. If this tool returned at least two lines of text then * USB tests are enabled. In all other cases they are disabled. */ public static void assumeUsbTestsEnabled() { if (usbTests == null && System.getProperty("USB_TESTS") != null) usbTests = Boolean.valueOf(System.getProperty("USB_TESTS")); if (usbTests == null) { usbTests = false; try { final Process proc = Runtime.getRuntime().exec("lsusb"); if (proc.waitFor() == 0) { InputStream inputStream = proc.getInputStream(); try { BufferedReader reader = new BufferedReader(new InputStreamReader( inputStream)); try { int lines = 0; while (reader.readLine() != null) lines++; usbTests = lines >= 2; } finally { reader.close(); } } finally { inputStream.close(); } } } catch (Exception e) { // Ignored. USB tests are silently disabled when lsusb could // not be run. } } assumeTrue("This test is ignored when USB_TESTS property is not set", usbTests); } /** * Assume that TCK tests are enabled. Call this in the first line of * tests method or preparation methods when you want to ignore the * tests when the system is not able to run the TCK tests anyway. * * TCK tests can be controlled with the system property TCK_TESTS. When * set to true then TCK tests are always run, if set to false then they * are never run. If this property is not set then the command-line tool * lsusb is called to scan for the TCK hardware. If this tool found the * TCK hardware then TCK tests are enabled. In all other cases they are * disabled. */ public static void assumeTckTestsEnabled() { assumeUsbTestsEnabled(); if (tckTests == null && System.getProperty("TCK_TESTS") != null) tckTests = Boolean.valueOf(System.getProperty("TCK_TESTS")); if (tckTests == null) { tckTests = false; try { final Process proc = Runtime.getRuntime().exec("lsusb"); if (proc.waitFor() == 0) { InputStream inputStream = proc.getInputStream(); try { BufferedReader reader = new BufferedReader(new InputStreamReader( inputStream)); try { String line = reader.readLine(); while (line != null) { if (line.contains("0547:1002")) { tckTests = true; break; } line = reader.readLine(); } } finally { reader.close(); } } finally { inputStream.close(); } } } catch (Exception e) { // Ignored. USB tests are silently disabled when lsusb could // not be run. } } assumeTrue("This test is ignored when TCK_TESTS property is not set", tckTests); } }
package integration; import com.codeborne.selenide.Configuration; import com.codeborne.selenide.Selectors; import com.codeborne.selenide.ex.InvalidStateException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import static com.codeborne.selenide.Condition.*; import static com.codeborne.selenide.Configuration.timeout; import static com.codeborne.selenide.Selenide.$; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; public class ReadonlyElementsTest extends IntegrationTest { @Before public void openTestPage() { openFile("page_with_readonly_elements.html"); timeout = 10 * averageSeleniumCommandDuration; } @After public void cleanUp() { Configuration.fastSetValue = false; } @Test public void cannotSetValueToReadonlyField_slowSetValue() { Configuration.fastSetValue = false; assertThat(verifySetValueThrowsException(), anyOf( containsString("Element is read-only and so may not be used for actions"), containsString("Element must be user-editable in order to clear it"), containsString("You may only edit editable elements") )); } @Test public void cannotSetValueToDisabledField_slowSetValue() { Configuration.fastSetValue = false; assertThat(verifySetValue2ThrowsException(), anyOf( containsString("Element must be user-editable in order to clear it"), containsString("You may only edit editable elements"), containsString("You may only interact with enabled elements"), containsString("Element is not currently interactable and may not be manipulated") )); } @Test public void cannotSetValueToReadonlyField_fastSetValue() { Configuration.fastSetValue = true; assertThat(verifySetValueThrowsException(), containsString("Cannot change value of readonly element")); } @Test public void cannotSetValueToDisabledField_fastSetValue() { Configuration.fastSetValue = true; assertThat(verifySetValue2ThrowsException(), anyOf( containsString("Cannot change value of disabled element"), containsString("Element is not currently interactable and may not be manipulated") )); } @Test(expected = InvalidStateException.class) public void cannotSetValueToReadonlyTextArea() { $("#text-area").val("textArea value"); } @Test(expected = InvalidStateException.class) public void cannotSetValueToDisabledTextArea() { $("#text-area-disabled").val("textArea value"); } @Test(expected = InvalidStateException.class) public void cannotSetValueToReadonlyCheckbox() { $(By.name("rememberMe")).setSelected(true); } @Test(expected = InvalidStateException.class) public void cannotSetValueToReadonlyRadiobutton() { $(By.name("me")).selectRadio("margarita"); } @Test public void waitsUntilInputGetsEditable_slowSetValue() { $("#enable-inputs").click(); Configuration.fastSetValue = false; $(By.name("username")).val("another-username"); $(By.name("username")).shouldHave(exactValue("another-username")); } @Test public void waitsUntilInputGetsEditable_fastSetValue() { $("#enable-inputs").click(); Configuration.fastSetValue = true; $(By.name("username")).val("another-username"); $(By.name("username")).shouldHave(exactValue("another-username")); } @Test public void waitsUntilTextAreaGetsEditable() { $("#enable-inputs").click(); $("#text-area").val("TextArea value"); $("#text-area").shouldHave(exactValue("TextArea value")); } @Test public void waitsUntilCheckboxGetsEditable() { $("#enable-inputs").click(); $(By.name("rememberMe")).setSelected(true); $(By.name("rememberMe")).shouldBe(selected); } @Test public void waitsUntilRadiobuttonGetsEditable() { $("#enable-inputs").click(); $(By.name("me")).selectRadio("margarita"); $(Selectors.byValue("margarita")).shouldBe(selected); } private String verifySetValueThrowsException() { try { $(By.name("username")).val("another-username"); fail("should throw InvalidStateException where setting value to readonly/disabled element"); return null; } catch (InvalidStateException expected) { $(By.name("username")).shouldBe(empty); $(By.name("username")).shouldHave(exactValue("")); return expected.getMessage(); } } private String verifySetValue2ThrowsException() { try { $(By.name("password")).setValue("another-pwd"); fail("should throw InvalidStateException where setting value to readonly/disabled element"); return null; } catch (InvalidStateException expected) { $(By.name("password")).shouldBe(empty); $(By.name("password")).shouldHave(exactValue("")); return expected.getMessage(); } } }
package net.emaze.dysfunctional; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import net.emaze.dysfunctional.options.Maybe; import net.emaze.dysfunctional.order.ComparableComparator; import net.emaze.dysfunctional.order.IntegerSequencingPolicy; import net.emaze.dysfunctional.ranges.DenseRange; import net.emaze.dysfunctional.ranges.Range; import net.emaze.dysfunctional.tuples.Pair; import org.junit.Assert; import org.junit.Test; /** * if you are going to add a test here, consider that Zips should be just a thin * facade, and tests on ZipsTest should be just "smoke tests" * * @author rferranti */ public class ZipsTest { public static Pair<Integer, Integer> p(int f, int l) { return Pair.of(f, l); } public static Pair<Maybe<Integer>, Maybe<Integer>> p(Maybe<Integer> f, Maybe<Integer> l) { return Pair.of(f, l); } @Test public void canZipShortestWithIterators() { final List<Integer> former = Arrays.asList(1, 3); final List<Integer> latter = Arrays.asList(2, 4, 5); final Iterator<Pair<Integer, Integer>> got = Zips.shortest(former.iterator(), latter.iterator()); Assert.assertEquals(Arrays.asList(p(1, 2), p(3, 4)), Consumers.all(got)); } @Test public void canZipShortestWithArrays() { final Integer[] former = new Integer[]{1, 3}; final Integer[] latter = new Integer[]{2, 4, 5}; final Iterator<Pair<Integer, Integer>> got = Zips.shortest(former, latter); Assert.assertEquals(Arrays.asList(p(1, 2), p(3, 4)), Consumers.all(got)); } @Test public void canZipShortestWithIterables() { final List<Integer> former = Arrays.asList(1, 3); final List<Integer> latter = Arrays.asList(2, 4, 5); final Iterator<Pair<Integer, Integer>> got = Zips.shortest(former, latter); Assert.assertEquals(Arrays.asList(p(1, 2), p(3, 4)), Consumers.all(got)); } @Test(expected = IllegalArgumentException.class) public void cannotZipShortestWithNullFormerIterable() { final List<Integer> former = null; final List<Integer> latter = Arrays.asList(2, 4, 5); Zips.shortest(former, latter); } @Test(expected = IllegalArgumentException.class) public void cannotZipShortestWithNullLatterIterable() { final List<Integer> former = Arrays.asList(2, 4, 5); final List<Integer> latter = null; Zips.shortest(former, latter); } @Test public void canZipLongestWithIterators() { final List<Integer> former = Arrays.asList(1, 3); final List<Integer> latter = Arrays.asList(2, 4, 5); final Iterator<Pair<Maybe<Integer>, Maybe<Integer>>> got = Zips.longest(former.iterator(), latter.iterator()); final List<Pair<Maybe<Integer>, Maybe<Integer>>> expected = new ArrayList<Pair<Maybe<Integer>, Maybe<Integer>>>(); expected.add(p(Maybe.just(1), Maybe.just(2))); expected.add(p(Maybe.just(3), Maybe.just(4))); expected.add(p(Maybe.<Integer>nothing(), Maybe.just(5))); Assert.assertEquals(expected, Consumers.all(got)); } @Test public void canZipLongestWithArrays() { final Integer[] former = new Integer[]{1, 3}; final Integer[] latter = new Integer[]{2, 4, 5}; final Iterator<Pair<Maybe<Integer>, Maybe<Integer>>> got = Zips.longest(former, latter); final List<Pair<Maybe<Integer>, Maybe<Integer>>> expected = new ArrayList<Pair<Maybe<Integer>, Maybe<Integer>>>(); expected.add(p(Maybe.just(1), Maybe.just(2))); expected.add(p(Maybe.just(3), Maybe.just(4))); expected.add(p(Maybe.<Integer>nothing(), Maybe.just(5))); Assert.assertEquals(expected, Consumers.all(got)); } @Test public void canZipLongestWithIterables() { final List<Integer> former = Arrays.asList(1, 3); final List<Integer> latter = Arrays.asList(2, 4, 5); Iterator<Pair<Maybe<Integer>, Maybe<Integer>>> got = Zips.longest(former, latter); final List<Pair<Maybe<Integer>, Maybe<Integer>>> expected = new ArrayList<Pair<Maybe<Integer>, Maybe<Integer>>>(); expected.add(p(Maybe.just(1), Maybe.just(2))); expected.add(p(Maybe.just(3), Maybe.just(4))); expected.add(p(Maybe.<Integer>nothing(), Maybe.just(5))); Assert.assertEquals(expected, Consumers.all(got)); } @Test(expected = IllegalArgumentException.class) public void canZipLongestWithNullFormerIterable() { final List<Integer> former = null; final List<Integer> latter = Arrays.asList(2, 4, 5); Zips.longest(former, latter); } @Test(expected = IllegalArgumentException.class) public void canZipLongestWithNullLatterIterable() { final List<Integer> former = Arrays.asList(2, 4, 5); final List<Integer> latter = null; Zips.longest(former, latter); } @Test public void canMakeAnIterableCounted() { final Iterable<String> bucket = Iterations.iterable("a", "b"); final Iterator<Pair<Integer, String>> iterator = Zips.counted(bucket); final Iterator<Pair<Integer, String>> expected = Iterations.iterator(Pair.of(0, "a"), Pair.of(1, "b")); Assert.assertEquals(Consumers.all(expected), Consumers.all(iterator)); } @Test public void canMakeAnIterableCountedWithRange() { final Range<Integer> range = new DenseRange<Integer>(new IntegerSequencingPolicy(), new ComparableComparator<Integer>(), 1, 10); final Iterable<String> bucket = Iterations.iterable("a", "b"); final Iterator<Pair<Integer, String>> iterator = Zips.counted(bucket, range); final Iterator<Pair<Integer, String>> expected = Iterations.iterator(Pair.of(1, "a"), Pair.of(2, "b")); Assert.assertEquals(Consumers.all(expected), Consumers.all(iterator)); } @Test public void canMakeAnIteratorCounted() { final Iterator<String> bucket = Iterations.iterator("a", "b"); final Iterator<Pair<Integer, String>> iterator = Zips.counted(bucket); final Iterator<Pair<Integer, String>> expected = Iterations.iterator(Pair.of(0, "a"), Pair.of(1, "b")); Assert.assertEquals(Consumers.all(expected), Consumers.all(iterator)); } @Test public void canMakeAnIteratorCountedWithRange() { final Range<Integer> range = new DenseRange<Integer>(new IntegerSequencingPolicy(), new ComparableComparator<Integer>(), 1, 10); final Iterator<String> bucket = Iterations.iterator("a", "b"); final Iterator<Pair<Integer, String>> iterator = Zips.counted(bucket, range); final Iterator<Pair<Integer, String>> expected = Iterations.iterator(Pair.of(1, "a"), Pair.of(2, "b")); Assert.assertEquals(Consumers.all(expected), Consumers.all(iterator)); } @Test public void canMakeAnArrayCounted() { final String[] bucket = {"a", "b"}; final Iterator<Pair<Integer, String>> iterator = Zips.counted(bucket); final Iterator<Pair<Integer, String>> expected = Iterations.iterator(Pair.of(0, "a"), Pair.of(1, "b")); Assert.assertEquals(Consumers.all(expected), Consumers.all(iterator)); } @Test public void canMakeAnArrayCountedWithRange() { final Range<Integer> range = new DenseRange<Integer>(new IntegerSequencingPolicy(), new ComparableComparator<Integer>(), 1, 10); final String[] bucket = {"a", "b"}; final Iterator<Pair<Integer, String>> iterator = Zips.counted(bucket, range); final Iterator<Pair<Integer, String>> expected = Iterations.iterator(Pair.of(1, "a"), Pair.of(2, "b")); Assert.assertEquals(Consumers.all(expected), Consumers.all(iterator)); } @Test(expected = IllegalArgumentException.class) public void cannotCallCountedWithANullIterable() { final Iterable<Object> iterable = null; Zips.counted(iterable); } @Test(expected = IllegalArgumentException.class) public void cannotCallCountedWithANullIterableAndARange() { final Iterable<Object> iterable = null; final StubRange range = new StubRange(); Zips.counted(iterable, range); } @Test(expected = IllegalArgumentException.class) public void cannotCallCountedWithANullArray() { final Object[] iterable = null; Zips.counted(iterable); } @Test(expected = IllegalArgumentException.class) public void cannotCallCountedWithANullArrayAndARange() { final Object[] iterable = null; final StubRange range = new StubRange(); Zips.counted(iterable, range); } private static class StubRange implements Range<Object> { @Override public boolean contains(Object element) { return false; } @Override public boolean overlaps(Range<Object> rhs) { return false; } @Override public Object lower() { return null; } @Override public Object upper() { return null; } @Override public List<DenseRange<Object>> densified() { return null; } @Override public Iterator<Object> iterator() { return null; } @Override public int compareTo(Range<Object> o) { return 0; } } @Test public void facadeIsNotFinal() { new Zips() { }; } }
package org.cactoos.iterable; import org.cactoos.list.ListOf; import org.hamcrest.collection.IsEmptyIterable; import org.hamcrest.core.IsEqual; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test Case for {@link Skipped}. * * @since 0.34 * @checkstyle JavadocMethodCheck (500 lines) */ public final class SkippedTest { @Test public void skipIterable() { final String one = "one"; final String two = "two"; final String three = "three"; final String four = "four"; new Assertion<>( "Must skip elements in iterable", new Skipped<>( 2, new IterableOf<>(one, two, three, four) ), new IsEqual<>( new IterableOf<>( three, four ) ) ).affirm(); } @Test public void skipArray() { final String five = "five"; final String six = "six"; final String seven = "seven"; final String eight = "eight"; new Assertion<>( "Must skip elements in array", new Skipped<>( 2, five, six, seven, eight ), new IsEqual<>( new IterableOf<>( seven, eight ) ) ).affirm(); } @Test public void skipCollection() { final String nine = "nine"; final String eleven = "eleven"; final String twelve = "twelve"; final String hundred = "hundred"; new Assertion<>( "Must skip elements in collection", new Skipped<>( 2, new ListOf<>(nine, eleven, twelve, hundred) ), new IsEqual<>( new IterableOf<>(twelve, hundred) ) ).affirm(); } @Test public void skippedAllElements() { new Assertion<>( "Must skip all elements", new Skipped<>( 2, "Frodo", "Gandalf" ), new IsEmptyIterable<>() ).affirm(); } @Test public void skippedMoreThanExists() { new Assertion<>( "Can't skip more than exists", new Skipped<>( Integer.MAX_VALUE, "Sauron", "Morgoth" ), new IsEmptyIterable<>() ).affirm(); } @Test @SuppressWarnings("PMD.AvoidDuplicateLiterals") public void skippedNegativeSize() { final String varda = "varda"; final String yavanna = "yavanna"; final String nessa = "nessa"; final String vaire = "vaire"; new Assertion<>( "Must process negative skipped size", new Skipped<>( -1, varda, yavanna, nessa, vaire ), new IsEqual<>( new IterableOf<>(varda, yavanna, nessa, vaire) ) ).affirm(); } }
package org.sfm.jdbc; import org.junit.Test; import org.sfm.beans.DbObject; import org.sfm.beans.Foo; import org.sfm.jdbc.impl.JdbcMapperImpl; import org.sfm.map.MapperBuilderErrorHandler; import org.sfm.map.MappingException; import org.sfm.map.FieldMapper; import org.sfm.map.impl.LogFieldMapperErrorHandler; import org.sfm.map.impl.RethrowRowHandlerErrorHandler; import org.sfm.reflect.Instantiator; import org.sfm.utils.RowHandler; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.*; public class JdbcMapperErrorTest { @Test public void testHandleMapperErrorSetterNotFound() throws NoSuchMethodException, SecurityException, IOException { MapperBuilderErrorHandler errorHandler = mock(MapperBuilderErrorHandler.class); JdbcMapperBuilder<DbObject> builder = JdbcMapperFactoryHelper.asm().mapperBuilderErrorHandler(errorHandler).newBuilder(DbObject.class); builder.addMapping("notthere1", 1); verify(errorHandler).propertyNotFound(DbObject.class, "notthere1"); builder.addMapping("notthere3"); verify(errorHandler).propertyNotFound(DbObject.class, "notthere3"); } public static class MyClass { public Foo prop; } @Test public void testHandleMapperErrorGetterNotFound() throws NoSuchMethodException, SecurityException, IOException { MapperBuilderErrorHandler errorHandler = mock(MapperBuilderErrorHandler.class); JdbcMapperBuilder<MyClass> builder = JdbcMapperFactoryHelper.asm().mapperBuilderErrorHandler(errorHandler).newBuilder(MyClass.class); builder.addMapping("prop", 1); builder.mapper(); verify(errorHandler).getterNotFound("Could not find getter for ColumnKey [columnName=prop, columnIndex=1, sqlType=-99999] type class org.sfm.beans.Foo"); } @Test public void setChangeFieldMapperErrorHandler() throws NoSuchMethodException, SecurityException, IOException { JdbcMapperBuilder<DbObject> builder = JdbcMapperFactoryHelper.asm().newBuilder(DbObject.class); builder.addMapping("id"); builder.fieldMapperErrorHandler(new LogFieldMapperErrorHandler<JdbcColumnKey>()); } @Test public void testInstantiatorError() { JdbcMapperImpl<DbObject> mapper = new JdbcMapperImpl<DbObject>(null, null, new Instantiator<ResultSet, DbObject>() { @Override public DbObject newInstance(ResultSet s) throws Exception { throw new IOException(); } }, new RethrowRowHandlerErrorHandler(), new JdbcMappingContextFactoryBuilder().newFactory()); try { mapper.map(null); fail("Expected error"); } catch(Exception e) { assertTrue(e instanceof IOException); } } @SuppressWarnings("unchecked") @Test public void testHandlerError() throws MappingException, SQLException { MyJdbcRawHandlerErrorHandler handler = new MyJdbcRawHandlerErrorHandler(); @SuppressWarnings("unchecked") FieldMapper<ResultSet, DbObject>[] fields = new FieldMapper[] {}; JdbcMapperImpl<DbObject> mapper = new JdbcMapperImpl<DbObject>(fields, new FieldMapper[] {}, new Instantiator<ResultSet, DbObject>() { @Override public DbObject newInstance(ResultSet s) throws Exception { return new DbObject(); } }, handler, new JdbcMappingContextFactoryBuilder().newFactory()); final Error error = new Error(); ResultSet rs = mock(ResultSet.class); when(rs.next()).thenReturn(true, false); mapper.forEach(rs, new RowHandler<DbObject>() { @Override public void handle(DbObject t) throws Exception { throw error; } }); assertSame(error, handler.error); } }
package org.smoothbuild.fs.base; import static org.fest.assertions.api.Assertions.assertThat; import static org.smoothbuild.fs.base.PathUtils.WORKING_DIR; import static org.smoothbuild.fs.base.PathUtils.isValid; import static org.smoothbuild.fs.base.PathUtils.parentOf; import static org.smoothbuild.fs.base.PathUtils.toCanonical; import static org.smoothbuild.fs.base.PathUtils.validationError; import java.util.List; import org.junit.Assert; import org.junit.Test; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; public class PathUtilsTest { @Test public void correctPath() throws Exception { for (String path : listOfCorrectPaths()) { assertThat(validationError(path)).isNull(); assertThat(isValid(path)).isTrue(); } } public static List<String> listOfCorrectPaths() { Builder<String> builder = ImmutableList.builder(); builder.add("."); builder.add("./"); builder.add("abc"); builder.add("abc/def"); builder.add("abc/def/ghi"); builder.add("abc/def/ghi/ijk"); builder.add("abc/"); builder.add("abc/def/"); builder.add("abc/def/ghi/"); builder.add("abc/def/ghi/ijk/"); builder.add("./abc"); builder.add("./abc/def"); builder.add("./abc/def/ghi"); builder.add("./abc/def/ghi/ijk"); builder.add("./abc/"); builder.add("./abc/def/"); builder.add("./abc/def/ghi/"); builder.add("./abc/def/ghi/ijk/"); // These paths look really strange but Linux allows creating them. // I cannot see any good reason for forbidding them. builder.add("..."); builder.add(".../abc"); builder.add("abc/..."); builder.add("abc/.../def"); builder.add(".../"); builder.add(".../abc/"); builder.add("abc/.../"); builder.add("abc/.../def/"); builder.add("./..."); builder.add("./.../abc"); builder.add("./abc/..."); builder.add("./abc/.../def"); builder.add("./.../"); builder.add("./.../abc/"); builder.add("./abc/.../"); builder.add("./abc/.../def/"); return builder.build(); } @Test public void invalidPathsAreDetected() { for (String path : listOfInvalidPaths()) { assertThat(validationError(path)).isNotNull(); assertThat(isValid(path)).isFalse(); } } public static ImmutableList<String> listOfInvalidPaths() { Builder<String> builder = ImmutableList.builder(); builder.add(""); builder.add("./."); builder.add("././"); builder.add(".."); builder.add("../"); builder.add("./../"); builder.add("../abc"); builder.add("abc/.."); builder.add("abc/../def"); builder.add("../.."); builder.add("/"); builder.add(" builder.add(" builder.add("/abc"); builder.add("//abc"); builder.add("///abc"); builder.add("abc builder.add("abc builder.add("abc//def"); builder.add("abc///def"); return builder.build(); } @Test public void testToCanonical() { assertToCanonical(".", "."); assertToCanonical("./", "."); assertToCanonical("abc", "abc"); assertToCanonical("abc/def", "abc/def"); assertToCanonical("abc/def/ghi", "abc/def/ghi"); assertToCanonical("abc/", "abc"); assertToCanonical("abc/def/", "abc/def"); assertToCanonical("abc/def/ghi/", "abc/def/ghi"); assertToCanonical("./abc", "abc"); assertToCanonical("./abc/def", "abc/def"); assertToCanonical("./abc/def/ghi", "abc/def/ghi"); assertToCanonical("./abc/", "abc"); assertToCanonical("./abc/def/", "abc/def"); assertToCanonical("./abc/def/ghi/", "abc/def/ghi"); } private void assertToCanonical(String input, String expected) { assertThat(toCanonical(input)).isEqualTo(expected); } @Test public void parentOfWorkingDirThrowsException() throws Exception { try { parentOf(WORKING_DIR); Assert.fail("exception should be thrown"); } catch (IllegalArgumentException e) { // expected } } @Test public void testParentOf() throws Exception { assertParentOf("abc", WORKING_DIR); assertParentOf("abc/def", "abc"); assertParentOf("abc/def/ghi", "abc/def"); assertParentOf(" ", WORKING_DIR); } private static void assertParentOf(String input, String expected) { assertThat(parentOf(input)).isEqualTo(expected); } @Test public void testToElements() throws Exception { assertToElements(WORKING_DIR, ImmutableList.<String> of()); assertToElements("abc", ImmutableList.of("abc")); assertToElements("abc/def", ImmutableList.of("abc", "def")); assertToElements("abc/def/ghi", ImmutableList.of("abc", "def", "ghi")); assertToElements(" ", ImmutableList.of(" ")); assertToElements(" / ", ImmutableList.of(" ", " ")); assertToElements(" / / ", ImmutableList.of(" ", " ", " ")); } private static void assertToElements(String input, List<String> expected) { assertThat(PathUtils.toElements(input)).isEqualTo(expected); } @Test public void lastElementOfWorkingDirThrowsException() throws Exception { try { PathUtils.lastElement(WORKING_DIR); Assert.fail("exception should be thrown"); } catch (IllegalArgumentException e) { // expected } } @Test public void testLastElement() throws Exception { assertLastElement(" ", " "); assertLastElement(" / ", " "); assertLastElement("abc", "abc"); assertLastElement("abc/def", "def"); assertLastElement("abc/def/ghi", "ghi"); } private static void assertLastElement(String input, String expected) { assertThat(PathUtils.lastElement(input)).isEqualTo(expected); } @Test public void testAppend() throws Exception { assertAppend(WORKING_DIR, WORKING_DIR, WORKING_DIR); assertAppend("abc", WORKING_DIR, "abc"); assertAppend("abc/def", WORKING_DIR, "abc/def"); assertAppend("abc/def/ghi", WORKING_DIR, "abc/def/ghi"); assertAppend(WORKING_DIR, "abc", "abc"); assertAppend(WORKING_DIR, "abc/def", "abc/def"); assertAppend(WORKING_DIR, "abc/def/ghi", "abc/def/ghi"); assertAppend("abc", "xyz", "abc/xyz"); assertAppend("abc", "xyz/uvw", "abc/xyz/uvw"); assertAppend("abc", "xyz/uvw/rst", "abc/xyz/uvw/rst"); assertAppend("abc/def", "xyz", "abc/def/xyz"); assertAppend("abc/def", "xyz/uvw", "abc/def/xyz/uvw"); assertAppend("abc/def", "xyz/uvw/rst", "abc/def/xyz/uvw/rst"); assertAppend("abc/def/ghi", "xyz", "abc/def/ghi/xyz"); assertAppend("abc/def/ghi", "xyz/uvw", "abc/def/ghi/xyz/uvw"); assertAppend("abc/def/ghi", "xyz/uvw/rst", "abc/def/ghi/xyz/uvw/rst"); assertAppend(" ", " ", " / "); assertAppend(" ", " / ", " / / "); assertAppend(" / ", " ", " / / "); assertAppend(" / ", " / ", " / / / "); } private static void assertAppend(String path1, String path2, String expected) { assertThat(PathUtils.append(path1, path2)).isEqualTo(expected); } }
package org.gluu.oxtrust.action; import java.io.Serializable; import javax.ejb.Stateless; import javax.enterprise.context.Conversation; import javax.inject.Inject; import javax.inject.Named; import org.gluu.jsf2.service.FacesService; @Stateless @Named public class MenuAction implements Serializable { private static final long serialVersionUID = -172441515451149801L; @Inject private Conversation conversation; @Inject private FacesService facesService; public String endConversation(final String viewId) { // TODO: CDI Review if (!conversation.isTransient()) { conversation.end(); } facesService.redirect(viewId); return viewId; } }
package timeBench.calendar; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import timeBench.data.TemporalDataException; /** * The calendarManager which maps calendar functionality to the Java Calendar class. * * <p> * Added: 2011-07-19 / TL<br> * Modifications: * </p> * * @author Tim Lammarsch * */ public class JavaDateCalendarManager implements CalendarManager { protected static JavaDateCalendarManager singleton = null; protected Calendar defaultCalendar = null; protected java.util.Calendar javaCalendar = null; /** * Constructs a JavaDateCalendarManager. Consider using the * {@linkplain JavaDateCalendarManager#getDefaultCalendar() singleton} instead. */ public JavaDateCalendarManager() { javaCalendar = java.util.Calendar.getInstance(); javaCalendar.setLenient(true); } /** * The granularities enumeration supports a certain number of granularities. * * <p> * Added: 2011-07-19 / TL<br> * Modifications: * </p> * * @author Tim Lammarsch * */ public enum Granularities { Millisecond (0), Second (1), Minute (2), Hour (3), Day (4), Week (5), Month (6), Quarter (7), Year (8), Calendar (16383), // Calendar has one granule from start to end of the calendar Top (32767); // Top has one granule from start to end of time private int intValue; Granularities(int toInt) { intValue = toInt; } /** * Converts a granularity from the enumeration to an identifier. * This identifier is not globally unique, it depends on calendarManager and calendar. * @return The equivalent identifier. */ public int toInt() { return intValue; } /** * Converts an identifier to a granularity from the enumeration. * This identifier is not globally unique, it depends on calendarManager and calendar. * @param intValue The identifier. * @return The granularity from the enumeration. * @throws TemporalDataException */ public static Granularities fromInt(int intValue) throws TemporalDataException { switch(intValue) { case 0: return Granularities.Millisecond; case 1: return Granularities.Second; case 2: return Granularities.Minute; case 3: return Granularities.Hour; case 4: return Granularities.Day; case 5: return Granularities.Week; case 6: return Granularities.Month; case 7: return Granularities.Quarter; case 8: return Granularities.Year; case 16383: return Granularities.Calendar; case 32767: return Granularities.Top; default: throw new TemporalDataException("Unknown Granularity: " + intValue); } } } /** * Provides access to a singleton instance of the class. This is not a generic factory method. It * does only create one instance and provides that one with every call. * @return The JavaDateCalendarManager instance. */ public static CalendarManager getSingleton() { if (singleton == null) singleton = new JavaDateCalendarManager(); return singleton; } /** * Generates an instance of a calendar, the only one currently provided by this class. * @return The calendar. */ public Calendar calendar() { return new Calendar(this); } /** * Provides access to a singleton instance of a calendar, the only one currently provided by this class. * It does only create one instance and provides that one with every call. * @return The calendar. */ public Calendar getDefaultCalendar() { if (defaultCalendar == null) defaultCalendar = calendar(); return defaultCalendar; } private int[] buildGranularityListForCreateGranule(Granularity granularity) throws TemporalDataException { int[] result; switch (Granularities.fromInt(granularity.getIdentifier())) { case Millisecond: result = new int[0]; break; case Second: result = new int[] { java.util.Calendar.MILLISECOND }; break; case Minute: result = new int[] { java.util.Calendar.SECOND, java.util.Calendar.MILLISECOND }; break; case Hour: result = new int[] { java.util.Calendar.MINUTE, java.util.Calendar.SECOND, java.util.Calendar.MILLISECOND }; break; case Day: result = new int[] { java.util.Calendar.AM_PM, java.util.Calendar.HOUR, java.util.Calendar.HOUR_OF_DAY, java.util.Calendar.MINUTE, java.util.Calendar.SECOND, java.util.Calendar.MILLISECOND }; break; case Week: result = new int[] { // java.util.Calendar.DAY_OF_WEEK, commented out because only works manually java.util.Calendar.AM_PM, java.util.Calendar.HOUR, java.util.Calendar.HOUR_OF_DAY, java.util.Calendar.MINUTE, java.util.Calendar.SECOND, java.util.Calendar.MILLISECOND }; break; case Month: result = new int[] { java.util.Calendar.DAY_OF_MONTH, java.util.Calendar.AM_PM, java.util.Calendar.HOUR, java.util.Calendar.HOUR_OF_DAY, java.util.Calendar.MINUTE, java.util.Calendar.SECOND, java.util.Calendar.MILLISECOND }; break; case Quarter: result = new int[] { java.util.Calendar.DAY_OF_MONTH, java.util.Calendar.AM_PM, java.util.Calendar.HOUR, java.util.Calendar.HOUR_OF_DAY, java.util.Calendar.MINUTE, java.util.Calendar.SECOND, java.util.Calendar.MILLISECOND }; break; case Year: result = new int[] { java.util.Calendar.DAY_OF_YEAR, java.util.Calendar.AM_PM, java.util.Calendar.HOUR, java.util.Calendar.HOUR_OF_DAY, java.util.Calendar.MINUTE, java.util.Calendar.SECOND, java.util.Calendar.MILLISECOND }; break; case Calendar: case Top: result = new int[] { java.util.Calendar.DAY_OF_YEAR, java.util.Calendar.AM_PM, java.util.Calendar.HOUR, java.util.Calendar.HOUR_OF_DAY, java.util.Calendar.MINUTE, java.util.Calendar.SECOND, java.util.Calendar.MILLISECOND, java.util.Calendar.YEAR }; break; default: throw new TemporalDataException("Granularity not implemented yet"); } return result; } protected Granule createGranule(long chronon, Granularity granularity) throws TemporalDataException { GregorianCalendar calInf = new GregorianCalendar(); GregorianCalendar calSup = new GregorianCalendar(); calInf.setTimeZone(TimeZone.getTimeZone("UTC")); calSup.setTimeZone(TimeZone.getTimeZone("UTC")); calInf.setTimeInMillis(chronon); calSup.setTimeInMillis(chronon); return createGranule(calInf,calSup,granularity); } /** * Constructs a {@link Granule} from a given {@link Date}. Consider using the adequate constructor of * {@link Granule} instead. * @param date the {@link Date} used to generate the granule * @param granularity granularity the {@link Granularity} to which the granule belongs * @return the constructed {@link Granule} * @throws TemporalDataException TemporalDataException thrown when granularities are not fully implemented */ public Granule createGranule(Date date, Granularity granularity) throws TemporalDataException { GregorianCalendar calInf = new GregorianCalendar(); GregorianCalendar calSup = new GregorianCalendar(); calInf.setTimeZone(TimeZone.getTimeZone("UTC")); calSup.setTimeZone(TimeZone.getTimeZone("UTC")); calInf.setTime(date); calSup.setTime(date); return createGranule(calInf,calSup,granularity); } private Granule createGranule(GregorianCalendar calInf, GregorianCalendar calSup, Granularity granularity) throws TemporalDataException { for (int field : buildGranularityListForCreateGranule(granularity)) { calInf.set(field, calInf.getActualMinimum(field)); calSup.set(field, calSup.getActualMaximum(field)); } if(granularity.getIdentifier() == Granularities.Quarter.intValue) { // calInf DAY_OF_MONTH is already at 1 // calSup DAY_OF_MONTH needs to be set to 1 first // because last day may change (e.g., 31 March --June--> 1 July) switch(calInf.get(GregorianCalendar.MONTH)) { case GregorianCalendar.JANUARY: case GregorianCalendar.FEBRUARY: case GregorianCalendar.MARCH: calInf.set(GregorianCalendar.MONTH,GregorianCalendar.JANUARY); calSup.set(GregorianCalendar.DAY_OF_MONTH, 1); calSup.set(GregorianCalendar.MONTH,GregorianCalendar.MARCH); calSup.set(GregorianCalendar.DAY_OF_MONTH, 31); break; case GregorianCalendar.APRIL: case GregorianCalendar.MAY: case GregorianCalendar.JUNE: calInf.set(GregorianCalendar.MONTH,GregorianCalendar.APRIL); calSup.set(GregorianCalendar.DAY_OF_MONTH, 1); calSup.set(GregorianCalendar.MONTH,GregorianCalendar.JUNE); calSup.set(GregorianCalendar.DAY_OF_MONTH, 30); break; case GregorianCalendar.JULY: case GregorianCalendar.AUGUST: case GregorianCalendar.SEPTEMBER: calInf.set(GregorianCalendar.MONTH,GregorianCalendar.JULY); calSup.set(GregorianCalendar.DAY_OF_MONTH, 1); calSup.set(GregorianCalendar.MONTH,GregorianCalendar.SEPTEMBER); calSup.set(GregorianCalendar.DAY_OF_MONTH, 30); break; case GregorianCalendar.OCTOBER: case GregorianCalendar.NOVEMBER: case GregorianCalendar.DECEMBER: calInf.set(GregorianCalendar.MONTH,GregorianCalendar.OCTOBER); calSup.set(GregorianCalendar.DAY_OF_MONTH, 1); calSup.set(GregorianCalendar.MONTH,GregorianCalendar.DECEMBER); calSup.set(GregorianCalendar.DAY_OF_MONTH, 31); break; } } else if(granularity.getIdentifier() == Granularities.Week.intValue) { long dow = (calInf.get(GregorianCalendar.DAY_OF_WEEK) + 5) % 7; long oldInf = calInf.getTimeInMillis(); calInf.setTimeInMillis(oldInf-dow*86400000L); long oldSup = calSup.getTimeInMillis(); calSup.setTimeInMillis(oldSup+(6-dow)*86400000L); if((granularity.getGranularityContextIdentifier() == Granularities.Month.intValue && calInf.get(GregorianCalendar.MONTH) != calSup.get(GregorianCalendar.MONTH)) || (granularity.getGranularityContextIdentifier() == Granularities.Quarter.intValue && calInf.get(GregorianCalendar.MONTH) / 3 != calSup.get(GregorianCalendar.MONTH) / 3) || (granularity.getGranularityContextIdentifier() == Granularities.Year.intValue) && calInf.get(GregorianCalendar.YEAR) != calSup.get(GregorianCalendar.YEAR)) { GregorianCalendar calBorder = new GregorianCalendar(); calBorder.setTimeZone(TimeZone.getTimeZone("UTC")); calBorder.setTimeInMillis(calInf.getTimeInMillis()); calBorder.set(GregorianCalendar.DAY_OF_MONTH, 1); calBorder.add(GregorianCalendar.MONTH,1); boolean front = oldSup < calBorder.getTimeInMillis(); if (!front) front = calBorder.getTimeInMillis() - oldInf > oldSup - calBorder.getTimeInMillis(); if (front) { calSup.set(GregorianCalendar.DAY_OF_MONTH, 1); calSup.set(GregorianCalendar.MONTH, calInf.get(GregorianCalendar.MONTH)); calSup.set(GregorianCalendar.YEAR, calInf.get(GregorianCalendar.YEAR)); calSup.set(GregorianCalendar.DAY_OF_MONTH, calSup.getActualMaximum(GregorianCalendar.DAY_OF_MONTH)); } else { calInf.set(GregorianCalendar.DAY_OF_MONTH, 1); calInf.set(GregorianCalendar.MONTH, calSup.get(GregorianCalendar.MONTH)); calInf.set(GregorianCalendar.YEAR, calSup.get(GregorianCalendar.YEAR)); } } } return new Granule(calInf.getTimeInMillis(),calSup.getTimeInMillis(),Granule.MODE_FORCE,granularity); } /** * Returns an {@link Array} of granularity identifiers that are provided by the calendar. * @return {@link Array} of granularity identifiers */ @Override public int[] getGranularityIdentifiers() { return new int[] {0,1,2,3,4,5,6,7,8,32767}; } /** * Calculate and return the identifier of a {@link Granule}. An identifier is a numeric label given in the context * of the {@link Granularity}. Consider using the adequate method of * {@link Granule} instead. * @return the identifier * @throws TemporalDataException thrown when granularities are not fully implemented */ @Override public long createGranuleIdentifier(Granule granule) throws TemporalDataException { long result = 0; switch(Granularities.fromInt(granule.getGranularity().getIdentifier())) { case Millisecond: switch(Granularities.fromInt(granule.getGranularity().getGranularityContextIdentifier())) { case Second: result = granule.getInf()%1000L; break; case Minute: result = granule.getInf()%60000L; break; case Hour: result = granule.getInf()%3600000L; break; case Day: result = granule.getInf()%86400000L; break; case Week: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = ((cal.get(GregorianCalendar.DAY_OF_WEEK)+5)%7)*86400000L + granule.getInf()%86400000L; break; } case Month: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = (cal.get(GregorianCalendar.DAY_OF_MONTH)-1)*86400000L + granule.getInf()%86400000L; break; } case Quarter: result = getDayInQuarter(granule.getInf())*86400000L + granule.getInf()%86400000L; break; case Year: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = (cal.get(GregorianCalendar.DAY_OF_YEAR)-1)*86400000L + granule.getInf()%86400000L; break; } default: result = granule.getInf(); } break; case Second: result = granule.getInf()/1000L; switch(Granularities.fromInt(granule.getGranularity().getGranularityContextIdentifier())) { case Minute: result %= 60L; break; case Hour: result %= 3600L; break; case Day: result %= 86400L; break; case Week: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = ((cal.get(GregorianCalendar.DAY_OF_WEEK)+5)%7)*86400L + result % 86400L; break; } case Month: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = (cal.get(GregorianCalendar.DAY_OF_MONTH)-1)*86400L + result % 86400L; break; } case Quarter: result = getDayInQuarter(granule.getInf())*86400L + result % 86400L; break; case Year: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = (cal.get(GregorianCalendar.DAY_OF_YEAR)-1)*86400L + result % 86400L; break; } } break; case Minute: result = granule.getInf()/60000L; switch(Granularities.fromInt(granule.getGranularity().getGranularityContextIdentifier())) { case Hour: result %= 60; break; case Day: result %= 1440; break; case Week: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = ((cal.get(GregorianCalendar.DAY_OF_WEEK)+5)%7)*1440L + result % 1440L; break; } case Month: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = (cal.get(GregorianCalendar.DAY_OF_MONTH)-1)*1440L + result % 1440L; break; } case Quarter: result = getDayInQuarter(granule.getInf())*1440L + result % 1440L; break; case Year: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = (cal.get(GregorianCalendar.DAY_OF_YEAR)-1)*1440L + result % 1440L; break; } } break; case Hour: result = granule.getInf()/3600000L; switch(Granularities.fromInt(granule.getGranularity().getGranularityContextIdentifier())) { case Day: result %= 24; break; case Week: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = ((cal.get(GregorianCalendar.DAY_OF_WEEK)+5)%7)*24 + result % 24; break; } case Month: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = (cal.get(GregorianCalendar.DAY_OF_MONTH)-1)*24 + result % 24; break; } case Quarter: result = getDayInQuarter(granule.getInf())*24 + result % 24; break; case Year: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = (cal.get(GregorianCalendar.DAY_OF_YEAR)-1)*24 + result % 24; break; } } break; case Day: switch(Granularities.fromInt(granule.getGranularity().getGranularityContextIdentifier())) { case Week: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = (cal.get(GregorianCalendar.DAY_OF_WEEK)+5)%7; break; } case Month: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = cal.get(GregorianCalendar.DAY_OF_MONTH)-1; break; } case Quarter: result = getDayInQuarter(granule.getInf()); break; case Year: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = cal.get(GregorianCalendar.DAY_OF_YEAR)-1; break; } default: result = granule.getInf() / 86400000L; } break; case Week: // TODO add context granule to make this "clean" switch(Granularities.fromInt(granule.getGranularity().getGranularityContextIdentifier())) { case Month: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = cal.get(GregorianCalendar.WEEK_OF_MONTH); break; } case Quarter: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); int weekCounter = 0; if (cal.get(GregorianCalendar.DAY_OF_WEEK) != GregorianCalendar.MONDAY) weekCounter int originalQuarter = cal.get(GregorianCalendar.MONTH) / 3; long chronon = granule.getInf(); while(cal.get(GregorianCalendar.MONTH) / 3 == originalQuarter) { weekCounter++; chronon -= 604800000L; cal.setTimeInMillis(chronon); } cal.set(GregorianCalendar.DAY_OF_MONTH, 1); cal.add(GregorianCalendar.MONTH,1); switch(cal.get(GregorianCalendar.DAY_OF_WEEK)) { case GregorianCalendar.MONDAY: case GregorianCalendar.TUESDAY: case GregorianCalendar.WEDNESDAY: case GregorianCalendar.THURSDAY: weekCounter++; } result = weekCounter; break;} case Year: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = cal.get(GregorianCalendar.WEEK_OF_YEAR)-1; break; } default: result = (granule.getInf() + 259200000L) / 604800000L; // Add the 3 days of week zero that were not in 1970 break; } break; case Month: { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); switch(Granularities.fromInt(granule.getGranularity().getGranularityContextIdentifier())) { case Quarter: result = cal.get(GregorianCalendar.MONTH) % 3; break; case Year: result = cal.get(GregorianCalendar.MONTH); break; default: result = (cal.get(GregorianCalendar.YEAR)-1970) * 12 + cal.get(GregorianCalendar.MONTH); break; } break;} case Quarter: switch(Granularities.fromInt(granule.getGranularity().getGranularityContextIdentifier())) { case Year:{ GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = cal.get(GregorianCalendar.MONTH) / 3; break;} default:{ GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = (cal.get(GregorianCalendar.YEAR)-1970) * 4 + cal.get(GregorianCalendar.MONTH) / 3; break;} } break; case Year: GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = cal.get(GregorianCalendar.YEAR)-1970; break; } return result; } private long getDayInQuarter(long inf) { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(inf); switch(cal.get(GregorianCalendar.MONTH)) { case GregorianCalendar.JANUARY: return cal.get(GregorianCalendar.DAY_OF_MONTH)-1; case GregorianCalendar.FEBRUARY: return 31+cal.get(GregorianCalendar.DAY_OF_MONTH)-1; case GregorianCalendar.MARCH: return 31+ (cal.isLeapYear(cal.get(GregorianCalendar.YEAR)) ? 29 : 28) + cal.get(GregorianCalendar.DAY_OF_MONTH)-1; case GregorianCalendar.APRIL: return cal.get(GregorianCalendar.DAY_OF_MONTH)-1; case GregorianCalendar.MAY: return 30+cal.get(GregorianCalendar.DAY_OF_MONTH)-1; case GregorianCalendar.JUNE: return 61+cal.get(GregorianCalendar.DAY_OF_MONTH)-1; case GregorianCalendar.JULY: return cal.get(GregorianCalendar.DAY_OF_MONTH)-1; case GregorianCalendar.AUGUST: return 31+cal.get(GregorianCalendar.DAY_OF_MONTH)-1; case GregorianCalendar.SEPTEMBER: return 62+cal.get(GregorianCalendar.DAY_OF_MONTH)-1; case GregorianCalendar.OCTOBER: return cal.get(GregorianCalendar.DAY_OF_MONTH)-1; case GregorianCalendar.NOVEMBER: return 31+cal.get(GregorianCalendar.DAY_OF_MONTH)-1; default: // GregorianCalendar.DECEMBER: return 61+cal.get(GregorianCalendar.DAY_OF_MONTH)-1; } } /** * Returns the identifier of the bottom granularity * @return the bottom granularity identifier */ public int getBottomGranularityIdentifier() { return 0; } /** * Returns the identifier of the top granularity. This is the highest possible granularity of the calendar. * Usually, this is a granularity where one granule is composed of all the time the calendar is defined for. * Let all calendars that would normally have this be modified so they have one. * @return the top granularity identifier */ public int getTopGranularityIdentifier() { return 16383; } /** * Constructs a {@link Granule} from inf to sup using a given {@linkplain Granule#MODE_INF_GANULE mode} and * for a given {@link Granularity}. * Consider using the adequate constructor of {@link Granule} instead. * @param inf the chronon that determines the start of the granule constructed * @param sup the chronon that determines the end of the granule constructed * @param mode the {@linkplain Granule#MODE_INF_GANULE mode} used to construct the granule * @param granularity the {@link Granularity} to use * @return the constructed {@link Granule} * @throws TemporalDataException TemporalDataException thrown when granularities are not fully implemented */ @Override public Granule createGranule(long inf, long sup, int mode, Granularity granularity) throws TemporalDataException { switch(mode) { case Granule.MODE_FORCE: return new Granule(inf,sup,mode,granularity); case Granule.MODE_INF_GRANULE: return createGranule(inf,granularity); case Granule.MODE_MIDDLE_GRANULE: return createGranule(inf+(sup-inf)/2,granularity); case Granule.MODE_SUP_GRANULE: return createGranule(sup,granularity); default: throw new TemporalDataException("Illegal mode in createGranule"); } } /** * Constructs several {@link Granule} objects from inf to sup that are at least partly in the given interval with * a coverage of a least a given fraction and * for a given {@link Granularity}. Consider using the adequate factory of {@link Granularity} instead. * @param inf the chronon that determines the start of the {@link Granule} range constructed * @param sup the chronon that determines the end of the {@link Granule} range constructed * @param cover the coverage fraction of a granule needed to be included in the result * @param granularity the {@link Granularity} to use * @return the constructed {@link Array} of {@link Granule} * @throws TemporalDataException TemporalDataException thrown when granularities are not fully implemented */ @Override public Granule[] createGranules(long inf, long sup, double cover, Granularity granularity) throws TemporalDataException { Granule first = createGranule(inf,granularity); Granule last = createGranule(sup, granularity); long firstIdentifier = first.getIdentifier(); long lastIdentifier = last.getIdentifier(); if( (double)(inf-first.getInf()) / (double)(first.getSup()-first.getInf()) < cover) { firstIdentifier++; } if( (double)(last.getSup()-sup) / (double)(last.getSup()-last.getInf()) < cover) { lastIdentifier } Granule[] result; if(firstIdentifier>lastIdentifier) result = new Granule[0]; else { result = new Granule[(int)(lastIdentifier-firstIdentifier+1)]; result[0] = first; for(int i=1; i<(int)(lastIdentifier-firstIdentifier); i++) { result[i] = createGranule(result[i-1].getSup()+1,granularity); } result[(int)(lastIdentifier-firstIdentifier)] = last; // when first=last set 0 again } return result; } /** * Constructs several {@link Granule} objects from other {@link Granule} objects for a given {@link Granularity} * that can (and most likely * will) be in a different {@link Granularity}. All {@link Granule} with * a coverage of a least a given fraction are returned. * Consider using the adequate factory of {@link Granularity} instead. * @param Granule[] the {@link Array} of {@link Granule} used as source * @param cover the coverage fraction of a granule needed to be included in the result * @param granularity the {@link Granularity} to use * @return the constructed {@link Array} of {@link Granule} * @throws TemporalDataException TemporalDataException thrown when granularities are not fully implemented */ @Override public Granule[] createGranules(Granule[] granules, double cover, Granularity granularity) throws TemporalDataException { ArrayList<Granule> result = new ArrayList<Granule>(); for(Granule iGran : granules) { for(Granule iGran2 : createGranules(iGran.getInf(), iGran.getSup(), cover, granularity)) { if(result.get(result.size()-1).getIdentifier() < iGran2.getIdentifier()) result.add(iGran2); } } return (Granule[])result.toArray(); } /** * Calculate and return the human readable label of a {@link Granule}. * Consider using the adequate method of * {@link Granule} instead. * @return the label * @throws TemporalDataException thrown when granularities are not fully implemented */ @Override public String createGranuleLabel(Granule granule) throws TemporalDataException { String result = null; switch(Granularities.fromInt(granule.getGranularity().getIdentifier())) { case Day: if(Granularities.fromInt(granule.getGranularity().getGranularityContextIdentifier()) == Granularities.Week ) { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = cal.getDisplayName(GregorianCalendar.DAY_OF_WEEK, GregorianCalendar.LONG, Locale.getDefault()); } else result = String.format("%d",granule.getIdentifier()+1); break; case Week: if(Granularities.fromInt(granule.getGranularity().getGranularityContextIdentifier()) == Granularities.Month || Granularities.fromInt(granule.getGranularity().getGranularityContextIdentifier()) == Granularities.Quarter ) { result = String.format("%d",granule.getIdentifier()); } else result = String.format("%d",granule.getIdentifier()+1); break; case Month: if(Granularities.fromInt(granule.getGranularity().getGranularityContextIdentifier()) == Granularities.Year ) { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(granule.getInf()); result = cal.getDisplayName(GregorianCalendar.MONTH, GregorianCalendar.LONG, Locale.getDefault()); } else result = String.format("%d",granule.getIdentifier()+1); break; case Year: result = String.format("%d",granule.getIdentifier()+1970); break; default: result = String.format("%d",granule.getIdentifier()+1); } return result; } /** * Calculate and return the inf of a {@link Granule}. * @return the inf * @throws TemporalDataException thrown when granularities are not fully implemented */ @Override public long createInf(Granule granule) throws TemporalDataException { long result = 0; switch(Granularities.fromInt(granule.getGranularity().getIdentifier())) { case Millisecond: result = granule.getIdentifier(); break; case Second: result = granule.getIdentifier()*1000L; break; case Minute: result = granule.getIdentifier()*60000L; break; case Hour: result = granule.getIdentifier()*3600000L; break; case Day: // Warning does not handle day light saving time result = granule.getIdentifier()*86400000L; break; case Week: // 1 Jan 1970 is a Thursday result = granule.getIdentifier() * 604800000L - 259200000; // = 3*24*60*60*1000 break; case Month:{ GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(0); cal.set(GregorianCalendar.YEAR, (int)(granule.getIdentifier()/12+1970)); cal.set(GregorianCalendar.MONTH, (int)(granule.getIdentifier()%12)); result = cal.getTimeInMillis(); break;} case Quarter:{ GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(0); cal.set(GregorianCalendar.YEAR, (int)(granule.getIdentifier()/4+1970)); cal.set(GregorianCalendar.MONTH, (int)(granule.getIdentifier()%4*3)); result = cal.getTimeInMillis(); break;} case Year:{ GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(0); cal.set(GregorianCalendar.YEAR, (int)(granule.getIdentifier()+1970)); result = cal.getTimeInMillis(); break;} } return result; } /** * Calculate and return the sup of a {@link Granule}. * @return the sup * @throws TemporalDataException thrown when granularities are not fully implemented */ @Override public long createSup(Granule granule) throws TemporalDataException { long result = 0; // invalid granule ids for context granularities are not defined (insert context granule) switch(Granularities.fromInt(granule.getGranularity().getIdentifier())) { case Millisecond: result = granule.getIdentifier(); break; case Second: result = granule.getIdentifier()*1000L+999L; break; case Minute: result = granule.getIdentifier()*60000L+59999L; break; case Hour: result = granule.getIdentifier()*3600000L+3599999L; break; case Day: result = granule.getIdentifier()*86400000L+86399999L; break; case Week: // 1 Jan 1970 is a Thursday result = granule.getIdentifier() * 604800000L + 345599999; // = 4*24*60*60*1000 - 1 break; case Month:{ GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(0); cal.set(GregorianCalendar.YEAR, (int)(granule.getIdentifier()/12+1970)); cal.set(GregorianCalendar.MONTH, (int)(granule.getIdentifier()%12)); result = cal.getTimeInMillis()+(cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH))*86400000L-1L; break;} case Quarter:{ GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(0); cal.set(GregorianCalendar.YEAR, (int)(granule.getIdentifier()/4+1970)); cal.set(GregorianCalendar.MONTH, (int)(granule.getIdentifier()%4*3)); result = cal.getTimeInMillis()+(cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH))*86400000L-1L; cal.add(GregorianCalendar.MONTH, 1); result += (cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH))*86400000L; cal.add(GregorianCalendar.MONTH, 1); result += (cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH))*86400000L; break;} case Year:{ GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(0); cal.set(GregorianCalendar.YEAR, (int)(granule.getIdentifier()+1970)); result = cal.getTimeInMillis()+cal.getActualMaximum(GregorianCalendar.DAY_OF_YEAR)*86400000L-1L; break;} } return result; } public static String formatDebugString(long inf) { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(inf); return String.format("%04d-%02d-%02d, %02d:%02d:%02d,%03d",cal.get(GregorianCalendar.YEAR),cal.get(GregorianCalendar.MONTH)+1,cal.get(GregorianCalendar.DAY_OF_MONTH), cal.get(GregorianCalendar.HOUR_OF_DAY),cal.get(GregorianCalendar.MINUTE),cal.get(GregorianCalendar.SECOND),cal.get(GregorianCalendar.MILLISECOND)); } @Override public long getMinGranuleIdentifier(Granularity granularity) throws TemporalDataException { switch(Granularities.fromInt(granularity.getIdentifier())) { case Millisecond: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } case Second: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } case Minute: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } case Hour: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } case Day: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } case Week: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } case Month: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } case Quarter: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } case Year: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } } return 0; } @Override public long getMaxGranuleIdentifier(Granularity granularity) throws TemporalDataException { switch(Granularities.fromInt(granularity.getIdentifier())) { case Millisecond: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Millisecond: return 0L; case Second: return 999L; case Minute: return 59999L; case Hour: return 3599999L; case Day: return 86399999L; case Week: return 604799999L; case Month: return 2678399999L; case Quarter: return 7948799999L; case Year: return 31622399999L; case Calendar: case Top: return Long.MIN_VALUE; default: return 1000L; } case Second: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Minute: return 59L; case Hour: return 3599L; case Day: return 86399L; case Week: return 604799L; case Month: return 2678399L; case Quarter: return 7948799L; case Year: return 31622399L; case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } case Minute: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Hour: return 59L; case Day: return 1439L; case Week: return 10079L; case Month: return 44639L; case Quarter: return 132479L; case Year: return 527039L; case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } case Hour: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Day: return 23L; case Week: return 167L; case Month: return 743L; case Quarter: return 2207L; case Year: return 8783L; case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } case Day: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Week: return 6L; case Month: return 30L; case Quarter: return 91L; case Year: return 365L; case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } case Week: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Month: return 5L; case Quarter: return 13L; case Year: return 51L; case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } case Month: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Quarter: return 2L; case Year: return 11L; case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } case Quarter: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Year: return 3L; case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } case Year: switch(Granularities.fromInt(granularity.getGranularityContextIdentifier())) { case Calendar: case Top: return Long.MIN_VALUE; default: return 0; } } return 0; } @Override public boolean contains(Granule granule, long chronon) throws TemporalDataException { if(granule.getGranularity().getGranularityContextIdentifier() == Granularities.Top.intValue || granule.getGranularity().getGranularityContextIdentifier() == Granularities.Calendar.intValue) { return chronon>=granule.getInf() && chronon<=granule.getSup(); } else { Granule g2 = new Granule(chronon,chronon,granule.getGranularity()); return granule.getIdentifier() == g2.getIdentifier(); } } @Override public long getStartOfTime() { return Long.MIN_VALUE; } @Override public long getEndOfTime() { return Long.MAX_VALUE; } }
package org.domokit.oknet; import android.content.Context; import android.util.Log; import com.squareup.okhttp.Cache; import com.squareup.okhttp.OkHttpClient; import org.chromium.mojo.bindings.InterfaceRequest; import org.chromium.mojo.system.Core; import org.chromium.mojo.system.DataPipe; import org.chromium.mojo.system.MessagePipeHandle; import org.chromium.mojo.system.MojoException; import org.chromium.mojom.mojo.CookieStore; import org.chromium.mojom.mojo.NetAddress; import org.chromium.mojom.mojo.NetworkService; import org.chromium.mojom.mojo.TcpBoundSocket; import org.chromium.mojom.mojo.TcpConnectedSocket; import org.chromium.mojom.mojo.UdpSocket; import org.chromium.mojom.mojo.UrlLoader; import org.chromium.mojom.mojo.WebSocket; import java.io.File; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * OkHttp implementation of NetworkService. */ public class NetworkServiceImpl implements NetworkService { private static final String TAG = "NetworkServiceImpl"; private static ExecutorService sThreadPool; private static OkHttpClient sClient; private Core mCore; public NetworkServiceImpl(Context context, Core core, MessagePipeHandle pipe) { assert core != null; mCore = core; if (sThreadPool == null) sThreadPool = Executors.newCachedThreadPool(); if (sClient == null) { sClient = new OkHttpClient(); try { int cacheSize = 10 * 1024 * 1024; // 10 MiB File cacheDirectory = new File(context.getCacheDir(), "ok_http_cache"); Cache cache = new Cache(cacheDirectory, cacheSize); sClient.setCache(cache); } catch (IOException e) { Log.e(TAG, "Unable to create HTTP cache", e); } } NetworkService.MANAGER.bind(this, pipe); } @Override public void close() {} @Override public void onConnectionError(MojoException e) {} @Override public void createUrlLoader(InterfaceRequest<UrlLoader> loader) { UrlLoader.MANAGER.bind(new UrlLoaderImpl(mCore, sClient, sThreadPool), loader); } @Override public void getCookieStore(InterfaceRequest<CookieStore> cookieStore) { cookieStore.close(); } @Override public void createWebSocket(InterfaceRequest<WebSocket> socket) { socket.close(); } @Override public void createTcpBoundSocket(NetAddress localAddress, InterfaceRequest<TcpBoundSocket> boundSocket, CreateTcpBoundSocketResponse callback) { boundSocket.close(); } @Override public void createTcpConnectedSocket(NetAddress remoteAddress, DataPipe.ConsumerHandle sendStream, DataPipe.ProducerHandle receiveStream, InterfaceRequest<TcpConnectedSocket> clientSocket, CreateTcpConnectedSocketResponse callback) { sendStream.close(); receiveStream.close(); clientSocket.close(); } @Override public void createUdpSocket(InterfaceRequest<UdpSocket> socket) { socket.close(); } }
package uk.org.ownage.dmdirc.ui.messages; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.InvalidPropertiesFormatException; import java.util.Properties; import uk.org.ownage.dmdirc.Config; import uk.org.ownage.dmdirc.logger.ErrorLevel; import uk.org.ownage.dmdirc.logger.Logger; /** * The Formatter provides a standard way to format messages for display. */ public final class Formatter { /** * The format strings used by the formatter. */ private static Properties properties; /** * The default properties we fall back to if the user hasn't defined their * own. */ private static Properties defaultProperties; /** * Creates a new instance of Formatter. */ private Formatter() { } /** * Inserts the supplied arguments into a format string for the specified * message type. * @param messageType The message type that the arguments should be formatted as * @param arguments The arguments to this message type * @return A formatted string */ public static String formatMessage(final String messageType, final Object... arguments) { if (properties == null) { initialise(); } if (properties.containsKey(messageType)) { return String.format(properties.getProperty(messageType), arguments); } else { Logger.error(ErrorLevel.ERROR, "Format string not found: " + messageType); return "<No format string for message type " + messageType + ">"; } } /** * Determines whether the formatter knows of a specific message type. * @param messageType the message type to check * @return True iff there is a matching format, false otherwise */ public static boolean hasFormat(final String messageType) { if (properties == null) { initialise(); } return properties.containsKey(messageType); } /** * Returns the default format strings for the client. * @return The default format strings */ private static void loadDefaults() { defaultProperties = new Properties(); final char colour = Styliser.CODE_COLOUR; final char stop = Styliser.CODE_STOP; final char fixed = Styliser.CODE_FIXED; // Type: Timestamp // 1: Current timestamp defaultProperties.setProperty("timestamp", "%1$tH:%1$tM:%1$tS | "); // Type: Channel Message // 1: User mode prefixes // 2: User nickname // 3: User ident // 4: User host // 5: Message content // 6: Channel name defaultProperties.setProperty("channelMessage", "<%1$s%2$s> %5$s"); defaultProperties.setProperty("channelAction", colour + "6* %1$s%2$s %5$s"); defaultProperties.setProperty("channelSelfMessage", "<%1$s%2$s> %5$s"); defaultProperties.setProperty("channelSelfAction", colour + "6* %1$s%2$s %5$s"); defaultProperties.setProperty("channelSelfExternalMessage", "<%1$s%2$s> %5$s"); defaultProperties.setProperty("channelSelfExternalAction", colour + "6* %1$s%2$s %5$s"); // Type: Channel CTCP // 1: User mode prefixes // 2: User nickname // 3: User ident // 4: User host // 5: CTCP type // 6: CTCP content // 7: Channel name defaultProperties.setProperty("channelCTCP", colour + "4-!- CTCP %5$S from %1$s%2$s"); // Type: Channel Event // 1: User mode prefixes // 2: User nickname // 3: User ident // 4: User host // 5: Channel name defaultProperties.setProperty("channelJoin", colour + "3* %2$s (%3$s@%4$s) has joined %5$s."); defaultProperties.setProperty("channelPart", colour + "3* %1$s%2$s (%3$s@%4$s) has left %5$s."); defaultProperties.setProperty("channelQuit", colour + "2* %1$s%2$s (%3$s@%4$s) has quit IRC."); defaultProperties.setProperty("channelSelfJoin", colour + "3* You are now talking in %5$s."); defaultProperties.setProperty("channelSelfPart", colour + "3* You have left the channel."); // Type: Channel Event with content // 1: User mode prefixes // 2: User nickname // 3: User ident // 4: User host // 5: Content // 6: Channel name defaultProperties.setProperty("channelPartReason", colour + "3* %1$s%2$s (%3$s@%4$s) has left %6$s (%5$s" + stop + ")."); defaultProperties.setProperty("channelQuitReason", colour + "2* %1$s%2$s (%3$s@%4$s) has quit IRC (%5$s" + stop + ")."); defaultProperties.setProperty("channelTopicChange", colour + "3* %1$s%2$s has changed the topic to '%5$s" + stop + "'."); defaultProperties.setProperty("channelNickChange", colour + "3* %1$s%2$s is now know as %5$s."); defaultProperties.setProperty("channelModeChange", colour + "3* %1$s%2$s sets mode: %5$s."); defaultProperties.setProperty("channelSelfNickChange", colour + "3* You are now know as %5$s."); defaultProperties.setProperty("channelSelfModeChange", colour + "3* You set mode: %5$s."); defaultProperties.setProperty("channelSelfPartReason", colour + "3* You have left the channel."); // Type: Binary Channel Event // 1: Source user mode prefixes // 2: Source user nickname // 3: Source user ident // 4: Source user host // 5: Target user mode prefixes // 6: Target user nickname // 7: Target user ident // 8: Target user host // 9: Channel name defaultProperties.setProperty("channelKick", colour + "3* %1$s%2$s has kicked %5$s%6$s from %9$s."); // Type: Binary Channel Event with content // 1: Source user mode prefixes // 2: Source user nickname // 3: Source user ident // 4: Source user host // 5: Target user mode prefixes // 6: Target user nickname // 7: Target user ident // 8: Target user host // 9: Content // 10: Channel name defaultProperties.setProperty("channelKickReason", colour + "3* %1$s%2$s has kicked %5$s%6$s from %10$s (%9$s" + stop + ")."); defaultProperties.setProperty("channelUserMode_default", colour + "3* %1$s%2$s sets mode %9$s on %6$s."); // Type: Channel topic sync // 1: Topic // 2: User responsible // 3: Time last changed // 4: Channel name defaultProperties.setProperty("channelJoinTopic", colour + "3* The topic for %4$s is '%1$s" + stop + "'.\n" + colour + "3* Topic was set by %2$s."); // Type: Channel mode discovery // 1: Channel modes // 2: Channel name defaultProperties.setProperty("channelModeDiscovered", colour + "3* Channel modes for %2$s are: %1$s."); // Type: Private CTCP // 1: User nickname // 2: User ident // 3: User host // 4: CTCP type // 5: CTCP content defaultProperties.setProperty("privateCTCP", colour + "4-!- CTCP %4$S from %1$s"); defaultProperties.setProperty("privateCTCPreply", colour + "4-!- CTCP %4$S reply from %1$s: %5$s"); // Type: Private communications // 1: User nickname // 2: User ident // 3: User host // 4: Message content defaultProperties.setProperty("privateNotice", colour + "5-%1$s- %4$s"); defaultProperties.setProperty("queryMessage", "<%1$s> %4$s"); defaultProperties.setProperty("queryAction", colour + "6* %1$s %4$s"); defaultProperties.setProperty("querySelfMessage", "<%1$s> %4$s"); defaultProperties.setProperty("querySelfAction", colour + "6* %1$s %4$s"); defaultProperties.setProperty("queryNickChanged", colour + "3* %1$s is now know as %4$s."); // Type: Outgoing message // 1: Target // 2: Message defaultProperties.setProperty("selfCTCP", colour + "4->- [%1$s] %2$s"); defaultProperties.setProperty("selfNotice", colour + "5>%1$s> %2$s"); // Type: Miscellaneous server // 1: Server name // 2: Miscellaneous argument defaultProperties.setProperty("connectError", colour + "2Error connecting: %2$s"); defaultProperties.setProperty("connectRetry", colour + "2Reconnecting in %2$s seconds..."); // Type: Miscellaneous // 1: Miscellaneous data defaultProperties.setProperty("channelNoTopic", colour + "3* There is no topic set for %1$s."); defaultProperties.setProperty("rawCommand", colour + "10 >>> %1$s"); defaultProperties.setProperty("socketClosed", colour + "2 -!- You have been disconnected from the server."); defaultProperties.setProperty("motdStart", colour + "10%1$s"); defaultProperties.setProperty("motdLine", colour + "10" + fixed + "%1$s"); defaultProperties.setProperty("motdEnd", colour + "10%1$s"); // Type: Numerical data defaultProperties.setProperty("numeric_301", "%4$s is away: %5$s"); defaultProperties.setProperty("numeric_311", "-\n%4$s is %5$s@%6$s (%8$s)."); defaultProperties.setProperty("numeric_312", "%4$s is connected to %5$s (%6$s)."); defaultProperties.setProperty("numeric_313", "%4$s %5$s."); defaultProperties.setProperty("numeric_318", "End of WHOIS info for %4$s.\n-"); defaultProperties.setProperty("numeric_319", "%4$s is on: %5$s"); defaultProperties.setProperty("numeric_330", "%4$s %6$s %5$s."); defaultProperties.setProperty("numeric_343", "%4$s %6$s %5$s."); } /** * Allows plugins (etc) to register new default formats. * @param name The name of the format * @param format The actual format itself */ public static void registerDefault(final String name, final String format) { if (defaultProperties == null) { loadDefaults(); } defaultProperties.setProperty(name, format); } /** * Reads the format strings from disk (if available), and initialises the * properties object. */ private static void initialise() { if (defaultProperties == null) { loadDefaults(); } properties = new Properties(defaultProperties); if (Config.hasOption("general", "formatters")) { for (String file : Config.getOption("general", "formatters").split("\n")) { loadFile(file); } } } /** * Loads the specified file into the formatter. * @param file File to be loaded * @return True iff the operation succeeeded, false otherwise */ public static boolean loadFile(final String file) { final File myFile = new File(Config.getConfigDir() + file); if (myFile.exists()) { try { properties.load(new FileInputStream(myFile)); } catch (InvalidPropertiesFormatException ex) { Logger.error(ErrorLevel.TRIVIAL, "Unable to load formatter", ex); return false; } catch (FileNotFoundException ex) { return false; } catch (IOException ex) { Logger.error(ErrorLevel.WARNING, "unable to load formatter", ex); return false; } return true; } else { return false; } } /** * Saves the current formatter into the specified file. * @param target The target file * @return True iff the operation succeeded, false otherwise */ public static boolean saveAs(final String target) { if (properties == null) { initialise(); } final File myFile = new File(Config.getConfigDir() + target); try { properties.store(new FileOutputStream(myFile), null); } catch (FileNotFoundException ex) { Logger.error(ErrorLevel.TRIVIAL, "Error saving formatter", ex); return false; } catch (IOException ex) { Logger.error(ErrorLevel.WARNING, "Error saving formatter", ex); return false; } return true; } /** * Reloads the formatter. */ public static void reload() { initialise(); } }
package org.intermine.web; /** * Container for ServletContext and Session attribute names used by the webapp * * @author Kim Rutherford */ public interface Constants { /** * ServletContext attribute used to store web.properties */ public static final String WEB_PROPERTIES = "WEB_PROPERTIES"; /** * ServletContext attribute used to store the example queries */ public static final String EXAMPLE_QUERIES = "EXAMPLE_QUERIES"; /** * ServletContext attribute used to store global template queries */ public static final String GLOBAL_TEMPLATE_QUERIES = "GLOBAL_TEMPLATE_QUERIES"; /** * ServletContext attribute maps category name to List of TemplateQuerys */ public static final String CATEGORY_TEMPLATES = "CATEGORY_TEMPLATES"; /** * ServletContext attribute maps a class name to a Map of category names to List of * TemplateQuerys. */ public static final String CLASS_CATEGORY_TEMPLATES = "CLASS_CATEGORY_TEMPLATES"; /** * ServletContext attribute maps a class name to a Map of template names to simple expressions - * the expression describes a field that should be set when a template is linked to from the * object details page. eg. Gene.identifier */ public static final String CLASS_TEMPLATE_EXPRS = "CLASS_TEMPLATE_EXPRS"; /** * ServletContext attribute maps category name to List of class names. */ public static final String CATEGORY_CLASSES = "CATEGORY_CLASSES"; /** * ServletContext attribute, List of category names. */ public static final String CATEGORIES = "CATEGORIES"; /** * ServletContext attribute, provides an interface for actions and * controllers to query some model meta-data like class counts and * field enumerations. */ public static final String OBJECT_STORE_SUMMARY = "OBJECT_STORE_SUMMARY"; /** * ServletContext attribute used to store the Map of class names to Displayer objects and * className+"."+fieldName to Displayer objects. */ public static final String DISPLAYERS = "DISPLAYERS"; /** * ServletContext attribute used to store the WebConfig object for the Model. */ public static final String WEBCONFIG = "WEBCONFIG"; /** * ServletContext attribute used to store the ObjectStore */ public static final String OBJECTSTORE = "OBJECTSTORE"; /** * ServletContext attribute used to store the ProfileManager */ public static final String PROFILE_MANAGER = "PROFILE_MANAGER"; /** * Session attribute used to store the user's Profile */ public static final String PROFILE = "PROFILE"; /** * Session attribute used to store the current query */ public static final String QUERY = "QUERY"; /** * Session attribute used to store the copy of the query that the user is * building a template with. */ public static final String TEMPLATE_PATHQUERY = "TEMPLATE_PATHQUERY"; /** * Session attribute used to store the original of the template being edited * in the query builder. */ public static final String EDITING_TEMPLATE = "EDITING_TEMPLATE"; /** * Session attribute used to store the results of running the current query */ public static final String QUERY_RESULTS = "QUERY_RESULTS"; /** * Session attribute used to store the active results table (which may be QUERY_RESULTS) */ public static final String RESULTS_TABLE = "RESULTS_TABLE"; /** * Session attribute storing a bean exposing the user's trail through the object details * pages. */ public static final String OBJECT_DETAILS_TRAIL = "OBJECT_DETAILS_TRAIL"; /** * Session attribute equals Boolean.TRUE when logged in user is superuser. */ public static final String IS_SUPERUSER = "IS_SUPERUSER"; /** * Session attribute containing Map containing 'collapsed' state of objectDetails.jsp * UI elements. */ public static final String COLLAPSED = "COLLAPSED"; /** * Servlet attribute used to store username of superuser (this attribute * will disappear when we implement a more fine-grained user privileges * system). */ public static final String SUPERUSER_ACCOUNT = "SUPERUSER_ACCOUNT"; /** * Session attribute that temporarily holds a Vector of messages that will be displayed by the * errorMessages.jsp on the next page viewed by the user and then removed (allows message * after redirect). */ public static final String MESSAGES = "MESSAGES"; /** * Session attribute that temporarily holds a Vector of errors that will be displayed by the * errorMessages.jsp on the next page viewed by the user and then removed (allows errors * after redirect). */ public static final String ERRORS = "ERRORS"; /** * The name of the property that is set to TRUE in the PortalQueryAction Action to indicate * to the ObjectDetailsController that we have come from a portal page. */ public static final String PORTAL_QUERY_FLAG = "PORTAL_QUERY_FLAG"; /** * The name of the property to look up to find the maximum size of an inline table. */ public static final String INLINE_TABLE_SIZE = "inline.table.size"; /** * Period of time to wait for client to poll a running query before cancelling the query. */ public static final int QUERY_TIMEOUT_SECONDS = 20; /** * Refresh period specified on query poll page. */ public static final int POLL_REFRESH_SECONDS = 2; }
package storm.state.hdfs; import carbonite.JavaBridge; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.serializers.DefaultSerializers.BigIntegerSerializer; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.Semaphore; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RawLocalFileSystem; import org.apache.log4j.Logger; import storm.state.hdfs.HDFSLog.LogWriter; import storm.state.Serializations; import storm.state.State; import storm.state.Transaction; public class HDFSState { public static final Logger LOG = Logger.getLogger(HDFSState.class); public static final String AUTO_COMPACT_BYTES_CONFIG = "topology.state.auto.compact.bytes"; public static final int DEFAULT_AUTO_COMPACT_BYTES = 10 * 1024 * 1024; List<Transaction> _pendingTransactions = new ArrayList<Transaction>(); Kryo _fgSerializer; Kryo _bgSerializer; BigInteger _currVersion; FileSystem _fs; String _rootDir; LogWriter _openLog; boolean _isLocal = false; Semaphore _compactionWaiter = new Semaphore(1); long _writtenSinceCompaction = 0; long _autoCompactFrequencyBytes; public HDFSState(Map conf, String dfsDir, Serializations sers) { _fs = HDFSUtils.getFS(dfsDir); _isLocal = _fs instanceof RawLocalFileSystem; _rootDir = new Path(dfsDir).toString(); Number autoCompactFrequency = (Number) conf.get(AUTO_COMPACT_BYTES_CONFIG); if(autoCompactFrequency == null) autoCompactFrequency = DEFAULT_AUTO_COMPACT_BYTES; _autoCompactFrequencyBytes = autoCompactFrequency.longValue(); HDFSUtils.mkdirs(_fs, tmpDir()); HDFSUtils.mkdirs(_fs, snapshotDir()); HDFSUtils.mkdirs(_fs, logDir()); _fgSerializer = makeKryo(sers); _bgSerializer = makeKryo(sers); cleanup(); } public static Kryo makeKryo(Serializations sers) { Kryo ret = new Kryo(); ret.setReferences(false); sers.apply(ret); ret.register(Commit.class); ret.register(Snapshot.class); ret.register(BigInteger.class, new BigIntegerSerializer()); try { // automatically support clojure collections since those are useful // for implementing these kinds of structures JavaBridge.registerCollections(ret); } catch (Exception e) { throw new RuntimeException(e); } return ret; } Executor _executor = null; public void setExecutor(Executor executor) { _executor = executor; } public Object appendAndApply(Transaction entry, State state) { _pendingTransactions.add(entry); return entry.apply(state); } public BigInteger getVersion() { return _currVersion; } public void commit(State state) { commit(null, state); } public void commit(BigInteger txid, State state) { Commit commit = new Commit(txid, _pendingTransactions); _pendingTransactions = new ArrayList<Transaction>(); if(txid==null || txid.equals(getVersion())) { _writtenSinceCompaction += _openLog.write(commit); if(_isLocal) { // see HADOOP-7844 rotateLog(); } else { _openLog.sync(); } _currVersion = txid; if(_autoCompactFrequencyBytes > 0 && _writtenSinceCompaction > _autoCompactFrequencyBytes) { compactAsync(state); _writtenSinceCompaction = 0; } } else { // we've done this update before, so reset the state resetToLatest(state); } } public void resetToLatest(State state) { // TODO: probably much better to serialize the snapshot directly into the output stream to prevent // so much more memory usage Long latestSnapshot = latestSnapshot(); BigInteger version = BigInteger.ZERO; if(latestSnapshot==null) { state.setState(null); } else { Snapshot snapshot = readSnapshot(_fs, latestSnapshot, _fgSerializer); state.setState(snapshot.snapshot); version = snapshot.txid; } if(latestSnapshot==null) latestSnapshot = -1L; List<Long> txLogs = allTxlogs(); _writtenSinceCompaction = 0; for(Long l: txLogs) { if(l > latestSnapshot) { HDFSLog.LogReader r = HDFSLog.open(_fs, txlogPath(l), _fgSerializer); while(true) { Commit c = (Commit) r.read(); if(c==null) break; version = c.txid; for(Transaction t: c.transactions) { t.apply(state); } } _writtenSinceCompaction += r.amtRead(); } } _currVersion = version; rotateLog(); } private long latestSnapshotOrLogVersion() { Long latestSnapshot = latestSnapshot(); Long latestTxlog = latestTxlog(); if(latestSnapshot==null) latestSnapshot = -1L; if(latestTxlog==null) latestTxlog = -1L; return Math.max(latestSnapshot, latestTxlog); } private void rotateLog() { if(_openLog!=null) { _openLog.close(); } long newTxLogVersion = latestSnapshotOrLogVersion() + 1; _openLog = HDFSLog.create(_fs, txlogPath(newTxLogVersion), _fgSerializer); } public void compact(State state) { Object snapshot = state.getSnapshot(); long version = prepareCompact(); doCompact(version, new Snapshot(_currVersion, snapshot)); } public void compactAsync(State state) { Object immutableSnapshot = state.getSnapshot(); if(_executor==null) { throw new RuntimeException("Need to configure with an executor to run compactions in the background"); } final long version = prepareCompact(); final Snapshot snapshot = new Snapshot(_currVersion, immutableSnapshot); _executor.execute(new Runnable() { @Override public void run() { doCompact(version, snapshot); } }); } private long prepareCompact() { //TODO: maybe it's better to skip the compaction if it's currently going on (rather than block here) try { _compactionWaiter.acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } long snapVersion = latestTxlog(); if(snapVersion<0) { throw new RuntimeException("Expected a txlog version greater than or equal to 0"); } rotateLog(); return snapVersion; } private void doCompact(long version, Snapshot snapshot) { try { writeSnapshot(_fs, version, snapshot, _bgSerializer); cleanup(); } finally { _compactionWaiter.release(); } } public static class Snapshot { BigInteger txid; Object snapshot; //for kryo public Snapshot() { } public Snapshot(BigInteger txid, Object snapshot) { this.txid = txid; this.snapshot = snapshot; } } public static class Commit { BigInteger txid; List<Transaction> transactions; //for kryo public Commit() { } public Commit(BigInteger txid, List<Transaction> transactions) { this.txid = txid; this.transactions = transactions; } } public void close() { _openLog.close(); } private String tmpDir() { return _rootDir + "/tmp"; } private String snapshotDir() { return _rootDir + "/snapshots"; } private String logDir() { return _rootDir + "/txlog"; } private String snapshotPath(Long version) { return snapshotDir() + "/" + version + ".snapshot"; } private String txlogPath(Long version) { return logDir() + "/" + version + ".txlog"; } private List<Long> allSnaphots() { return HDFSUtils.getSortedVersions(_fs, snapshotDir(), ".snapshot"); } private List<Long> allTxlogs() { return HDFSUtils.getSortedVersions(_fs, logDir(), ".txlog"); } private Long latestSnapshot() { List<Long> all = allSnaphots(); if(all.isEmpty()) return null; else return all.get(all.size()-1); } private Long latestTxlog() { List<Long> all = allTxlogs(); if(all.isEmpty()) return null; else return all.get(all.size()-1); } private void cleanup() { Long latest = latestSnapshot(); HDFSUtils.clearDir(_fs, tmpDir()); if(latest!=null) { for(Long s: allSnaphots()) { if(s < latest) { HDFSUtils.deleteFile(_fs, snapshotPath(s)); } } for(Long t: allTxlogs()) { if(t <= latest) { HDFSUtils.deleteFile(_fs, txlogPath(t)); } } } } private Snapshot readSnapshot(FileSystem fs, long version, Kryo kryo) { FSDataInputStream in = null; try { in = fs.open(new Path(snapshotPath(version))); Input input = new Input(in); Snapshot ret = kryo.readObject(input, Snapshot.class); input.close(); return ret; } catch (IOException e) { throw new RuntimeException(e); } } private void writeSnapshot(FileSystem fs, long version, Snapshot snapshot, Kryo kryo) { try { String finalPath = snapshotPath(version); String tmpPath = tmpDir() + "/" + version + ".tmp"; FSDataOutputStream os = fs.create(new Path(tmpPath), true); Output output = new Output(os); kryo.writeObject(output, snapshot); output.flush(); output.close(); fs.rename(new Path(tmpPath), new Path(finalPath)); } catch(IOException e) { throw new RuntimeException(e); } } }
package com.czt.util; import java.io.IOException; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.preference.PreferenceManager; import android.text.TextUtils; public class ChannelUtil { private static final String CHANNEL_KEY = "cztchannel"; private static final String CHANNEL_VERSION_KEY = "cztchannel_version"; private static String mChannel; /** * "" * @param context * @return */ public static String getChannel(Context context){ return getChannel(context, ""); } /** * defaultChannel * @param context * @param defaultChannel * @return */ public static String getChannel(Context context, String defaultChannel) { if(!TextUtils.isEmpty(mChannel)){ return mChannel; } mChannel = getChannelBySharedPreferences(context); if(!TextUtils.isEmpty(mChannel)){ return mChannel; } //apk mChannel = getChannelFromApk(context, CHANNEL_KEY); if(!TextUtils.isEmpty(mChannel)){ saveChannelBySharedPreferences(context, mChannel); return mChannel; } return defaultChannel; } /** * apk * @param context * @param channelKey * @return */ private static String getChannelFromApk(Context context, String channelKey) { //apk ApplicationInfo appinfo = context.getApplicationInfo(); String sourceDir = appinfo.sourceDir; //meta-inf/ String key = "META-INF/" + channelKey; String ret = ""; ZipFile zipfile = null; try { zipfile = new ZipFile(sourceDir); Enumeration<?> entries = zipfile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = ((ZipEntry) entries.nextElement()); String entryName = entry.getName(); if (entryName.startsWith(key)) { ret = entryName; break; } } } catch (IOException e) { e.printStackTrace(); } finally { if (zipfile != null) { try { zipfile.close(); } catch (IOException e) { e.printStackTrace(); } } } String[] split = ret.split("_"); String channel = ""; if (split != null && split.length >= 2) { channel = ret.substring(split[0].length() + 1); } return channel; } /** * channel & * @param context * @param channel */ private static void saveChannelBySharedPreferences(Context context, String channel){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); Editor editor = sp.edit(); editor.putString(CHANNEL_KEY, channel); editor.putInt(CHANNEL_VERSION_KEY, getVersionCode(context)); editor.commit(); } /** * spchannel * @param context * @return spsp */ private static String getChannelBySharedPreferences(Context context){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); int currentVersionCode = getVersionCode(context); if(currentVersionCode == -1){ return ""; } int versionCodeSaved = sp.getInt(CHANNEL_VERSION_KEY, -1); if(versionCodeSaved == -1){ //channel return ""; } if(currentVersionCode != versionCodeSaved){ return ""; } return sp.getString(CHANNEL_KEY, ""); } /** * * @param context * @return */ private static int getVersionCode(Context context){ try{ return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode; }catch(NameNotFoundException e) { e.printStackTrace(); } return -1; } }
package com.actram.captair.ui; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class WordAttainer extends Application { public static void main(String[] args) { Application.launch(WordAttainer.class, args); } @Override public void start(Stage stage) throws Exception { Parent root = new FXMLLoader().load(getClass().getResourceAsStream("/ui/modify_results.fxml")); stage.setTitle("FXML Welcome"); stage.setScene(new Scene(root)); stage.show(); } }
package VASSAL.tools.image; import java.awt.Dimension; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.imageio.ImageIO; import VASSAL.tools.io.IOUtils; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import static VASSAL.tools.image.AssertImage.*; public class ImageIOImageLoaderTest { protected static final String jpg = "test/VASSAL/tools/image/rainbow.jpg"; protected static BufferedImage src; @BeforeClass public static void setup() throws IOException { src = ImageIO.read(new File(jpg)); } protected BufferedImage read(ImageLoader loader, String file) throws IOException { FileInputStream in = null; try { in = new FileInputStream(file); final BufferedImage img = loader.load( file, in, BufferedImage.TYPE_INT_RGB, BufferedImage.TYPE_INT_ARGB, false ); in.close(); return img; } finally { IOUtils.closeQuietly(in); } } @Test public void testLoadOk() throws IOException { final ImageTypeConverter mconv = new MemoryImageTypeConverter(); final ImageIOImageLoader loader = new ImageIOImageLoader(mconv); final BufferedImage actual = read(loader, jpg); assertEquals(BufferedImage.TYPE_INT_RGB, actual.getType()); assertImageContentEquals(src, actual); } @Test public void testLoadType2tRNSBug() throws IOException { final String efile = "test/VASSAL/tools/image/non-type2-tRNS.png"; final String afile = "test/VASSAL/tools/image/type2-tRNS.png"; final ImageTypeConverter mconv = new MemoryImageTypeConverter(); final ImageIOImageLoader loader = new ImageIOImageLoader(mconv); final BufferedImage expected = ImageIO.read(new File(efile)); final BufferedImage actual = read(loader, afile); assertEquals(BufferedImage.TYPE_INT_ARGB, actual.getType()); // We check that: // (1) the images have the same fully-transparent pixels, and // (2) all other pixels are identical final int w = expected.getWidth(); final int h = expected.getHeight(); for (int x = 0; x < w; ++x) { for (int y = 0; y < h; ++y) { final int ep = expected.getRGB(x, y); final int ap = actual.getRGB(x, y); if ((ep & 0xff000000) == 0 && (ap & 0xff000000) == 0) { // color components of fully-transparent pixels don't matter continue; } assertEquals(ep, ap); } } } protected Dimension size(ImageLoader loader, String file) throws IOException { FileInputStream in = null; try { in = new FileInputStream(file); final Dimension d = loader.size(file, in); in.close(); return d; } finally { IOUtils.closeQuietly(in); } } @Test public void testSizeOk() throws IOException { final ImageTypeConverter mconv = new MemoryImageTypeConverter(); final ImageIOImageLoader loader = new ImageIOImageLoader(mconv); final Dimension ed = new Dimension(src.getWidth(), src.getHeight()); final Dimension ad = size(loader, jpg); assertEquals(ed, ad); } @Test(expected=UnrecognizedImageTypeException.class) public void testSizeUnrecognized() throws IOException { final String junk = "test/VASSAL/tools/image/ImageIOImageLoaderTest.java"; final ImageTypeConverter mconv = new MemoryImageTypeConverter(); final ImageIOImageLoader loader = new ImageIOImageLoader(mconv); final Dimension ad = size(loader, junk); } }
package com.jme3.texture; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import com.jme3.export.Savable; import com.jme3.math.FastMath; import com.jme3.renderer.Caps; import com.jme3.renderer.Renderer; import com.jme3.texture.image.ColorSpace; import com.jme3.texture.image.LastTextureState; import com.jme3.util.BufferUtils; import com.jme3.util.NativeObject; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * <code>Image</code> defines a data format for a graphical image. The image * is defined by a format, a height and width, and the image data. The width and * height must be greater than 0. The data is contained in a byte buffer, and * should be packed before creation of the image object. * * @author Mark Powell * @author Joshua Slack * @version $Id: Image.java 4131 2009-03-19 20:15:28Z blaine.dev $ */ public class Image extends NativeObject implements Savable /*, Cloneable*/ { public enum Format { /** * 8-bit alpha */ Alpha8(8), @Deprecated Reserved1(0), /** * 8-bit grayscale/luminance. */ Luminance8(8), @Deprecated Reserved2(0), /** * half-precision floating-point grayscale/luminance. * * Requires {@link Caps#FloatTexture}. */ Luminance16F(16,true), /** * single-precision floating-point grayscale/luminance. * * Requires {@link Caps#FloatTexture}. */ Luminance32F(32,true), /** * 8-bit luminance/grayscale and 8-bit alpha. */ Luminance8Alpha8(16), @Deprecated Reserved3(0), /** * half-precision floating-point grayscale/luminance and alpha. * * Requires {@link Caps#FloatTexture}. */ Luminance16FAlpha16F(32,true), @Deprecated Reserved4(0), @Deprecated Reserved5(0), /** * 8-bit blue, green, and red. */ BGR8(24), // BGR and ABGR formats are often used on windows systems /** * 8-bit red, green, and blue. */ RGB8(24), @Deprecated Reserved6(0), @Deprecated Reserved7(0), /** * 5-bit red, 6-bit green, and 5-bit blue. */ RGB565(16), @Deprecated Reserved8(0), /** * 5-bit red, green, and blue with 1-bit alpha. */ RGB5A1(16), /** * 8-bit red, green, blue, and alpha. */ RGBA8(32), /** * 8-bit alpha, blue, green, and red. */ ABGR8(32), /** * 8-bit alpha, red, blue and green */ ARGB8(32), /** * 8-bit blue, green, red and alpha. */ BGRA8(32), @Deprecated Reserved9(0), /** * S3TC compression DXT1. */ DXT1(4,false,true, false), /** * S3TC compression DXT1 with 1-bit alpha. */ DXT1A(4,false,true, false), /** * S3TC compression DXT3 with 4-bit alpha. */ DXT3(8,false,true, false), /** * S3TC compression DXT5 with interpolated 8-bit alpha. * */ DXT5(8,false,true, false), RGTC2(8,false,true, false), SIGNED_RGTC2(8,false,true, false), RGTC1(4,false,true, false), SIGNED_RGTC1(4,false,true, false), /** * Luminance-Alpha Texture Compression. * * @deprecated Not supported by OpenGL 3.0. */ @Deprecated Reserved10(0), /** * Arbitrary depth format. The precision is chosen by the video * hardware. */ Depth(0,true,false,false), /** * 16-bit depth. */ Depth16(16,true,false,false), /** * 24-bit depth. */ Depth24(24,true,false,false), /** * 32-bit depth. */ Depth32(32,true,false,false), /** * single-precision floating point depth. * * Requires {@link Caps#FloatDepthBuffer}. */ Depth32F(32,true,false,true), /** * Texture data is stored as {@link Format#RGB16F} in system memory, * but will be converted to {@link Format#RGB111110F} when sent * to the video hardware. * * Requires {@link Caps#FloatTexture} and {@link Caps#PackedFloatTexture}. */ RGB16F_to_RGB111110F(48,true), /** * unsigned floating-point red, green and blue that uses 32 bits. * * Requires {@link Caps#PackedFloatTexture}. */ RGB111110F(32,true), /** * Texture data is stored as {@link Format#RGB16F} in system memory, * but will be converted to {@link Format#RGB9E5} when sent * to the video hardware. * * Requires {@link Caps#FloatTexture} and {@link Caps#SharedExponentTexture}. */ RGB16F_to_RGB9E5(48,true), /** * 9-bit red, green and blue with 5-bit exponent. * * Requires {@link Caps#SharedExponentTexture}. */ RGB9E5(32,true), /** * half-precision floating point red, green, and blue. * * Requires {@link Caps#FloatTexture}. * May be supported for renderbuffers, but the OpenGL specification does not require it. */ RGB16F(48,true), /** * half-precision floating point red, green, blue, and alpha. * * Requires {@link Caps#FloatTexture}. */ RGBA16F(64,true), /** * single-precision floating point red, green, and blue. * * Requires {@link Caps#FloatTexture}. * May be supported for renderbuffers, but the OpenGL specification does not require it. */ RGB32F(96,true), /** * single-precision floating point red, green, blue and alpha. * * Requires {@link Caps#FloatTexture}. */ RGBA32F(128,true), @Deprecated Reserved11(0), /** * 24-bit depth with 8-bit stencil. * Check the cap {@link Caps#PackedDepthStencilBuffer}. */ Depth24Stencil8(32, true, false, false), @Deprecated Reserved12(0), /** * Ericsson Texture Compression. Typically used on Android. * * Requires {@link Caps#TextureCompressionETC1}. */ ETC1(4, false, true, false), /** * 8 bit signed int red. * * Requires {@link Caps#IntegerTexture}. */ R8I(8), /** * 8 bit unsigned int red. * * Requires {@link Caps#IntegerTexture}. */ R8UI(8), /** * 16 bit signed int red. * * Requires {@link Caps#IntegerTexture}. */ R16I(16), /** * 16 bit unsigned int red. * * Requires {@link Caps#IntegerTexture}. */ R16UI(16), /** * 32 bit signed int red. * * Requires {@link Caps#IntegerTexture}. */ R32I(32), /** * 32 bit unsigned int red. * * Requires {@link Caps#IntegerTexture}. */ R32UI(32), /** * 8 bit signed int red and green. * * Requires {@link Caps#IntegerTexture}. */ RG8I(16), /** * 8 bit unsigned int red and green. * * Requires {@link Caps#IntegerTexture}. */ RG8UI(16), /** * 16 bit signed int red and green. * * Requires {@link Caps#IntegerTexture}. */ RG16I(32), /** * 16 bit unsigned int red and green. * * Requires {@link Caps#IntegerTexture}. */ RG16UI(32), /** * 32 bit signed int red and green. * * Requires {@link Caps#IntegerTexture}. */ RG32I(64), /** * 32 bit unsigned int red and green. * * Requires {@link Caps#IntegerTexture}. */ RG32UI(64), /** * 8 bit signed int red, green and blue. * * Requires {@link Caps#IntegerTexture} to be supported for textures. * May be supported for renderbuffers, but the OpenGL specification does not require it. */ RGB8I(24), /** * 8 bit unsigned int red, green and blue. * * Requires {@link Caps#IntegerTexture} to be supported for textures. * May be supported for renderbuffers, but the OpenGL specification does not require it. */ RGB8UI(24), /** * 16 bit signed int red, green and blue. * * Requires {@link Caps#IntegerTexture} to be supported for textures. * May be supported for renderbuffers, but the OpenGL specification does not require it. */ RGB16I(48), /** * 16 bit unsigned int red, green and blue. * * Requires {@link Caps#IntegerTexture} to be supported for textures. * May be supported for renderbuffers, but the OpenGL specification does not require it. */ RGB16UI(48), /** * 32 bit signed int red, green and blue. * * Requires {@link Caps#IntegerTexture} to be supported for textures. * May be supported for renderbuffers, but the OpenGL specification does not require it. */ RGB32I(96), /** * 32 bit unsigned int red, green and blue. * * Requires {@link Caps#IntegerTexture} to be supported for textures. * May be supported for renderbuffers, but the OpenGL specification does not require it. */ RGB32UI(96), /** * 8 bit signed int red, green, blue and alpha. * * Requires {@link Caps#IntegerTexture}. */ RGBA8I(32), /** * 8 bit unsigned int red, green, blue and alpha. * * Requires {@link Caps#IntegerTexture}. */ RGBA8UI(32), /** * 16 bit signed int red, green, blue and alpha. * * Requires {@link Caps#IntegerTexture}. */ RGBA16I(64), /** * 16 bit unsigned int red, green, blue and alpha. * * Requires {@link Caps#IntegerTexture}. */ RGBA16UI(64), /** * 32 bit signed int red, green, blue and alpha. * * Requires {@link Caps#IntegerTexture}. */ RGBA32I(128), /** * 32 bit unsigned int red, green, blue and alpha. * * Requires {@link Caps#IntegerTexture}. */ RGBA32UI(128), /** * half-precision floating point red. * * Requires {@link Caps#FloatTexture}. */ R16F(16,true), /** * single-precision floating point red. * * Requires {@link Caps#FloatTexture}. */ R32F(32,true), /** * half-precision floating point red and green. * * Requires {@link Caps#FloatTexture}. */ RG16F(32,true), /** * single-precision floating point red and green. * * Requires {@link Caps#FloatTexture}. */ RG32F(64,true), /** * 10-bit red, green, and blue with 2-bit alpha. */ RGB10A2(32), ; private int bpp; private boolean isDepth; private boolean isCompressed; private boolean isFloatingPoint; private Format(int bpp){ this.bpp = bpp; } private Format(int bpp, boolean isFP){ this(bpp); this.isFloatingPoint = isFP; } private Format(int bpp, boolean isDepth, boolean isCompressed, boolean isFP){ this(bpp, isFP); this.isDepth = isDepth; this.isCompressed = isCompressed; } /** * @return bits per pixel. */ public int getBitsPerPixel(){ return bpp; } /** * @return True if this format is a depth format, false otherwise. */ public boolean isDepthFormat(){ return isDepth; } /** * @return True if this format is a depth + stencil (packed) format, false otherwise. */ boolean isDepthStencilFormat() { return this == Depth24Stencil8; } /** * @return True if this is a compressed image format, false if * uncompressed. */ public boolean isCompressed() { return isCompressed; } /** * @return True if this image format is in floating point, * false if it is an integer format. */ public boolean isFloatingPont(){ return isFloatingPoint; } } // image attributes protected Format format; protected int width, height, depth; protected int[] mipMapSizes; protected ArrayList<ByteBuffer> data; protected int multiSamples = 1; protected ColorSpace colorSpace = null; // protected int mipOffset = 0; // attributes relating to GL object protected boolean mipsWereGenerated = false; protected boolean needGeneratedMips = false; protected LastTextureState lastTextureState = new LastTextureState(); /** * Internal use only. * The renderer stores the texture state set from the last texture * so it doesn't have to change it unless necessary. * * @return The image parameter state. */ public LastTextureState getLastTextureState() { return lastTextureState; } /** * Internal use only. * The renderer marks which images have generated mipmaps in VRAM * and which do not, so it can generate them as needed. * * @param generated If mipmaps were generated or not. */ public void setMipmapsGenerated(boolean generated) { this.mipsWereGenerated = generated; } /** * Internal use only. * Check if the renderer has generated mipmaps for this image in VRAM * or not. * * @return If mipmaps were generated already. */ public boolean isMipmapsGenerated() { return mipsWereGenerated; } /** * (Package private) Called by {@link Texture} when * {@link #isMipmapsGenerated() } is false in order to generate * mipmaps for this image. */ void setNeedGeneratedMipmaps() { needGeneratedMips = true; } /** * @return True if the image needs to have mipmaps generated * for it (as requested by the texture). This stays true even * after mipmaps have been generated. */ public boolean isGeneratedMipmapsRequired() { return needGeneratedMips; } /** * Sets the update needed flag, while also checking if mipmaps * need to be regenerated. */ @Override public void setUpdateNeeded() { super.setUpdateNeeded(); if (isGeneratedMipmapsRequired() && !hasMipmaps()) { // Mipmaps are no longer valid, since the image was changed. setMipmapsGenerated(false); } } /** * Determine if the image is NPOT. * * @return if the image is a non-power-of-2 image, e.g. having dimensions * that are not powers of 2. */ public boolean isNPOT() { return width != 0 && height != 0 && (!FastMath.isPowerOfTwo(width) || !FastMath.isPowerOfTwo(height)); } @Override public void resetObject() { this.id = -1; this.mipsWereGenerated = false; this.lastTextureState.reset(); setUpdateNeeded(); } @Override protected void deleteNativeBuffers() { for (ByteBuffer buf : data) { BufferUtils.destroyDirectBuffer(buf); } } @Override public void deleteObject(Object rendererObject) { ((Renderer)rendererObject).deleteImage(this); } @Override public NativeObject createDestructableClone() { return new Image(id); } @Override public long getUniqueId() { return ((long)OBJTYPE_TEXTURE << 32) | ((long)id); } /** * @return A shallow clone of this image. The data is not cloned. */ @Override public Image clone(){ Image clone = (Image) super.clone(); clone.mipMapSizes = mipMapSizes != null ? mipMapSizes.clone() : null; clone.data = data != null ? new ArrayList<ByteBuffer>(data) : null; clone.lastTextureState = new LastTextureState(); clone.setUpdateNeeded(); return clone; } /** * Constructor instantiates a new <code>Image</code> object. All values * are undefined. */ public Image() { super(); data = new ArrayList<ByteBuffer>(1); } protected Image(int id){ super(id); } /** * Constructor instantiates a new <code>Image</code> object. The * attributes of the image are defined during construction. * * @param format * the data format of the image. * @param width * the width of the image. * @param height * the height of the image. * @param depth * the desired image depth * @param data * the image data. * @param mipMapSizes * the array of mipmap sizes, or null for no mipmaps. * @param colorSpace * the colorSpace of the image */ public Image(Format format, int width, int height, int depth, ArrayList<ByteBuffer> data, int[] mipMapSizes, ColorSpace colorSpace) { this(); if (mipMapSizes != null) { if (mipMapSizes.length <= 1) { mipMapSizes = null; } else { needGeneratedMips = false; mipsWereGenerated = true; } } setFormat(format); this.width = width; this.height = height; this.data = data; this.depth = depth; this.mipMapSizes = mipMapSizes; this.colorSpace = colorSpace; } /** * @see #Image(com.jme3.texture.Image.Format, int, int, int, java.util.ArrayList, int[], com.jme3.texture.image.ColorSpace) * @param format the desired data format * @param width the desired width (in pixels) * @param height the desired height (in pixels) * @param depth the desired image depth * @param data the image data to use * @param mipMapSizes the desired mipmap sizes, or null for no mipmaps * @deprecated use {@link #Image(com.jme3.texture.Image.Format, int, int, int, java.util.ArrayList, int[], com.jme3.texture.image.ColorSpace)} */ @Deprecated public Image(Format format, int width, int height, int depth, ArrayList<ByteBuffer> data, int[] mipMapSizes) { this(format, width, height, depth, data, mipMapSizes, ColorSpace.Linear); } /** * Constructor instantiates a new <code>Image</code> object. The * attributes of the image are defined during construction. * * @param format * the data format of the image. * @param width * the width of the image. * @param height * the height of the image. * @param data * the image data. * @param mipMapSizes * the array of mipmap sizes, or null for no mipmaps. * @param colorSpace * the colorSpace of the image */ public Image(Format format, int width, int height, ByteBuffer data, int[] mipMapSizes, ColorSpace colorSpace) { this(); if (mipMapSizes != null && mipMapSizes.length <= 1) { mipMapSizes = null; } else { needGeneratedMips = false; mipsWereGenerated = true; } setFormat(format); this.width = width; this.height = height; if (data != null){ this.data = new ArrayList<ByteBuffer>(1); this.data.add(data); } this.mipMapSizes = mipMapSizes; this.colorSpace = colorSpace; } /** * @see #Image(com.jme3.texture.Image.Format, int, int, java.nio.ByteBuffer, int[], com.jme3.texture.image.ColorSpace) * @param format the desired data format * @param width the desired width (in pixels) * @param height the desired height (in pixels) * @param data the image data to use * @param mipMapSizes the desired mipmap sizes, or null for no mipmaps * @deprecated use {@link #Image(com.jme3.texture.Image.Format, int, int, java.nio.ByteBuffer, int[], com.jme3.texture.image.ColorSpace)} */ @Deprecated public Image(Format format, int width, int height, ByteBuffer data, int[] mipMapSizes) { this(format, width, height, data, mipMapSizes, ColorSpace.Linear); } /** * Constructor instantiates a new <code>Image</code> object. The * attributes of the image are defined during construction. * * @param format * the data format of the image. * @param width * the width of the image. * @param height * the height of the image. * @param depth * the desired image depth * @param data * the image data. * @param colorSpace * the colorSpace of the image */ public Image(Format format, int width, int height, int depth, ArrayList<ByteBuffer> data, ColorSpace colorSpace) { this(format, width, height, depth, data, null, colorSpace); } /** * @see #Image(com.jme3.texture.Image.Format, int, int, int, java.util.ArrayList, com.jme3.texture.image.ColorSpace) * @param format the desired data format * @param width the desired width (in pixels) * @param height the desired height (in pixels) * @param depth the desired image depth * @param data the image data to use * @deprecated use {@link #Image(com.jme3.texture.Image.Format, int, int, int, java.util.ArrayList, com.jme3.texture.image.ColorSpace)} */ @Deprecated public Image(Format format, int width, int height, int depth, ArrayList<ByteBuffer> data) { this(format, width, height, depth, data, ColorSpace.Linear); } /** * Constructor instantiates a new <code>Image</code> object. The * attributes of the image are defined during construction. * * @param format * the data format of the image. * @param width * the width of the image. * @param height * the height of the image. * @param data * the image data. * @param colorSpace * the colorSpace of the image */ public Image(Format format, int width, int height, ByteBuffer data, ColorSpace colorSpace) { this(format, width, height, data, null, colorSpace); } /** * @see #Image(com.jme3.texture.Image.Format, int, int, java.nio.ByteBuffer, com.jme3.texture.image.ColorSpace) * @param format the desired data format * @param width the desired width (in pixels) * @param height the desired height (in pixels) * @param data the image data * @deprecated use {@link #Image(com.jme3.texture.Image.Format, int, int, java.nio.ByteBuffer, com.jme3.texture.image.ColorSpace)} */ @Deprecated public Image(Format format, int width, int height, ByteBuffer data) { this(format, width, height, data, null, ColorSpace.Linear); } /** * @return The number of samples (for multisampled textures). * @see Image#setMultiSamples(int) */ public int getMultiSamples() { return multiSamples; } /** * @param multiSamples Set the number of samples to use for this image, * setting this to a value higher than 1 turns this image/texture * into a multisample texture (on OpenGL3.1 and higher). */ public void setMultiSamples(int multiSamples) { if (multiSamples <= 0) throw new IllegalArgumentException("multiSamples must be > 0"); if (getData(0) != null) throw new IllegalArgumentException("Cannot upload data as multisample texture"); if (hasMipmaps()) throw new IllegalArgumentException("Multisample textures do not support mipmaps"); this.multiSamples = multiSamples; } /** * <code>setData</code> sets the data that makes up the image. This data * is packed into an array of <code>ByteBuffer</code> objects. * * @param data * the data that contains the image information. */ public void setData(ArrayList<ByteBuffer> data) { this.data = data; setUpdateNeeded(); } /** * <code>setData</code> sets the data that makes up the image. This data * is packed into a single <code>ByteBuffer</code>. * * @param data * the data that contains the image information. */ public void setData(ByteBuffer data) { this.data = new ArrayList<ByteBuffer>(1); this.data.add(data); setUpdateNeeded(); } public void addData(ByteBuffer data) { if (this.data == null) this.data = new ArrayList<ByteBuffer>(1); this.data.add(data); setUpdateNeeded(); } public void setData(int index, ByteBuffer data) { if (index >= 0) { while (this.data.size() <= index) { this.data.add(null); } this.data.set(index, data); setUpdateNeeded(); } else { throw new IllegalArgumentException("index must be greater than or equal to 0."); } } /** * @return null * @deprecated This feature is no longer used by the engine */ @Deprecated public Object getEfficentData(){ return null; } /** * Sets the mipmap sizes stored in this image's data buffer. Mipmaps are * stored sequentially, and the first mipmap is the main image data. To * specify no mipmaps, pass null and this will automatically be expanded * into a single mipmap of the full * * @param mipMapSizes * the mipmap sizes array, or null for a single image map. */ public void setMipMapSizes(int[] mipMapSizes) { if (mipMapSizes != null && mipMapSizes.length <= 1) mipMapSizes = null; this.mipMapSizes = mipMapSizes; if (mipMapSizes != null) { needGeneratedMips = false; mipsWereGenerated = false; } else { needGeneratedMips = true; mipsWereGenerated = false; } setUpdateNeeded(); } /** * <code>setHeight</code> sets the height value of the image. It is * typically a good idea to try to keep this as a multiple of 2. * * @param height * the height of the image. */ public void setHeight(int height) { this.height = height; setUpdateNeeded(); } /** * <code>setDepth</code> sets the depth value of the image. It is * typically a good idea to try to keep this as a multiple of 2. This is * used for 3d images. * * @param depth * the depth of the image. */ public void setDepth(int depth) { this.depth = depth; setUpdateNeeded(); } /** * <code>setWidth</code> sets the width value of the image. It is * typically a good idea to try to keep this as a multiple of 2. * * @param width * the width of the image. */ public void setWidth(int width) { this.width = width; setUpdateNeeded(); } public void setFormat(Format format) { if (format == null) { throw new IllegalArgumentException("format may not be null."); } this.format = format; setUpdateNeeded(); } /** * <code>getFormat</code> returns the image format for this image. * * @return the image format. * @see Format */ public Format getFormat() { return format; } /** * <code>getWidth</code> returns the width of this image. * * @return the width of this image. */ public int getWidth() { return width; } /** * <code>getHeight</code> returns the height of this image. * * @return the height of this image. */ public int getHeight() { return height; } /** * <code>getDepth</code> returns the depth of this image (for 3d images). * * @return the depth of this image. */ public int getDepth() { return depth; } /** * <code>getData</code> returns the data for this image. If the data is * undefined, null will be returned. * * @return the data for this image. */ public List<ByteBuffer> getData() { return data; } /** * <code>getData</code> returns the data for this image. If the data is * undefined, null will be returned. * * @param index index of the data buffer to access * @return the data for this image. */ public ByteBuffer getData(int index) { if (data.size() > index) return data.get(index); else return null; } /** * Returns whether the image data contains mipmaps. * * @return true if the image data contains mipmaps, false if not. */ public boolean hasMipmaps() { return mipMapSizes != null; } /** * Returns the mipmap sizes for this image. * * @return the mipmap sizes for this image. */ public int[] getMipMapSizes() { return mipMapSizes; } /** * image loader is responsible for setting this attribute based on the color * space in which the image has been encoded with. In the majority of cases, * this flag will be set to sRGB by default since many image formats do not * contain any color space information and the most frequently used colors * space is sRGB * * The material loader may override this attribute to Lineat if it determines that * such conversion must not be performed, for example, when loading normal * maps. * * @param colorSpace Set to sRGB to enable srgb -&gt; linear * conversion, Linear otherwise. * * @see Renderer#setLinearizeSrgbImages(boolean) * */ public void setColorSpace(ColorSpace colorSpace) { this.colorSpace = colorSpace; } /** * Specifies that this image is an SRGB image and therefore must undergo an * sRGB -&gt; linear RGB color conversion prior to being read by a shader and * with the {@link Renderer#setLinearizeSrgbImages(boolean)} option is * enabled. * * This option is only supported for the 8-bit color and grayscale image * formats. Determines if the image is in SRGB color space or not. * * @return True, if the image is an SRGB image, false if it is linear RGB. * * @see Renderer#setLinearizeSrgbImages(boolean) */ public ColorSpace getColorSpace() { return colorSpace; } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append("[size=").append(width).append("x").append(height); if (depth > 1) sb.append("x").append(depth); sb.append(", format=").append(format.name()); if (hasMipmaps()) sb.append(", mips"); if (getId() >= 0) sb.append(", id=").append(id); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Image)) { return false; } Image that = (Image) other; if (this.getFormat() != that.getFormat()) return false; if (this.getWidth() != that.getWidth()) return false; if (this.getHeight() != that.getHeight()) return false; if (this.getData() != null && !this.getData().equals(that.getData())) return false; if (this.getData() == null && that.getData() != null) return false; if (this.getMipMapSizes() != null && !Arrays.equals(this.getMipMapSizes(), that.getMipMapSizes())) return false; if (this.getMipMapSizes() == null && that.getMipMapSizes() != null) return false; if (this.getMultiSamples() != that.getMultiSamples()) return false; return true; } @Override public int hashCode() { int hash = 7; hash = 97 * hash + (this.format != null ? this.format.hashCode() : 0); hash = 97 * hash + this.width; hash = 97 * hash + this.height; hash = 97 * hash + this.depth; hash = 97 * hash + Arrays.hashCode(this.mipMapSizes); hash = 97 * hash + (this.data != null ? this.data.hashCode() : 0); hash = 97 * hash + this.multiSamples; return hash; } @Override public void write(JmeExporter e) throws IOException { OutputCapsule capsule = e.getCapsule(this); capsule.write(format, "format", Format.RGBA8); capsule.write(width, "width", 0); capsule.write(height, "height", 0); capsule.write(depth, "depth", 0); capsule.write(mipMapSizes, "mipMapSizes", null); capsule.write(multiSamples, "multiSamples", 1); capsule.writeByteBufferArrayList(data, "data", null); capsule.write(colorSpace, "colorSpace", null); } @Override public void read(JmeImporter e) throws IOException { InputCapsule capsule = e.getCapsule(this); format = capsule.readEnum("format", Format.class, Format.RGBA8); width = capsule.readInt("width", 0); height = capsule.readInt("height", 0); depth = capsule.readInt("depth", 0); mipMapSizes = capsule.readIntArray("mipMapSizes", null); multiSamples = capsule.readInt("multiSamples", 1); data = capsule.readByteBufferArrayList("data", null); colorSpace = capsule.readEnum("colorSpace", ColorSpace.class, null); if (mipMapSizes != null) { needGeneratedMips = false; mipsWereGenerated = true; } } }
package jswingshell.gui; import java.awt.Color; import java.awt.Font; import java.awt.event.KeyEvent; import jswingshell.AbstractJssModel; import jswingshell.IJssView; import jswingshell.JssSimpleModel; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author brunot */ public class JssTextAreaControllerTest { public JssTextAreaControllerTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getView method, of class JssTextAreaController. */ @Test public void testGetView() { System.out.println("getView"); JssTextAreaController instance = new JssTextAreaController(); JssTextArea notExpResult = null; JssTextArea result = instance.getView(); assertNotEquals(notExpResult, result); } /** * Test of setView method, of class JssTextAreaController. */ @Test public void testSetView() { System.out.println("setView"); IJssView anotherView = new JssTextArea(); JssTextAreaController instance = new JssTextAreaController(); instance.setView(anotherView); } /** * Test of getModel method, of class JssTextAreaController. */ @Test public void testGetModel() { System.out.println("getModel"); JssTextAreaController instance = new JssTextAreaController(); AbstractJssModel notExpResult = null; AbstractJssModel result = instance.getModel(); assertNotEquals(notExpResult, result); } /** * Test of setModel method, of class JssTextAreaController. */ @Test public void testSetModel() { System.out.println("setModel"); JssTextAreaController instance = new JssTextAreaController(); AbstractJssModel anotherModel = new JssSimpleModel(instance); instance.setModel(anotherModel); } /** * Test of setShellText method, of class JssTextAreaController. */ @Test public void testSetShellText() { System.out.println("setShellText"); String newShellText = ""; JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); instance.setShellText(newShellText); } /** * Test of addNewLineToShell method, of class JssTextAreaController. */ @Test public void testAddNewLineToShell_0args() { System.out.println("addNewLineToShell"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); instance.addNewLineToShell(); } /** * Test of addNewLineToShell method, of class JssTextAreaController. */ @Test public void testAddNewLineToShell_String() { System.out.println("addNewLineToShell"); String text = ""; JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); instance.addNewLineToShell(text); } /** * Test of getLastShellLinePosition method, of class JssTextAreaController. */ @Test public void testGetLastShellLinePosition() { System.out.println("getLastShellLinePosition"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); int expResult = 0; int result = instance.getLastShellLinePosition(); assertEquals(expResult, result); } /** * Test of addNewCommandLine method, of class JssTextAreaController. */ @Test public void testAddNewCommandLine_0args() { System.out.println("addNewCommandLine"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); instance.addNewCommandLine(); } /** * Test of addNewCommandLine method, of class JssTextAreaController. */ @Test public void testAddNewCommandLine_String() { System.out.println("addNewCommandLine"); String newCommandLine = ""; JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); instance.addNewCommandLine(newCommandLine); } /** * Test of getCommandLine method, of class JssTextAreaController. */ @Test public void testGetCommandLine() { System.out.println("getCommandLine"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); String expResult = ""; String result = instance.getCommandLine(); assertEquals(expResult, result); } /** * Test of setCommandLine method, of class JssTextAreaController. */ @Test public void testSetCommandLine() { System.out.println("setCommandLine"); String newCommandLine = ""; JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); instance.setCommandLine(newCommandLine); } /** * Test of getCommandLinePosition method, of class JssTextAreaController. */ @Test public void testGetCommandLinePosition() { System.out.println("getCommandLinePosition"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); int notExpResult = 0; int result = instance.getCommandLinePosition(); assertNotEquals(notExpResult, result); } /** * Test of getCaretPosition method, of class JssTextAreaController. */ @Test public void testGetCaretPosition() { System.out.println("getCaretPosition"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); int notExpResult = 4; int result = instance.getCaretPosition(); assertNotEquals(notExpResult, result); } /** * Test of setCaretPosition method, of class JssTextAreaController. */ @Test public void testSetCaretPosition() { System.out.println("setCaretPosition"); int caretPosition = 0; JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); instance.setCaretPosition(caretPosition); } /** * Test of setCaretToEndOfDocument method, of class JssTextAreaController. */ @Test public void testSetCaretToEndOfDocument() { System.out.println("setCaretToEndOfDocument"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); instance.setCaretToEndOfDocument(); } /** * Test of moveCaretPosition method, of class JssTextAreaController. */ @Test public void testMoveCaretPosition() { System.out.println("moveCaretPosition"); int caretPosition = 0; JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); instance.moveCaretPosition(caretPosition); } /** * Test of isCaretBeforeStartOfCommandLine method, of class JssTextAreaController. */ @Test public void testIsCaretBeforeStartOfCommandLine() { System.out.println("isCaretBeforeStartOfCommandLine"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); boolean expResult = false; boolean result = instance.isCaretBeforeStartOfCommandLine(); assertEquals(expResult, result); } /** * Test of isCaretBeforeOrEqualToStartOfCommandLine method, of class JssTextAreaController. */ @Test public void testIsCaretBeforeOrEqualToStartOfCommandLine() { System.out.println("isCaretBeforeOrEqualToStartOfCommandLine"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); boolean expResult = true; boolean result = instance.isCaretBeforeOrEqualToStartOfCommandLine(); assertEquals(expResult, result); } /** * Test of isCaretAtStartOfCommandLine method, of class JssTextAreaController. */ @Test public void testIsCaretAtStartOfCommandLine() { System.out.println("isCaretAtStartOfCommandLine"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); boolean expResult = true; boolean result = instance.isCaretAtStartOfCommandLine(); assertEquals(expResult, result); } /** * Test of isCaretAfterOrEqualToStartOfCommandLine method, of class JssTextAreaController. */ @Test public void testIsCaretAfterOrEqualToStartOfCommandLine() { System.out.println("isCaretAfterOrEqualToStartOfCommandLine"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); boolean expResult = true; boolean result = instance.isCaretAfterOrEqualToStartOfCommandLine(); assertEquals(expResult, result); } /** * Test of isCaretAfterStartOfCommandLine method, of class JssTextAreaController. */ @Test public void testIsCaretAfterStartOfCommandLine() { System.out.println("isCaretAfterStartOfCommandLine"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); boolean expResult = false; boolean result = instance.isCaretAfterStartOfCommandLine(); assertEquals(expResult, result); } /** * Test of keyPressed method, of class JssTextAreaController. */ @Test public void testKeyPressed() { System.out.println("keyPressed"); KeyEvent evt = null; JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); instance.keyPressed(evt); } /** * Test of fixSelection method, of class JssTextAreaController. */ @Test public void testFixSelection() { System.out.println("fixSelection"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); instance.fixSelection(); } /** * Test of getBackground method, of class JssTextAreaController. */ @Test public void testGetBackground() { System.out.println("getBackground"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); Color expResult = Color.BLACK; Color result = instance.getBackground(); assertEquals(expResult, result); } /** * Test of setBackground method, of class JssTextAreaController. */ @Test public void testSetBackground() { System.out.println("setBackground"); Color backgroundColor = Color.WHITE; JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); instance.setBackground(backgroundColor); } /** * Test of getForeground method, of class JssTextAreaController. */ @Test public void testGetForeground() { System.out.println("getForeground"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); Color expResult = Color.WHITE; Color result = instance.getForeground(); assertEquals(expResult, result); } /** * Test of setForeground method, of class JssTextAreaController. */ @Test public void testSetForeground() { System.out.println("setForeground"); Color foregroundColor = Color.BLACK; JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); instance.setForeground(foregroundColor); } /** * Test of getTabSize method, of class JssTextAreaController. */ @Test public void testGetTabSize() { System.out.println("getTabSize"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); int expResult = 2; int result = instance.getTabSize(); assertEquals(expResult, result); } /** * Test of setTabSize method, of class JssTextAreaController. */ @Test public void testSetTabSize() { System.out.println("setTabSize"); int size = 0; JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); instance.setTabSize(size); } /** * Test of getFont method, of class JssTextAreaController. */ @Test public void testGetFont() { System.out.println("getFont"); JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); Font notExpResult = null; Font result = instance.getFont(); assertNotEquals(notExpResult, result); } /** * Test of setFont method, of class JssTextAreaController. */ @Test public void testSetFont() { System.out.println("setFont"); Font f = null; JssTextAreaController instance = new JssTextAreaController(new JssTextArea()); instance.setFont(f); } }
package net.bolbat.utils.lang; import java.util.Calendar; import org.junit.Assert; import org.junit.Test; /** * {@link TimeUtilsTest} test. * * @author Alexandr Bolbat */ public class TimeUtilsTest { @Test public void generalTest() { // check TimeUnit values Assert.assertEquals("Should be equal.", Calendar.YEAR, TimeUtils.TimeUnit.YEAR.getMappedCalendarField()); Assert.assertEquals("Should be equal.", Calendar.MONTH, TimeUtils.TimeUnit.MONTH.getMappedCalendarField()); Assert.assertEquals("Should be equal.", Calendar.DAY_OF_MONTH, TimeUtils.TimeUnit.DAY.getMappedCalendarField()); Assert.assertEquals("Should be equal.", Calendar.HOUR_OF_DAY, TimeUtils.TimeUnit.HOUR.getMappedCalendarField()); Assert.assertEquals("Should be equal.", Calendar.MINUTE, TimeUtils.TimeUnit.MINUTE.getMappedCalendarField()); Assert.assertEquals("Should be equal.", Calendar.SECOND, TimeUtils.TimeUnit.SECOND.getMappedCalendarField()); // check rounding checkRound(TimeUtils.TimeUnit.SECOND, TimeUtils.Rounding.DOWN); checkRound(TimeUtils.TimeUnit.SECOND, TimeUtils.Rounding.UP); checkRound(TimeUtils.TimeUnit.MINUTE, TimeUtils.Rounding.DOWN); checkRound(TimeUtils.TimeUnit.MINUTE, TimeUtils.Rounding.UP); checkRound(TimeUtils.TimeUnit.HOUR, TimeUtils.Rounding.DOWN); checkRound(TimeUtils.TimeUnit.HOUR, TimeUtils.Rounding.UP); checkRound(TimeUtils.TimeUnit.DAY, TimeUtils.Rounding.DOWN); checkRound(TimeUtils.TimeUnit.DAY, TimeUtils.Rounding.UP); checkRound(TimeUtils.TimeUnit.MONTH, TimeUtils.Rounding.DOWN); checkRound(TimeUtils.TimeUnit.MONTH, TimeUtils.Rounding.UP); checkRound(TimeUtils.TimeUnit.YEAR, TimeUtils.Rounding.DOWN); checkRound(TimeUtils.TimeUnit.YEAR, TimeUtils.Rounding.UP); // check 'from now' checkFromNow(1, TimeUtils.TimeUnit.YEAR); checkFromNow(-1, TimeUtils.TimeUnit.YEAR); checkFromNow(1, TimeUtils.TimeUnit.MONTH); checkFromNow(-1, TimeUtils.TimeUnit.MONTH); checkFromNow(1, TimeUtils.TimeUnit.DAY); checkFromNow(-1, TimeUtils.TimeUnit.DAY); checkFromNow(1, TimeUtils.TimeUnit.HOUR); checkFromNow(-1, TimeUtils.TimeUnit.HOUR); checkFromNow(1, TimeUtils.TimeUnit.MINUTE); checkFromNow(-1, TimeUtils.TimeUnit.MINUTE); checkFromNow(1, TimeUtils.TimeUnit.SECOND); checkFromNow(-1, TimeUtils.TimeUnit.SECOND); // check 'from now' with no rounding param int fromNow = 1; TimeUtils.TimeUnit timeUnit = TimeUtils.TimeUnit.DAY; Calendar calendar = Calendar.getInstance(); calendar.add(timeUnit.getMappedCalendarField(), fromNow); // manual calculation roundCalendarManually(calendar, timeUnit, TimeUtils.Rounding.UP); long fromNowRoundUpByCalendar = calendar.getTimeInMillis(); // util calculation calendar.setTimeInMillis(TimeUtils.fromNow(fromNow, timeUnit)); roundCalendarManually(calendar, timeUnit, TimeUtils.Rounding.UP); Assert.assertEquals("Test time unit[" + timeUnit + "]. Values should be equal", fromNowRoundUpByCalendar, calendar.getTimeInMillis()); } @Test public void errorCaseTests() { try { TimeUtils.fromNow(0, null, TimeUtils.Rounding.DOWN); Assert.fail("Should fail cause param is wrong."); } catch (IllegalArgumentException e) { Assert.assertTrue(e instanceof IllegalArgumentException); } try { TimeUtils.fromNow(0, null); Assert.fail("Should fail cause param is wrong."); } catch (IllegalArgumentException e) { Assert.assertTrue(e instanceof IllegalArgumentException); } try { TimeUtils.round(null, TimeUtils.TimeUnit.SECOND, TimeUtils.Rounding.DOWN); Assert.fail("Should fail cause param is wrong."); } catch (IllegalArgumentException e) { Assert.assertTrue(e instanceof IllegalArgumentException); } try { TimeUtils.round(Calendar.getInstance(), null, TimeUtils.Rounding.DOWN); Assert.fail("Should fail cause param is wrong."); } catch (IllegalArgumentException e) { Assert.assertTrue(e instanceof IllegalArgumentException); } try { TimeUtils.round(Calendar.getInstance().getTimeInMillis(), null, TimeUtils.Rounding.DOWN); Assert.fail("Should fail cause param is wrong."); } catch (IllegalArgumentException e) { Assert.assertTrue(e instanceof IllegalArgumentException); } } /** * Check method 'round'. * * @param timeUnit * {@link TimeUtils.TimeUnit} * @param rounding * {@link TimeUtils.Rounding} */ private void checkRound(TimeUtils.TimeUnit timeUnit, TimeUtils.Rounding rounding) { Calendar calendar = Calendar.getInstance(); roundCalendarManually(calendar, timeUnit, rounding); Calendar utilCal = Calendar.getInstance(); TimeUtils.round(utilCal, timeUnit, rounding); Assert.assertEquals("Round value should be same", calendar.getTimeInMillis(), utilCal.getTimeInMillis()); } /** * Check method 'from now'. * * @param amount * amount of time units from now * @param timeUnit * {@link TimeUtils.TimeUnit} */ private void checkFromNow(int amount, TimeUtils.TimeUnit timeUnit) { Calendar calendar = Calendar.getInstance(); calendar.add(timeUnit.getMappedCalendarField(), amount); // manual calculation roundCalendarManually(calendar, timeUnit, TimeUtils.Rounding.UP); long fromNowRoundUpByCalendar = calendar.getTimeInMillis(); roundCalendarManually(calendar, timeUnit, TimeUtils.Rounding.DOWN); long fromNowRoundDownByCalendar = calendar.getTimeInMillis(); // util calculation long fromNowRoundUpByUtil = TimeUtils.fromNow(amount, timeUnit, TimeUtils.Rounding.UP); long fromNowRoundDownByUtil = TimeUtils.fromNow(amount, timeUnit, TimeUtils.Rounding.DOWN); Assert.assertEquals("Test time unit[" + timeUnit + "]. Values should be equal", fromNowRoundUpByCalendar, fromNowRoundUpByUtil); Assert.assertEquals("Test time unit[" + timeUnit + "]. Values should be equal", fromNowRoundDownByCalendar, fromNowRoundDownByUtil); } /** * Round calendar manually. * * @param cal * {@link Calendar} * @param timeUnit * {@link TimeUtils.TimeUnit} * @param rounding * {@link TimeUtils.Rounding} */ private void roundCalendarManually(Calendar cal, TimeUtils.TimeUnit timeUnit, TimeUtils.Rounding rounding) { if (rounding == null || TimeUtils.Rounding.NONE.equals(rounding)) return; boolean roundDown = TimeUtils.Rounding.DOWN.equals(rounding); switch (timeUnit) { case SECOND: cal.set(Calendar.MILLISECOND, roundDown ? cal.getActualMinimum(Calendar.MILLISECOND) : cal.getActualMaximum(Calendar.MILLISECOND)); break; case MINUTE: cal.set(Calendar.MILLISECOND, roundDown ? cal.getActualMinimum(Calendar.MILLISECOND) : cal.getActualMaximum(Calendar.MILLISECOND)); cal.set(Calendar.SECOND, roundDown ? cal.getActualMinimum(Calendar.SECOND) : cal.getActualMaximum(Calendar.SECOND)); break; case HOUR: cal.set(Calendar.MILLISECOND, roundDown ? cal.getActualMinimum(Calendar.MILLISECOND) : cal.getActualMaximum(Calendar.MILLISECOND)); cal.set(Calendar.SECOND, roundDown ? cal.getActualMinimum(Calendar.SECOND) : cal.getActualMaximum(Calendar.SECOND)); cal.set(Calendar.MINUTE, roundDown ? cal.getActualMinimum(Calendar.MINUTE) : cal.getActualMaximum(Calendar.MINUTE)); break; case DAY: cal.set(Calendar.MILLISECOND, roundDown ? cal.getActualMinimum(Calendar.MILLISECOND) : cal.getActualMaximum(Calendar.MILLISECOND)); cal.set(Calendar.SECOND, roundDown ? cal.getActualMinimum(Calendar.SECOND) : cal.getActualMaximum(Calendar.SECOND)); cal.set(Calendar.MINUTE, roundDown ? cal.getActualMinimum(Calendar.MINUTE) : cal.getActualMaximum(Calendar.MINUTE)); cal.set(Calendar.HOUR_OF_DAY, roundDown ? cal.getActualMinimum(Calendar.HOUR_OF_DAY) : cal.getActualMaximum(Calendar.HOUR_OF_DAY)); break; case MONTH: cal.set(Calendar.MILLISECOND, roundDown ? cal.getActualMinimum(Calendar.MILLISECOND) : cal.getActualMaximum(Calendar.MILLISECOND)); cal.set(Calendar.SECOND, roundDown ? cal.getActualMinimum(Calendar.SECOND) : cal.getActualMaximum(Calendar.SECOND)); cal.set(Calendar.MINUTE, roundDown ? cal.getActualMinimum(Calendar.MINUTE) : cal.getActualMaximum(Calendar.MINUTE)); cal.set(Calendar.HOUR_OF_DAY, roundDown ? cal.getActualMinimum(Calendar.HOUR_OF_DAY) : cal.getActualMaximum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.DAY_OF_MONTH, roundDown ? cal.getActualMinimum(Calendar.DAY_OF_MONTH) : cal.getActualMaximum(Calendar.DAY_OF_MONTH)); break; case YEAR: cal.set(Calendar.MILLISECOND, roundDown ? cal.getActualMinimum(Calendar.MILLISECOND) : cal.getActualMaximum(Calendar.MILLISECOND)); cal.set(Calendar.SECOND, roundDown ? cal.getActualMinimum(Calendar.SECOND) : cal.getActualMaximum(Calendar.SECOND)); cal.set(Calendar.MINUTE, roundDown ? cal.getActualMinimum(Calendar.MINUTE) : cal.getActualMaximum(Calendar.MINUTE)); cal.set(Calendar.HOUR_OF_DAY, roundDown ? cal.getActualMinimum(Calendar.HOUR_OF_DAY) : cal.getActualMaximum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.DAY_OF_YEAR, roundDown ? cal.getActualMinimum(Calendar.DAY_OF_YEAR) : cal.getActualMaximum(Calendar.DAY_OF_YEAR)); cal.set(Calendar.MONTH, roundDown ? cal.getActualMinimum(Calendar.MONTH) : cal.getActualMaximum(Calendar.MONTH)); break; } } }
package hudson.model; import org.jvnet.hudson.test.HudsonTestCase; import org.jvnet.hudson.test.CaptureEnvironmentBuilder; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlTextInput; import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput; import com.gargoylesoftware.htmlunit.html.HtmlOption; import java.util.Set; /** * @author huybrechts */ public class ParametersTest extends HudsonTestCase { public void testParameterTypes() throws Exception { FreeStyleProject otherProject = createFreeStyleProject(); otherProject.scheduleBuild2(0).get(); FreeStyleProject project = createFreeStyleProject(); ParametersDefinitionProperty pdp = new ParametersDefinitionProperty( new StringParameterDefinition("string", "defaultValue", "string description"), new BooleanParameterDefinition("boolean", true, "boolean description"), new ChoiceParameterDefinition("choice", "Choice 1\nChoice 2", "choice description"), new RunParameterDefinition("run", otherProject.getName(), "run description", null)); project.addProperty(pdp); CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder(); project.getBuildersList().add(builder); WebClient wc = new WebClient(); wc.setThrowExceptionOnFailingStatusCode(false); HtmlPage page = wc.goTo("/job/" + project.getName() + "/build?delay=0sec"); HtmlForm form = page.getFormByName("parameters"); HtmlElement element = (HtmlElement) form.selectSingleNode("//tr[td/div/input/@value='string']"); assertNotNull(element); assertEquals("string description", ((HtmlElement) element.getNextSibling().getNextSibling().selectSingleNode("td[@class='setting-description']")).getTextContent()); HtmlTextInput stringParameterInput = (HtmlTextInput) element.selectSingleNode(".//input[@name='value']"); assertEquals("defaultValue", stringParameterInput.getAttribute("value")); assertEquals("string", ((HtmlElement) element.selectSingleNode("td[@class='setting-name']")).getTextContent()); stringParameterInput.setAttribute("value", "newValue"); element = (HtmlElement) form.selectSingleNode("//tr[td/div/input/@value='boolean']"); assertNotNull(element); assertEquals("boolean description", ((HtmlElement) element.selectSingleNode("td/div")).getAttribute("description")); Object o = element.selectSingleNode(".//input[@name='value']"); System.out.println(o); HtmlCheckBoxInput booleanParameterInput = (HtmlCheckBoxInput) o; assertEquals(true, booleanParameterInput.isChecked()); assertEquals("boolean", ((HtmlElement) element.selectSingleNode("td[@class='setting-name']")).getTextContent()); element = (HtmlElement) form.selectSingleNode(".//tr[td/div/input/@value='choice']"); assertNotNull(element); assertEquals("choice description", ((HtmlElement) element.selectSingleNode("td/div")).getAttribute("description")); assertEquals("choice", ((HtmlElement) element.selectSingleNode("td[@class='setting-name']")).getTextContent()); element = (HtmlElement) form.selectSingleNode(".//tr[td/div/input/@value='run']"); assertNotNull(element); assertEquals("run description", ((HtmlElement) element.selectSingleNode("td/div")).getAttribute("description")); assertEquals("run", ((HtmlElement) element.selectSingleNode("td[@class='setting-name']")).getTextContent()); submit(form); Queue.Item q = jenkins.getQueue().getItem(project); if (q != null) q.getFuture().get(); else Thread.sleep(1000); assertEquals("newValue", builder.getEnvVars().get("STRING")); assertEquals("true", builder.getEnvVars().get("BOOLEAN")); assertEquals("Choice 1", builder.getEnvVars().get("CHOICE")); assertEquals(jenkins.getRootUrl() + otherProject.getLastBuild().getUrl(), builder.getEnvVars().get("RUN")); } public void testChoiceWithLTGT() throws Exception { FreeStyleProject project = createFreeStyleProject(); ParametersDefinitionProperty pdp = new ParametersDefinitionProperty( new ChoiceParameterDefinition("choice", "Choice 1\nChoice <2>", "choice description")); project.addProperty(pdp); CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder(); project.getBuildersList().add(builder); WebClient wc = new WebClient(); wc.setThrowExceptionOnFailingStatusCode(false); HtmlPage page = wc.goTo("/job/" + project.getName() + "/build?delay=0sec"); HtmlForm form = page.getFormByName("parameters"); HtmlElement element = (HtmlElement) form.selectSingleNode(".//tr[td/div/input/@value='choice']"); assertNotNull(element); assertEquals("choice description", ((HtmlElement) element.selectSingleNode("td/div")).getAttribute("description")); assertEquals("choice", ((HtmlElement) element.selectSingleNode("td[@class='setting-name']")).getTextContent()); HtmlOption opt = (HtmlOption)element.selectSingleNode("td/div/select/option[@value='Choice <2>']"); assertNotNull(opt); assertEquals("Choice <2>", opt.asText()); opt.setSelected(true); submit(form); Queue.Item q = jenkins.getQueue().getItem(project); if (q != null) q.getFuture().get(); else Thread.sleep(1000); assertNotNull(builder.getEnvVars()); assertEquals("Choice <2>", builder.getEnvVars().get("CHOICE")); } public void testSensitiveParameters() throws Exception { FreeStyleProject project = createFreeStyleProject(); ParametersDefinitionProperty pdb = new ParametersDefinitionProperty( new PasswordParameterDefinition("password", "12345", "password description")); project.addProperty(pdb); CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder(); project.getBuildersList().add(builder); FreeStyleBuild build = project.scheduleBuild2(0).get(); Set<String> sensitiveVars = build.getSensitiveBuildVariables(); assertNotNull(sensitiveVars); assertTrue(sensitiveVars.contains("password")); } public void testNonSensitiveParameters() throws Exception { FreeStyleProject project = createFreeStyleProject(); ParametersDefinitionProperty pdb = new ParametersDefinitionProperty( new StringParameterDefinition("string", "defaultValue", "string description")); project.addProperty(pdb); CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder(); project.getBuildersList().add(builder); FreeStyleBuild build = project.scheduleBuild2(0).get(); Set<String> sensitiveVars = build.getSensitiveBuildVariables(); assertNotNull(sensitiveVars); assertFalse(sensitiveVars.contains("string")); } public void testMixedSensitivity() throws Exception { FreeStyleProject project = createFreeStyleProject(); ParametersDefinitionProperty pdb = new ParametersDefinitionProperty( new StringParameterDefinition("string", "defaultValue", "string description"), new PasswordParameterDefinition("password", "12345", "password description"), new StringParameterDefinition("string2", "Value2", "string description") ); project.addProperty(pdb); CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder(); project.getBuildersList().add(builder); FreeStyleBuild build = project.scheduleBuild2(0).get(); Set<String> sensitiveVars = build.getSensitiveBuildVariables(); assertNotNull(sensitiveVars); assertFalse(sensitiveVars.contains("string")); assertTrue(sensitiveVars.contains("password")); assertFalse(sensitiveVars.contains("string2")); } }
package mondrian.olap.fun; import junit.framework.TestCase; import org.apache.commons.collections.ComparatorUtils; import org.apache.commons.collections.comparators.ReverseComparator; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Random; /** * <code>PartialSortTest</code> is a unit test for the partial-sort algorithm * {@link FunUtil#partialSort}, which supports MDX functions like TopCount and * BottomCount. No MDX here; there are tests of TopCount etc in FunctionTest. * * @author Marc Berkowitz * @since Nov 2008 * @version $Id$ */ public class PartialSortTest extends TestCase { final Random random = new Random(); // subroutines // returns a new array of random integers private Integer[] newRandomIntegers(int length, int minValue, int maxValue) { final int delta = maxValue - minValue; Integer[] vec = new Integer[length]; for (int i = 0; i < length; i++) { vec[i] = minValue + random.nextInt(delta); } return vec; } // calls partialSort() for natural ascending or descending order private void doPartialSort(Object[] items, boolean descending, int limit) { Comparator comp = ComparatorUtils.naturalComparator(); if (descending) { comp = ComparatorUtils.reversedComparator(comp); } FunUtil.partialSort(items, comp, limit); } // predicate: checks that results have been partially sorted; simplest case, on int[] private static boolean isPartiallySorted(int[] vec, int limit, boolean descending) { // elements {0 <= i < limit} are sorted for (int i = 1; i < limit; i++) { int delta = vec[i] - vec[i - 1]; if (descending) { if (delta > 0) { return false; } } else { if (delta < 0) { return false; } } } // elements {limit <= i} are just bigger or smaller than the bound vec[limit - 1]; int bound = vec[limit - 1]; for (int i = limit; i < vec.length; i++) { int delta = vec[i] - bound; if (descending) { if (delta > 0) { return false; } } else { if (delta < 0) { return false; } } } return true; } // same predicate generalized: uses natural comparison private static <T extends Comparable> boolean isPartiallySorted( T [] vec, int limit, boolean descending) { return isPartiallySorted( vec, limit, ComparatorUtils.naturalComparator(), descending); } // same predicate generalized: uses a given Comparator private static <T> boolean isPartiallySorted( T[] vec, int limit, Comparator<? super T> order, boolean descending) { return isPartiallySorted(vec, limit, order, descending, null); } // Same predicate generalized: uses two Comparators, a sort key (ascending or // descending), and a tie-breaker (always ascending). This is a contrivance to // verify a stable partial sort, on a special input array. private static <T> boolean isPartiallySorted( T[] vec, int limit, Comparator<? super T> order, boolean descending, Comparator<? super T> tieBreaker) { // elements {0 <= i < limit} are sorted for (int i = 1; i < limit; i++) { int delta = order.compare(vec[i], vec[i - 1]); if (delta == 0) { if (tieBreaker != null && tieBreaker.compare(vec[i], vec[i - 1]) < 0) { return false; } } else if (descending) { if (delta > 0) { return false; } } else { if (delta < 0) { return false; } } } // elements {limit <= i} are just bigger or smaller than the bound vec[limit - 1]; T bound = vec[limit - 1]; for (int i = limit; i < vec.length; i++) { int delta = order.compare(vec[i], bound); if (descending) { if (delta > 0) { return false; } } else { if (delta < 0) { return false; } } } return true; } // validate the predicate isPartiallySorted() public void testPredicate1() { int errct = 0; int size = 10 * 1000; int[] vec = new int[size]; // all sorted, ascending int key = 0; for (int i = 0; i < size; i++) { vec[i] = key; key += i % 3; } if (isPartiallySorted(vec, size, true)) { errct++; } if (!isPartiallySorted(vec, size, false)) { errct++; } // partially sorted, ascending key = 0; int limit = 2000; for (int i = 0; i < limit; i++) { vec[i] = key; key += i % 3; } for (int i = limit; i < size; i++) { vec[i] = 2 * key + random.nextInt(1000); } if (isPartiallySorted(vec, limit, true)) { errct++; } if (!isPartiallySorted(vec, limit, false)) { errct++; } // all sorted, descending; key = 2 * size; for (int i = 0; i < size; i++) { vec[i] = key; key -= i % 3; } if (!isPartiallySorted(vec, size, true)) { errct++; } if (isPartiallySorted(vec, size, false)) { errct++; } // partially sorted, descending key = 2 * size; limit = 2000; for (int i = 0; i < limit; i++) { vec[i] = key; key -= i % 3; } for (int i = limit; i < size; i++) { vec[i] = key - random.nextInt(size); } if (!isPartiallySorted(vec, limit, true)) { errct++; } if (isPartiallySorted(vec, limit, false)) { errct++; } assertTrue(errct == 0); } // same as testPredicate() but boxed public void testPredicate2() { int errct = 0; int size = 10 * 1000; Integer[] vec = new Integer[size]; Random random = new Random(); // all sorted, ascending int key = 0; for (int i = 0; i < size; i++) { vec[i] = key; key += i % 3; } if (isPartiallySorted(vec, size, true)) { errct++; } if (!isPartiallySorted(vec, size, false)) { errct++; } // partially sorted, ascending key = 0; int limit = 2000; for (int i = 0; i < limit; i++) { vec[i] = key; key += i % 3; } for (int i = limit; i < size; i++) { vec[i] = 2 * key + random.nextInt(1000); } if (isPartiallySorted(vec, limit, true)) { errct++; } if (!isPartiallySorted(vec, limit, false)) { errct++; } // all sorted, descending; key = 2 * size; for (int i = 0; i < size; i++) { vec[i] = key; key -= i % 3; } if (!isPartiallySorted(vec, size, true)) { errct++; } if (isPartiallySorted(vec, size, false)) { errct++; } // partially sorted, descending key = 2 * size; limit = 2000; for (int i = 0; i < limit; i++) { vec[i] = key; key -= i % 3; } for (int i = limit; i < size; i++) { vec[i] = key - random.nextInt(size); } if (!isPartiallySorted(vec, limit, true)) { errct++; } if (isPartiallySorted(vec, limit, false)) { errct++; } assertTrue(errct == 0); } public void testQuick() { final int length = 40; final int limit = 4; Integer vec[] = newRandomIntegers(length, 0, length); // sort descending doPartialSort(vec, true, limit); assertTrue(isPartiallySorted(vec, limit, true)); } public void testOnAlreadySorted() { final int length = 200; final int limit = 8; Integer vec[] = new Integer[length]; for (int i = 0; i < length; i++) { vec[i] = i; } // sort ascending doPartialSort(vec, false, limit); assertTrue(isPartiallySorted(vec, limit, false)); } public void testOnAlreadyReverseSorted() { final int length = 200; final int limit = 8; Integer vec[] = new Integer[length]; for (int i = 0; i < length; i++) { vec[i] = length - i; } // sort ascending doPartialSort(vec, false, limit); assertTrue(isPartiallySorted(vec, limit, false)); } // tests partial sort on arras of random integers private void randomIntegerTests(int length, int limit) { Integer vec[] = newRandomIntegers(length, 0, length); // sort descending doPartialSort(vec, true, limit); assertTrue(isPartiallySorted(vec, limit, true)); // sort ascending vec = newRandomIntegers(length, 0, length); doPartialSort(vec, false, limit); assertTrue(isPartiallySorted(vec, limit, false)); // both again with a wider range of values vec = newRandomIntegers(length, 10, 4 * length); doPartialSort(vec, true, limit); assertTrue(isPartiallySorted(vec, limit, true)); vec = newRandomIntegers(length, 10, 4 * length); doPartialSort(vec, false, limit); assertTrue(isPartiallySorted(vec, limit, false)); // and again with a narrower range values vec = newRandomIntegers(length, 0, length / 10); doPartialSort(vec, true, limit); assertTrue(isPartiallySorted(vec, limit, true)); vec = newRandomIntegers(length, 0, length / 10); doPartialSort(vec, false, limit); assertTrue(isPartiallySorted(vec, limit, false)); } // test correctness public void testOnRandomIntegers() { randomIntegerTests(100, 20); randomIntegerTests(50000, 10); randomIntegerTests(50000, 500); randomIntegerTests(50000, 12000); } // test with large vector public void testOnManyRandomIntegers() { randomIntegerTests(1000 * 1000, 5000); randomIntegerTests(1000 * 1000, 10); } public void longTest() { int count = 128; while (count testOnRandomIntegers(); } } // Test stable partial sort, Test input; a vector of itens with an explicit // index; sort should not pernute the index. static class Item { final int index; final int key; Item(int index, int key) { this.index = index; this.key = key; } static final Comparator<Item> byIndex = new Comparator<Item>() { public int compare(Item x, Item y) { return x.index - y.index; } }; static final Comparator<Item> byKey = new Comparator<Item>() { public int compare(Item x, Item y) { return x.key - y.key; } }; // returns true iff VEC is partially sorted 1st by key (ascending or // descending), 2nd by index (always ascending) static boolean isStablySorted(Item[] vec, int limit, boolean desc) { return isPartiallySorted(vec, limit, byKey, desc, byIndex); } } // returns a new array of partially sorted Items private Item[] newPartlySortedItems(int length, int limit, boolean desc) { Item[] vec = new Item[length]; int factor = desc? -1 : 1; int key = desc ? (2 * length) : 0; int i; for (i = 0; i < limit; i++) { vec[i] = new Item(i, key); key += factor * (i % 3); // stutter } for (; i < length; i++) { vec[i] = new Item(i, key + factor * random.nextInt(length)); } return vec; } // returns a new array of random Items private Item[] newRandomItems(int length, int minKey, int maxKey) { final int delta = maxKey - minKey; Item[] vec = new Item[length]; for (int i = 0; i < length; i++) { vec[i] = new Item(i, minKey + random.nextInt(delta)); } return vec; } // just glue private Item[] doStablePartialSort(Item[] vec, boolean desc, int limit) { Comparator<Item> comp = Item.byKey; if (desc) { comp = new ReverseComparator(comp); } List<Item> sorted = FunUtil.stablePartialSort(Arrays.asList(vec), comp, limit); return sorted.toArray(new Item[0]); } public void testPredicateIsStablySorted() { Item[] vec = newPartlySortedItems(24 ,4, false); assertTrue(Item.isStablySorted(vec, 4, false)); assertFalse(Item.isStablySorted(vec, 4, true)); vec = newPartlySortedItems(24 ,8, true); assertTrue(Item.isStablySorted(vec, 4, true)); assertFalse(Item.isStablySorted(vec, 4, false)); vec = newPartlySortedItems(1000, 100, true); assertTrue(Item.isStablySorted(vec, 100, true)); assertTrue(Item.isStablySorted(vec, 20, true)); assertTrue(Item.isStablySorted(vec, 4, true)); } public void testStableQuick() { final int length = 40; final int limit = 4; Item vec[] = newRandomItems(length, 0, length); // sort descending vec = doStablePartialSort(vec, true, limit); assertTrue(Item.isStablySorted(vec, limit, true)); } // tests stable partial sort on arras of random Items private void randomItemTests(int length, int limit) { Item vec[] = newRandomItems(length, 0, length); // sort descending vec = doStablePartialSort(vec, true, limit); assertTrue(Item.isStablySorted(vec, limit, true)); // sort ascending vec = newRandomItems(length, 0, length); vec = doStablePartialSort(vec, false, limit); assertTrue(Item.isStablySorted(vec, limit, false)); // both again with a wider range of values vec = newRandomItems(length, 10, 4 * length); vec = doStablePartialSort(vec, true, limit); assertTrue(Item.isStablySorted(vec, limit, true)); vec = newRandomItems(length, 10, 4 * length); vec = doStablePartialSort(vec, false, limit); assertTrue(Item.isStablySorted(vec, limit, false)); // and again with a narrower range values vec = newRandomItems(length, 0, length / 10); vec = doStablePartialSort(vec, true, limit); assertTrue(Item.isStablySorted(vec, limit, true)); vec = newRandomItems(length, 0, length / 10); vec = doStablePartialSort(vec, false, limit); assertTrue(Item.isStablySorted(vec, limit, false)); } public void testStableOnRandomItems() { randomItemTests(100, 20); randomItemTests(50000, 10); randomItemTests(50000, 500); randomItemTests(50000, 12000); } // Compares elapsed time of full sort (mergesort), partial sort, and stable // partial sort on the same input set. private void speedTest(int length, int limit) { System.out.println("sorting the max " + limit + " of " + length + " random Integers"); // random input, 3 copies Integer[] vec1 = newRandomIntegers(length, 0, length / 5); // repeated keys Integer[] vec2 = new Integer[length]; Integer[] vec3 = new Integer[length]; System.arraycopy(vec1, 0, vec2, 0, length); System.arraycopy(vec1, 0, vec3, 0, length); // full sort vec1 long now = System.currentTimeMillis(); Arrays.sort(vec1); long dt = System.currentTimeMillis() - now; System.out.println(" full mergesort took " + dt + " msecs"); // partial sort vec2 now = System.currentTimeMillis(); doPartialSort(vec2, true, limit); dt = System.currentTimeMillis() - now; System.out.println(" partial quicksort took " + dt + " msecs"); // stable partial sort vec3 Comparator comp = new ReverseComparator(ComparatorUtils.naturalComparator()); List<Integer> vec3List = Arrays.asList(vec3); now = System.currentTimeMillis(); FunUtil.stablePartialSort(vec3List, comp, limit); dt = System.currentTimeMillis() - now; System.out.println(" stable partial quicksort took " + dt + " msecs"); } // compare speed on different sizes of input public void _testSpeed() { speedTest(60, 2); // tiny speedTest(600, 12); // small speedTest(600, 200); speedTest(16000, 4); // medium speedTest(16000, 160); speedTest(400 * 400, 4); // large // speedTest(1600 * 1600, 4); // very large needs bigger heap } } // End PartialSortTest.java
package mondrian.rolap; import mondrian.calc.ResultStyle; import mondrian.olap.*; import mondrian.olap.*; import mondrian.test.FoodMartTestCase; import mondrian.test.TestContext; import mondrian.test.DiffRepository; import java.util.*; import java.lang.ref.*; /** * Unit-test for non cacheable elementos of high dimensions. * * @author jlopez, lcanals * @version $Id$ * @since May, 2008 */ public class HighDimensionsTest extends FoodMartTestCase { public HighDimensionsTest() { } public HighDimensionsTest(String name) { super(name); } public void testBug1971406() throws Exception { final Connection connection = TestContext.instance() .getFoodMartConnection(); Query query = connection.parseQuery( "with set necj as " + "NonEmptyCrossJoin(NonEmptyCrossJoin(" + "[Customers].[Name].members,[Store].[Store Name].members)," + "[Product].[Product Name].members) " + "select {[Measures].[Unit Sales]} on columns," + "tail(intersect(necj,necj,ALL),5) on rows from sales"); final long t0 = System.currentTimeMillis(); Result result = connection.execute(query); for (final Position o : result.getAxes()[0].getPositions()) { assertNotNull(o.get(0)); } final long t1 = System.currentTimeMillis(); assertTrue(t1 - t0 < 60000); } public void testPromotionsTwoDimensions() throws Exception { execHighCardTest("select {[Measures].[Unit Sales]} on columns,\n" + "{[Promotions].[Promotion Name].Members} on rows\n" + "from [Sales Ragged]", 1, "Promotions", highCardResults, null, true); } public void testHead() throws Exception { execHighCardTest("select {[Measures].[Unit Sales]} on columns,\n" + "head({[Promotions].[Promotion Name].Members},40) " + "on rows from [Sales Ragged]", 1, "Promotions", first40HighCardResults, null, true); } public void testTopCount() throws Exception { final Connection connection = TestContext.instance() .getFoodMartConnection(); final StringBuffer buffer = new StringBuffer(); Query query = connection.parseQuery( "select {[Measures].[Unit Sales]} on columns,\n" + "TopCount({[Promotions].[Promotion Name].Members},41, " + "[Measures].[Unit Sales]) " + "on rows from [Sales Ragged]"); Result result = connection.execute(query); int i = 0; String topcount40HighCardResults = null; String topcount41HighCardResults = null; for (final Position o : result.getAxes()[1].getPositions()) { buffer.append(o.get(0)); i++; if (i == 40) { topcount40HighCardResults = buffer.toString(); } } topcount41HighCardResults = buffer.toString(); execHighCardTest("select {[Measures].[Unit Sales]} on columns,\n" + "TopCount({[Promotions].[Promotion Name].Members},40, " + "[Measures].[Unit Sales]) " + "on rows from [Sales Ragged]", 1, "Promotions", topcount40HighCardResults, topcount40Cells, false); execHighCardTest("select {[Measures].[Unit Sales]} on columns,\n" + "TopCount({[Promotions].[Promotion Name].Members},41, " + "[Measures].[Unit Sales]) " + "on rows from [Sales Ragged]", 1, "Promotions", topcount41HighCardResults, topcount41Cells, false); execHighCardTest("select {[Measures].[Unit Sales]} on columns,\n" + "TopCount({[Promotions].[Promotion Name].Members},40, " + "[Measures].[Unit Sales]) " + "on rows from [Sales Ragged]", 1, "Promotions", topcount40HighCardResults, topcount40Cells, false); } public void testNonEmpty() throws Exception { execHighCardTest("select {[Measures].[Unit Sales]} on columns,\n" + "non empty {[Promotions].[Promotion Name].Members} " + "on rows from [Sales Ragged]", 1, "Promotions", nonEmptyHighCardResults, nonEmptyCells, true); } public void testFilter() throws Exception { execHighCardTest("select [Measures].[Unit Sales] on columns, " + "filter([Promotions].[Promotion Name].Members, " + "[Measures].[Unit Sales]>0) " + "on rows from [Sales Ragged]", 1, "Promotions", nonEmptyHighCardResults, nonEmptyCells, true); execHighCardTest("select [Measures].[Unit Sales] on columns, " + "filter([Promotions].[Promotion Name].Members, " + "[Measures].[Unit Sales]>4000) " + "on rows from [Sales Ragged]", 1, "Promotions", moreThan4000highCardResults, moreThan4000Cells , true); } /** * Executes query test trying to [Promotions].[Promotion Name] elements * into an axis from the results. */ private void execHighCardTest(final String queryString, final int axisIndex, final String highDimensionName, final String results, final String results2, final boolean shouldForget) throws Exception { final int old = MondrianProperties.instance() .ResultLimit.get(); try { MondrianProperties.instance().ResultLimit.set(40); final TestContext testContext = TestContext.createSubstitutingCube( "Sales Ragged", "<Dimension name=\"Promotions\" highCardinality=\"true\" " + "foreignKey=\"promotion_id\">" + "<Hierarchy hasAll=\"true\" " + "allMemberName=\"All Promotions\" " + "primaryKey=\"promotion_id\">" + "<Table name=\"promotion\"/>" + "<Level name=\"Promotion Name\" " + "column=\"promotion_name\" " + "uniqueMembers=\"true\"/>" + "</Hierarchy>" + "</Dimension>"); final Connection connection = testContext.getConnection(); final Query query = connection.parseQuery(queryString); query.setResultStyle(ResultStyle.ITERABLE); Result result = connection.execute(query); StringBuffer buffer = new StringBuffer(); StringBuffer buffer2 = new StringBuffer(); final List<SoftReference> softReferences = new ArrayList<SoftReference>(); // Tests results aren't got from database before this point int ii = 0; for (final Position o : result.getAxes()[axisIndex].getPositions()) { assertNotNull(o.get(0)); buffer2.append(result.getCell( new int[]{0, ii}).getValue().toString()); ii++; softReferences.add(new SoftReference(o.get(0))); buffer.append(o.get(0).toString()); } assertEquals(buffer.toString(), results); if (results2 != null) { assertEquals(buffer2.toString(), results2); } buffer2 = null; buffer = null; if (!shouldForget) { return; } // Tests that really results over ResultLimit are erased from // memory final List overloader = new ArrayList(); try { for (;;) { overloader.add(new long[99999999]); } } catch (OutOfMemoryError out) { // OK, outofmemory } System.gc(); for (int i = 4; i < ii - 40; i++) { assertNull(softReferences.get(i).get()); } for (int i = 4; i < ii - 40; i++) { try { result.getAxes()[axisIndex].getPositions().get(i).get(0); assert false; } catch (RuntimeException nsee) { // Everything is ok } } } finally { MondrianProperties.instance().ResultLimit.set(old); } } private static final String first40HighCardResults = "[Promotions].[All Promotions].[Bag Stuffers]" + "[Promotions].[All Promotions].[Best Savings]" + "[Promotions].[All Promotions].[Big Promo]" + "[Promotions].[All Promotions].[Big Time Discounts]" + "[Promotions].[All Promotions].[Big Time Savings]" + "[Promotions].[All Promotions].[Bye Bye Baby]" + "[Promotions].[All Promotions].[Cash Register Lottery]" + "[Promotions].[All Promotions].[Coupon Spectacular]" + "[Promotions].[All Promotions].[Dimes Off]" + "[Promotions].[All Promotions].[Dollar Cutters]" + "[Promotions].[All Promotions].[Dollar Days]" + "[Promotions].[All Promotions].[Double Down Sale]" + "[Promotions].[All Promotions].[Double Your Savings]" + "[Promotions].[All Promotions].[Fantastic Discounts]" + "[Promotions].[All Promotions].[Free For All]" + "[Promotions].[All Promotions].[Go For It]" + "[Promotions].[All Promotions].[Green Light Days]" + "[Promotions].[All Promotions].[Green Light Special]" + "[Promotions].[All Promotions].[High Roller Savings]" + "[Promotions].[All Promotions].[I Cant Believe It Sale]" + "[Promotions].[All Promotions].[Money Grabbers]" + "[Promotions].[All Promotions].[Money Savers]" + "[Promotions].[All Promotions].[Mystery Sale]" + "[Promotions].[All Promotions].[No Promotion]" + "[Promotions].[All Promotions].[One Day Sale]" + "[Promotions].[All Promotions].[Pick Your Savings]" + "[Promotions].[All Promotions].[Price Cutters]" + "[Promotions].[All Promotions].[Price Destroyers]" + "[Promotions].[All Promotions].[Price Savers]" + "[Promotions].[All Promotions].[Price Slashers]" + "[Promotions].[All Promotions].[Price Smashers]" + "[Promotions].[All Promotions].[Price Winners]" + "[Promotions].[All Promotions].[Sale Winners]" + "[Promotions].[All Promotions].[Sales Days]" + "[Promotions].[All Promotions].[Sales Galore]" + "[Promotions].[All Promotions].[Save-It Sale]" + "[Promotions].[All Promotions].[Saving Days]" + "[Promotions].[All Promotions].[Savings Galore]" + "[Promotions].[All Promotions].[Shelf Clearing Days]" + "[Promotions].[All Promotions].[Shelf Emptiers]"; private static final String nonEmptyHighCardResults = "[Promotions].[All Promotions].[Bag Stuffers]" + "[Promotions].[All Promotions].[Best Savings]" + "[Promotions].[All Promotions].[Big Promo]" + "[Promotions].[All Promotions].[Big Time Discounts]" + "[Promotions].[All Promotions].[Big Time Savings]" + "[Promotions].[All Promotions].[Bye Bye Baby]" + "[Promotions].[All Promotions].[Cash Register Lottery]" + "[Promotions].[All Promotions].[Dimes Off]" + "[Promotions].[All Promotions].[Dollar Cutters]" + "[Promotions].[All Promotions].[Dollar Days]" + "[Promotions].[All Promotions].[Double Down Sale]" + "[Promotions].[All Promotions].[Double Your Savings]" + "[Promotions].[All Promotions].[Free For All]" + "[Promotions].[All Promotions].[Go For It]" + "[Promotions].[All Promotions].[Green Light Days]" + "[Promotions].[All Promotions].[Green Light Special]" + "[Promotions].[All Promotions].[High Roller Savings]" + "[Promotions].[All Promotions].[I Cant Believe It Sale]" + "[Promotions].[All Promotions].[Money Savers]" + "[Promotions].[All Promotions].[Mystery Sale]" + "[Promotions].[All Promotions].[No Promotion]" + "[Promotions].[All Promotions].[One Day Sale]" + "[Promotions].[All Promotions].[Pick Your Savings]" + "[Promotions].[All Promotions].[Price Cutters]" + "[Promotions].[All Promotions].[Price Destroyers]" + "[Promotions].[All Promotions].[Price Savers]" + "[Promotions].[All Promotions].[Price Slashers]" + "[Promotions].[All Promotions].[Price Smashers]" + "[Promotions].[All Promotions].[Price Winners]" + "[Promotions].[All Promotions].[Sale Winners]" + "[Promotions].[All Promotions].[Sales Days]" + "[Promotions].[All Promotions].[Sales Galore]" + "[Promotions].[All Promotions].[Save-It Sale]" + "[Promotions].[All Promotions].[Saving Days]" + "[Promotions].[All Promotions].[Savings Galore]" + "[Promotions].[All Promotions].[Shelf Clearing Days]" + "[Promotions].[All Promotions].[Shelf Emptiers]" + "[Promotions].[All Promotions].[Super Duper Savers]" + "[Promotions].[All Promotions].[Super Savers]" + "[Promotions].[All Promotions].[Super Wallet Savers]" + "[Promotions].[All Promotions].[Three for One]" + "[Promotions].[All Promotions].[Tip Top Savings]" + "[Promotions].[All Promotions].[Two Day Sale]" + "[Promotions].[All Promotions].[Two for One]" + "[Promotions].[All Promotions].[Unbeatable Price Savers]" + "[Promotions].[All Promotions].[Wallet Savers]" + "[Promotions].[All Promotions].[Weekend Markdown]" + "[Promotions].[All Promotions].[You Save Days]"; private static final String highCardResults = "[Promotions].[All Promotions].[Bag Stuffers]" + "[Promotions].[All Promotions].[Best Savings]" + "[Promotions].[All Promotions].[Big Promo]" + "[Promotions].[All Promotions].[Big Time Discounts]" + "[Promotions].[All Promotions].[Big Time Savings]" + "[Promotions].[All Promotions].[Bye Bye Baby]" + "[Promotions].[All Promotions].[Cash Register Lottery]" + "[Promotions].[All Promotions].[Coupon Spectacular]" + "[Promotions].[All Promotions].[Dimes Off]" + "[Promotions].[All Promotions].[Dollar Cutters]" + "[Promotions].[All Promotions].[Dollar Days]" + "[Promotions].[All Promotions].[Double Down Sale]" + "[Promotions].[All Promotions].[Double Your Savings]" + "[Promotions].[All Promotions].[Fantastic Discounts]" + "[Promotions].[All Promotions].[Free For All]" + "[Promotions].[All Promotions].[Go For It]" + "[Promotions].[All Promotions].[Green Light Days]" + "[Promotions].[All Promotions].[Green Light Special]" + "[Promotions].[All Promotions].[High Roller Savings]" + "[Promotions].[All Promotions].[I Cant Believe It Sale]" + "[Promotions].[All Promotions].[Money Grabbers]" + "[Promotions].[All Promotions].[Money Savers]" + "[Promotions].[All Promotions].[Mystery Sale]" + "[Promotions].[All Promotions].[No Promotion]" + "[Promotions].[All Promotions].[One Day Sale]" + "[Promotions].[All Promotions].[Pick Your Savings]" + "[Promotions].[All Promotions].[Price Cutters]" + "[Promotions].[All Promotions].[Price Destroyers]" + "[Promotions].[All Promotions].[Price Savers]" + "[Promotions].[All Promotions].[Price Slashers]" + "[Promotions].[All Promotions].[Price Smashers]" + "[Promotions].[All Promotions].[Price Winners]" + "[Promotions].[All Promotions].[Sale Winners]" + "[Promotions].[All Promotions].[Sales Days]" + "[Promotions].[All Promotions].[Sales Galore]" + "[Promotions].[All Promotions].[Save-It Sale]" + "[Promotions].[All Promotions].[Saving Days]" + "[Promotions].[All Promotions].[Savings Galore]" + "[Promotions].[All Promotions].[Shelf Clearing Days]" + "[Promotions].[All Promotions].[Shelf Emptiers]" + "[Promotions].[All Promotions].[Super Duper Savers]" + "[Promotions].[All Promotions].[Super Savers]" + "[Promotions].[All Promotions].[Super Wallet Savers]" + "[Promotions].[All Promotions].[Three for One]" + "[Promotions].[All Promotions].[Tip Top Savings]" + "[Promotions].[All Promotions].[Two Day Sale]" + "[Promotions].[All Promotions].[Two for One]" + "[Promotions].[All Promotions].[Unbeatable Price Savers]" + "[Promotions].[All Promotions].[Wallet Savers]" + "[Promotions].[All Promotions].[Weekend Markdown]" + "[Promotions].[All Promotions].[You Save Days]"; private static final String moreThan4000highCardResults = "[Promotions].[All Promotions].[Cash Register Lottery]" + "[Promotions].[All Promotions].[No Promotion]" + "[Promotions].[All Promotions].[Price Savers]"; private static final String moreThan4000Cells = "4792.0195448.04094.0"; private static final String nonEmptyCells = "901.02081.01789.0932.0700.0921.04792.01219.0" +"781.01652.01959.0843.01638.0689.01607.0436.0" +"2654.0253.0899.01021.0195448.01973.0323.01624.0" +"2173.04094.01148.0504.01294.0444.02055.02572.0" +"2203.01446.01382.0754.02118.02628.02497.01183.0" +"1155.0525.02053.0335.02100.0916.0914.03145.0"; private static final String topcount40Cells = "195448.04792.04094.03145.02654.02628.02572.02497.0" +"2203.02173.02118.02100.02081.02055.02053.01973.0" +"1959.01789.01652.01638.01624.01607.01446.01382.0" +"1294.01219.01183.01155.01148.01021.0932.0921.0" +"916.0914.0901.0899.0843.0781.0754.0700.0"; private static final String topcount41Cells = "195448.04792.04094.03145.02654.02628.02572.02497.02203.0" + "2173.02118.02100.02081.02055.02053.01973.01959.01789.0" + "1652.01638.01624.01607.01446.01382.01294.01219.01183.0" + "1155.01148.01021.0932.0921.0916.0914.0901.0899.0843.0781" + ".0754.0700.0689.0"; } // End HighDimensionsTest.java
package com.litesuits.orm.db.model; import com.litesuits.orm.db.assit.Checker; import com.litesuits.orm.db.assit.SQLStatement; import java.util.ArrayList; /** * * * @author MaTianyu * 2014-3-83:20:20 */ public class MapInfo { public static class MapTable { public MapTable(String name, String col1, String col2) { this.name = name; this.column1 = col1; this.column2 = col2; } public String name; public String column1; public String column2; } public ArrayList<MapTable> tableList; public ArrayList<SQLStatement> mapNewRelationSQL; public ArrayList<SQLStatement> delOldRelationSQL; public boolean addTable(MapTable table) { if (table.name == null) return false; if (tableList == null) { tableList = new ArrayList<>(); } //for (MapTable mt : tableList) { // if (mt.name.equals(table.name)) return false; return tableList.add(table); } public boolean addNewRelationSQL(SQLStatement st) { if (mapNewRelationSQL == null) { mapNewRelationSQL = new ArrayList<>(); } return mapNewRelationSQL.add(st); } public boolean addNewRelationSQL(ArrayList<SQLStatement> list) { if (mapNewRelationSQL == null) { mapNewRelationSQL = new ArrayList<>(); } return mapNewRelationSQL.addAll(list); } public boolean addDelOldRelationSQL(SQLStatement st) { if (delOldRelationSQL == null) { delOldRelationSQL = new ArrayList<>(); } return delOldRelationSQL.add(st); } public boolean isEmpty() { return Checker.isEmpty(tableList) || Checker.isEmpty(mapNewRelationSQL) && Checker.isEmpty(delOldRelationSQL); } }
package org.holoeverywhere.widget; import java.util.ArrayList; import java.util.List; import org.holoeverywhere.HoloEverywhere; import org.holoeverywhere.app.Activity; import org.holoeverywhere.widget.HeaderViewListAdapter.ViewInfo; import org.holoeverywhere.widget.ListAdapterWrapper.ListAdapterCallback; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Rect; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.support.v4.app._HoloActivity.OnWindowFocusChangeListener; import android.support.v4.util.LongSparseArray; import android.util.AttributeSet; import android.util.SparseBooleanArray; import android.view.ContextMenu.ContextMenuInfo; import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.View; import android.view.ViewDebug.ExportedProperty; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.Checkable; import android.widget.ListAdapter; import com.actionbarsherlock.internal.view.menu.ContextMenuBuilder.ContextMenuInfoGetter; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; public class GridView extends android.widget.GridView implements OnWindowFocusChangeListener, ContextMenuInfoGetter, ListAdapterCallback { private final class MultiChoiceModeWrapper implements org.holoeverywhere.widget.ListView.MultiChoiceModeListener { private org.holoeverywhere.widget.ListView.MultiChoiceModeListener mWrapped; @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return mWrapped.onActionItemClicked(mode, item); } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { if (mWrapped.onCreateActionMode(mode, menu)) { setLongClickable(false); return true; } return false; } @SuppressLint("NewApi") @Override public void onDestroyActionMode(ActionMode mode) { mWrapped.onDestroyActionMode(mode); mChoiceActionMode = null; clearChoices(); invalidateViews(); setLongClickable(true); } @SuppressLint("NewApi") @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { mWrapped.onItemCheckedStateChanged(mode, position, id, checked); if (getCheckedItemCount() == 0) { mode.finish(); } } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return mWrapped.onPrepareActionMode(mode, menu); } public void setWrapped(org.holoeverywhere.widget.ListView.MultiChoiceModeListener wrapped) { mWrapped = wrapped; } } private final class OnItemLongClickListenerWrapper implements OnItemLongClickListener { private OnItemLongClickListener wrapped; @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) { return performItemLongClick(view, position, id); } public void setWrapped(OnItemLongClickListener wrapped) { this.wrapped = wrapped; if (wrapped != null) { setLongClickable(true); } } } @SuppressLint("InlinedApi") public static final int CHOICE_MODE_MULTIPLE_MODAL = AbsListView.CHOICE_MODE_MULTIPLE_MODAL; private static final boolean USE_ACTIVATED = VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB; private Activity mActivity; private ListAdapterWrapper mAdapter; private boolean mAdapterHasStableIds; private LongSparseArray<Integer> mCheckedIdStates; private int mCheckedItemCount; private SparseBooleanArray mCheckStates; private ActionMode mChoiceActionMode; private int mChoiceMode; private ContextMenuInfo mContextMenuInfo; private boolean mEnableModalBackgroundWrapper; private boolean mFastScrollEnabled; private final List<ViewInfo> mFooterViewInfos = new ArrayList<ViewInfo>(), mHeaderViewInfos = new ArrayList<ViewInfo>(); private boolean mForceHeaderListAdapter = false; private boolean mIsAttached; private int mLastScrollState = OnScrollListener.SCROLL_STATE_IDLE; private MultiChoiceModeWrapper mMultiChoiceModeCallback; private final OnItemLongClickListenerWrapper mOnItemLongClickListenerWrapper; private OnScrollListener mOnScrollListener; public GridView(Context context) { this(context, null); } public GridView(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.gridViewStyle); } @SuppressLint("NewApi") public GridView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); if (context instanceof Activity) { setActivity((Activity) context); } if (HoloEverywhere.DISABLE_OVERSCROLL_EFFECT && VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { setOverScrollMode(OVER_SCROLL_NEVER); } mOnItemLongClickListenerWrapper = new OnItemLongClickListenerWrapper(); super.setOnItemLongClickListener(mOnItemLongClickListenerWrapper); setLongClickable(false); } public void addFooterView(View v) { addFooterView(v, null, true); } public void addFooterView(View v, Object data, boolean isSelectable) { if (mAdapter != null && !(mAdapter instanceof HeaderViewListAdapter)) { throw new IllegalStateException( "Cannot add footer view to list -- setAdapter has already been called."); } ViewInfo info = new ViewInfo(); info.view = v; info.data = data; info.isSelectable = isSelectable; mFooterViewInfos.add(info); if (mAdapter != null) { invalidateViews(); } } public void addHeaderView(View v) { addHeaderView(v, null, true); } public void addHeaderView(View v, Object data, boolean isSelectable) { if (mAdapter != null && !(mAdapter instanceof HeaderViewListAdapter)) { throw new IllegalStateException( "Cannot add header view to list -- setAdapter has already been called."); } ViewInfo info = new ViewInfo(); info.view = v; info.data = data; info.isSelectable = isSelectable; mHeaderViewInfos.add(info); if (mAdapter != null) { invalidateViews(); } } @Override public void clearChoices() { if (mCheckStates != null) { mCheckStates.clear(); } if (mCheckedIdStates != null) { mCheckedIdStates.clear(); } mCheckedItemCount = 0; } protected ContextMenuInfo createContextMenuInfo(View view, int position, long id) { return new AdapterContextMenuInfo(view, position, id); } public Activity getActivity() { return mActivity; } @Override public int getCheckedItemCount() { return mCheckedItemCount; } @Override public long[] getCheckedItemIds() { if (mChoiceMode == CHOICE_MODE_NONE || mCheckedIdStates == null || mAdapter == null) { return new long[0]; } final LongSparseArray<Integer> idStates = mCheckedIdStates; final int count = idStates.size(); final long[] ids = new long[count]; for (int i = 0; i < count; i++) { ids[i] = idStates.keyAt(i); } return ids; } @Override public int getCheckedItemPosition() { if (mChoiceMode == CHOICE_MODE_SINGLE && mCheckStates != null && mCheckStates.size() == 1) { return mCheckStates.keyAt(0); } return INVALID_POSITION; } @Override public SparseBooleanArray getCheckedItemPositions() { if (mChoiceMode != CHOICE_MODE_NONE) { return mCheckStates; } return null; } @Deprecated public long[] getCheckItemIds() { return getCheckedItemIds(); } @Override public int getChoiceMode() { return mChoiceMode; } @Override public ContextMenuInfo getContextMenuInfo() { return mContextMenuInfo; } public int getFooterViewsCount() { return mFooterViewInfos.size(); } public int getHeaderViewsCount() { return mHeaderViewInfos.size(); } public boolean isAttached() { return mIsAttached; } @Override @ExportedProperty public boolean isFastScrollEnabled() { return mFastScrollEnabled; } public boolean isForceHeaderListAdapter() { return mForceHeaderListAdapter; } @SuppressLint("NewApi") public boolean isInScrollingContainer() { ViewParent p = getParent(); while (p != null && p instanceof ViewGroup) { if (VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH && ((ViewGroup) p).shouldDelayChildPressedState()) { return true; } p = p.getParent(); } return false; } @Override public boolean isItemChecked(int position) { if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) { return mCheckStates.get(position); } return false; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mIsAttached = true; } @Override public void onChanged() { } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mIsAttached = false; } @Override protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); if (gainFocus && getSelectedItemPosition() < 0 && !isInTouchMode()) { if (!mIsAttached && mAdapter != null) { invalidateViews(); } } } @Override public void onInvalidated() { } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: if (!isEnabled()) { return true; } if (isClickable() && isPressed() && getSelectedItemPosition() >= 0 && mAdapter != null && getSelectedItemPosition() < mAdapter.getCount()) { final View view = getChildAt(getSelectedItemPosition() - getFirstVisiblePosition()); if (view != null) { performItemClick(view, getSelectedItemPosition(), getSelectedItemId()); view.setPressed(false); } setPressed(false); return true; } break; } return super.onKeyUp(keyCode, event); } @Override public View onPrepareView(View view, int position) { if (mCheckStates != null) { setStateOnView(view, mCheckStates.get(position)); } else { setStateOnView(view, false); } return view; } @Override public void onWindowFocusChanged(boolean hasWindowFocus) { super.onWindowFocusChanged(hasWindowFocus); if (hasWindowFocus) { invalidate(); invalidateViews(); } } @Override public boolean performItemClick(View view, int position, long id) { boolean handled = false; boolean dispatchItemClick = true; if (mChoiceMode != CHOICE_MODE_NONE) { handled = true; boolean checkedStateChanged = false; if (mChoiceMode == CHOICE_MODE_MULTIPLE || mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode != null) { boolean newValue = !mCheckStates.get(position, false); mCheckStates.put(position, newValue); if (mCheckedIdStates != null && mAdapter.hasStableIds()) { if (newValue) { mCheckedIdStates.put(mAdapter.getItemId(position), position); } else { mCheckedIdStates.delete(mAdapter.getItemId(position)); } } if (newValue) { mCheckedItemCount++; } else { mCheckedItemCount } if (mChoiceActionMode != null) { mMultiChoiceModeCallback.onItemCheckedStateChanged(mChoiceActionMode, position, id, newValue); dispatchItemClick = false; } checkedStateChanged = true; } else if (mChoiceMode == CHOICE_MODE_SINGLE) { boolean newValue = !mCheckStates.get(position, false); if (newValue) { mCheckStates.clear(); mCheckStates.put(position, true); if (mCheckedIdStates != null && mAdapter.hasStableIds()) { mCheckedIdStates.clear(); mCheckedIdStates.put(mAdapter.getItemId(position), position); } mCheckedItemCount = 1; } else if (mCheckStates.size() == 0 || !mCheckStates.valueAt(0)) { mCheckedItemCount = 0; } checkedStateChanged = true; } if (checkedStateChanged) { updateOnScreenCheckedViews(); } } if (dispatchItemClick) { handled |= super.performItemClick(view, position, id); } return handled; } public boolean performItemLongClick(final View child, final int longPressPosition, final long longPressId) { if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) { if (mChoiceActionMode == null && (mChoiceActionMode = startActionMode(mMultiChoiceModeCallback)) != null) { setItemChecked(longPressPosition, true); performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); } return true; } boolean handled = false; if (mOnItemLongClickListenerWrapper.wrapped != null) { handled = mOnItemLongClickListenerWrapper.wrapped.onItemLongClick(GridView.this, child, longPressPosition, longPressId); } if (!handled) { mContextMenuInfo = createContextMenuInfo(child, longPressPosition, longPressId); handled = super.showContextMenuForChild(GridView.this); } if (handled) { performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); } return handled; } public boolean removeFooterView(View v) { if (mFooterViewInfos.size() > 0) { boolean result = false; if (mAdapter != null && ((HeaderViewListAdapter) mAdapter).removeFooter(v)) { invalidateViews(); result = true; } removeViewInfo(v, mFooterViewInfos); return result; } return false; } public boolean removeHeaderView(View v) { if (mHeaderViewInfos.size() > 0) { boolean result = false; if (mAdapter != null && ((HeaderViewListAdapter) mAdapter).removeHeader(v)) { invalidateViews(); result = true; } removeViewInfo(v, mHeaderViewInfos); return result; } return false; } private void removeViewInfo(View v, List<ViewInfo> where) { int len = where.size(); for (int i = 0; i < len; ++i) { ViewInfo info = where.get(i); if (info.view == v) { where.remove(i); break; } } } protected void reportScrollStateChange(int newState) { if (newState != mLastScrollState) { if (mOnScrollListener != null) { mLastScrollState = newState; mOnScrollListener.onScrollStateChanged(this, newState); } } } public final void setActivity(Activity activity) { mActivity = activity; if (mActivity != null) { mActivity.addOnWindowFocusChangeListener(this); } } @Override public void setAdapter(ListAdapter adapter) { if (adapter == null) { mAdapter = null; } else if (mForceHeaderListAdapter || mHeaderViewInfos.size() > 0 || mFooterViewInfos.size() > 0) { mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, adapter, this); } else { mAdapter = new ListAdapterWrapper(adapter, this); } if (mAdapter != null) { mAdapterHasStableIds = mAdapter.hasStableIds(); if (mChoiceMode != CHOICE_MODE_NONE && mAdapterHasStableIds && mCheckedIdStates == null) { mCheckedIdStates = new LongSparseArray<Integer>(); } } if (mCheckStates != null) { mCheckStates.clear(); } if (mCheckedIdStates != null) { mCheckedIdStates.clear(); } super.setAdapter(mAdapter); } @Override public void setChoiceMode(int choiceMode) { mChoiceMode = choiceMode; if (mChoiceActionMode != null) { mChoiceActionMode.finish(); mChoiceActionMode = null; } if (mChoiceMode != CHOICE_MODE_NONE) { if (mCheckStates == null) { mCheckStates = new SparseBooleanArray(); } if (mCheckedIdStates == null && mAdapter != null && mAdapter.hasStableIds()) { mCheckedIdStates = new LongSparseArray<Integer>(); } if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) { clearChoices(); setLongClickable(true); setEnableModalBackgroundWrapper(true); } } } public void setEnableModalBackgroundWrapper(boolean enableModalBackgroundWrapper) { if (enableModalBackgroundWrapper == mEnableModalBackgroundWrapper) { return; } mEnableModalBackgroundWrapper = enableModalBackgroundWrapper; if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } } public void setForceHeaderListAdapter(boolean forceHeaderListAdapter) { mForceHeaderListAdapter = forceHeaderListAdapter; } @Override public void setItemChecked(int position, boolean value) { if (mChoiceMode == CHOICE_MODE_NONE) { return; } if (value && mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode == null) { mChoiceActionMode = startActionMode(mMultiChoiceModeCallback); } if (mChoiceMode == CHOICE_MODE_MULTIPLE || mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) { boolean oldValue = mCheckStates.get(position); mCheckStates.put(position, value); if (mCheckedIdStates != null && mAdapter.hasStableIds()) { if (value) { mCheckedIdStates.put(mAdapter.getItemId(position), position); } else { mCheckedIdStates.delete(mAdapter.getItemId(position)); } } if (oldValue != value) { if (value) { mCheckedItemCount++; } else { mCheckedItemCount } } if (mChoiceActionMode != null) { final long id = mAdapter.getItemId(position); mMultiChoiceModeCallback.onItemCheckedStateChanged(mChoiceActionMode, position, id, value); } } else { boolean updateIds = mCheckedIdStates != null && mAdapter.hasStableIds(); if (value || isItemChecked(position)) { mCheckStates.clear(); if (updateIds) { mCheckedIdStates.clear(); } } if (value) { mCheckStates.put(position, true); if (updateIds) { mCheckedIdStates.put(mAdapter.getItemId(position), position); } mCheckedItemCount = 1; } else if (mCheckStates.size() == 0 || !mCheckStates.valueAt(0)) { mCheckedItemCount = 0; } } updateOnScreenCheckedViews(); invalidateViews(); } public void setMultiChoiceModeListener( org.holoeverywhere.widget.ListView.MultiChoiceModeListener listener) { if (mMultiChoiceModeCallback == null) { mMultiChoiceModeCallback = new MultiChoiceModeWrapper(); } mMultiChoiceModeCallback.setWrapped(listener); } @Override public void setOnItemLongClickListener(OnItemLongClickListener listener) { mOnItemLongClickListenerWrapper.setWrapped(listener); } @Override public void setOnScrollListener(OnScrollListener l) { super.setOnScrollListener(mOnScrollListener = l); } @SuppressLint("NewApi") protected final void setStateOnView(View child, boolean value) { if (child instanceof Checkable) { ((Checkable) child).setChecked(value); } else if (USE_ACTIVATED) { child.setActivated(value); } } @Override public boolean showContextMenuForChild(View originalView) { final int longPressPosition = getPositionForView(originalView); if (longPressPosition >= 0) { final long longPressId = mAdapter.getItemId(longPressPosition); boolean handled = false; if (mOnItemLongClickListenerWrapper.wrapped != null) { handled = mOnItemLongClickListenerWrapper.wrapped.onItemLongClick(GridView.this, originalView, longPressPosition, longPressId); } if (!handled) { mContextMenuInfo = createContextMenuInfo(getChildAt(longPressPosition - getFirstVisiblePosition()), longPressPosition, longPressId); handled = super.showContextMenuForChild(originalView); } return handled; } return false; } public ActionMode startActionMode(ActionMode.Callback callback) { if (mActivity != null) { return mActivity.startActionMode(callback); } throw new RuntimeException("HoloEverywhere.ListView (" + this + ") don't have reference on Activity"); } private void updateOnScreenCheckedViews() { if (mCheckStates == null) { return; } final int firstPos = getFirstVisiblePosition(); final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); final int position = firstPos + i; final boolean value = mCheckStates.get(position); setStateOnView(child, value); } } }
package cx2x.xcodeml.xelement; /** * The XexprModel represents the exprModel (9.4) element in XcodeML * intermediate representation. * * Elements: * - Required: on of the followings elements: * - FintConstant (XintConstant), FrealConstant (XrealConstant), * FcomplexConstant (XcomplexConstant), FcharacterConstant * (XcharacterConstant), FlogicalConstant (XlogicalConstant) * - FarrayConstructor TODO, FstructConstructor TODO * - Var (Xvar) * - FarrayRef (XarrayRef), FcharacterRef TODO, FmemberRef TODO, * FcoArrayRef TODO, varRef (XvarRef) * - functionCall (XfunctionCall) * - plusExpr, minusExpr, mulExpr, divExpr, FpowerExpr, FconcatExpr * - logEQExpr, logNEQExpr, logGEExpr, logGTExpr, logLEExpr, logLTExpr, * logAndExpr, logOrExpr, logEQVExpr, logNEQVExpr, logNotExpr TODO ALL * - unaryMinusExpr, userBinaryExpr, userUnaryExpr TODO * - FdoLoop (Xdo) * * @author clementval */ public class XexprModel { private XbaseElement _element = null; /** * Constructs a new XexprModel object from an XbaseElement. * @param baseElement The root XbaseElement. */ public XexprModel(XbaseElement baseElement){ _element = baseElement; } /** * Get the root XbaseElement. * @return The root XbaseElement. */ public XbaseElement getElement(){ return _element; } /** * Set the root XbaseElement. * @param element The root XbaseElement. */ public void setElement(XbaseElement element){ _element = element; } /** * Check whether the exprModel is a var. * @return True if the exprModel is a var. False otherwise. */ public boolean isVar(){ return isOfType(Xvar.class); } /** * Get the exprModel as var. * @return Xvar object if the exprModel is a var. Null otherwise. */ public Xvar getVar(){ if(isVar()){ return (Xvar)_element; } return null; } /** * Check whether the exprModel is an integer constant. * @return True if the exprModel is an integer constant. False otherwise. */ public boolean isIntConst(){ return isOfType(XintConstant.class); } /** * Check whether the exprModel is a real constant. * @return True if the exprModel is a real constant. False otherwise. */ public boolean isRealConst(){ return isOfType(XrealConstant.class); } /** * Check whether the exprModel is a character constant. * @return True if the exprModel is a character constant. False otherwise. */ public boolean isCharConst(){ return isOfType(XcharacterConstant.class); } /** * Check whether the exprModel is a logical constant. * @return True if the exprModel is a logical constant. False otherwise. */ public boolean isLogicalConst(){ return isOfType(XlogicalConstant.class); } /** * Check whether the exprModel is a complex constant. * @return True if the exprModel is a complex constant. False otherwise. */ public boolean isComplexConst(){ return isOfType(XcomplexConstant.class); } /** * Check whether the exprModel is a constant type. * @return True if the exprModel is a constant type. False otherwise. */ public boolean isConstant() { return isIntConst() || isRealConst() || isLogicalConst() || isCharConst() || isComplexConst(); } /** * Get the constant element. * @return the constant element. */ public Xconstant getConstant(){ if(isConstant()){ return (Xconstant)_element; } return null; } /** * Check whether the exprModel is a function call. * @return True if the exprModel is a function call. False otherwise. */ public boolean isFctCall(){ return isOfType(XfunctionCall.class); } /** * Get the exprModel as integer constant. * @return XintConstant object if the exprModel is an integer constant. * Null otherwise. */ public XintConstant getIntConstant(){ if(isIntConst()){ return (XintConstant)_element; } return null; } /** * Get the exprModel as logical constant. * @return XlogicalConstant object if the exprModel is a logical constant. * Null otherwise. */ public XlogicalConstant getLogicalConstant(){ if(isLogicalConst()){ return (XlogicalConstant)_element; } return null; } /** * Check whether the exprModel is of a given class type. * @param type Class to be checked (Derived type of XbaseElement). * @return True if the exprModel is of the given class. False otherwise. */ private <T extends XbaseElement> boolean isOfType(Class<T> type){ return _element != null && type.isInstance(_element); } }
package ly.count.android.sdk; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class Countly { private String DEFAULT_COUNTLY_SDK_VERSION_STRING = "20.11.10"; /** * Used as request meta data on every request */ private String DEFAULT_COUNTLY_SDK_NAME = "java-native-android"; /** * Current version of the Count.ly Android SDK as a displayable string. */ public String COUNTLY_SDK_VERSION_STRING = DEFAULT_COUNTLY_SDK_VERSION_STRING; /** * Used as request meta data on every request */ public String COUNTLY_SDK_NAME = DEFAULT_COUNTLY_SDK_NAME; /** * Default string used in the begin session metrics if the * app version cannot be found. */ protected static final String DEFAULT_APP_VERSION = "1.0"; /** * Tag used in all logging in the Count.ly SDK. */ public static final String TAG = "Countly"; /** * Countly internal logger * Should not be used outside of the SDK * No guarantees of not breaking functionality * Exposed only for the SDK push implementation */ public ModuleLog L = new ModuleLog(); /** * Broadcast sent when consent set is changed */ public static final String CONSENT_BROADCAST = "ly.count.android.sdk.Countly.CONSENT_BROADCAST"; /** * Determines how many custom events can be queued locally before * an attempt is made to submit them to a Count.ly server. */ private static int EVENT_QUEUE_SIZE_THRESHOLD = 100; /** * How often onTimer() is called. */ private static final long TIMER_DELAY_IN_SECONDS = 60; protected static List<String> publicKeyPinCertificates; protected static List<String> certificatePinCertificates; /** * Enum used in Countly.initMessaging() method which controls what kind of * app installation it is. Later (in Countly Dashboard or when calling Countly API method), * you'll be able to choose whether you want to send a message to test devices, * or to production ones. */ public enum CountlyMessagingMode { TEST, PRODUCTION, } /** * Enum used in Countly.initMessaging() method which controls what kind of * messaging provider is in use in current app installation. */ public enum CountlyMessagingProvider { FCM, // Firebase HMS, // Huawei } private static class SingletonHolder { @SuppressLint("StaticFieldLeak") static final Countly instance = new Countly(); } ConnectionQueue connectionQueue_; private final ScheduledExecutorService timerService_; private ScheduledFuture<?> timerFuture = null; private int activityCount_; boolean disableUpdateSessionRequests_ = false;//todo, move to module after 'setDisableUpdateSessionRequests' is removed boolean sdkIsInitialised = false; //w - warnings //e - errors //i - user accessible calls and important SDK internals //d - regular SDK internals //v - spammy SDK internals private boolean enableLogging_; Context context_; //Internal modules for functionality grouping List<ModuleBase> modules = new ArrayList<>(); ModuleCrash moduleCrash = null; ModuleEvents moduleEvents = null; ModuleViews moduleViews = null; ModuleRatings moduleRatings = null; ModuleSessions moduleSessions = null; ModuleRemoteConfig moduleRemoteConfig = null; ModuleAPM moduleAPM = null; ModuleConsent moduleConsent = null; ModuleDeviceId moduleDeviceId = null; ModuleLocation moduleLocation = null; ModuleFeedback moduleFeedback = null; //reference to countly store CountlyStore countlyStore; //user data access public static UserData userData; //view related things boolean autoViewTracker = false;//todo, move to module after "setViewTracking" is removed boolean automaticTrackingShouldUseShortName = false;//flag for using short names | todo, move to module after setter is removed //if set to true, it will automatically download remote configs on module startup boolean remoteConfigAutomaticUpdateEnabled = false;//todo, move to module after setter is removed RemoteConfigCallback remoteConfigInitCallback = null;//todo, move to module after setter is removed //overrides private boolean isHttpPostForced = false;//when true, all data sent to the server will be sent using HTTP POST //app crawlers private boolean shouldIgnoreCrawlers = true;//ignore app crawlers by default private boolean deviceIsAppCrawler = false;//by default assume that device is not a app crawler @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") private final List<String> appCrawlerNames = new ArrayList<>(Arrays.asList("Calypso AppCrawler"));//List against which device name is checked to determine if device is app crawler //push related private boolean addMetadataToPushIntents = false;// a flag that indicates if metadata should be added to push notification intents //internal flags private boolean calledAtLeastOnceOnStart = false;//flag for if the onStart function has been called at least once //attribution protected boolean isAttributionEnabled = true; protected boolean isBeginSessionSent = false; //custom request header fields Map<String, String> requestHeaderCustomValues; static long applicationStart = System.currentTimeMillis(); //GDPR protected boolean requiresConsent = false; final Map<String, Boolean> featureConsentValues = new HashMap<>(); private final Map<String, String[]> groupedFeatures = new HashMap<>(); final List<String> collectedConsentChanges = new ArrayList<>(); Boolean delayedPushConsent = null;//if this is set, consent for push has to be set before finishing init and sending push changes boolean delayedLocationErasure = false;//if location needs to be cleared at the end of init String[] locationFallback;//temporary used until location can't be set before init private boolean appLaunchDeepLink = true; CountlyConfig config_ = null; public static class CountlyFeatureNames { public static final String sessions = "sessions"; public static final String events = "events"; public static final String views = "views"; //public static final String scrolls = "scrolls"; //public static final String clicks = "clicks"; //public static final String forms = "forms"; public static final String location = "location"; public static final String crashes = "crashes"; public static final String attribution = "attribution"; public static final String users = "users"; public static final String push = "push"; public static final String starRating = "star-rating"; public static final String apm = "apm"; public static final String feedback = "feedback"; public static final String remoteConfig = "remote-config"; //public static final String accessoryDevices = "accessory-devices"; } //a list of valid feature names that are used for checking protected final String[] validFeatureNames = new String[] { CountlyFeatureNames.sessions, CountlyFeatureNames.events, CountlyFeatureNames.views, CountlyFeatureNames.location, CountlyFeatureNames.crashes, CountlyFeatureNames.attribution, CountlyFeatureNames.users, CountlyFeatureNames.push, CountlyFeatureNames.starRating, CountlyFeatureNames.remoteConfig, CountlyFeatureNames.apm, CountlyFeatureNames.feedback }; /** * Returns the Countly singleton. */ public static Countly sharedInstance() { return SingletonHolder.instance; } /** * Constructs a Countly object. * Creates a new ConnectionQueue and initializes the session timer. */ Countly() { timerService_ = Executors.newSingleThreadScheduledExecutor(); staticInit(); } private void staticInit() { connectionQueue_ = new ConnectionQueue(); Countly.userData = new UserData(connectionQueue_); startTimerService(timerService_, timerFuture, TIMER_DELAY_IN_SECONDS); } private void startTimerService(ScheduledExecutorService service, ScheduledFuture<?> previousTimer, long timerDelay) { if (previousTimer != null && !previousTimer.isCancelled()) { previousTimer.cancel(false); } //minimum delay of 1 second //maximum delay if 10 minutes if (timerDelay < 1) { timerDelay = 1; } else if (timerDelay > 600) { timerDelay = 600; } timerFuture = service.scheduleWithFixedDelay(new Runnable() { @Override public void run() { onTimer(); } }, timerDelay, timerDelay, TimeUnit.SECONDS); } public Countly init(final Context context, final String serverURL, final String appKey) { return init(context, serverURL, appKey, null, DeviceId.Type.OPEN_UDID); } public Countly init(final Context context, final String serverURL, final String appKey, final String deviceID) { return init(context, serverURL, appKey, deviceID, null); } public synchronized Countly init(final Context context, final String serverURL, final String appKey, final String deviceID, DeviceId.Type idMode) { return init(context, serverURL, appKey, deviceID, idMode, -1, null, null, null, null); } public synchronized Countly init(final Context context, String serverURL, final String appKey, final String deviceID, DeviceId.Type idMode, int starRatingLimit, final CountlyStarRating.RatingCallback starRatingCallback, String starRatingTextTitle, String starRatingTextMessage, String starRatingTextDismiss) { CountlyConfig config = new CountlyConfig(); config.setContext(context).setServerURL(serverURL).setAppKey(appKey).setDeviceId(deviceID) .setStarRatingTextTitle(starRatingTextTitle).setStarRatingTextMessage(starRatingTextMessage) .setStarRatingTextDismiss(starRatingTextDismiss) .setIdMode(idMode).setStarRatingSessionLimit(starRatingLimit).setStarRatingCallback(new StarRatingCallback() { @Override public void onRate(int rating) { if (starRatingCallback != null) { starRatingCallback.onRate(rating); } } @Override public void onDismiss() { if (starRatingCallback != null) { starRatingCallback.onDismiss(); } } }); return init(config); } /** * Initializes the Countly SDK. Call from your main Activity's onCreate() method. * Must be called before other SDK methods can be used. * To initialise the SDK, you must pass a CountlyConfig object that contains * all the necessary information for setting up the SDK * * @param config contains all needed information to init SDK */ public synchronized Countly init(CountlyConfig config) { if (config == null) { throw new IllegalArgumentException("Can't init SDK with 'null' config"); } //enable logging if (config.loggingEnabled) { //enable logging before any potential logging calls setLoggingEnabled(true); } L.SetListener(config.providedLogCallback); L.d("[Init] Initializing Countly [" + COUNTLY_SDK_NAME + "] SDK version [" + COUNTLY_SDK_VERSION_STRING + "]"); if (config.context == null) { if (config.application != null) { L.d("[Init] No explicit context provided. Using context from the provided application class"); config.context = config.application; } else { throw new IllegalArgumentException("valid context is required in Countly init, but was provided 'null'"); } } else { L.d("[Init] Using explicitly provided context"); } if (!UtilsNetworking.isValidURL(config.serverURL)) { throw new IllegalArgumentException("valid serverURL is required"); } //enable unhandled crash reporting if (config.enableUnhandledCrashReporting) { enableCrashReporting(); } //react to given consent if (config.shouldRequireConsent) { setRequiresConsent(true); if (config.enabledFeatureNames == null) { L.i("[Init] Consent has been required but no consent was given during init"); } else { setConsentInternal(config.enabledFeatureNames, true); } } if (config.serverURL.charAt(config.serverURL.length() - 1) == '/') { L.v("[Init] Removing trailing '/' from provided server url"); config.serverURL = config.serverURL.substring(0, config.serverURL.length() - 1);//removing trailing '/' from server url } if (config.appKey == null || config.appKey.length() == 0) { throw new IllegalArgumentException("valid appKey is required, but was provided either 'null' or empty String"); } if (config.application == null) { L.w("[Init] Initialising the SDK without providing the application class is deprecated"); } if (config.deviceID != null && config.deviceID.length() == 0) { //device ID is provided but it's a empty string throw new IllegalArgumentException("valid deviceID is required, but was provided as empty String"); } if (config.idMode == DeviceId.Type.TEMPORARY_ID) { throw new IllegalArgumentException("Temporary_ID type can't be provided during init"); } if (config.deviceID == null && config.idMode == null) { //device ID was not provided and no preferred mode specified. Choosing default config.idMode = DeviceId.Type.OPEN_UDID; } if (config.idMode == DeviceId.Type.DEVELOPER_SUPPLIED && config.deviceID == null) { throw new IllegalArgumentException("Valid device ID has to be provided with the Developer_Supplied device ID type"); } if (config.deviceID == null && config.idMode == DeviceId.Type.ADVERTISING_ID && !AdvertisingIdAdapter.isAdvertisingIdAvailable()) { //choosing advertising ID as type, but it's available on this device L.e("valid deviceID is required because Advertising ID is not available (you need to include Google Play services 4.0+ into your project)"); return this; } if (isLoggingEnabled()) { String halfAppKey = config.appKey.substring(0, config.appKey.length() / 2); L.d("[Init] SDK initialised with the URL:[" + config.serverURL + "] and first half of the appKey:[" + halfAppKey + "]"); } if (sdkIsInitialised && (!connectionQueue_.getServerURL().equals(config.serverURL) || !connectionQueue_.getAppKey().equals(config.appKey) || !DeviceId.deviceIDEqualsNullSafe(config.deviceID, config.idMode, connectionQueue_.getDeviceId()))) { //not sure if this needed L.e("Countly cannot be reinitialized with different values"); return this; } if (L.logEnabled()) { L.i("[Init] Checking init parameters"); L.i("[Init] Is consent required? [" + requiresConsent + "]"); // Context class hierarchy // Context //|- ContextWrapper //|- - Application //|- - ContextThemeWrapper //|- - - - Activity //|- - Service //|- - - IntentService Class contextClass = config.context.getClass(); Class contextSuperClass = contextClass.getSuperclass(); String contextText = "[Init] Provided Context [" + config.context.getClass().getSimpleName() + "]"; if (contextSuperClass != null) { contextText += ", it's superclass: [" + contextSuperClass.getSimpleName() + "]"; } L.i(contextText); } //set internal context, it's allowed to be changed on the second init call context_ = config.context.getApplicationContext(); // if we get here and eventQueue_ != null, init is being called again with the same values, // so there is nothing to do, because we are already initialized with those values if (!sdkIsInitialised) { L.d("[Init] About to init internal systems"); config_ = config; if (config.sessionUpdateTimerDelay != null) { //if we need to change the timer delay, do that first L.d("[Init] Setting custom session update timer delay, [" + config.sessionUpdateTimerDelay + "]"); startTimerService(timerService_, timerFuture, config.sessionUpdateTimerDelay); } //set or create the CountlyStore if (config.countlyStore != null) { //we are running a test and using a mock object countlyStore = config.countlyStore; } else { countlyStore = new CountlyStore(config.context, L); config.setCountlyStore(countlyStore); } if (config.storageProvider == null) { // outside of tests this should be null config.storageProvider = config.countlyStore; } else { L.d("[Init] Custom event storage provider was provided"); } if (config.eventQueueProvider == null) { config.eventQueueProvider = countlyStore; } else { L.d("[Init] Custom event queue provider was provided"); } //check legacy access methods if (locationFallback != null && config.locationCountyCode == null && config.locationCity == null && config.locationLocation == null && config.locationIpAddress == null) { //if the fallback was set and config did not contain any location, use the fallback info // { country_code, city, gpsCoordinates, ipAddress }; config.locationCountyCode = locationFallback[0]; config.locationCity = locationFallback[1]; config.locationLocation = locationFallback[2]; config.locationIpAddress = locationFallback[3]; } //perform data migration if needed MigrationHelper mHelper = new MigrationHelper(config.storageProvider, L); mHelper.doWork(); //initialise modules moduleConsent = new ModuleConsent(this, config); moduleDeviceId = new ModuleDeviceId(this, config); moduleCrash = new ModuleCrash(this, config); moduleEvents = new ModuleEvents(this, config); moduleViews = new ModuleViews(this, config); moduleRatings = new ModuleRatings(this, config); moduleSessions = new ModuleSessions(this, config); moduleRemoteConfig = new ModuleRemoteConfig(this, config); moduleAPM = new ModuleAPM(this, config); moduleLocation = new ModuleLocation(this, config); moduleFeedback = new ModuleFeedback(this, config); modules.clear(); modules.add(moduleConsent); modules.add(moduleDeviceId); modules.add(moduleCrash); modules.add(moduleEvents); modules.add(moduleViews); modules.add(moduleRatings); modules.add(moduleSessions); modules.add(moduleRemoteConfig); modules.add(moduleAPM); modules.add(moduleLocation); modules.add(moduleFeedback); //add missing providers moduleConsent.eventProvider = config.eventProvider; moduleDeviceId.eventProvider = config.eventProvider; moduleCrash.eventProvider = config.eventProvider; L.i("[Init] Finished initialising modules"); //init other things L.d("[Init] Currently cached advertising ID [" + countlyStore.getCachedAdvertisingId() + "]"); AdvertisingIdAdapter.cacheAdvertisingID(config.context, countlyStore); addCustomNetworkRequestHeaders(config.customNetworkRequestHeaders); setHttpPostForced(config.httpPostForced); enableParameterTamperingProtectionInternal(config.tamperingProtectionSalt); setPushIntentAddMetadata(config.pushIntentAddMetadata); if (config.eventQueueSizeThreshold != null) { setEventQueueSizeToSend(config.eventQueueSizeThreshold); } if (config.publicKeyPinningCertificates != null) { enablePublicKeyPinning(Arrays.asList(config.publicKeyPinningCertificates)); } if (config.certificatePinningCertificates != null) { enableCertificatePinning(Arrays.asList(config.certificatePinningCertificates)); } if (config.enableAttribution != null) { setEnableAttribution(config.enableAttribution); } //app crawler check shouldIgnoreCrawlers = config.shouldIgnoreAppCrawlers; if (config.appCrawlerNames != null) { Collections.addAll(Arrays.asList(config.appCrawlerNames)); } checkIfDeviceIsAppCrawler(); //initialize networking queues connectionQueue_.L = L; connectionQueue_.consentProvider = moduleConsent; connectionQueue_.setServerURL(config.serverURL); connectionQueue_.setAppKey(config.appKey); connectionQueue_.setCountlyStore(countlyStore); connectionQueue_.setDeviceId(config.deviceIdInstance); connectionQueue_.setRequestHeaderCustomValues(requestHeaderCustomValues); connectionQueue_.setMetricOverride(config.metricOverride); connectionQueue_.setContext(context_); sdkIsInitialised = true; //AFTER THIS POINT THE SDK IS COUNTED AS INITIALISED //set global application listeners if (config.application != null) { config.application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (L.logEnabled()) { L.d("[Countly] onActivityCreated, " + activity.getClass().getSimpleName()); } for (ModuleBase module : modules) { module.callbackOnActivityCreated(activity); } } @Override public void onActivityStarted(Activity activity) { if (L.logEnabled()) { L.d("[Countly] onActivityStarted, " + activity.getClass().getSimpleName()); } for (ModuleBase module : modules) { module.callbackOnActivityStarted(activity); } } @Override public void onActivityResumed(Activity activity) { if (L.logEnabled()) { L.d("[Countly] onActivityResumed, " + activity.getClass().getSimpleName()); } for (ModuleBase module : modules) { module.callbackOnActivityResumed(activity); } } @Override public void onActivityPaused(Activity activity) { if (L.logEnabled()) { L.d("[Countly] onActivityPaused, " + activity.getClass().getSimpleName()); } for (ModuleBase module : modules) { module.callbackOnActivityPaused(activity); } } @Override public void onActivityStopped(Activity activity) { if (L.logEnabled()) { L.d("[Countly] onActivityStopped, " + activity.getClass().getSimpleName()); } for (ModuleBase module : modules) { module.callbackOnActivityStopped(activity); } } @Override public void onActivitySaveInstanceState(Activity activity, Bundle bundle) { if (L.logEnabled()) { L.d("[Countly] onActivitySaveInstanceState, " + activity.getClass().getSimpleName()); } for (ModuleBase module : modules) { module.callbackOnActivitySaveInstanceState(activity); } } @Override public void onActivityDestroyed(Activity activity) { if (L.logEnabled()) { L.d("[Countly] onActivityDestroyed, " + activity.getClass().getSimpleName()); } for (ModuleBase module : modules) { module.callbackOnActivityDestroyed(activity); } } }); /* config.application.registerComponentCallbacks(new ComponentCallbacks() { @Override public void onConfigurationChanged(Configuration configuration) { } @Override public void onLowMemory() { } }); */ } for (ModuleBase module : modules) { module.initFinished(config); } L.i("[Init] Finished initialising SDK"); } else { //if this is not the first time we are calling init L.i("[Init] Getting in the 'else' block"); // context is allowed to be changed on the second init call connectionQueue_.setContext(context_); } return this; } /** * Checks whether Countly.init has been already called. * * @return true if Countly is ready to use */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") public synchronized boolean isInitialized() { return sdkIsInitialised; } /** * Immediately disables session &amp; event tracking and clears any stored session &amp; event data. * This API is useful if your app has a tracking opt-out switch, and you want to immediately * disable tracking when a user opts out. * * This will destroy all stored data */ public synchronized void halt() { L.i("Halting Countly!"); sdkIsInitialised = false; L.SetListener(null); if (connectionQueue_ != null) { final CountlyStore countlyStore = connectionQueue_.getCountlyStore(); if (countlyStore != null) { countlyStore.clear(); } connectionQueue_.setContext(null); connectionQueue_.setServerURL(null); connectionQueue_.setAppKey(null); connectionQueue_.setCountlyStore(null); connectionQueue_ = null; } activityCount_ = 0; for (ModuleBase module : modules) { module.halt(); } modules.clear(); moduleCrash = null; moduleViews = null; moduleEvents = null; moduleRatings = null; moduleSessions = null; moduleRemoteConfig = null; moduleConsent = null; moduleAPM = null; moduleDeviceId = null; moduleLocation = null; moduleFeedback = null; COUNTLY_SDK_VERSION_STRING = DEFAULT_COUNTLY_SDK_VERSION_STRING; COUNTLY_SDK_NAME = DEFAULT_COUNTLY_SDK_NAME; staticInit(); } synchronized void notifyDeviceIdChange() { L.d("Notifying modules that device ID changed"); for (ModuleBase module : modules) { module.deviceIdChanged(); } } /** * Tells the Countly SDK that an Activity has started. Since Android does not have an * easy way to determine when an application instance starts and stops, you must call this * method from every one of your Activity's onStart methods for accurate application * session tracking. */ public synchronized void onStart(Activity activity) { if (L.logEnabled()) { String activityName = "NULL ACTIVITY PROVIDED"; if (activity != null) { activityName = activity.getClass().getSimpleName(); } L.d("Countly onStart called, name:[" + activityName + "], [" + activityCount_ + "] -> [" + (activityCount_ + 1) + "] activities now open"); } appLaunchDeepLink = false; if (!isInitialized()) { L.e("init must be called before onStart"); return; } ++activityCount_; if (activityCount_ == 1 && !moduleSessions.manualSessionControlEnabled) { //if we open the first activity //and we are not using manual session control, //begin a session moduleSessions.beginSessionInternal(); } //check if there is an install referrer data String referrer = ReferrerReceiver.getReferrer(context_); L.d("Checking referrer: " + referrer); if (referrer != null) { connectionQueue_.sendReferrerData(referrer); ReferrerReceiver.deleteReferrer(context_); } CrashDetails.inForeground(); for (ModuleBase module : modules) { module.onActivityStarted(activity); } calledAtLeastOnceOnStart = true; } /** * Tells the Countly SDK that an Activity has stopped. Since Android does not have an * easy way to determine when an application instance starts and stops, you must call this * method from every one of your Activity's onStop methods for accurate application * session tracking. * unbalanced calls to onStart/onStop are detected */ public synchronized void onStop() { L.d("Countly onStop called, [" + activityCount_ + "] -> [" + (activityCount_ - 1) + "] activities now open"); if (!isInitialized()) { L.e("init must be called before onStop"); return; } if (activityCount_ == 0) { L.e("must call onStart before onStop"); return; } --activityCount_; if (activityCount_ == 0 && !moduleSessions.manualSessionControlEnabled) { // if we don't use manual session control // Called when final Activity is stopped. // Sends an end session event to the server, also sends any unsent custom events. moduleSessions.endSessionInternal(null); } CrashDetails.inBackground(); for (ModuleBase module : modules) { module.onActivityStopped(); } } public synchronized void onConfigurationChanged(Configuration newConfig) { L.d("Calling [onConfigurationChanged]"); if (!isInitialized()) { L.e("init must be called before onConfigurationChanged"); return; } for (ModuleBase module : modules) { module.onConfigurationChanged(newConfig); } } /** * DON'T USE THIS!!!! */ public void onRegistrationId(String registrationId, CountlyMessagingMode mode) { onRegistrationId(registrationId, mode, CountlyMessagingProvider.FCM); } /** * DON'T USE THIS!!!! */ public void onRegistrationId(String registrationId, CountlyMessagingMode mode, CountlyMessagingProvider provider) { if (!getConsent(CountlyFeatureNames.push)) { return; } connectionQueue_.tokenSession(registrationId, mode, provider); } /** * Changes current device id type to the one specified in parameter. Closes current session and * reopens new one with new id. Doesn't merge user profiles on the server * * @param type Device ID type to change to * @param deviceId Optional device ID for a case when type = DEVELOPER_SPECIFIED */ public void changeDeviceIdWithoutMerge(DeviceId.Type type, String deviceId) { L.d("Calling [changeDeviceIdWithoutMerge] with type and ID"); if (!isInitialized()) { L.e("init must be called before changeDeviceIdWithoutMerge"); return; } moduleDeviceId.changeDeviceIdWithoutMerge(type, deviceId); } /** * Changes current device id to the one specified in parameter. Merges user profile with new id * (if any) with old profile. * * @param deviceId new device id */ public void changeDeviceIdWithMerge(String deviceId) { L.d("Calling [changeDeviceIdWithMerge] only with ID"); if (!isInitialized()) { L.e("init must be called before changeDeviceIdWithMerge"); return; } moduleDeviceId.changeDeviceIdWithMerge(deviceId); } /** * Changes current device id type to the one specified in parameter. Closes current session and * reopens new one with new id. Doesn't merge user profiles on the server * * @param type Device ID type to change to * @param deviceId Optional device ID for a case when type = DEVELOPER_SPECIFIED * @deprecated use 'changeDeviceIdWithoutMerge' */ public void changeDeviceId(DeviceId.Type type, String deviceId) { L.d("Calling [changeDeviceId] with type and ID"); if (!isInitialized()) { L.e("init must be called before changeDeviceId"); return; } moduleDeviceId.changeDeviceIdWithoutMerge(type, deviceId); } /** * Changes current device id to the one specified in parameter. Merges user profile with new id * (if any) with old profile. * * @param deviceId new device id * @deprecated use 'changeDeviceIdWithMerge' */ public void changeDeviceId(String deviceId) { L.d("Calling [changeDeviceId] only with ID"); if (!isInitialized()) { L.e("init must be called before changeDeviceId"); return; } moduleDeviceId.changeDeviceIdWithMerge(deviceId); } /** * Records a custom event with no segmentation values, a count of one and a sum of zero. * * @param key name of the custom event, required, must not be the empty string * @deprecated record events through 'Countly.sharedInstance().events()' */ public void recordEvent(final String key) { recordEvent(key, null, 1, 0); } /** * Records a custom event with no segmentation values, the specified count, and a sum of zero. * * @param key name of the custom event, required, must not be the empty string * @param count count to associate with the event, should be more than zero * @deprecated record events through 'Countly.sharedInstance().events()' */ public void recordEvent(final String key, final int count) { recordEvent(key, null, count, 0); } /** * Records a custom event with no segmentation values, and the specified count and sum. * * @param key name of the custom event, required, must not be the empty string * @param count count to associate with the event, should be more than zero * @param sum sum to associate with the event * @deprecated record events through 'Countly.sharedInstance().events()' */ public void recordEvent(final String key, final int count, final double sum) { recordEvent(key, null, count, sum); } /** * Records a custom event with the specified segmentation values and count, and a sum of zero. * * @param key name of the custom event, required, must not be the empty string * @param segmentation segmentation dictionary to associate with the event, can be null * @param count count to associate with the event, should be more than zero * @deprecated record events through 'Countly.sharedInstance().events()' */ public void recordEvent(final String key, final Map<String, String> segmentation, final int count) { recordEvent(key, segmentation, count, 0); } /** * Records a custom event with the specified values. * * @param key name of the custom event, required, must not be the empty string * @param segmentation segmentation dictionary to associate with the event, can be null * @param count count to associate with the event, should be more than zero * @param sum sum to associate with the event * segmentation contains null or empty keys or values * @deprecated record events through 'Countly.sharedInstance().events()' */ public synchronized void recordEvent(final String key, final Map<String, String> segmentation, final int count, final double sum) { recordEvent(key, segmentation, count, sum, 0); } /** * Records a custom event with the specified values. * * @param key name of the custom event, required, must not be the empty string * @param segmentation segmentation dictionary to associate with the event, can be null * @param count count to associate with the event, should be more than zero * @param sum sum to associate with the event * @param dur duration of an event * segmentation contains null or empty keys or values * @deprecated record events through 'Countly.sharedInstance().events()' */ public synchronized void recordEvent(final String key, final Map<String, String> segmentation, final int count, final double sum, final double dur) { recordEvent(key, segmentation, null, null, count, sum, dur); } /** * Records a custom event with the specified values. * * @param key name of the custom event, required, must not be the empty string * @param segmentation segmentation dictionary to associate with the event, can be null * @param count count to associate with the event, should be more than zero * @param sum sum to associate with the event * @param dur duration of an event * segmentation contains null or empty keys or values * @deprecated record events through 'Countly.sharedInstance().events()' */ public synchronized void recordEvent(final String key, final Map<String, String> segmentation, final Map<String, Integer> segmentationInt, final Map<String, Double> segmentationDouble, final int count, final double sum, final double dur) { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before recordEvent"); return; } Map<String, Object> segmentationGroup = new HashMap<>(); if (segmentation != null) { segmentationGroup.putAll(segmentation); } if (segmentationInt != null) { segmentationGroup.putAll(segmentationInt); } if (segmentationDouble != null) { segmentationGroup.putAll(segmentationDouble); } events().recordEvent(key, segmentationGroup, count, sum, dur); } /** * Enable or disable automatic view tracking * * @param enable boolean for the state of automatic view tracking * @return Returns link to Countly for call chaining * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setViewTracking(boolean enable) { L.d("Enabling automatic view tracking"); autoViewTracker = enable; return this; } /** * Check state of automatic view tracking * * @return boolean - true if enabled, false if disabled * @deprecated use 'Countly.sharedInstance().views().isAutomaticViewTrackingEnabled()' */ public synchronized boolean isViewTrackingEnabled() { return autoViewTracker; } /** * Record a view manually, without automatic tracking * or track view that is not automatically tracked * like fragment, Message box or transparent Activity * * @param viewName String - name of the view * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().views().recordView()' */ public synchronized Countly recordView(String viewName) { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before recordView"); return this; } return recordView(viewName, null); } /** * Record a view manually, without automatic tracking * or track view that is not automatically tracked * like fragment, Message box or transparent Activity * * @param viewName String - name of the view * @param viewSegmentation Map<String, Object> - segmentation that will be added to the view, set 'null' if none should be added * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().views().recordView()' */ public synchronized Countly recordView(String viewName, Map<String, Object> viewSegmentation) { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before recordView"); return this; } return moduleViews.recordViewInternal(viewName, viewSegmentation); } /** * Disable sending of location data * * @return Returns link to Countly for call chaining * @deprecated Use 'Countly.sharedInstance().location().disableLocation()' */ public synchronized Countly disableLocation() { L.d("Disabling location"); if (!isInitialized()) { L.w("The use of 'disableLocation' before init is deprecated, use CountlyConfig instead of this"); return this; } location().disableLocation(); return this; } /** * Set location parameters. If they are set before begin_session, they will be sent as part of it. * If they are set after, then they will be sent as a separate request. * If this is called after disabling location, it will enable it. * * @param country_code ISO Country code for the user's country * @param city Name of the user's city * @param gpsCoordinates comma separate lat and lng values. For example, "56.42345,123.45325" * @return Returns link to Countly for call chaining * @deprecated Use 'Countly.sharedInstance().location().setLocation()' */ public synchronized Countly setLocation(String country_code, String city, String gpsCoordinates, String ipAddress) { L.d("Setting location parameters, cc[" + country_code + "] cy[" + city + "] gps[" + gpsCoordinates + "] ip[" + ipAddress + "]"); if (!isInitialized()) { L.w("The use of 'setLocation' before init is deprecated, use CountlyConfig instead of this"); return this; } if (isInitialized()) { location().setLocation(country_code, city, gpsCoordinates, ipAddress); } else { //use fallback locationFallback = new String[] { country_code, city, gpsCoordinates, ipAddress }; } return this; } /** * Sets custom segments to be reported with crash reports * In custom segments you can provide any string key values to segments crashes by * * @param segments Map&lt;String, String&gt; key segments and their values * @return Returns link to Countly for call chaining * @deprecated set this through CountlyConfig during init */ public synchronized Countly setCustomCrashSegments(Map<String, String> segments) { L.d("Calling setCustomCrashSegments"); if (segments == null) { return this; } Map<String, Object> segm = new HashMap<>(); segm.putAll(segments); setCustomCrashSegmentsInternal(segm); return this; } /** * Sets custom segments to be reported with crash reports * In custom segments you can provide any string key values to segments crashes by * * @param segments Map&lt;String, Object&gt; key segments and their values * todo move to module after 'setCustomCrashSegments' is removed */ synchronized void setCustomCrashSegmentsInternal(Map<String, Object> segments) { L.d("[ModuleCrash] Calling setCustomCrashSegmentsInternal"); if (!getConsent(Countly.CountlyFeatureNames.crashes)) { return; } if (segments != null) { Utils.removeUnsupportedDataTypes(segments); CrashDetails.setCustomSegments(segments); } } /** * Add crash breadcrumb like log record to the log that will be send together with crash report * * @param record String a bread crumb for the crash report * @return Returns link to Countly for call chaining * @deprecated use crashes().addCrashBreadcrumb */ public synchronized Countly addCrashBreadcrumb(String record) { return crashes().addCrashBreadcrumb(record); } /** * Log handled exception to report it to server as non fatal crash * * @param exception Exception to log * @return Returns link to Countly for call chaining * @deprecated use crashes().recordHandledException */ public synchronized Countly recordHandledException(Exception exception) { return moduleCrash.recordExceptionInternal(exception, true, null); } /** * Log handled exception to report it to server as non fatal crash * * @param exception Throwable to log * @return Returns link to Countly for call chaining * @deprecated use crashes().recordHandledException */ public synchronized Countly recordHandledException(Throwable exception) { return moduleCrash.recordExceptionInternal(exception, true, null); } /** * Log unhandled exception to report it to server as fatal crash * * @param exception Exception to log * @return Returns link to Countly for call chaining * @deprecated use crashes().recordUnhandledException */ public synchronized Countly recordUnhandledException(Exception exception) { return moduleCrash.recordExceptionInternal(exception, false, null); } /** * Log unhandled exception to report it to server as fatal crash * * @param exception Throwable to log * @return Returns link to Countly for call chaining * @deprecated use crashes().recordUnhandledException */ public synchronized Countly recordUnhandledException(Throwable exception) { return moduleCrash.recordExceptionInternal(exception, false, null); } /** * Enable crash reporting to send unhandled crash reports to server * * @return Returns link to Countly for call chaining * @deprecated use CountlyConfig during init to set this */ public synchronized Countly enableCrashReporting() { L.d("Enabling unhandled crash reporting"); //get default handler final Thread.UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { L.d("Uncaught crash handler triggered"); if (getConsent(CountlyFeatureNames.crashes)) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); //add other threads if (moduleCrash.recordAllThreads) { moduleCrash.addAllThreadInformationToCrash(pw); } String exceptionString = sw.toString(); //check if it passes the crash filter if (!moduleCrash.crashFilterCheck(exceptionString)) { Countly.sharedInstance().connectionQueue_.sendCrashReport(exceptionString, false, false, null); } } //if there was another handler before if (oldHandler != null) { //notify it also oldHandler.uncaughtException(t, e); } } }; Thread.setDefaultUncaughtExceptionHandler(handler); return this; } /** * Start timed event with a specified key * * @param key name of the custom event, required, must not be the empty string or null * @return true if no event with this key existed before and event is started, false otherwise * @deprecated use events().startEvent */ public synchronized boolean startEvent(final String key) { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before recordEvent"); return false; } return events().startEvent(key); } /** * End timed event with a specified key * * @param key name of the custom event, required, must not be the empty string or null * @return true if event with this key has been previously started, false otherwise * @deprecated use events().endEvent */ public synchronized boolean endEvent(final String key) { return endEvent(key, null, 1, 0); } /** * End timed event with a specified key * * @param key name of the custom event, required, must not be the empty string * @param segmentation segmentation dictionary to associate with the event, can be null * @param count count to associate with the event, should be more than zero * @param sum sum to associate with the event * @return true if event with this key has been previously started, false otherwise * segmentation contains null or empty keys or values * @deprecated use events().endEvent */ public synchronized boolean endEvent(final String key, final Map<String, String> segmentation, final int count, final double sum) { return endEvent(key, segmentation, null, null, count, sum); } /** * End timed event with a specified key * * @param key name of the custom event, required, must not be the empty string * @param segmentation segmentation dictionary to associate with the event, can be null * @param count count to associate with the event, should be more than zero * @param sum sum to associate with the event * @return true if event with this key has been previously started, false otherwise * segmentation contains null or empty keys or values * @deprecated use events().endEvent */ public synchronized boolean endEvent(final String key, final Map<String, String> segmentation, final Map<String, Integer> segmentationInt, final Map<String, Double> segmentationDouble, final int count, final double sum) { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before recordEvent"); return false; } Map<String, Object> segmentationGroup = new HashMap<>(); if (segmentation != null) { segmentationGroup.putAll(segmentation); } if (segmentationInt != null) { segmentationGroup.putAll(segmentationInt); } if (segmentationDouble != null) { segmentationGroup.putAll(segmentationDouble); } return events().endEvent(key, segmentationGroup, count, sum); } /** * Disable periodic session time updates. * By default, Countly will send a request to the server each 30 seconds with a small update * containing session duration time. This method allows you to disable such behavior. * Note that event updates will still be sent every 10 events or 30 seconds after event recording. * * @param disable whether or not to disable session time updates * @return Countly instance for easy method chaining * @deprecated set through countlyConfig */ public synchronized Countly setDisableUpdateSessionRequests(final boolean disable) { L.d("Disabling periodic session time updates"); disableUpdateSessionRequests_ = disable; return this; } /** * Sets whether debug logging is turned on or off. Logging is disabled by default. * * @param enableLogging true to enable logging, false to disable logging * @return Countly instance for easy method chaining * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setLoggingEnabled(final boolean enableLogging) { enableLogging_ = enableLogging; L.d("Enabling logging"); return this; } /** * Check if logging has been enabled internally in the SDK * * @return true means "yes" */ public synchronized boolean isLoggingEnabled() { return enableLogging_; } /** * @param salt * @return * @deprecated use CountlyConfig (setParameterTamperingProtectionSalt) during init to set this */ public synchronized Countly enableParameterTamperingProtection(String salt) { L.d("Enabling tamper protection"); enableParameterTamperingProtectionInternal(salt); return this; } /** * Use by both the external call and config call * * @param salt */ private synchronized void enableParameterTamperingProtectionInternal(String salt) { ConnectionProcessor.salt = salt; } /** * Returns if the countly sdk onStart function has been called at least once * * @return true - yes, it has, false - no it has not */ public synchronized boolean hasBeenCalledOnStart() { return calledAtLeastOnceOnStart; } /** * @param size * @return * @deprecated use countly config to set this */ public synchronized Countly setEventQueueSizeToSend(int size) { L.d("Setting event queue size: [" + size + "]"); if (size < 1) { L.d("[setEventQueueSizeToSend] queue size can't be less than zero"); size = 1; } EVENT_QUEUE_SIZE_THRESHOLD = size; return this; } public static void onCreate(Activity activity) { Intent launchIntent = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName()); if (sharedInstance().L.logEnabled()) { String mainClassName = "[VALUE NULL]"; if (launchIntent != null && launchIntent.getComponent() != null) { mainClassName = launchIntent.getComponent().getClassName(); } sharedInstance().L.d("[onCreate] Activity created: " + activity.getClass().getName() + " ( main is " + mainClassName + ")"); } Intent intent = activity.getIntent(); if (intent != null) { Uri data = intent.getData(); if (data != null) { if (sharedInstance().L.logEnabled()) { sharedInstance().L.d("Data in activity created intent: " + data + " (appLaunchDeepLink " + sharedInstance().appLaunchDeepLink + ") "); } if (sharedInstance().appLaunchDeepLink) { DeviceInfo.deepLink = data.toString(); } } } } /** * Check if events from event queue need to be added to the request queue * They will be sent either if the exceed the Threshold size or if their sending is forced */ protected void sendEventsIfNeeded(boolean forceSendingEvents) { int eventsInEventQueue = config_.storageProvider.getEventQueueSize(); L.v("[Countly] forceSendingEvents, forced:[" + forceSendingEvents + "], event count:[" + eventsInEventQueue + "]"); if ((forceSendingEvents && eventsInEventQueue > 0) || eventsInEventQueue >= EVENT_QUEUE_SIZE_THRESHOLD) { connectionQueue_.recordEvents(config_.storageProvider.getEventsForRequestAndEmptyEventQueue()); } } /** * Called every 60 seconds to send a session heartbeat to the server. Does nothing if there * is not an active application session. */ synchronized void onTimer() { L.v("[onTimer] Calling heartbeat, Activity count:[" + activityCount_ + "]"); if (isInitialized()) { final boolean hasActiveSession = activityCount_ > 0; if (hasActiveSession) { if (!moduleSessions.manualSessionControlEnabled) { moduleSessions.updateSessionInternal(); } } //on every timer tick we collect all events and attempt to send requests sendEventsIfNeeded(true); connectionQueue_.tick(); } } public static Countly enablePublicKeyPinning(List<String> certificates) { sharedInstance().L.i("Enabling public key pinning"); publicKeyPinCertificates = certificates; return Countly.sharedInstance(); } public static Countly enableCertificatePinning(List<String> certificates) { Countly.sharedInstance().L.i("Enabling certificate pinning"); certificatePinCertificates = certificates; return Countly.sharedInstance(); } /** * Shows the star rating dialog * * @param activity the activity that will own the dialog * @param callback callback for the star rating dialog "rate" and "dismiss" events * @deprecated call this trough 'Countly.sharedInstance().remoteConfig()' */ public void showStarRating(Activity activity, final CountlyStarRating.RatingCallback callback) { if (!isInitialized()) { L.e("Can't call this function before init has been called"); return; } if (callback == null) { ratings().showStarRating(activity, null); } else { ratings().showStarRating(activity, new StarRatingCallback() { @Override public void onRate(int rating) { callback.onRate(rating); } @Override public void onDismiss() { callback.onDismiss(); } }); } } /** * Set's the text's for the different fields in the star rating dialog. Set value null if for some field you want to keep the old value * * @param starRatingTextTitle dialog's title text * @param starRatingTextMessage dialog's message text * @param starRatingTextDismiss dialog's dismiss buttons text * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setStarRatingDialogTexts(String starRatingTextTitle, String starRatingTextMessage, String starRatingTextDismiss) { if (!isInitialized()) { L.e("Can't call this function before init has been called"); return this; } L.d("Setting star rating texts"); moduleRatings.setStarRatingInitConfig(connectionQueue_.getCountlyStore(), -1, starRatingTextTitle, starRatingTextMessage, starRatingTextDismiss); return this; } /** * Set if the star rating should be shown automatically * * @param IsShownAutomatically set it true if you want to show the app star rating dialog automatically for each new version after the specified session amount * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setIfStarRatingShownAutomatically(boolean IsShownAutomatically) { if (!isInitialized()) { L.e("Can't call this function before init has been called"); return this; } L.d("Setting to show star rating automatically: [" + IsShownAutomatically + "]"); moduleRatings.setShowDialogAutomatically(connectionQueue_.getCountlyStore(), IsShownAutomatically); return this; } /** * Set if the star rating is shown only once per app lifetime * * @param disableAsking set true if you want to disable asking the app rating for each new app version (show it only once per apps lifetime) * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setStarRatingDisableAskingForEachAppVersion(boolean disableAsking) { if (!isInitialized()) { L.e("Can't call this function before init has been called"); return this; } L.d("Setting to disable showing of star rating for each app version:[" + disableAsking + "]"); moduleRatings.setStarRatingDisableAskingForEachAppVersion(connectionQueue_.getCountlyStore(), disableAsking); return this; } /** * Set after how many sessions the automatic star rating will be shown for each app version * * @param limit app session amount for the limit * @return Returns link to Countly for call chaining * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setAutomaticStarRatingSessionLimit(int limit) { if (!isInitialized()) { L.e("Can't call this function before init has been called"); return this; } L.d("Setting automatic star rating session limit: [" + limit + "]"); moduleRatings.setStarRatingInitConfig(connectionQueue_.getCountlyStore(), limit, null, null, null); return this; } /** * Returns the session limit set for automatic star rating * * @deprecated use 'Countly.sharedInstance().ratings().getAutomaticStarRatingSessionLimit()' */ public int getAutomaticStarRatingSessionLimit() { if (!isInitialized()) { L.e("Can't call this function before init has been called"); return -1; } int sessionLimit = ModuleRatings.getAutomaticStarRatingSessionLimitInternal(connectionQueue_.getCountlyStore()); L.d("Getting automatic star rating session limit: [" + sessionLimit + "]"); return sessionLimit; } /** * Returns how many sessions has star rating counted internally for the current apps version * * @deprecated use 'Countly.sharedInstance().ratings().getCurrentVersionsSessionCount()' */ public int getStarRatingsCurrentVersionsSessionCount() { if (!isInitialized()) { L.e("Can't call this function before init has been called"); return -1; } return ratings().getCurrentVersionsSessionCount(); } /** * Set the automatic star rating session count back to 0 * * @deprecated use 'Countly.sharedInstance().ratings().getCurrentVersionsSessionCount()' to get achieve this */ public void clearAutomaticStarRatingSessionCount() { if (!isInitialized()) { L.e("Can't call this function before init has been called"); return; } ratings().clearAutomaticStarRatingSessionCount(); } /** * Set if the star rating dialog is cancellable * * @param isCancellable set this true if it should be cancellable * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setIfStarRatingDialogIsCancellable(boolean isCancellable) { if (!isInitialized()) { L.e("Can't call this function before init has been called"); return this; } L.d("Setting if star rating is cancellable: [" + isCancellable + "]"); moduleRatings.setIfRatingDialogIsCancellableInternal(connectionQueue_.getCountlyStore(), isCancellable); return this; } /** * Set the override for forcing to use HTTP POST for all connections to the server * * @param isItForced the flag for the new status, set "true" if you want it to be forced * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setHttpPostForced(boolean isItForced) { L.d("Setting if HTTP POST is forced: [" + isItForced + "]"); isHttpPostForced = isItForced; return this; } /** * Get the status of the override for HTTP POST * * @return return "true" if HTTP POST ir forced */ public boolean isHttpPostForced() { return isHttpPostForced; } private void checkIfDeviceIsAppCrawler() { String deviceName = DeviceInfo.getDevice(); for (int a = 0; a < appCrawlerNames.size(); a++) { if (deviceName.equals(appCrawlerNames.get(a))) { deviceIsAppCrawler = true; return; } } } /** * Set if Countly SDK should ignore app crawlers * * @param shouldIgnore if crawlers should be ignored * @deprecated use CountlyConfig to set this */ public synchronized Countly setShouldIgnoreCrawlers(boolean shouldIgnore) { L.d("Setting if should ignore app crawlers: [" + shouldIgnore + "]"); shouldIgnoreCrawlers = shouldIgnore; return this; } /** * Add app crawler device name to the list of names that should be ignored * * @param crawlerName the name to be ignored * @deprecated use CountlyConfig to set this */ public void addAppCrawlerName(String crawlerName) { L.d("Adding app crawler name: [" + crawlerName + "]"); if (crawlerName != null && !crawlerName.isEmpty()) { appCrawlerNames.add(crawlerName); } } /** * Return if current device is detected as a app crawler * * @return returns if devices is detected as a app crawler */ public boolean isDeviceAppCrawler() { return deviceIsAppCrawler; } /** * Return if the countly sdk should ignore app crawlers */ public boolean ifShouldIgnoreCrawlers() { if (!isInitialized()) { L.e("init must be called before ifShouldIgnoreCrawlers"); return false; } return shouldIgnoreCrawlers; } /** * Returns the device id used by countly for this device * * @return device ID */ public synchronized String getDeviceID() { if (!isInitialized()) { L.e("init must be called before getDeviceID"); return null; } L.d("[Countly] Calling 'getDeviceID'"); return connectionQueue_.getDeviceId().getId(); } /** * Returns the type of the device ID used by countly for this device. * * @return device ID type */ public synchronized DeviceId.Type getDeviceIDType() { if (!isInitialized()) { L.e("init must be called before getDeviceID"); return null; } L.d("[Countly] Calling 'getDeviceIDType'"); return connectionQueue_.getDeviceId().getType(); } /** * @param shouldAddMetadata * @return * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setPushIntentAddMetadata(boolean shouldAddMetadata) { L.d("[Countly] Setting if adding metadata to push intents: [" + shouldAddMetadata + "]"); addMetadataToPushIntents = shouldAddMetadata; return this; } /** * Set if automatic activity tracking should use short names * * @param shouldUseShortName set true if you want short names * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setAutoTrackingUseShortName(boolean shouldUseShortName) { L.d("[Countly] Setting if automatic view tracking should use short names: [" + shouldUseShortName + "]"); automaticTrackingShouldUseShortName = shouldUseShortName; return this; } /** * Set if attribution should be enabled * * @param shouldEnableAttribution set true if you want to enable it, set false if you want to disable it * @deprecated use CountlyConfig to set this */ public synchronized Countly setEnableAttribution(boolean shouldEnableAttribution) { L.d("[Countly] Setting if attribution should be enabled"); isAttributionEnabled = shouldEnableAttribution; return this; } /** * @param shouldRequireConsent * @return * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setRequiresConsent(boolean shouldRequireConsent) { L.d("[Countly] Setting if consent should be required, [" + shouldRequireConsent + "]"); requiresConsent = shouldRequireConsent; return this; } /** * Special things needed to be done during setting push consent * * @param consentValue The value of push consent */ void doPushConsentSpecialAction(boolean consentValue) { L.d("[Countly] Doing push consent special action: [" + consentValue + "]"); connectionQueue_.getCountlyStore().setConsentPush(consentValue); } /** * Actions needed to be done for the consent related location erasure */ void doLocationConsentSpecialErasure() { moduleLocation.resetLocationValues(); connectionQueue_.sendLocation(true, null, null, null, null); } /** * Check if the given name is a valid feature name * * @param name the name of the feature to be tested if it is valid * @return returns true if value is contained in feature name array */ private boolean isValidFeatureName(String name) { for (String fName : validFeatureNames) { if (fName.equals(name)) { return true; } } return false; } /** * Prepare features into json format * * @param features the names of features that are about to be changed * @param consentValue the value for the new consent * @return provided consent changes in json format */ private String formatConsentChanges(String[] features, boolean consentValue) { StringBuilder preparedConsent = new StringBuilder(); preparedConsent.append("{"); for (int a = 0; a < features.length; a++) { if (a != 0) { preparedConsent.append(","); } preparedConsent.append('"'); preparedConsent.append(features[a]); preparedConsent.append('"'); preparedConsent.append(':'); preparedConsent.append(consentValue); } preparedConsent.append("}"); return preparedConsent.toString(); } /** * Group multiple features into a feature group * * @param groupName name of the consent group * @param features array of feature to be added to the consent group * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().consent().createFeatureGroup' */ public synchronized Countly createFeatureGroup(String groupName, String[] features) { L.d("[Countly] Creating a feature group with the name: [" + groupName + "]"); if (!isInitialized()) { L.w("[Countly] Calling 'createFeatureGroup' before initialising the SDK is deprecated!"); } groupedFeatures.put(groupName, features); return this; } /** * Set the consent of a feature group * * @param groupName name of the consent group * @param isConsentGiven the value that should be set for this consent group * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().consent().setConsent' */ public synchronized Countly setConsentFeatureGroup(String groupName, boolean isConsentGiven) { L.v("[Countly] Setting consent for feature group: [" + groupName + "] with value: [" + isConsentGiven + "]"); if (!isInitialized()) { L.w("[Countly] Calling 'setConsentFeatureGroup' before initialising the SDK is deprecated!"); } if (!groupedFeatures.containsKey(groupName)) { L.d("[Countly] Trying to set consent for a unknown feature group: [" + groupName + "]"); return this; } setConsentInternal(groupedFeatures.get(groupName), isConsentGiven); return this; } /** * Set the consent of a feature * * @param featureNames feature names for which consent should be changed * @param isConsentGiven the consent value that should be set * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().consent().setConsent' or set consent through CountlyConfig */ public synchronized Countly setConsent(String[] featureNames, boolean isConsentGiven) { if (!isInitialized()) { L.w("[Countly] Calling 'setConsent' before initialising the SDK is deprecated!"); } return setConsentInternal(featureNames, isConsentGiven); } Countly setConsentInternal(String[] featureNames, boolean isConsentGiven) { final boolean isInit = isInitialized();//is the SDK initialized if (!requiresConsent) { //if consent is not required, ignore all calls to it return this; } if (featureNames == null) { L.w("[Countly] Calling setConsent with null featureNames!"); return this; } boolean previousSessionsConsent = false; if (featureConsentValues.containsKey(CountlyFeatureNames.sessions)) { previousSessionsConsent = featureConsentValues.get(CountlyFeatureNames.sessions); } boolean previousLocationConsent = false; if (featureConsentValues.containsKey(CountlyFeatureNames.location)) { previousLocationConsent = featureConsentValues.get(CountlyFeatureNames.location); } boolean currentSessionConsent = previousSessionsConsent; for (String featureName : featureNames) { L.d("[Countly] Setting consent for feature: [" + featureName + "] with value: [" + isConsentGiven + "]"); if (!isValidFeatureName(featureName)) { L.w("[Countly] Given feature: [" + featureName + "] is not a valid name, ignoring it"); continue; } featureConsentValues.put(featureName, isConsentGiven); //special actions for each feature switch (featureName) { case CountlyFeatureNames.push: if (isInit) { //if the SDK is already initialized, do the special action now doPushConsentSpecialAction(isConsentGiven); } else { //do the special action later delayedPushConsent = isConsentGiven; } break; case CountlyFeatureNames.sessions: currentSessionConsent = isConsentGiven; break; case CountlyFeatureNames.location: if (previousLocationConsent && !isConsentGiven) { //if consent is about to be removed if (isInit) { doLocationConsentSpecialErasure(); } else { delayedLocationErasure = true; } } break; case CountlyFeatureNames.apm: if (!isConsentGiven) { //in case APM consent is removed, clear custom and network traces moduleAPM.clearNetworkTraces(); moduleAPM.cancelAllTracesInternal(); } } } String formattedChanges = formatConsentChanges(featureNames, isConsentGiven); if (isInit && (collectedConsentChanges.size() == 0)) { //if countly is initialized and collected changes are already sent, send consent now connectionQueue_.sendConsentChanges(formattedChanges); context_.sendBroadcast(new Intent(CONSENT_BROADCAST)); //if consent has changed and it was set to true if ((previousSessionsConsent != currentSessionConsent) && currentSessionConsent) { //if consent was given, we need to begin the session if (isBeginSessionSent) { //if the first timing for a beginSession call was missed, send it again if (!moduleSessions.manualSessionControlEnabled) { moduleSessions.beginSessionInternal(); } } } //if consent was changed and set to false if ((previousSessionsConsent != currentSessionConsent) && !currentSessionConsent) { if (!isBeginSessionSent) { //if session consent was removed and first begins session was not sent //that means that we might not have sent the initially given location information if (moduleLocation.anyValidLocation()) { moduleLocation.sendCurrentLocation(); } } } } else { // if countly is not initialized, collect and send it after it is collectedConsentChanges.add(formattedChanges); } return this; } /** * Give the consent to a feature * * @param featureNames the names of features for which consent should be given * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().consent().giveConsent(featureNames)' or set consent through CountlyConfig */ public synchronized Countly giveConsent(String[] featureNames) { L.i("[Countly] Giving consent for features named: [" + Arrays.toString(featureNames) + "]"); if (!isInitialized()) { L.w("[Countly] Calling 'giveConsent' before initialising the SDK is deprecated!"); } setConsentInternal(featureNames, true); return this; } /** * Remove the consent of a feature * * @param featureNames the names of features for which consent should be removed * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().consent().removeConsent(featureNames)' */ public synchronized Countly removeConsent(String[] featureNames) { L.d("[Countly] Removing consent for features named: [" + Arrays.toString(featureNames) + "]"); if (!isInitialized()) { L.w("Calling 'removeConsent' before initialising the SDK is deprecated!"); } setConsentInternal(featureNames, false); return this; } /** * Remove consent for all features * * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().consent().removeConsentAll()' */ public synchronized Countly removeConsentAll() { L.d("[Countly] Removing consent for all features"); if (!isInitialized()) { L.w("Calling 'removeConsentAll' before initialising the SDK is deprecated!"); } removeConsent(validFeatureNames); return this; } /** * Get the current consent state of a feature * * @param featureName the name of a feature for which consent should be checked * @return the consent value * @deprecated use 'Countly.sharedInstance().consent().getConsent(featureName)' */ public synchronized boolean getConsent(String featureName) { if (!requiresConsent) { //return true silently return true; } Boolean returnValue = featureConsentValues.get(featureName); if (returnValue == null) { returnValue = false; } L.v("[Countly] Returning consent for feature named: [" + featureName + "] [" + returnValue + "]"); return returnValue; } /** * Print the consent values of all features * * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().consent().checkAllConsent()' */ public synchronized Countly checkAllConsent() { L.d("[Countly] Checking and printing consent for All features"); L.d("[Countly] Is consent required? [" + requiresConsent + "]"); //make sure push consent has been added to the feature map getConsent(CountlyFeatureNames.push); StringBuilder sb = new StringBuilder(); for (String key : featureConsentValues.keySet()) { sb.append("Feature named [").append(key).append("], consent value: [").append(featureConsentValues.get(key)).append("]\n"); } L.d(sb.toString()); return this; } /** * Returns true if any consent has been given * * @return true - any consent has been given, false - no consent has been given * todo move to module */ protected boolean anyConsentGiven() { if (!requiresConsent) { //no consent required - all consent given return true; } for (String key : featureConsentValues.keySet()) { if (featureConsentValues.get(key)) { return true; } } return false; } /** * Show the rating dialog to the user * * @param widgetId ID that identifies this dialog * @return * @deprecated use 'Countly.sharedInstance().ratings().showFeedbackPopup' */ public synchronized Countly showFeedbackPopup(final String widgetId, final String closeButtonText, final Activity activity, final CountlyStarRating.FeedbackRatingCallback feedbackCallback) { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before showFeedbackPopup"); return this; } if (feedbackCallback == null) { ratings().showFeedbackPopup(widgetId, closeButtonText, activity, null); } else { ratings().showFeedbackPopup(widgetId, closeButtonText, activity, new FeedbackRatingCallback() { @Override public void callback(String error) { feedbackCallback.callback(error); } }); } return this; } /** * If enable, will automatically download newest remote config_ values on init. * * @param enabled set true for enabling it * @param feedbackCallback callback called after the update was done * @return * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setRemoteConfigAutomaticDownload(boolean enabled, final RemoteConfig.RemoteConfigCallback feedbackCallback) { L.d("[Countly] Setting if remote config Automatic download will be enabled, " + enabled); remoteConfigAutomaticUpdateEnabled = enabled; if (feedbackCallback != null) { remoteConfigInitCallback = new RemoteConfigCallback() { @Override public void callback(String error) { feedbackCallback.callback(error); } }; } return this; } /** * Manually update remote config_ values * * @param providedCallback * @deprecated use 'Countly.sharedInstance().remoteConfig().update(callback)' */ public void remoteConfigUpdate(final RemoteConfig.RemoteConfigCallback providedCallback) { L.d("[Countly] Manually calling to updateRemoteConfig"); if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before remoteConfigUpdate"); return; } if (providedCallback == null) { remoteConfig().update(null); } else { remoteConfig().update(new RemoteConfigCallback() { @Override public void callback(String error) { providedCallback.callback(error); } }); } } /** * Manual remote config_ update call. Will only update the keys provided. * * @param keysToInclude * @param providedCallback * @deprecated use 'Countly.sharedInstance().remoteConfig().updateForKeysOnly(keys, callback)' */ public void updateRemoteConfigForKeysOnly(String[] keysToInclude, final RemoteConfig.RemoteConfigCallback providedCallback) { L.d("[Countly] Manually calling to updateRemoteConfig with include keys"); if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before updateRemoteConfigForKeysOnly"); return; } if (providedCallback == null) { remoteConfig().updateForKeysOnly(keysToInclude, null); } else { remoteConfig().updateForKeysOnly(keysToInclude, new RemoteConfigCallback() { @Override public void callback(String error) { providedCallback.callback(error); } }); } } /** * Manual remote config_ update call. Will update all keys except the ones provided * * @param keysToExclude * @param providedCallback * @deprecated use 'Countly.sharedInstance().remoteConfig().updateExceptKeys(keys, callback)' */ public void updateRemoteConfigExceptKeys(String[] keysToExclude, final RemoteConfig.RemoteConfigCallback providedCallback) { L.i("[Countly] Manually calling to updateRemoteConfig with exclude keys"); if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before updateRemoteConfigExceptKeys"); return; } if (providedCallback == null) { remoteConfig().updateExceptKeys(keysToExclude, null); } else { remoteConfig().updateExceptKeys(keysToExclude, new RemoteConfigCallback() { @Override public void callback(String error) { providedCallback.callback(error); } }); } } /** * Get the stored value for the provided remote config_ key * * @param key * @return * @deprecated use 'Countly.sharedInstance().remoteConfig().getValueForKey(key)' */ public Object getRemoteConfigValueForKey(String key) { L.i("[Countly] Calling remoteConfigValueForKey"); if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before remoteConfigValueForKey"); return null; } return remoteConfig().getValueForKey(key); } /** * Clear all stored remote config_ values * * @deprecated use 'Countly.sharedInstance().remoteConfig().clearStoredValues();' */ public void remoteConfigClearValues() { L.i("[Countly] Calling remoteConfigClearValues"); if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before remoteConfigClearValues"); return; } remoteConfig().clearStoredValues(); } /** * Allows you to add custom header key/value pairs to each request * * @deprecated use CountlyConfig during init to set this */ public void addCustomNetworkRequestHeaders(Map<String, String> headerValues) { L.i("[Countly] Calling addCustomNetworkRequestHeaders"); requestHeaderCustomValues = headerValues; if (connectionQueue_ != null) { connectionQueue_.setRequestHeaderCustomValues(requestHeaderCustomValues); } } /** * Deletes all stored requests to server. * This includes events, crashes, views, sessions, etc * Call only if you don't need that information */ public void flushRequestQueues() { L.i("[Countly] Calling flushRequestQueues"); if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before flushRequestQueues"); return; } CountlyStore store = connectionQueue_.getCountlyStore(); int count = 0; while (true) { final String[] storedEvents = store.getRequests(); if (storedEvents == null || storedEvents.length == 0) { // currently no data to send, we are done for now break; } //remove stored data store.removeRequest(storedEvents[0]); count++; } L.d("[Countly] flushRequestQueues removed [" + count + "] requests"); } /** * Combine all events in event queue into a request and * attempt to process stored requests on demand */ public void doStoredRequests() { L.i("[Countly] Calling doStoredRequests"); if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before doStoredRequests"); return; } //combine all available events into a request sendEventsIfNeeded(true); //trigger the processing of the request queue connectionQueue_.tick(); } /** * Go through the request queue and replace the appKey of all requests with the current appKey */ synchronized public void requestQueueOverwriteAppKeys() { L.i("[Countly] Calling requestQueueOverwriteAppKeys"); if (!isInitialized()) { L.e("[Countly] Countly.sharedInstance().init must be called before requestQueueOverwriteAppKeys"); return; } List<String> filteredRequests = requestQueueReplaceWithAppKey(connectionQueue_.getCountlyStore().getRequests(), connectionQueue_.getAppKey()); if (filteredRequests != null) { config_.storageProvider.replaceRequestList(filteredRequests); doStoredRequests(); } } /** * Go through the request queue and delete all requests that don't have the current application key */ synchronized public void requestQueueEraseAppKeysRequests() { L.i("[Countly] Calling requestQueueEraseAppKeysRequests"); if (!isInitialized()) { L.e("[Countly] Countly.sharedInstance().init must be called before requestQueueEraseAppKeysRequests"); return; } List<String> filteredRequests = requestQueueRemoveWithoutAppKey(connectionQueue_.getCountlyStore().getRequests(), connectionQueue_.getAppKey()); config_.storageProvider.replaceRequestList(filteredRequests); doStoredRequests(); } synchronized List<String> requestQueueReplaceWithAppKey(String[] storedRequests, String targetAppKey) { try { List<String> filteredRequests = new ArrayList<>(); if (storedRequests == null || targetAppKey == null) { //early abort return filteredRequests; } String replacementPart = "app_key=" + UtilsNetworking.urlEncodeString(targetAppKey); for (String storedRequest : storedRequests) { if (storedRequest == null) { continue; } boolean found = false; String[] parts = storedRequest.split("&"); for (int b = 0; b < parts.length; b++) { if (parts[b].contains("app_key=")) { parts[b] = replacementPart; found = true; break; } } if (found) { //recombine and add StringBuilder stringBuilder = new StringBuilder(storedRequest.length()); for (int c = 0; c < parts.length; c++) { if (c != 0) { stringBuilder.append("&"); } stringBuilder.append(parts[c]); } filteredRequests.add(stringBuilder.toString()); } else { //pass through the old one filteredRequests.add(storedRequest); } } return filteredRequests; } catch (Exception ex) { //in case of failure, abort L.e("[Countly] Failed while overwriting appKeys, " + ex.toString()); return null; } } synchronized List<String> requestQueueRemoveWithoutAppKey(String[] storedRequests, String targetAppKey) { List<String> filteredRequests = new ArrayList<>(); if (storedRequests == null || targetAppKey == null) { //early abort return filteredRequests; } String searchablePart = "app_key=" + targetAppKey; for (String storedRequest : storedRequests) { if (storedRequest == null) { continue; } if (!storedRequest.contains(searchablePart)) { L.d("[requestQueueEraseAppKeysRequests] Found a entry to remove: [" + storedRequest + "]"); } else { filteredRequests.add(storedRequest); } } return filteredRequests; } /** * Go into temporary device ID mode * * @return */ public Countly enableTemporaryIdMode() { L.i("[Countly] Calling enableTemporaryIdMode"); if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before enableTemporaryIdMode"); return this; } moduleDeviceId.changeDeviceIdWithoutMerge(DeviceId.Type.TEMPORARY_ID, DeviceId.temporaryCountlyDeviceId); return this; } public ModuleCrash.Crashes crashes() { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before accessing crashes"); return null; } return moduleCrash.crashesInterface; } public ModuleEvents.Events events() { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before accessing events"); return null; } return moduleEvents.eventsInterface; } public ModuleViews.Views views() { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before accessing views"); return null; } return moduleViews.viewsInterface; } public ModuleRatings.Ratings ratings() { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before accessing ratings"); return null; } return moduleRatings.ratingsInterface; } public ModuleSessions.Sessions sessions() { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before accessing sessions"); return null; } return moduleSessions.sessionInterface; } public ModuleRemoteConfig.RemoteConfig remoteConfig() { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before accessing remote config"); return null; } return moduleRemoteConfig.remoteConfigInterface; } public ModuleAPM.Apm apm() { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before accessing apm"); return null; } return moduleAPM.apmInterface; } public ModuleConsent.Consent consent() { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before accessing consent"); return null; } return moduleConsent.consentInterface; } public ModuleLocation.Location location() { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before accessing location"); return null; } return moduleLocation.locationInterface; } public ModuleFeedback.Feedback feedback() { if (!isInitialized()) { L.e("Countly.sharedInstance().init must be called before accessing feedback"); return null; } return moduleFeedback.feedbackInterface; } public static void applicationOnCreate() { } // for unit testing ConnectionQueue getConnectionQueue() { return connectionQueue_; } void setConnectionQueue(final ConnectionQueue connectionQueue) { connectionQueue_ = connectionQueue; } ExecutorService getTimerService() { return timerService_; } long getPrevSessionDurationStartTime() { return moduleSessions.prevSessionDurationStartTime_; } void setPrevSessionDurationStartTime(final long prevSessionDurationStartTime) { moduleSessions.prevSessionDurationStartTime_ = prevSessionDurationStartTime; } int getActivityCount() { return activityCount_; } synchronized boolean getDisableUpdateSessionRequests() { return disableUpdateSessionRequests_; } }
package org.cytoscape.internal.view; import static org.cytoscape.internal.util.ViewUtil.createUniqueKey; import static org.cytoscape.internal.util.ViewUtil.getTitle; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.GraphicsConfiguration; import java.awt.KeyboardFocusManager; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.AWTEventListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.beans.PropertyChangeEvent; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import org.cytoscape.application.swing.CySwingApplication; import org.cytoscape.internal.view.GridViewToggleModel.Mode; import org.cytoscape.internal.view.NetworkViewGrid.ThumbnailPanel; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.subnetwork.CySubNetwork; import org.cytoscape.service.util.CyServiceRegistrar; import org.cytoscape.task.create.CreateNetworkViewTaskFactory; import org.cytoscape.task.destroy.DestroyNetworkViewTaskFactory; import org.cytoscape.util.swing.LookAndFeelUtil; import org.cytoscape.view.model.CyNetworkView; import org.cytoscape.view.presentation.RenderingEngine; import org.cytoscape.view.presentation.RenderingEngineFactory; import org.cytoscape.view.presentation.property.BasicVisualLexicon; import org.cytoscape.work.swing.DialogTaskManager; @SuppressWarnings("serial") public class NetworkViewMainPanel extends JPanel { private JPanel contentPane; private final CardLayout cardLayout; private final NetworkViewGrid networkViewGrid; private final GridViewToggleModel gridViewToggleModel; /** Attached View Containers */ private final Map<CyNetworkView, NetworkViewContainer> allViewContainers; /** Attached View Containers */ private final Map<String, NetworkViewContainer> viewCards; /** Detached View Frames */ private final Map<String, NetworkViewFrame> viewFrames; private final Map<String, NetworkViewComparisonPanel> comparisonPanels; private final NullNetworkViewPanel nullViewPanel; private final Set<CyNetworkView> dirtyThumbnails; private NetworkViewFrame currentViewFrame; private final MousePressedAWTEventListener mousePressedAWTEventListener; private final CytoscapeMenus cyMenus; private final Comparator<CyNetworkView> viewComparator; private final CyServiceRegistrar serviceRegistrar; public NetworkViewMainPanel( final GridViewToggleModel gridViewToggleModel, final CytoscapeMenus cyMenus, final Comparator<CyNetworkView> viewComparator, final CyServiceRegistrar serviceRegistrar ) { this.gridViewToggleModel = gridViewToggleModel; this.cyMenus = cyMenus; this.viewComparator = viewComparator; this.serviceRegistrar = serviceRegistrar; allViewContainers = new HashMap<>(); viewCards = new LinkedHashMap<>(); viewFrames = new HashMap<>(); comparisonPanels = new HashMap<>(); dirtyThumbnails = new HashSet<>(); mousePressedAWTEventListener = new MousePressedAWTEventListener(); cardLayout = new CardLayout(); networkViewGrid = createNetworkViewGrid(); nullViewPanel = new NullNetworkViewPanel(gridViewToggleModel, serviceRegistrar); init(); } public RenderingEngine<CyNetwork> addNetworkView(final CyNetworkView view, final RenderingEngineFactory<CyNetwork> engineFactory, boolean showView) { if (isRendered(view)) return null; final GraphicsConfiguration gc = currentViewFrame != null ? currentViewFrame.getGraphicsConfiguration() : null; final NetworkViewContainer vc = new NetworkViewContainer(view, view.equals(getCurrentNetworkView()), engineFactory, gridViewToggleModel, serviceRegistrar); vc.getDetachViewButton().addActionListener((ActionEvent e) -> { detachNetworkView(view); }); vc.getReattachViewButton().addActionListener((ActionEvent e) -> { reattachNetworkView(view); }); vc.getViewTitleTextField().addActionListener((ActionEvent e) -> { changeCurrentViewTitle(vc); vc.requestFocusInWindow(); }); vc.getViewTitleTextField().addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) cancelViewTitleChange(vc); } }); vc.getViewTitleTextField().addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { changeCurrentViewTitle(vc); vc.requestFocusInWindow(); Toolkit.getDefaultToolkit().addAWTEventListener(mousePressedAWTEventListener, MouseEvent.MOUSE_EVENT_MASK); } @Override public void focusGained(FocusEvent e) { Toolkit.getDefaultToolkit().removeAWTEventListener(mousePressedAWTEventListener); } }); allViewContainers.put(view, vc); viewCards.put(vc.getName(), vc); networkViewGrid.addItem(vc.getRenderingEngine()); getContentPane().add(vc, vc.getName()); setDirtyThumbnail(view); if (showView) { if (isGridMode()) updateGrid(); else showViewContainer(vc.getName()); // If the latest focused view was in a detached frame, // detach the new one as well and put it in the same monitor if (gc != null) detachNetworkView(view, gc); } return vc.getRenderingEngine(); } public boolean isRendered(final CyNetworkView view) { return allViewContainers.containsKey(view); } public void remove(final CyNetworkView view) { if (view == null) return; allViewContainers.remove(view); dirtyThumbnails.remove(view); final Component[] components = getContentPane().getComponents(); if (components != null) { for (Component c : components) { if (c instanceof NetworkViewContainer) { final NetworkViewContainer vc = (NetworkViewContainer) c; if (vc.getNetworkView().equals(view)) { networkViewGrid.removeItems(Collections.singleton(vc.getRenderingEngine())); removeCard(vc); vc.dispose(); } } else if (c instanceof NetworkViewComparisonPanel) { final NetworkViewContainer vc = ((NetworkViewComparisonPanel) c).getContainer(view); if (vc != null) { networkViewGrid.removeItems(Collections.singleton(vc.getRenderingEngine())); ((NetworkViewComparisonPanel) c).removeView(view); // Show regular view container if only one remains if (((NetworkViewComparisonPanel) c).viewCount() < 2) endComparison(((NetworkViewComparisonPanel) c)); } } else if (c instanceof NullNetworkViewPanel) { if (view.equals(((NullNetworkViewPanel) c).getNetworkView())); nullViewPanel.update((CyNetwork) null); } } } final NetworkViewFrame frame = viewFrames.remove(createUniqueKey(view)); if (frame != null) { networkViewGrid.removeItems(Collections.singleton(frame.getRenderingEngine())); frame.getRootPane().getLayeredPane().removeAll(); frame.getRootPane().getContentPane().removeAll(); frame.dispose(); for (ComponentListener l : frame.getComponentListeners()) frame.removeComponentListener(l); for (WindowListener l : frame.getWindowListeners()) frame.removeWindowListener(l); } if (isGridMode()) updateGrid(); } public void setSelectedNetworkViews(final Collection<CyNetworkView> networkViews) { networkViewGrid.setSelectedNetworkViews(networkViews); } public List<CyNetworkView> getSelectedNetworkViews() { return networkViewGrid.getSelectedNetworkViews(); } public CyNetworkView getCurrentNetworkView() { return networkViewGrid.getCurrentNetworkView(); } public void setCurrentNetworkView(final CyNetworkView view) { final boolean currentViewChanged = networkViewGrid.setCurrentNetworkView(view); if (currentViewChanged) { if (view != null) { if (isGridMode()) { if (isGridVisible()) updateGrid(); else showGrid(true); } else { showViewContainer(createUniqueKey(view)); } if (isGridVisible()) networkViewGrid.scrollToCurrentItem(); } } } public void showNullView(final CyNetwork network) { if (isGridMode()) { if (isGridVisible()) updateGrid(); else showGrid(true); } else { showNullViewContainer(network); } } public void showGrid() { showGrid(false); } public void showGrid(final boolean scrollToCurrentItem) { if (!isGridMode()) { gridViewToggleModel.setMode(Mode.GRID); return; } if (!isGridVisible()) { cardLayout.show(getContentPane(), networkViewGrid.getName()); updateGrid(); } if (scrollToCurrentItem) networkViewGrid.scrollToCurrentItem(); } public void updateGrid() { networkViewGrid.update(networkViewGrid.getThumbnailSlider().getValue()); // TODO remove it when already updating after view changes networkViewGrid.getReattachAllViewsButton().setEnabled(!viewFrames.isEmpty()); final HashSet<CyNetworkView> dirtySet = new HashSet<>(dirtyThumbnails); for (CyNetworkView view : dirtySet) updateThumbnail(view); } public NetworkViewFrame detachNetworkView(final CyNetworkView view) { if (view == null) return null; final GraphicsConfiguration gc = serviceRegistrar.getService(CySwingApplication.class).getJFrame() .getGraphicsConfiguration(); return detachNetworkView(view, gc); } public NetworkViewFrame detachNetworkView(final CyNetworkView view, final GraphicsConfiguration gc) { if (view == null) return null; final NetworkViewContainer vc = getNetworkViewCard(view); if (vc == null) return null; // Show grid first to prevent changing the current view getNetworkViewGrid().setDetached(vc.getNetworkView(), true); // Remove the container from the card layout removeCard(vc); if (!isGridMode()) showNullViewContainer(view); // Create and show the frame final NetworkViewFrame frame = new NetworkViewFrame(vc, gc, cyMenus.createViewFrameToolBar(), serviceRegistrar); vc.setDetached(true); vc.setComparing(false); viewFrames.put(vc.getName(), frame); if (!LookAndFeelUtil.isAquaLAF()) frame.setJMenuBar(cyMenus.createDummyMenuBar()); frame.addWindowListener(new WindowAdapter() { @Override public void windowActivated(WindowEvent e) { // So Tunable dialogs open in the same monitor of the current frame serviceRegistrar.getService(DialogTaskManager.class).setExecutionContext(frame); currentViewFrame = frame; // This is necessary because the same menu bar is used by other frames, including CytoscapeDesktop final JMenuBar menuBar = cyMenus.getJMenuBar(); final Window window = SwingUtilities.getWindowAncestor(menuBar); if (!frame.equals(window)) { if (window instanceof JFrame && !LookAndFeelUtil.isAquaLAF()) { // Do this first, or the user could see the menu disappearing from the out-of-focus windows final JMenuBar dummyMenuBar = cyMenus.createDummyMenuBar(); ((JFrame) window).setJMenuBar(dummyMenuBar); dummyMenuBar.updateUI(); window.repaint(); } frame.setJMenuBar(menuBar); menuBar.updateUI(); } } @Override public void windowClosed(WindowEvent e) { reattachNetworkView(view); } @Override public void windowOpened(WindowEvent e) { // Add another window listener so subsequent Window Activated events trigger // a current view change action. // It has to be done this way (after the Open event), otherwise it can cause infinite loops // when detaching more than one view at the same time. frame.addWindowListener(new WindowAdapter() { @Override public void windowActivated(WindowEvent e) { setSelectedNetworkViews(Collections.singletonList(frame.getNetworkView())); setCurrentNetworkView(frame.getNetworkView()); } }); } }); int w = view.getVisualProperty(BasicVisualLexicon.NETWORK_WIDTH).intValue(); int h = view.getVisualProperty(BasicVisualLexicon.NETWORK_HEIGHT).intValue(); final boolean resizable = !view.isValueLocked(BasicVisualLexicon.NETWORK_WIDTH) && !view.isValueLocked(BasicVisualLexicon.NETWORK_HEIGHT); if (w > 0 && h > 0) frame.getContentPane().setPreferredSize(new Dimension(w, h)); frame.pack(); frame.setResizable(resizable); frame.setVisible(true); return frame; } public void reattachNetworkView(final CyNetworkView view) { final NetworkViewFrame frame = getNetworkViewFrame(view); if (frame != null) { final NetworkViewContainer vc = frame.getNetworkViewContainer(); frame.setJMenuBar(null); frame.dispose(); viewFrames.remove(vc.getName()); vc.setDetached(false); vc.setComparing(false); getContentPane().add(vc, vc.getName()); viewCards.put(vc.getName(), vc); getNetworkViewGrid().setDetached(view, false); if (!isGridMode() && view.equals(getCurrentNetworkView())) showViewContainer(vc.getName()); } } public void updateThumbnail(final CyNetworkView view) { networkViewGrid.updateThumbnail(view); dirtyThumbnails.remove(view); } public void updateThumbnailPanel(final CyNetworkView view, final boolean redraw) { // If the Grid is not visible, just flag this view as dirty. if (isGridVisible()) { final ThumbnailPanel tp = networkViewGrid.getItem(view); if (tp != null) tp.update(redraw); if (redraw) dirtyThumbnails.remove(view); } else { setDirtyThumbnail(view); } } public void setDirtyThumbnail(final CyNetworkView view) { dirtyThumbnails.add(view); } public void update(final CyNetworkView view) { final NetworkViewFrame frame = getNetworkViewFrame(view); if (frame != null) { // Frame Title frame.setTitle(getTitle(view)); // Frame Size final int w = view.getVisualProperty(BasicVisualLexicon.NETWORK_WIDTH).intValue(); final int h = view.getVisualProperty(BasicVisualLexicon.NETWORK_HEIGHT).intValue(); final boolean resizable = !view.isValueLocked(BasicVisualLexicon.NETWORK_WIDTH) && !view.isValueLocked(BasicVisualLexicon.NETWORK_HEIGHT); if (w > 0 && h > 0) { if (w != frame.getContentPane().getWidth() && h != frame.getContentPane().getHeight()) { frame.getContentPane().setPreferredSize(new Dimension(w, h)); frame.pack(); } } frame.setResizable(resizable); frame.update(); frame.invalidate(); } else if (!isGridVisible()) { final NetworkViewContainer vc = getNetworkViewCard(view); if (vc != null && vc.equals(getCurrentViewContainer())) vc.update(); final NetworkViewComparisonPanel cp = getComparisonPanel(view); if (cp != null) cp.update(); } updateThumbnailPanel(view, false); } public void updateSelectionInfo(final CyNetworkView view) { final NetworkViewContainer vc = getNetworkViewContainer(view); if (vc != null) vc.updateInfoPanel(); } public boolean isEmpty() { return allViewContainers.isEmpty(); } public NetworkViewGrid getNetworkViewGrid() { return networkViewGrid; } public Set<NetworkViewFrame> getAllNetworkViewFrames() { return new HashSet<>(viewFrames.values()); } public Set<NetworkViewContainer> getAllNetworkViewContainers() { return new HashSet<>(allViewContainers.values()); } public void showNullViewContainer(final CyNetwork net) { nullViewPanel.update(net instanceof CySubNetwork ? (CySubNetwork) net : null); showNullViewContainer(); } public void showNullViewContainer(final CyNetworkView view) { nullViewPanel.update(view); showNullViewContainer(); } public NetworkViewContainer showViewContainer(final CyNetworkView view) { return view != null ? showViewContainer(createUniqueKey(view)) : null; } private NetworkViewContainer showViewContainer(final String key) { NetworkViewContainer viewContainer = null; if (key != null) { viewContainer = viewCards.get(key); if (viewContainer != null) { cardLayout.show(getContentPane(), key); viewContainer.update(); currentViewFrame = null; } else { NetworkViewComparisonPanel foundCompPanel = null; for (NetworkViewComparisonPanel cp : comparisonPanels.values()) { if (key.equals(cp.getName())) { foundCompPanel = cp; } else { for (NetworkViewContainer vc : cp.getAllContainers()) { if (key.equals(vc.getName())) { foundCompPanel = cp; break; } } } } if (foundCompPanel != null) { cardLayout.show(getContentPane(), foundCompPanel.getName()); foundCompPanel.update(); currentViewFrame = null; viewContainer = foundCompPanel.getCurrentContainer(); } else { final NetworkViewFrame frame = getNetworkViewFrame(key); if (frame != null && !isGridMode()) showNullViewContainer(frame.getNetworkView()); } } } else { showGrid(); } return viewContainer; } private void showNullViewContainer() { cardLayout.show(getContentPane(), nullViewPanel.getName()); } private void showViewFrame(final NetworkViewFrame frame) { frame.setVisible(true); frame.toFront(); } protected void showComparisonPanel(final Set<CyNetworkView> views) { final CyNetworkView currentView = getCurrentNetworkView(); final String key = NetworkViewComparisonPanel.createUniqueKey(views); NetworkViewComparisonPanel cp = comparisonPanels.get(key); if (cp == null) { // End previous comparison panels that have one of the new selected views first for (CyNetworkView v : views) { cp = getComparisonPanel(v); if (cp != null) endComparison(cp); } final Set<NetworkViewContainer> containersToCompare = new LinkedHashSet<>(); // Then check if any of the views are detached for (CyNetworkView v : views) { final NetworkViewFrame frame = getNetworkViewFrame(v); if (frame != null) reattachNetworkView(v); final NetworkViewContainer vc = getNetworkViewCard(v); if (vc != null) { removeCard(vc); containersToCompare.add(vc); } } // Now we can create the comparison panel cp = new NetworkViewComparisonPanel(gridViewToggleModel, containersToCompare, currentView, serviceRegistrar); cp.getDetachComparedViewsButton().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final Component currentCard = getCurrentCard(); if (currentCard instanceof NetworkViewComparisonPanel) { final NetworkViewComparisonPanel cp = (NetworkViewComparisonPanel) currentCard; final CyNetworkView currentView = getCurrentNetworkView(); // Get the current view first final Set<CyNetworkView>views = cp.getAllNetworkViews(); // End comparison first endComparison(cp); // Then detach the views for (CyNetworkView v : views) detachNetworkView(v); // Set the original current view by bringing its frame to front, if it is detached final NetworkViewFrame frame = getNetworkViewFrame(currentView); if (frame != null) frame.toFront(); } } }); cp.addPropertyChangeListener("currentNetworkView", (PropertyChangeEvent evt) -> { final CyNetworkView newCurrentView = (CyNetworkView) evt.getNewValue(); setCurrentNetworkView(newCurrentView); }); getContentPane().add(cp, cp.getName()); comparisonPanels.put(cp.getName(), cp); } if (cp != null) { gridViewToggleModel.setMode(Mode.VIEW); showViewContainer(cp.getName()); } } protected void endComparison(final NetworkViewComparisonPanel cp) { if (cp != null) { removeCard(cp); cp.dispose(); // Don't forget to call this method! for (NetworkViewContainer vc : cp.getAllContainers()) { getContentPane().add(vc, vc.getName()); viewCards.put(vc.getName(), vc); } } } private NetworkViewComparisonPanel getComparisonPanel(final CyNetworkView view) { for (NetworkViewComparisonPanel cp : comparisonPanels.values()) { if (cp.contains(view)) return cp; } return null; } private void removeCard(final JComponent comp) { if (comp == null) return; if (comp instanceof NetworkViewContainer) viewCards.remove(((NetworkViewContainer) comp).getName()); else if (comp instanceof NetworkViewComparisonPanel) comparisonPanels.remove(((NetworkViewComparisonPanel) comp).getName()); cardLayout.removeLayoutComponent(comp); getContentPane().remove(comp); } protected boolean isGridMode() { return gridViewToggleModel.getMode() == Mode.GRID; } protected boolean isGridVisible() { return getCurrentCard() == networkViewGrid; } /** * @return The current attached View container */ protected NetworkViewContainer getCurrentViewContainer() { final Component c = getCurrentCard(); return c instanceof NetworkViewContainer ? (NetworkViewContainer) c : null; } protected Component getCurrentCard() { Component current = null; for (Component comp : getContentPane().getComponents()) { if (comp.isVisible()) current = comp; } return current; } private NetworkViewGrid createNetworkViewGrid() { final NetworkViewGrid nvg = new NetworkViewGrid(gridViewToggleModel, viewComparator, serviceRegistrar); nvg.getDetachSelectedViewsButton().addActionListener((ActionEvent e) -> { final List<ThumbnailPanel> selectedItems = networkViewGrid.getSelectedItems(); if (selectedItems != null) { // Get the current view first final CyNetworkView currentView = getCurrentNetworkView(); // Detach the views for (ThumbnailPanel tp : selectedItems) { if (getNetworkViewCard(tp.getNetworkView()) != null) detachNetworkView(tp.getNetworkView()); } // Set the original current view by bringing its frame to front, if it is detached final NetworkViewFrame frame = getNetworkViewFrame(currentView); if (frame != null) frame.toFront(); } }); nvg.getReattachAllViewsButton().addActionListener((ActionEvent e) -> { final Collection<NetworkViewFrame> allFrames = new ArrayList<>(viewFrames.values()); for (NetworkViewFrame f : allFrames) reattachNetworkView(f.getNetworkView()); }); nvg.getDestroySelectedViewsButton().addActionListener((ActionEvent e) -> { final List<CyNetworkView> selectedViews = getSelectedNetworkViews(); if (selectedViews != null && !selectedViews.isEmpty()) { final DialogTaskManager taskMgr = serviceRegistrar.getService(DialogTaskManager.class); final DestroyNetworkViewTaskFactory taskFactory = serviceRegistrar.getService(DestroyNetworkViewTaskFactory.class); taskMgr.execute(taskFactory.createTaskIterator(selectedViews)); } }); return nvg; } private void init() { setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, UIManager.getColor("Separator.foreground"))); setLayout(new BorderLayout()); add(getContentPane(), BorderLayout.CENTER); // Add Listeners nullViewPanel.getCreateViewButton().addActionListener((ActionEvent e) -> { if (nullViewPanel.getNetwork() instanceof CySubNetwork) { final CreateNetworkViewTaskFactory factory = serviceRegistrar.getService(CreateNetworkViewTaskFactory.class); final DialogTaskManager taskManager = serviceRegistrar.getService(DialogTaskManager.class); taskManager.execute(factory.createTaskIterator(Collections.singleton(nullViewPanel.getNetwork()))); } }); nullViewPanel.getInfoIconLabel().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (!e.isPopupTrigger() && nullViewPanel.getNetworkView() != null) { final NetworkViewFrame frame = getNetworkViewFrame(nullViewPanel.getNetworkView()); if (frame != null) showViewFrame(frame); } } }); nullViewPanel.getReattachViewButton().addActionListener((ActionEvent e) -> { if (nullViewPanel.getNetworkView() != null) reattachNetworkView(nullViewPanel.getNetworkView()); }); networkViewGrid.addPropertyChangeListener("thumbnailPanels", (PropertyChangeEvent e) -> { networkViewGrid.updateToolBar(); networkViewGrid.getReattachAllViewsButton().setEnabled(!viewFrames.isEmpty()); // TODO Should not be done here for (ThumbnailPanel tp : networkViewGrid.getItems()) { tp.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { // Double-Click: set this one as current and show attached view or view frame final NetworkViewFrame frame = getNetworkViewFrame(tp.getNetworkView()); if (frame != null) showViewFrame(frame); else gridViewToggleModel.setMode(Mode.VIEW); } } }); tp.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { updateThumbnail(tp.getNetworkView()); }; }); } }); networkViewGrid.addPropertyChangeListener("selectedNetworkViews", (PropertyChangeEvent e) -> { // Just fire the same event firePropertyChange("selectedNetworkViews", e.getOldValue(), e.getNewValue()); }); networkViewGrid.addPropertyChangeListener("selectedItems", (PropertyChangeEvent e) -> { networkViewGrid.updateToolBar(); networkViewGrid.getReattachAllViewsButton().setEnabled(!viewFrames.isEmpty()); // TODO }); networkViewGrid.addPropertyChangeListener("currentNetworkView", (PropertyChangeEvent e) -> { final CyNetworkView curView = (CyNetworkView) e.getNewValue(); for (NetworkViewContainer vc : getAllNetworkViewContainers()) vc.setCurrent(vc.getNetworkView().equals(curView)); }); Toolkit.getDefaultToolkit().addAWTEventListener(mousePressedAWTEventListener, MouseEvent.MOUSE_EVENT_MASK); // Update updateGrid(); } private JPanel getContentPane() { if (contentPane == null) { contentPane = new JPanel(); contentPane.setLayout(cardLayout); contentPane.add(nullViewPanel, nullViewPanel.getName()); contentPane.add(networkViewGrid, networkViewGrid.getName()); } return contentPane; } protected NetworkViewContainer getNetworkViewContainer(final CyNetworkView view) { return view != null ? allViewContainers.get(view) : null; } private NetworkViewContainer getNetworkViewCard(final CyNetworkView view) { return view != null ? viewCards.get(createUniqueKey(view)) : null; } protected NetworkViewFrame getNetworkViewFrame(final CyNetworkView view) { return getNetworkViewFrame(createUniqueKey(view)); } protected NetworkViewFrame getNetworkViewFrame(final String key) { return key != null ? viewFrames.get(key) : null; } private void changeCurrentViewTitle(final NetworkViewContainer vc) { String text = vc.getViewTitleTextField().getText(); if (text != null) { text = text.trim(); // TODO Make sure it's unique if (!text.isEmpty()) { vc.getViewTitleLabel().setText(text); // TODO This will fire a ViewChangedEvent - Just let the NetworkViewManager ask this panel to update itself instead? final CyNetworkView view = vc.getNetworkView(); view.setVisualProperty(BasicVisualLexicon.NETWORK_TITLE, text); updateThumbnailPanel(view, false); } } vc.getViewTitleTextField().setText(null); vc.getViewTitleTextField().setVisible(false); vc.getViewTitleLabel().setVisible(true); vc.getToolBar().updateUI(); } private void cancelViewTitleChange(final NetworkViewContainer vc) { vc.getViewTitleTextField().setText(null); vc.getViewTitleTextField().setVisible(false); vc.getViewTitleLabel().setVisible(true); } private class MousePressedAWTEventListener implements AWTEventListener { @Override public void eventDispatched(AWTEvent event) { if (event.getID() == MouseEvent.MOUSE_PRESSED && event instanceof MouseEvent) { final KeyboardFocusManager keyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); final Window window = keyboardFocusManager.getActiveWindow(); if (!(window instanceof NetworkViewFrame || window instanceof CytoscapeDesktop)) return; // Detect if a new view container received the mouse pressed event. // If so, it must request focus. MouseEvent me = (MouseEvent) event; final Set<Component> targets = new HashSet<>(); // Find the view container to be verified if (window instanceof NetworkViewFrame) { targets.add(((NetworkViewFrame) window).getContainerRootPane().getContentPane()); } else { final Component currentCard = getCurrentCard(); if (currentCard instanceof NetworkViewContainer) { final NetworkViewContainer vc = (NetworkViewContainer) currentCard; targets.add(vc.getContentPane()); } else if (currentCard instanceof NetworkViewComparisonPanel) { // Get the view component which is not in focus final NetworkViewComparisonPanel cp = (NetworkViewComparisonPanel) currentCard; final NetworkViewContainer currentContainer = cp.getCurrentContainer(); for (NetworkViewContainer vc : cp.getAllContainers()) { if (vc != currentContainer) targets.add(vc.getContentPane()); } } } for (Component c : targets) { me = SwingUtilities.convertMouseEvent(me.getComponent(), me, c); // Received the mouse event? So it should get focus now. if (c.getBounds().contains(me.getPoint())) c.requestFocusInWindow(); } } } } }
package org.strangeforest.tcb.stats.model.records; import java.lang.reflect.*; import org.strangeforest.tcb.stats.model.records.rows.*; import static java.lang.String.*; public enum RecordRowFactory { INTEGER(IntegerRecordRow.class), SEASON_INTEGER(SeasonIntegerRecordRow.class), SEASON_RANGE_INTEGER(SeasonRangeIntegerRecordRow.class), SEASON_TWO_INTEGERS(SeasonTwoIntegersRecordRow.class), TOURNAMENT_INTEGER(TournamentIntegerRecordRow.class), TOURNAMENT_EVENT_INTEGER(TournamentEventIntegerRecordRow.class), DATE_INTEGER(DateIntegerRecordRow.class), DATE_RANGE_INTEGER(DateRangeIntegerRecordRow.class), DATE_AGE(DateAgeRecordRow.class), STREAK(StreakRecordRow.class), CAREER_SPAN(CareerSpanRecordRow.class), TOURNAMENT_CAREER_SPAN(TournamentCareerSpanRecordRow.class), TOURNAMENT_EVENT_AGE(TournamentEventAgeRecordRow.class), RANKING_DIFF(RankingDiffRecordRow.class), WINNING_PCT(WinningPctRecordRow.class), LOSING_PCT(LosingPctRecordRow.class), WINNING_W_DRAW_PCT(WinningWDrawPctRecordRow.class), LOSING_W_DRAW_PCT(LosingWDrawPctRecordRow.class), SEASON_WINNING_PCT(SeasonWinningPctRecordRow.class), SEASON_LOSING_PCT(SeasonLosingPctRecordRow.class), TOURNAMENT_WINNING_PCT(TournamentWinningPctRecordRow.class), TOURNAMENT_LOSING_PCT(TournamentLosingPctRecordRow.class); private final Constructor<? extends RecordRow> constructor; RecordRowFactory(Class<? extends RecordRow> rowClass) { try { this.constructor = rowClass.getDeclaredConstructor(int.class, int.class, String.class, String.class, Boolean.class); } catch (NoSuchMethodException ex) { throw new IllegalArgumentException(format("RecordRow class %s does not have adequate constructor.", rowClass.getName())); } } public RecordRow createRow(int rank, int playerId, String name, String countryId, Boolean active) { try { return constructor.newInstance(rank, playerId, name, countryId, active); } catch (Exception ex) { throw new IllegalStateException(format("RecordRow %s cannot be instantiated.", constructor.getDeclaringClass().getName()), ex); } } }
package org.openlmis.functional; import cucumber.api.DataTable; import cucumber.api.java.After; import cucumber.api.java.Before; import cucumber.api.java.en.And; import org.openlmis.UiUtils.CaptureScreenshotOnFailureListener; import org.openlmis.UiUtils.TestCaseHelper; import org.openlmis.pageobjects.ConvertOrderPage; import org.openlmis.pageobjects.HomePage; import org.openlmis.pageobjects.LoginPage; import org.openlmis.pageobjects.ViewOrdersPage; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import org.testng.annotations.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue; import static java.lang.System.getProperty; @TransactionConfiguration(defaultRollback = true) @Transactional @Listeners(CaptureScreenshotOnFailureListener.class) public class DownloadOrderFile extends TestCaseHelper { public String program = "HIV"; public String passwordUsers = "TQskzK3iiLfbRVHeM1muvBCiiKriibfl6lh8ipo91hb74G3OvsybvkzpPI4S3KIeWTXAiiwlUU0iiSxWii4wSuS8mokSAieie"; public String userSICUserName = "storeIncharge"; private final String separator = getProperty("file.separator"); public String[] csvRows; @Before @BeforeMethod(groups = "requisition") public void setUp() throws Exception { super.setup(); } @DataProvider(name = "envData") public Object[][] getEnvData() { return new Object[][]{}; } @And("^I configure order file:$") public void setupOrderFileConfiguration(DataTable userTable) throws Exception { List<Map<String, String>> data = userTable.asMaps(); for (Map map : data) dbWrapper.setupOrderFileConfiguration(map.get("File Prefix").toString(), map.get("Header In File").toString()); } @And("^I configure non openlmis order file columns:$") public void setupOrderFileNonOpenLMISColumns(DataTable userTable) throws Exception { dbWrapper.deleteOrderFileNonOpenLMISColumns(); List<Map<String, String>> data = userTable.asMaps(); for (Map map : data) dbWrapper.setupOrderFileNonOpenLMISColumns(map.get("Data Field Label").toString(), map.get("Include In Order File").toString(), map.get("Column Label").toString(), Integer.parseInt(map.get("Position").toString())); } @And("^I configure openlmis order file columns:$") public void setupOrderFileOpenLMISColumns(DataTable userTable) throws Exception { dbWrapper.defaultSetupOrderFileOpenLMISColumns(); List<Map<String, String>> data = userTable.asMaps(); for (Map map : data) dbWrapper.setupOrderFileOpenLMISColumns(map.get("Data Field Label").toString(), map.get("Include In Order File").toString(), map.get("Column Label").toString(), Integer.parseInt(map.get("Position").toString()), map.get("Format").toString()); } @And("^I download order file$") public void downloadOrderFile() throws Exception { ViewOrdersPage viewOrderPage = new ViewOrdersPage(testWebDriver); viewOrderPage.downloadCSV(); testWebDriver.sleep(5000); } @And("^I get order data in file prefix \"([^\"]*)\"$") public String[] getOrderDataFromDownloadedFile(String filePrefix) throws Exception { csvRows = null; String orderId = dbWrapper.getOrderId(); csvRows = readCSVFile(filePrefix + orderId + ".csv"); testWebDriver.sleep(5000); deleteFile(filePrefix + orderId + ".csv"); return csvRows; } @And("^I verify order file line \"([^\"]*)\" having \"([^\"]*)\"$") public void checkOrderFileData(int lineNumber,String data) throws Exception { testWebDriver.sleep(1000); assertTrue("Order data incorrect in line number "+ lineNumber, csvRows[lineNumber-1].contains(data)); } @And("^I verify order date format \"([^\"]*)\" in line \"([^\"]*)\"$") public void checkOrderFileOrderDate(String dateFormat,int lineNumber) throws Exception { String createdDate = dbWrapper.getCreatedDate("orders", dateFormat); assertTrue("Order date incorrect.", csvRows[lineNumber-1].contains(createdDate)); } @And("^I verify order id in line \"([^\"]*)\"$") public void checkOrderFileOrderId(int lineNumber) throws Exception { String orderId = dbWrapper.getOrderId(); assertTrue("Order date incorrect.", csvRows[lineNumber-1].contains(orderId)); } @Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function") public void testVerifyOrderFileForSpecificConfiguration(String password) throws Exception { dbWrapper.setupOrderFileConfiguration("Zero", "TRUE"); dbWrapper.defaultSetupOrderFileOpenLMISColumns(); dbWrapper.setupOrderFileOpenLMISColumns("create.facility.code", "TRUE", "Facility code", 5, ""); dbWrapper.setupOrderFileOpenLMISColumns("header.order.number", "TRUE", "Order number", 7, ""); dbWrapper.setupOrderFileOpenLMISColumns("header.quantity.approved", "TRUE", "Approved quantity", 2, ""); dbWrapper.setupOrderFileOpenLMISColumns("header.product.code", "TRUE", "Product code", 3, ""); dbWrapper.setupOrderFileOpenLMISColumns("header.order.date", "TRUE", "Order date", 4, "MM-dd-yyyy"); dbWrapper.setupOrderFileOpenLMISColumns("label.period", "TRUE", "Period", 6, "yyyy-MM"); dbWrapper.deleteOrderFileNonOpenLMISColumns(); dbWrapper.setupOrderFileNonOpenLMISColumns("Not Applicable", "TRUE", "Extra 1", 1); dbWrapper.setupOrderFileNonOpenLMISColumns("Not Applicable", "TRUE", "", 8); setupDownloadOrderFileSetup(password); getOrderDataFromDownloadedFile("Zero"); checkOrderFileData(1, "Extra 1,Approved quantity,Product code,Order date,Facility code,Period,Order number,"); checkOrderFileData(2, ",10,P10,"); checkOrderFileData(2,",F10,2012-01,"); checkOrderFileOrderDate("MM-dd-yyyy", 2); checkOrderFileOrderId(2); } @Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function") public void testVerifyOrderFileForDefaultConfiguration(String password) throws Exception { dbWrapper.setupOrderFileConfiguration("O", "TRUE"); dbWrapper.defaultSetupOrderFileOpenLMISColumns(); setupDownloadOrderFileSetup(password); getOrderDataFromDownloadedFile("O"); checkOrderFileData(1,"Order number,Facility code,Product code,Approved quantity,Period,Order date"); checkOrderFileData(2,",F10,P10,10,01/12,"); checkOrderFileOrderDate("dd/MM/yy", 2); checkOrderFileOrderId(2); } @Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function") public void testVerifyOrderFileForDefaultConfigurationWithNoHeades(String password) throws Exception { dbWrapper.setupOrderFileConfiguration("O", "FALSE"); dbWrapper.defaultSetupOrderFileOpenLMISColumns(); setupDownloadOrderFileSetup(password); getOrderDataFromDownloadedFile("O"); checkOrderFileData(1,",F10,P10,10,01/12,"); checkOrderFileOrderDate("dd/MM/yy", 1); checkOrderFileOrderId(1); } public void setupDownloadOrderFileSetup(String password) throws Exception { List<String> rightsList = new ArrayList<String>(); rightsList.add("CREATE_REQUISITION"); rightsList.add("VIEW_REQUISITION"); rightsList.add("APPROVE_REQUISITION"); setupTestDataToInitiateRnR(true, program, userSICUserName, "200", rightsList); setupTestRoleRightsData("lmu", "CONVERT_TO_ORDER,VIEW_ORDER"); dbWrapper.insertUser("212", "lmu", passwordUsers, "F10", "Jake_Doe@openlmis.com"); dbWrapper.insertRoleAssignment("212", "lmu"); dbWrapper.insertFulfilmentRoleAssignment("lmu","lmu","F10"); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); HomePage homePage = loginPage.loginAs(userSICUserName, password); homePage.navigateAndInitiateRnr(program); homePage.clickProceed(); testWebDriver.sleep(2000); dbWrapper.insertValuesInRequisition(false); dbWrapper.insertValuesInRegimenLineItems("100", "200", "300", "Regimens data filled"); dbWrapper.updateRequisitionStatus("SUBMITTED", userSICUserName, "HIV"); dbWrapper.updateRequisitionStatus("AUTHORIZED", userSICUserName, "HIV"); dbWrapper.insertApprovedQuantity(10); dbWrapper.updateRequisitionStatus("APPROVED", userSICUserName, "HIV"); homePage.logout(baseUrlGlobal); loginPage.loginAs("lmu", password); homePage.navigateConvertToOrder(); ConvertOrderPage convertOrderPage = new ConvertOrderPage(testWebDriver); convertOrderPage.clickConvertToOrderButton(); convertOrderPage.clickCheckBoxConvertToOrder(); convertOrderPage.clickConvertToOrderButton(); convertOrderPage.clickOk(); homePage.navigateViewOrders(); downloadOrderFile(); } @After @AfterMethod(groups = "requisition") public void tearDown() throws Exception { testWebDriver.sleep(500); if (!testWebDriver.getElementById("username").isDisplayed()) { HomePage homePage = new HomePage(testWebDriver); homePage.logout(baseUrlGlobal); dbWrapper.deleteData(); dbWrapper.closeConnection(); } } @DataProvider(name = "Data-Provider-Function") public Object[][] parameterIntTestProviderPositive() { return new Object[][]{ {"Admin123"} }; } }
package io.spine.testing.server.blackbox; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import com.google.common.truth.extensions.proto.ProtoSubject; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.protobuf.Message; import io.grpc.stub.StreamObserver; import io.spine.base.CommandMessage; import io.spine.base.EntityState; import io.spine.base.EventMessage; import io.spine.base.RejectionMessage; import io.spine.client.Query; import io.spine.client.QueryFactory; import io.spine.client.QueryResponse; import io.spine.client.Subscription; import io.spine.client.Topic; import io.spine.core.Ack; import io.spine.core.BoundedContextName; import io.spine.core.Command; import io.spine.core.Event; import io.spine.grpc.MemoizingObserver; import io.spine.logging.Logging; import io.spine.protobuf.AnyPacker; import io.spine.server.BoundedContext; import io.spine.server.BoundedContextBuilder; import io.spine.server.QueryService; import io.spine.server.SubscriptionService; import io.spine.server.commandbus.CommandBus; import io.spine.server.commandbus.CommandDispatcher; import io.spine.server.entity.Entity; import io.spine.server.entity.Repository; import io.spine.server.event.AbstractEventSubscriber; import io.spine.server.event.EventBus; import io.spine.server.event.EventDispatcher; import io.spine.server.event.EventEnricher; import io.spine.server.integration.IntegrationBroker; import io.spine.server.type.EventClass; import io.spine.server.type.EventEnvelope; import io.spine.system.server.event.CommandErrored; import io.spine.testing.client.TestActorRequestFactory; import io.spine.testing.client.blackbox.Acknowledgements; import io.spine.testing.client.blackbox.VerifyAcknowledgements; import io.spine.testing.server.CommandSubject; import io.spine.testing.server.EventSubject; import io.spine.testing.server.SubscriptionActivator; import io.spine.testing.server.SubscriptionObserver; import io.spine.testing.server.VerifyingCounter; import io.spine.testing.server.blackbox.verify.query.QueryResultSubject; import io.spine.testing.server.blackbox.verify.state.VerifyState; import io.spine.testing.server.blackbox.verify.subscription.ToProtoSubjects; import io.spine.testing.server.entity.EntitySubject; import io.spine.type.TypeName; import org.checkerframework.checker.nullness.qual.Nullable; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Lists.asList; import static com.google.common.collect.Maps.newHashMap; import static io.spine.core.BoundedContextNames.assumingTestsValue; import static io.spine.grpc.StreamObservers.memoizingObserver; import static io.spine.server.entity.model.EntityClass.stateClassOf; import static io.spine.util.Exceptions.illegalStateWithCauseOf; import static java.util.Collections.singletonList; import static java.util.Collections.synchronizedSet; import static org.junit.jupiter.api.Assertions.assertTrue; /** * This class provides means for integration testing of Bounded Contexts. * * <p>Such a test suite would send commands or events to the Bounded Context under the test, * and then verify consequences of handling a command or an event. * * <p>Handling a command or an event usually results in {@link VerifyEvents emitted events}) and * {@linkplain VerifyState updated state} of an entity. This class provides API for testing such * effects. * * @param <T> * the type of a sub-class for return type covariance * @apiNote It is expected that instances of classes derived from * {@code BlackBoxBoundedContext} are obtained by factory * methods provided by this class. */ @SuppressWarnings({ "ClassReferencesSubclass", /* See the API note. */ "ClassWithTooManyMethods", "OverlyCoupledClass"}) @VisibleForTesting public abstract class BlackBoxBoundedContext<T extends BlackBoxBoundedContext> extends AbstractEventSubscriber implements Logging { private final BoundedContext context; /** * Collects all commands, including posted to the context during its setup or * generated by the entities in response to posted or generated events or commands. */ private final CommandCollector commands; /** * Commands received by this instance and posted to Command Bus during the test setup. * * <p>These commands are filtered out from those generated in the Bounded Context * (in response to posted or generated events or commands), which are used for assertions. */ private final Set<Command> postedCommands; /** * Collects all events, including posted to the context during its setup or * generated by the entities in response to posted or generated events or commands. */ private final EventCollector events; /** * Events received by this instance and posted to the Event Bus during the test setup. * * <p>These events are filtered out from those stored in the Bounded Context to * collect only the emitted events, which are used for assertions. * * @see #emittedEvents() */ private final Set<Event> postedEvents; private final MemoizingObserver<Ack> observer; /** * A guard that verifies that unsupported commands do not get posted to the * {@code BlackBoxBoundedContext}. */ private final UnsupportedCommandGuard unsupportedCommandGuard; private final Map<Class<? extends EntityState>, Repository<?, ?>> repositories; @SuppressWarnings("ThisEscapedInObjectConstruction") // to inject self as event dispatcher. protected BlackBoxBoundedContext(boolean multitenant, EventEnricher enricher, String name) { super(); this.commands = new CommandCollector(); this.postedCommands = synchronizedSet(new HashSet<>()); this.events = new EventCollector(); this.postedEvents = synchronizedSet(new HashSet<>()); BoundedContextBuilder builder = multitenant ? BoundedContext.multitenant(name) : BoundedContext.singleTenant(name); this.context = builder .addCommandListener(commands) .addEventListener(events) .enrichEventsUsing(enricher) .build(); this.observer = memoizingObserver(); this.unsupportedCommandGuard = new UnsupportedCommandGuard(name); this.repositories = newHashMap(); this.context.registerEventDispatcher(this); this.context.registerEventDispatcher(DiagnosticLog.instance()); } /** * Creates a single-tenant instance with the default configuration. */ public static SingleTenantBlackBoxContext singleTenant() { return singleTenant(emptyEnricher()); } /** * Creates a single-tenant instance with the specified name. */ public static SingleTenantBlackBoxContext singleTenant(String name) { return singleTenant(name, emptyEnricher()); } /** * Creates a single-tenant instance with the specified enricher. */ public static SingleTenantBlackBoxContext singleTenant(EventEnricher enricher) { return singleTenant(assumingTestsValue(), enricher); } /** * Creates a single-tenant instance with the specified name and enricher. */ public static SingleTenantBlackBoxContext singleTenant(String name, EventEnricher enricher) { return new SingleTenantBlackBoxContext(name, enricher); } /** * Creates a multitenant instance the default configuration. */ public static MultitenantBlackBoxContext multiTenant() { return multiTenant(emptyEnricher()); } /** * Creates a multitenant instance with the specified name. */ public static MultitenantBlackBoxContext multiTenant(String name) { return multiTenant(name, emptyEnricher()); } /** * Creates a multitenant instance with the specified enricher. */ public static MultitenantBlackBoxContext multiTenant(EventEnricher enricher) { return multiTenant(assumingTestsValue(), enricher); } /** * Creates a multitenant instance with the specified name and enricher. */ public static MultitenantBlackBoxContext multiTenant(String name, EventEnricher enricher) { return new MultitenantBlackBoxContext(name, enricher); } /** * Creates new instance obtaining configuration parameters from the passed builder. * * <p>In particular: * <ul> * <li>multi-tenancy status; * <li>{@code Enricher}; * <li>added repositories. * </ul> */ public static BlackBoxBoundedContext<?> from(BoundedContextBuilder builder) { EventEnricher enricher = builder.eventEnricher() .orElseGet(BlackBoxBoundedContext::emptyEnricher); BlackBoxBoundedContext<?> result = builder.isMultitenant() ? multiTenant(enricher) : singleTenant(enricher); builder.repositories() .forEach(result::with); builder.commandDispatchers() .forEach(result::withHandlers); builder.eventDispatchers() .forEach(result::withEventDispatchers); return result; } /** * Throws an {@link AssertionError}. * * <p>Only reachable after {@code unsupportedGuard} has * {@linkplain #canDispatch(EventEnvelope) detected} a violation. */ @Override protected void handle(EventEnvelope event) { unsupportedCommandGuard.failTest(); } /** * Checks if the given {@link CommandErrored} message represents an unsupported command * {@linkplain io.spine.server.commandbus.UnsupportedCommandException error}. */ @Override public boolean canDispatch(EventEnvelope eventEnvelope) { CommandErrored event = (CommandErrored) eventEnvelope.message(); return unsupportedCommandGuard.checkAndRemember(event); } @Override public ImmutableSet<EventClass> messageClasses() { return EventClass.setOf(CommandErrored.class); } /** * {@inheritDoc} * * <p>The {@code BlackBoxBoundedContext} only consumes domestic events. */ @Override public ImmutableSet<EventClass> domesticEventClasses() { return eventClasses(); } /** * {@inheritDoc} * * <p>The {@code BlackBoxBoundedContext} does not consume external events. */ @Override public ImmutableSet<EventClass> externalEventClasses() { return ImmutableSet.of(); } /** Obtains the name of this bounded context. */ public BoundedContextName name() { return context.name(); } /** * Obtains set of type names of entities known to this Bounded Context. */ @VisibleForTesting Set<TypeName> allStateTypes() { return context.stateTypes(); } /** Obtains {@code event bus} instance used by this bounded context. */ public EventBus eventBus() { return context.eventBus(); } /** Obtains {@code command bus} instance used by this bounded context. */ public CommandBus commandBus() { return context.commandBus(); } /** * Registers passed repositories with the Bounded Context under the test. * * @param repositories * repositories to register in the Bounded Context * @return current instance */ @CanIgnoreReturnValue public final T with(Repository<?, ?>... repositories) { registerAll(this::registerRepository, repositories); return thisRef(); } private void registerRepository(Repository<?, ?> repository) { context.register(repository); remember(repository); } private void remember(Repository<?, ?> repository) { Class<? extends EntityState> stateClass = repository.entityModelClass() .stateClass(); repositories.put(stateClass, repository); } /** * Registers the specified command dispatchers with this bounded context. * * @param dispatchers * command dispatchers to register with the bounded context * @return current instance */ @CanIgnoreReturnValue public final T withHandlers(CommandDispatcher... dispatchers) { registerAll(this::registerCommandDispatcher, dispatchers); return thisRef(); } private void registerCommandDispatcher(CommandDispatcher dispatcher) { if (dispatcher instanceof Repository) { registerRepository((Repository<?, ?>) dispatcher); } else { context.registerCommandDispatcher(dispatcher); } } /** * Registers the specified event dispatchers with the {@code event bus} of this * bounded context. * * @param dispatchers * dispatchers to register with the event bus of this bounded context */ @CanIgnoreReturnValue public final T withEventDispatchers(EventDispatcher... dispatchers) { registerAll(this::registerEventDispatcher, dispatchers); return thisRef(); } private void registerEventDispatcher(EventDispatcher dispatcher) { if (dispatcher instanceof Repository) { registerRepository((Repository<?, ?>) dispatcher); } else { context.registerEventDispatcher(dispatcher); } } @SafeVarargs private static <S> void registerAll(Consumer<S> registerFn, S... itemsToRegister) { checkNotNull(itemsToRegister); for (S item : itemsToRegister) { checkNotNull(item); registerFn.accept(item); } } /** * Sends off a provided command to the Bounded Context. * * @param domainCommand * a domain command to be dispatched to the Bounded Context * @return current instance * @apiNote Returned value can be ignored when this method invoked for test setup. */ @CanIgnoreReturnValue public T receivesCommand(CommandMessage domainCommand) { return receivesCommands(singletonList(domainCommand)); } /** * Sends off provided commands to the Bounded Context. * * @param first * a domain command to be dispatched to the Bounded Context first * @param second * a domain command to be dispatched to the Bounded Context second * @param rest * optional domain commands to be dispatched to the Bounded Context in supplied order * @return current instance * @apiNote Returned value can be ignored when this method invoked for test setup. */ @CanIgnoreReturnValue public T receivesCommands(CommandMessage first, CommandMessage second, CommandMessage... rest) { return receivesCommands(asList(first, second, rest)); } /** * Sends off a provided command to the Bounded Context. * * @param domainCommands * a list of domain commands to be dispatched to the Bounded Context * @return current instance */ private T receivesCommands(Collection<CommandMessage> domainCommands) { List<Command> posted = setup().postCommands(domainCommands); postedCommands.addAll(posted); return thisRef(); } /** * Sends off a provided event to the Bounded Context. * * @param messageOrEvent * an event message or {@link io.spine.core.Event}. If an instance of {@code Event} is * passed, it will be posted to {@link EventBus} as is. * Otherwise, an instance of {@code Event} will be generated basing on the passed * event message and posted to the bus. * @return current instance * @apiNote Returned value can be ignored when this method invoked for test setup. */ @CanIgnoreReturnValue public T receivesEvent(EventMessage messageOrEvent) { return receivesEvents(singletonList(messageOrEvent)); } /** * Sends off provided events to the Bounded Context. * * <p>The method accepts event messages or instances of {@link io.spine.core.Event}. * If an instance of {@code Event} is passed, it will be posted to {@link EventBus} as is. * Otherwise, an instance of {@code Event} will be generated basing on the passed event * message and posted to the bus. * * @param first * a domain event to be dispatched to the Bounded Context first * @param second * a domain event to be dispatched to the Bounded Context second * @param rest * optional domain events to be dispatched to the Bounded Context in supplied order * @return current instance * @apiNote Returned value can be ignored when this method invoked for test setup. */ @CanIgnoreReturnValue public T receivesEvents(EventMessage first, EventMessage second, EventMessage... rest) { return receivesEvents(asList(first, second, rest)); } /** * Sends off a provided event to the Bounded Context as event from an external source. * * @param messageOrEvent * an event message or {@link Event}. If an instance of {@code Event} is * passed, it will be posted to {@link IntegrationBroker} as is. Otherwise, an instance * of {@code Event} will be generated basing on the passed event message and posted to * the bus. * @return current instance * @apiNote Returned value can be ignored when this method invoked for test setup. */ @CanIgnoreReturnValue public T receivesExternalEvent(Message messageOrEvent) { setup().postExternalEvent(messageOrEvent); return thisRef(); } /** * Sends off provided events to the Bounded Context as events from an external source. * * <p>The method accepts event messages or instances of {@link io.spine.core.Event}. * If an instance of {@code Event} is passed, it will be posted to * {@link IntegrationBroker} as is. * Otherwise, an instance of {@code Event} will be generated basing on the passed event * message and posted to the bus. * * @param firstEvent * an external event to be dispatched to the Bounded Context first * @param secondEvent * an external event to be dispatched to the Bounded Context second * @param otherEvents * optional external events to be dispatched to the Bounded Context * in supplied order * @return current instance * @apiNote Returned value can be ignored when this method invoked for test setup. */ @CanIgnoreReturnValue public T receivesExternalEvents(EventMessage firstEvent, EventMessage secondEvent, EventMessage... otherEvents) { return receivesExternalEvents(asList(firstEvent, secondEvent, otherEvents)); } /** * Sends off provided events to the Bounded Context as events from an external source. * * @param eventMessages * a list of external events to be dispatched to the Bounded Context * @return current instance */ private T receivesExternalEvents(Collection<EventMessage> eventMessages) { setup().postExternalEvents(eventMessages); return thisRef(); } /** * Sends off events using the specified producer to the Bounded Context. * * <p>The method is needed to route events based on a proper producer ID. * * @param producerId * the {@linkplain io.spine.core.EventContext#getProducerId() producer} for events * @param first * a domain event to be dispatched to the Bounded Context first * @param rest * optional domain events to be dispatched to the Bounded Context in supplied order * @return current instance */ @CanIgnoreReturnValue public T receivesEventsProducedBy(Object producerId, EventMessage first, EventMessage... rest) { List<Event> sentEvents = setup().postEvents(producerId, first, rest); postedEvents.addAll(sentEvents); return thisRef(); } /** * Sends off provided events to the Bounded Context. * * @param domainEvents * a list of domain event to be dispatched to the Bounded Context * @return current instance */ private T receivesEvents(Collection<EventMessage> domainEvents) { List<Event> sentEvents = setup().postEvents(domainEvents); this.postedEvents.addAll(sentEvents); return thisRef(); } @CanIgnoreReturnValue public T importsEvent(Message eventOrMessage) { setup().importEvent(eventOrMessage); return thisRef(); } @CanIgnoreReturnValue public T importsEvents(EventMessage first, EventMessage second, EventMessage... rest) { return importAll(asList(first, second, rest)); } private T importAll(Collection<EventMessage> eventMessages) { setup().importEvents(eventMessages); return thisRef(); } /** * Asserts that an event of the passed class was emitted once. * * @param eventClass * the class of events to verify * @return current instance * @deprecated use {@link #assertEvents()} instead; to be removed in future versions */ @Deprecated @CanIgnoreReturnValue public T assertEmitted(Class<? extends EventMessage> eventClass) { assertEvents() .withType(eventClass) .hasSize(1); return thisRef(); } /** * Asserts that a rejection of the passed class was emitted once. * * @param rejectionClass * the class of the rejection to verify * @return current instance * @deprecated use {@link #assertEvents()} instead; to be removed in future versions */ @Deprecated @CanIgnoreReturnValue public T assertRejectedWith(Class<? extends RejectionMessage> rejectionClass) { return assertEmitted(rejectionClass); } /** * Verifies emitted events by the passed verifier. * * @param verifier * a verifier that checks the events emitted in this Bounded Context * @return current instance * @deprecated use {@link #assertEvents()} instead; to be removed in future versions */ @Deprecated @CanIgnoreReturnValue public T assertThat(VerifyEvents verifier) { EmittedEvents events = emittedEvents(); verifier.verify(events); return thisRef(); } /** * Executes the provided verifier, which throws an assertion error in case of * unexpected results. * * @param verifier * a verifier that checks the acknowledgements in this Bounded Context * @return current instance * @deprecated verify command outcome instead of acknowledgements; to be removed in future * versions */ @Deprecated @CanIgnoreReturnValue public T assertThat(VerifyAcknowledgements verifier) { Acknowledgements acks = commandAcknowledgements(observer); verifier.verify(acks); return thisRef(); } /** * Verifies emitted commands by the passed verifier. * * @param verifier * a verifier that checks the commands emitted in this Bounded Context * @return current instance * @deprecated use {@link #assertCommands()} instead; to be removed in future versions */ @Deprecated @CanIgnoreReturnValue public T assertThat(VerifyCommands verifier) { EmittedCommands commands = emittedCommands(); verifier.verify(commands); return thisRef(); } /** * Asserts the state of an entity using the specified tenant ID. * * @param verifier * a verifier of entity states * @return current instance * @deprecated use {@link #assertEntity}, {@link #assertEntityWithState}, * or {@link #assertQueryResult} instead; to be removed in future versions */ @Deprecated @CanIgnoreReturnValue public T assertThat(VerifyState verifier) { QueryFactory queryFactory = requestFactory().query(); verifier.verify(context, queryFactory); return thisRef(); } private BlackBoxSetup setup() { return new BlackBoxSetup(context, requestFactory(), observer); } public void close() { try { context.close(); } catch (Exception e) { throw illegalStateWithCauseOf(e); } } /** Casts this to generic type to provide type covariance in the derived classes. */ @SuppressWarnings("unchecked" /* See Javadoc. */) private T thisRef() { return (T) this; } /** * Obtains the request factory to operate with. */ protected abstract TestActorRequestFactory requestFactory(); /** * Obtains commands emitted in the bounded context. */ private EmittedCommands emittedCommands() { List<Command> allWithoutPosted = commands(); return new EmittedCommands(allWithoutPosted); } /** * Obtains immutable list of commands generated in this Bounded Context in response to posted * messages. * * <p>The returned list does <em>NOT</em> contain commands posted to this Bounded Context * during test setup. * * @see #commandMessages() */ public List<Command> commands() { Predicate<Command> wasNotReceived = ((Predicate<Command>) postedCommands::contains).negate(); return select(this.commands) .stream() .filter(wasNotReceived) .collect(toImmutableList()); } /** * Obtains immutable list of command messages generated in this Bounded Context in response * to posted messages. * * <p>The returned list does <em>NOT</em> contain commands posted to this Bounded Context * during test setup. * * @see #commands() */ public List<CommandMessage> commandMessages() { return commands().stream() .map(Command::getMessage) .map(AnyPacker::unpack) .map(m -> (CommandMessage) m) .collect(toImmutableList()); } /** * Selects commands that belong to the current tenant. */ protected abstract List<Command> select(CommandCollector collector); /** * Obtains acknowledgements of {@linkplain #emittedCommands() * emitted commands}. */ private static Acknowledgements commandAcknowledgements(MemoizingObserver<Ack> observer) { List<Ack> acknowledgements = observer.responses(); return new Acknowledgements(acknowledgements); } /** * Obtains events emitted in the Bounded Context. * * <p>They do not include the events posted to the bounded context via {@code receivesEvent...} * calls. */ private EmittedEvents emittedEvents() { List<Event> allWithoutPosted = events(); return new EmittedEvents(allWithoutPosted); } /** * Obtains immutable list of events generated in this Bounded Context in response to posted * messages. * * <p>The returned list does <em>NOT</em> contain events posted to this Bounded Context * during test setup. */ public List<Event> events() { Predicate<Event> wasNotReceived = ((Predicate<Event>) postedEvents::contains).negate(); return select(this.events) .stream() .filter(wasNotReceived) .collect(toImmutableList()); } /** * Obtains immutable list of event messages generated in this Bounded Context in response * to posted messages. * * <p>The returned list does <em>NOT</em> contain events posted to this Bounded Context * during test setup. * * @see #events() */ public List<EventMessage> eventMessages() { return events().stream() .map(Event::enclosedMessage) .collect(toImmutableList()); } /** * Selects events that belong to the current tenant. */ protected abstract List<Event> select(EventCollector collector); private static EventEnricher emptyEnricher() { return EventEnricher.newBuilder() .build(); } /** * Performs data reading operation in a tenant context. */ protected <@Nullable D> D readOperation(Supplier<D> supplier) { return supplier.get(); } /** * Obtains a Subject for an entity of the passed class with the given ID. */ public <I, E extends Entity<I, ? extends EntityState>> EntitySubject assertEntity(Class<E> entityClass, I id) { @Nullable Entity<I, ?> found = findEntity(entityClass, id); return EntitySubject.assertEntity(found); } private <I> @Nullable Entity<I, ?> findEntity(Class<? extends Entity<I, ?>> entityClass, I id) { Class<? extends EntityState> stateClass = stateClassOf(entityClass); return findByState(stateClass, id); } /** * Obtains a Subject for an entity which has the state of the passed class with the given ID. */ public <I, S extends EntityState> EntitySubject assertEntityWithState(Class<S> stateClass, I id) { @Nullable Entity<I, S> found = findByState(stateClass, id); return EntitySubject.assertEntity(found); } private <I, S extends EntityState> @Nullable Entity<I, S> findByState(Class<S> stateClass, I id) { @SuppressWarnings("unchecked") Repository<I, ? extends Entity<I, S>> repo = (Repository<I, ? extends Entity<I, S>>) repositoryOf(stateClass); return readOperation(() -> (Entity<I, S>) repo.find(id).orElse(null)); } private Repository<?, ?> repositoryOf(Class<? extends EntityState> stateClass) { Repository<?, ?> repository = repositories.get(stateClass); return repository; } /** * Obtains the subject for checking commands generated by the entities of this Bounded Context. */ public CommandSubject assertCommands() { return CommandSubject.assertThat(commands()); } /** * Obtains the subject for checking events emitted by the entities of this Bounded Context. */ public EventSubject assertEvents() { return EventSubject.assertThat(events()); } /** * Obtains the subject for checking the {@code Query} execution result. */ public QueryResultSubject assertQueryResult(Query query) { MemoizingObserver<QueryResponse> observer = memoizingObserver(); QueryService queryService = QueryService.newBuilder() .add(context) .build(); queryService.read(query, observer); assertTrue(observer.isCompleted()); QueryResponse response = observer.firstResponse(); return QueryResultSubject.assertQueryResult(response); } /** * Subscribes to the {@code topic} and verifies the incoming updates. * * <p>The verification happens on a per-item basis, where item is a single entity state or * event update represented as {@link ProtoSubject}. * * <p>The returned value allows to check the number of updates received. * * <p>The method may be used as follows: * <pre> * VerifyingCounter updateCounter = * context.assertSubscriptionUpdates( * topic, * assertEachReceived -> assertEachReceived.comparingExpectedFieldsOnly() * .isEqualTo(expected) * ); * context.receivesCommand(createProject); // Some command creating the `expected`. * updateCounter.verifyEquals(1); * </pre> * * <p>Please note that the return value may be ignored, but then receiving {@code 0} incoming * updates will count as valid and won't fail the test. */ @CanIgnoreReturnValue public VerifyingCounter assertSubscriptionUpdates(Topic topic, Consumer<ProtoSubject> assertEachReceived) { SubscriptionService subscriptionService = SubscriptionService.newBuilder() .add(context) .build(); SubscriptionObserver updateObserver = new SubscriptionObserver( update -> new ToProtoSubjects().apply(update) .forEach(assertEachReceived) ); StreamObserver<Subscription> activator = new SubscriptionActivator(subscriptionService, updateObserver); subscriptionService.subscribe(topic, activator); return updateObserver.counter(); } }
package org.apache.hadoop.hbase.themis.cp; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.metrics.MetricsContext; import org.apache.hadoop.metrics.MetricsRecord; import org.apache.hadoop.metrics.MetricsUtil; import org.apache.hadoop.metrics.Updater; import org.apache.hadoop.metrics.util.MetricsRegistry; import org.apache.hadoop.metrics.util.MetricsTimeVaryingLong; import org.apache.hadoop.metrics.util.MetricsTimeVaryingRate; // latency statistics for key steps of themis coprocessor public class ThemisCpStatistics implements Updater { private static final Log LOG = LogFactory.getLog(ThemisCpStatistics.class); public static final String THEMIS_CP_SLOW_OPERATION_CUTOFF_KEY = "themis.cp.slow.operation.cutoff"; public static final long DEFAULT_THEMIS_CP_SLOW_OPERATION_CUTOFF = 100; private static long slowCutoff = DEFAULT_THEMIS_CP_SLOW_OPERATION_CUTOFF * 1000; // in us private static final ThemisCpStatistics statistcs = new ThemisCpStatistics(); private final MetricsRegistry registry = new MetricsRegistry(); private final MetricsContext context; private final MetricsRecord metricsRecord; public final MetricsTimeVaryingRate getLockAndWriteLatency = new MetricsTimeVaryingRate("getLockAndWriteLatency", registry); public final MetricsTimeVaryingRate getDataLatency = new MetricsTimeVaryingRate("getDataLatency", registry); public final MetricsTimeVaryingRate prewriteReadLockLatency = new MetricsTimeVaryingRate("prewriteReadLockLatency", registry); public final MetricsTimeVaryingRate prewriteReadWriteLatency = new MetricsTimeVaryingRate("prewriteReadWriteLatency", registry); public final MetricsTimeVaryingRate prewriteWriteLatency = new MetricsTimeVaryingRate("prewriteWriteLatency", registry); public final MetricsTimeVaryingRate prewriteTotalLatency = new MetricsTimeVaryingRate("prewriteTotalLatency", registry); public final MetricsTimeVaryingRate commitPrimaryReadLatency = new MetricsTimeVaryingRate("commitPrimaryReadLatency", registry); public final MetricsTimeVaryingRate commitWriteLatency = new MetricsTimeVaryingRate("commitWriteLatency", registry); public final MetricsTimeVaryingRate commitTotalLatency = new MetricsTimeVaryingRate("commitTotalLatency", registry); public final MetricsTimeVaryingRate getLockAndEraseReadLatency = new MetricsTimeVaryingRate("getLockAndEraseReadLatency", registry); public final MetricsTimeVaryingRate getLockAndEraseDeleteLatency = new MetricsTimeVaryingRate("getLockAndEraseDeleteLatency", registry); // metrics for lock clean public final MetricsTimeVaryingRate cleanLockLatency = new MetricsTimeVaryingRate("cleanLockLatency", registry); public final MetricsTimeVaryingLong cleanLockSuccessCount = new MetricsTimeVaryingLong("cleanLockSuccessCount", registry); public final MetricsTimeVaryingLong cleanLockFailCount = new MetricsTimeVaryingLong("cleanLockFailCount", registry); public final MetricsTimeVaryingLong cleanLockByEraseCount = new MetricsTimeVaryingLong("cleanLockWithEraseCount", registry); public final MetricsTimeVaryingLong cleanLockByCommitCount = new MetricsTimeVaryingLong("cleanLockWithCommitCount", registry); public ThemisCpStatistics() { context = MetricsUtil.getContext("themis"); metricsRecord = MetricsUtil.createRecord(context, "coprocessor"); context.registerUpdater(this); } public static void init(Configuration conf) { slowCutoff = conf.getLong(ThemisCpStatistics.THEMIS_CP_SLOW_OPERATION_CUTOFF_KEY, ThemisCpStatistics.DEFAULT_THEMIS_CP_SLOW_OPERATION_CUTOFF) * 1000; } public void doUpdates(MetricsContext context) { getLockAndWriteLatency.pushMetric(metricsRecord); getDataLatency.pushMetric(metricsRecord); prewriteReadLockLatency.pushMetric(metricsRecord); prewriteReadWriteLatency.pushMetric(metricsRecord); prewriteWriteLatency.pushMetric(metricsRecord); prewriteTotalLatency.pushMetric(metricsRecord); commitPrimaryReadLatency.pushMetric(metricsRecord); commitWriteLatency.pushMetric(metricsRecord); commitTotalLatency.pushMetric(metricsRecord); getLockAndEraseReadLatency.pushMetric(metricsRecord); getLockAndEraseDeleteLatency.pushMetric(metricsRecord); cleanLockLatency.pushMetric(metricsRecord); cleanLockSuccessCount.pushMetric(metricsRecord); cleanLockFailCount.pushMetric(metricsRecord); cleanLockByEraseCount.pushMetric(metricsRecord); cleanLockByCommitCount.pushMetric(metricsRecord); metricsRecord.update(); } public static ThemisCpStatistics getThemisCpStatistics() { return statistcs; } public static void updateLatency(MetricsTimeVaryingRate metric, long beginTs) { long consumeInUs = (System.nanoTime() - beginTs) / 1000; metric.inc((System.nanoTime() - beginTs) / 1000); if (consumeInUs > slowCutoff) { LOG.warn("themis cp slow operation " + metric.getName() + ", latency(ms)=" + (consumeInUs / 1000)); } } }
package org.cipres.treebase.domain.nexus; import java.util.Collection; import java.util.List; import java.util.Set; import junit.framework.Assert; import org.cipres.treebase.dao.AbstractDAOTest; import org.cipres.treebase.domain.matrix.CharSet; import org.cipres.treebase.domain.matrix.CharacterMatrix; import org.cipres.treebase.domain.matrix.ColumnRange; import org.cipres.treebase.domain.nexus.nexml.NexmlDocumentConverter; import org.cipres.treebase.domain.study.Study; import org.cipres.treebase.domain.taxon.TaxonLabelHome; import org.nexml.model.CategoricalMatrix; import org.nexml.model.ContinuousMatrix; import org.nexml.model.DocumentFactory; import org.nexml.model.Document; import org.nexml.model.Matrix; import org.nexml.model.MolecularMatrix; import org.nexml.model.Subset; public class NexmlMatrixConverterTest extends AbstractDAOTest { private TaxonLabelHome mTaxonLabelHome; /** * Test for {@link org.cipres.treebase.domain.nexus.nexml.NexmlMatrixConverter#fromTreeBaseToXml(CharacterMatrix)}. * Finds an equivalent, created NexmlMatrix within a NeXML document to go with the matrix * fetched from the TreeBASE database. */ public void testNexmlMatrixConverter() { String testName = "testNexmlMatrixConverter"; //signal beginning of test if (logger.isInfoEnabled()) { logger.info("Running Test: " + testName); } long studyId = 794; // this study seems to have character sets // this is the full study as it is stored by the database Study tbStudy = (Study)loadObject(Study.class, studyId); // these are the character state matrices that are part of the study Set<org.cipres.treebase.domain.matrix.Matrix> tbMatrices = tbStudy.getMatrices(); // this is an object representation of a NeXML document Document nexDoc = DocumentFactory.safeCreateDocument(); // the converter populates the NeXML document with the contents of the treebase study NexmlDocumentConverter ndc = new NexmlDocumentConverter(tbStudy,getTaxonLabelHome(),nexDoc); ndc.fromTreeBaseToXml(tbStudy); // here is where the conversion happens // these are the NeXML matrices that were created from the study List<Matrix<?>> nexMatrices = nexDoc.getMatrices(); // there most be more than zero matrices because every treebase study has at least one matrix Assert.assertTrue(nexMatrices.size() != 0 ); // now we're going to match up the NeXML matrices with their equivalent treebase ones for ( Matrix<?> nexMatrix : nexMatrices ) { // the xml id is the same as the primary key of the equivalent matrix stored by treebase String nexId = nexMatrix.getId(); boolean foundEquivalentMatrix = false; // iterate over all treebase matrices for the study for ( org.cipres.treebase.domain.matrix.Matrix tbMatrix : tbMatrices ) { String tbId = "M" + tbMatrix.getId(); // although there is a class DistanceMatrix, it is my belief that we don't actually have // any distance matrices stored, nor can we convert them to NeXML Assert.assertTrue("TreeBASE matrix "+tbId+" must be a character matrix, not a distance matrix", tbMatrix instanceof CharacterMatrix); // if true, the matrices are equivalent if ( nexId.equals(tbId) ) { foundEquivalentMatrix = true; Assert.assertTrue("NeXML matrix "+nexId+ " is one of the known subclasses", nexMatrix instanceof CategoricalMatrix || nexMatrix instanceof MolecularMatrix || nexMatrix instanceof ContinuousMatrix); // we have to coerce the tbMatrix into a character matrix to get its character sets CharacterMatrix tbCharacterMatrix = (CharacterMatrix)tbMatrix; Set<CharSet> tbCharSets = tbCharacterMatrix.getCharSets(); // a treebase matrix has zero or more character sets, we must iterate over them for ( CharSet tbCharSet : tbCharSets ) { // the coordinates of the character set are defined by a collection of column ranges that we iterate over Collection<ColumnRange> tbColumnRanges = tbCharSet.getColumns(tbCharacterMatrix); for ( ColumnRange tbColumnRange : tbColumnRanges ) { // these are the beginning and end of the range int start = tbColumnRange.getStartColIndex(); int stop = tbColumnRange.getEndColIndex(); // this is how we increment from beginning to end. This number is probably either null, for a // contiguous range, or perhaps 3 for codon positions int inc = 1; // need to do this to prevent nullpointerexceptions if ( null != tbColumnRange.getRepeatInterval() ) { inc = tbColumnRange.getRepeatInterval(); } // this is how we create the equivalent nexml character set // you will need to update CharSet to get the new implementation of getLabel(), which // returns the same value as getTitle() Subset nexSubset = nexMatrix.createSubset(tbCharSet.getLabel()); // we have to assign character objects to the subset. Here we get the full list List<org.nexml.model.Character> nexCharacters = nexMatrix.getCharacters(); // now we iterate over the coordinates and assign the nexml characters to the set for ( int i = start; i <= stop; i += inc ) { nexSubset.addThing(nexCharacters.get(i)); } } } } } Assert.assertTrue("Searched for equivalent to NeXML matrix "+nexId, foundEquivalentMatrix); System.out.println(nexDoc.getXmlString()); } } /** * Test for {@link org.cipres.treebase.domain.nexus.nexml.NexmlMatrixConverter#}. * It verifies that NexmlCharSets have the same name and coordinates as those in the * TreeBASE matrix. */ public void testNexmlMatrixCharSets() { String testName = "testNexmlCharSets"; //signal beginning of test if (logger.isInfoEnabled()) { logger.info("Running Test: " + testName); } long studyId = 794; // this is the full study as it is stored by the database Study tbStudy = (Study)loadObject(Study.class, studyId); //check if study has character state matrices exist if (tbStudy.getMatrices() != null) { // these are the character state matrices that are part of the study Set<org.cipres.treebase.domain.matrix.Matrix> tbMatrices = tbStudy.getMatrices(); // this is an object representation of a NeXML document Document nexDoc = DocumentFactory.safeCreateDocument(); // the converter populates the NeXML document with the contents of the treebase study NexmlDocumentConverter ndc = new NexmlDocumentConverter(tbStudy,getTaxonLabelHome(),nexDoc); ndc.fromTreeBaseToXml(tbStudy); // here is where the conversion happens // these are the NeXML matrices that were created from the study List<Matrix<?>> nexMatrices = nexDoc.getMatrices(); // there most be more than zero matrices because every treebase study has at least one matrix Assert.assertTrue(nexMatrices.size() != 0 ); // now we're going to match up the NeXML matrices with their equivalent treebase ones for ( Matrix<?> nexMatrix : nexMatrices ) { // the xml id is the same as the primary key of the equivalent matrix stored by treebase String nexId = nexMatrix.getId(); // iterate over all treebase matrices for the study for ( org.cipres.treebase.domain.matrix.Matrix tbMatrix : tbMatrices ) { String tbId = "M" + tbMatrix.getId(); // if true, the matrices are equivalent if ( nexId.equals(tbId) ) { Assert.assertTrue("NeXML matrix "+nexId+ " is one of the known subclasses", nexMatrix instanceof CategoricalMatrix || nexMatrix instanceof MolecularMatrix || nexMatrix instanceof ContinuousMatrix); // we have to coerce the tbMatrix into a character matrix to get its character sets CharacterMatrix tbCharacterMatrix = (CharacterMatrix)tbMatrix; Set<CharSet> tbCharSets = tbCharacterMatrix.getCharSets(); // a treebase matrix has zero or more character sets, we must iterate over them for ( CharSet tbCharSet : tbCharSets ) { // the coordinates of the character set are defined by a collection of column ranges that we iterate over Collection<ColumnRange> tbColumnRanges = tbCharSet.getColumns(tbCharacterMatrix); for ( ColumnRange tbColumnRange : tbColumnRanges ) { // these are the beginning and end of the range int tbStart = tbColumnRange.getStartColIndex(); int tbStop = tbColumnRange.getEndColIndex(); // this is how we increment from beginning to end. This number is probably either null, for a // contiguous range, or perhaps 3 for codon positions int tbInc = 1; // need to do this to prevent nullpointerexceptions if ( null != tbColumnRange.getRepeatInterval()) { tbInc = tbColumnRange.getRepeatInterval(); } // this is how we create the equivalent nexml character set Subset nexSubset = nexMatrix.createSubset(tbCharSet.getLabel()); //get names of TreeBASE and NeXML character set String tbCharSetName = tbCharSet.getLabel(); String nexCharSetName = nexSubset.getLabel(); //verify that the names are the same Assert.assertTrue(tbCharSetName.equals(nexCharSetName)); // we have to assign character objects to the subset. Here we get the full list List<org.nexml.model.Character> nexCharacters = nexMatrix.getCharacters(); // now we iterate over the coordinates and assign the nexml characters to the set //and verify coordinates of TreeBASE characterset and nexml characterset //are the same for ( int i = tbStart; i <= tbStop; i += tbInc ) { nexSubset.addThing(nexCharacters.get(i)); //declare coordinate index int nexCharSetCoordinate = nexCharacters.indexOf(nexCharacters.get(i)); int tbCharSetCoordinate = i; Assert.assertTrue( nexCharSetCoordinate == tbCharSetCoordinate ); } } } } } } } else { System.out.println("This study has no associated character sets!"); } } /** * Return the TaxonLabelHome field. * * @return TaxonLabelHome mTaxonLabelHome */ public TaxonLabelHome getTaxonLabelHome() { return mTaxonLabelHome; } /** * Set the TaxonLabelHome field. */ public void setTaxonLabelHome(TaxonLabelHome pNewTaxonLabelHome) { mTaxonLabelHome = pNewTaxonLabelHome; } }
package org.jboss.forge.addon.ui.impl.annotation; import java.io.File; import org.jboss.forge.addon.ui.UIDesktop; import org.jboss.forge.addon.ui.UIProvider; import org.jboss.forge.addon.ui.context.UIContext; import org.jboss.forge.addon.ui.context.UIExecutionContext; import org.jboss.forge.addon.ui.input.UIPrompt; import org.jboss.forge.addon.ui.output.UIOutput; import org.jboss.forge.addon.ui.progress.UIProgressMonitor; import org.junit.Assert; import org.junit.Test; /** * Test class for {@link ReservedParameters} * * @author <a href="ggastald@redhat.com">George Gastaldi</a> */ public class ReservedParametersTest { @Test public void testIsReservedParameter() { Assert.assertTrue(ReservedParameters.isReservedParameter(UIContext.class)); Assert.assertTrue(ReservedParameters.isReservedParameter(UIPrompt.class)); Assert.assertTrue(ReservedParameters.isReservedParameter(UIOutput.class)); Assert.assertTrue(ReservedParameters.isReservedParameter(UIProgressMonitor.class)); Assert.assertTrue(ReservedParameters.isReservedParameter(UIProvider.class)); Assert.assertTrue(ReservedParameters.isReservedParameter(UIExecutionContext.class)); Assert.assertTrue(ReservedParameters.isReservedParameter(UIDesktop.class)); Assert.assertFalse(ReservedParameters.isReservedParameter(String.class)); Assert.assertFalse(ReservedParameters.isReservedParameter(File.class)); } }
package com.bounswe.group7.web.controller; import com.bounswe.group7.api.client.CommentServiceClient; import com.bounswe.group7.api.client.LoginServiceClient; import com.bounswe.group7.api.client.TopicServiceClient; import com.bounswe.group7.model.Topics; import com.bounswe.group7.model.Users; import com.bounswe.group7.model.security.Authority; import com.bounswe.group7.model.security.AuthorityName; import com.bounswe.group7.web.domain.TopicWithStatistics; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; /** * * @author ugurbor */ @RestController public class MainController { @RequestMapping("/") public ModelAndView index(HttpServletRequest request, HttpServletResponse response, RedirectAttributes attributes) { ModelAndView index = new ModelAndView("index"); HttpSession session = request.getSession(); TopicServiceClient client = new TopicServiceClient((String) session.getAttribute("token")); CommentServiceClient commentClient = new CommentServiceClient((String) session.getAttribute("token")); try { List<Topics> recentTopicsList = client.getRecentTopics(); List<Topics> topTopicsList = client.getTopTopics(); List<TopicWithStatistics> recentTopicStatisticsList = new ArrayList<TopicWithStatistics>(); for (Topics temp : recentTopicsList) { Long topicId = temp.getTopicId(); int commentNumber = commentClient.getTopicComments(topicId).size(); recentTopicStatisticsList.add(new TopicWithStatistics(temp.getTopicId(), temp.getHeader(), commentNumber)); } List<TopicWithStatistics> topTopicStatisticsList = new ArrayList<TopicWithStatistics>(); for (Topics temp : topTopicsList) { Long topicId = temp.getTopicId(); int commentNumber = commentClient.getTopicComments(topicId).size(); recentTopicStatisticsList.add(new TopicWithStatistics(temp.getTopicId(), temp.getHeader(), commentNumber)); } ObjectMapper mapper = new ObjectMapper(); String recentTopics = mapper.writeValueAsString(recentTopicStatisticsList); String topTopics = mapper.writeValueAsString(topTopicStatisticsList); index.addObject("recentTopics", recentTopics); index.addObject("topTopics", topTopics); } catch (Exception ex) { ex.printStackTrace(); attributes.addFlashAttribute("error", ex.getMessage()); } return index; } @RequestMapping("/home") public ModelAndView home(HttpServletRequest request, HttpServletResponse response, RedirectAttributes attributes) { ModelAndView index = new ModelAndView("home"); HttpSession session = request.getSession(); TopicServiceClient client = new TopicServiceClient((String) session.getAttribute("token")); CommentServiceClient commentClient = new CommentServiceClient((String) session.getAttribute("token")); try { List<Topics> recentTopicsList = client.getRecentTopics(); List<Topics> topTopicsList = client.getTopTopics(); List<TopicWithStatistics> recentTopicStatisticsList = new ArrayList<TopicWithStatistics>(); for (Topics temp : recentTopicsList) { Long topicId = temp.getTopicId(); int commentNumber = commentClient.getTopicComments(topicId).size(); recentTopicStatisticsList.add(new TopicWithStatistics(temp.getTopicId(), temp.getHeader(), commentNumber)); } List<TopicWithStatistics> topTopicStatisticsList = new ArrayList<TopicWithStatistics>(); for (Topics temp : topTopicsList) { Long topicId = temp.getTopicId(); int commentNumber = commentClient.getTopicComments(topicId).size(); recentTopicStatisticsList.add(new TopicWithStatistics(temp.getTopicId(), temp.getHeader(), commentNumber)); } ObjectMapper mapper = new ObjectMapper(); String recentTopics = mapper.writeValueAsString(recentTopicStatisticsList); String topTopics = mapper.writeValueAsString(topTopicStatisticsList); index.addObject("recentTopics", recentTopics); index.addObject("topTopics", topTopics); } catch (Exception ex) { ex.printStackTrace(); attributes.addFlashAttribute("error", ex.getMessage()); } return index; } @RequestMapping(value = "/register", method = RequestMethod.POST) public ModelAndView register(HttpServletRequest request, RedirectAttributes attributes) throws NullPointerException { Users user = new Users(); LoginServiceClient client = new LoginServiceClient(); ModelAndView modelAndView = new ModelAndView("redirect:/"); try { user.setFirstname(request.getParameter("firstname")); user.setLastname(request.getParameter("lastname")); user.setUsername(request.getParameter("username")); user.setPassword(request.getParameter("password")); user.setEmail(request.getParameter("email")); user.setGender(request.getParameter("gender")); String level = request.getParameter("status"); List<Authority> authorityList = new ArrayList<Authority>(); if (level.equals("creator")) { authorityList.add(new Authority(new Long(AuthorityName.ROLE_CREATOR.getId()), AuthorityName.ROLE_CREATOR)); authorityList.add(new Authority(new Long(AuthorityName.ROLE_EXPLORER.getId()), AuthorityName.ROLE_EXPLORER)); } else if (level.equals("explorer")) { authorityList.add(new Authority(new Long(AuthorityName.ROLE_EXPLORER.getId()), AuthorityName.ROLE_EXPLORER)); } user.setAuthorities(authorityList); client.register(user); //TODO mailing is needed after the registration } catch (Exception ex) { ex.printStackTrace(); attributes.addFlashAttribute("error", ex.getMessage()); } return modelAndView; } }
package com.snowble.android.verticalstepper; import android.app.Activity; import android.os.Build; import android.support.v7.widget.AppCompatButton; import android.view.View; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.util.ActivityController; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(RobolectricTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.M) public class VerticalStepperTest { private Activity activity; private VerticalStepper stepper; @Before public void before() { ActivityController<DummyActivity> activityController = Robolectric.buildActivity(DummyActivity.class); activity = activityController.create().get(); stepper = new VerticalStepper(activity); } @Test public void toggleStepExpandedState_Inactive_ShouldBecomeActiveAndExpanded() { testStepToggle(false, View.GONE, true, View.VISIBLE); } @Test public void toggleStepExpandedState_Active_ShouldBecomeInactiveAndCollapsed() { testStepToggle(true, View.VISIBLE, false, View.GONE); } private void testStepToggle(boolean initialActivateState, int initialVisibility, boolean finalExpectedActiveState, int finalExpectedVisibility) { VerticalStepper.LayoutParams lp = createTestLayoutParams(); lp.active = initialActivateState; when(lp.continueButton.getVisibility()).thenReturn(initialVisibility); View innerView = mock(View.class); when(innerView.getVisibility()).thenReturn(initialVisibility); when(innerView.getLayoutParams()).thenReturn(lp); stepper.toggleStepExpandedState(innerView); assertThat(lp.active).isEqualTo(finalExpectedActiveState); verify(innerView).setVisibility(finalExpectedVisibility); verify(lp.continueButton).setVisibility(finalExpectedVisibility); } private VerticalStepper.LayoutParams createTestLayoutParams() { Robolectric.AttributeSetBuilder attributeSetBuilder = Robolectric.buildAttributeSet(); attributeSetBuilder.addAttribute(android.R.attr.layout_width, "wrap_content"); attributeSetBuilder.addAttribute(android.R.attr.layout_height, "wrap_content"); attributeSetBuilder.addAttribute(R.attr.step_title, "title"); VerticalStepper.LayoutParams lp = new VerticalStepper.LayoutParams(activity, attributeSetBuilder.build()); lp.continueButton = mock(AppCompatButton.class); return lp; } private static class DummyActivity extends Activity { } }
package org.opens.tgol.controller; import java.util.Collection; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.opens.tgol.command.CreateContractCommand; import org.opens.tgol.command.CreateUserCommand; import org.opens.tgol.command.factory.CreateContractCommandFactory; import org.opens.tgol.entity.contract.Contract; import org.opens.tgol.entity.user.User; import org.opens.tgol.exception.ForbiddenUserException; import org.opens.tgol.form.parameterization.ContractOptionFormField; import org.opens.tgol.form.parameterization.helper.ContractOptionFormFieldHelper; import org.opens.tgol.util.TgolKeyStore; import org.springframework.beans.propertyeditors.CustomCollectionEditor; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; /** * * @author jkowalczyk */ @Controller public class UserManagementController extends AbstractUserAndContractsController { public UserManagementController() { super(); } @InitBinder @Override protected void initBinder(WebDataBinder binder) { super.initBinder(binder); binder.registerCustomEditor(Collection.class, "userList", new CustomCollectionEditor(Collection.class) { @Override protected Object convertElement(Object element) { Long id = null; if (element instanceof String && !((String) element).equals("")) { //From the JSP 'element' will be a String try { id = Long.parseLong((String) element); } catch (NumberFormatException e) { Logger.getLogger(this.getClass()).warn("Element was " + ((String) element)); } } else if (element instanceof Long) { //From the database 'element' will be a Long id = (Long) element; } return id != null ? getUserDataService().read(id) : null; } }); } /** * @param request * @param response * @param model * @return The pages audit set-up form page */ @RequestMapping(value = TgolKeyStore.ADMIN_URL, method = RequestMethod.GET) @Secured(TgolKeyStore.ROLE_ADMIN_KEY) public String displayAdminPage( HttpServletRequest request, HttpServletResponse response, Model model) { model.addAttribute(TgolKeyStore.USER_LIST_KEY, getUserDataService().findAll()); // Due to different redirection that can lead to this page, we need // to test the different session attribute to display an appropriate // message and thus clean up the session with uneeded attributes if (request.getSession().getAttribute(TgolKeyStore.DELETED_USER_NAME_KEY) != null) { model.addAttribute(TgolKeyStore.DELETED_USER_NAME_KEY, request.getSession().getAttribute(TgolKeyStore.DELETED_USER_NAME_KEY)); request.getSession().removeAttribute(TgolKeyStore.DELETED_USER_NAME_KEY); } if (request.getSession().getAttribute(TgolKeyStore.DELETED_USER_AUDITS_KEY) != null) { model.addAttribute(TgolKeyStore.DELETED_USER_AUDITS_KEY, request.getSession().getAttribute(TgolKeyStore.DELETED_USER_AUDITS_KEY)); request.getSession().removeAttribute(TgolKeyStore.DELETED_USER_AUDITS_KEY); } if (request.getSession().getAttribute(TgolKeyStore.UPDATED_USER_NAME_KEY) != null) { model.addAttribute(TgolKeyStore.UPDATED_USER_NAME_KEY, request.getSession().getAttribute(TgolKeyStore.UPDATED_USER_NAME_KEY)); request.getSession().removeAttribute(TgolKeyStore.UPDATED_USER_NAME_KEY); } if (request.getSession().getAttribute(TgolKeyStore.ADDED_USER_NAME_KEY) != null) { model.addAttribute(TgolKeyStore.ADDED_USER_NAME_KEY, request.getSession().getAttribute(TgolKeyStore.ADDED_USER_NAME_KEY)); request.getSession().removeAttribute(TgolKeyStore.UPDATED_USER_NAME_KEY); } if (request.getSession().getAttribute(TgolKeyStore.ADDED_CONTRACT_NAME_KEY) != null && request.getSession().getAttribute(TgolKeyStore.ADDED_CONTRACT_USERS_NAME_KEY) != null) { model.addAttribute(TgolKeyStore.ADDED_CONTRACT_NAME_KEY, request.getSession().getAttribute(TgolKeyStore.ADDED_CONTRACT_NAME_KEY)); model.addAttribute(TgolKeyStore.ADDED_CONTRACT_USERS_NAME_KEY, request.getSession().getAttribute(TgolKeyStore.ADDED_CONTRACT_USERS_NAME_KEY)); request.getSession().removeAttribute(TgolKeyStore.ADDED_CONTRACT_USERS_NAME_KEY); request.getSession().removeAttribute(TgolKeyStore.ADDED_CONTRACT_NAME_KEY); } return TgolKeyStore.ADMIN_VIEW_NAME; } /** * @param userId * @param request * @param response * @param model * @return The pages audit set-up form page */ @RequestMapping(value = TgolKeyStore.EDIT_USER_URL, method = RequestMethod.GET) @Secured(TgolKeyStore.ROLE_ADMIN_KEY) public String displayEditUserAdminPage( @RequestParam(TgolKeyStore.USER_ID_KEY) String userId, HttpServletRequest request, HttpServletResponse response, Model model) { Long lUserId; try { lUserId = Long.valueOf(userId); } catch (NumberFormatException nfe) { throw new ForbiddenUserException(); } User userToModify = getUserDataService().read(lUserId); model.addAttribute(TgolKeyStore.USER_NAME_KEY, userToModify.getEmail1()); request.getSession().setAttribute(TgolKeyStore.USER_ID_KEY, lUserId); return prepateDataAndReturnCreateUserView( model, userToModify, TgolKeyStore.EDIT_USER_VIEW_NAME); } /** * This methods controls the validity of the form and launch an audit with * values populated by the user. In case of audit failure, an appropriate * message is displayed * * @param createUserCommand * @param result * @param request * @param model * @return * @throws Exception */ @RequestMapping(value = TgolKeyStore.EDIT_USER_URL, method = RequestMethod.POST) @Secured(TgolKeyStore.ROLE_ADMIN_KEY) protected String submitEditUserForm( @ModelAttribute(TgolKeyStore.CREATE_USER_COMMAND_KEY) CreateUserCommand createUserCommand, BindingResult result, HttpServletRequest request, Model model) throws Exception { Long userId; try { userId = (Long) (request.getSession().getAttribute(TgolKeyStore.USER_ID_KEY)); } catch (NumberFormatException nfe) { throw new ForbiddenUserException(); } boolean updateAllData = true; if (getCurrentUser().getId().equals(userId)) { updateAllData = false; } return submitUpdateUserForm( createUserCommand, result, request, model, getUserDataService().read(userId), TgolKeyStore.ADMIN_VIEW_NAME, TgolKeyStore.EDIT_USER_VIEW_NAME, updateAllData, true, TgolKeyStore.UPDATED_USER_NAME_KEY); } /** * @param request * @param response * @param model * @return The pages audit set-up form page */ @RequestMapping(value = TgolKeyStore.ADD_USER_URL, method = RequestMethod.GET) @Secured(TgolKeyStore.ROLE_ADMIN_KEY) public String displayAddUserAdminPage( HttpServletRequest request, HttpServletResponse response, Model model) { return prepateDataAndReturnCreateUserView( model, null, TgolKeyStore.ADD_USER_VIEW_NAME); } /** * This methods controls the validity of the form and launch an audit with * values populated by the user. In case of audit failure, an appropriate * message is displayed * * @param createUserCommand * @param result * @param model * @return * @throws Exception */ @RequestMapping(value = TgolKeyStore.ADD_USER_URL, method = RequestMethod.POST) protected String submitAddUserForm( @ModelAttribute(TgolKeyStore.CREATE_USER_COMMAND_KEY) CreateUserCommand createUserCommand, BindingResult result, Model model) throws Exception { return submitCreateUserForm( createUserCommand, result, model, TgolKeyStore.ADMIN_VIEW_NAME, TgolKeyStore.ADD_USER_VIEW_NAME, true, TgolKeyStore.ADDED_USER_NAME_KEY); } /** * @param userId * @param request * @param response * @param model * @return The pages audit set-up form page */ @RequestMapping(value = TgolKeyStore.DELETE_USER_URL, method = RequestMethod.GET) @Secured(TgolKeyStore.ROLE_ADMIN_KEY) public String displayDeleteUserPage( @RequestParam(TgolKeyStore.USER_ID_KEY) String userId, HttpServletRequest request, HttpServletResponse response, Model model) { Long lUserId; try { lUserId = Long.valueOf(userId); } catch (NumberFormatException nfe) { throw new ForbiddenUserException(); } User userToDelete = getUserDataService().read(lUserId); if (userToDelete == null || getCurrentUser().getId().equals(userToDelete.getId())) { return TgolKeyStore.ACCESS_DENIED_VIEW_NAME; } model.addAttribute(TgolKeyStore.USER_NAME_TO_DELETE_KEY, userToDelete.getEmail1()); request.getSession().setAttribute(TgolKeyStore.USER_ID_TO_DELETE_KEY, userToDelete.getId()); return TgolKeyStore.DELETE_USER_VIEW_NAME; } /** * @param request * @param response * @param model * @return The pages audit set-up form page */ @RequestMapping(value = TgolKeyStore.DELETE_USER_URL, method = RequestMethod.POST) @Secured(TgolKeyStore.ROLE_ADMIN_KEY) public String displayDeleteUserConfirmation( HttpServletRequest request, HttpServletResponse response, Model model) { Object userId = request.getSession().getAttribute(TgolKeyStore.USER_ID_TO_DELETE_KEY); Long lUserId; if (userId instanceof Long) { lUserId = (Long) userId; } else { try { lUserId = Long.valueOf(userId.toString()); } catch (NumberFormatException nfe) { throw new ForbiddenUserException(); } } User user = getCurrentUser(); User userToDelete = getUserDataService().read(lUserId); if (userToDelete == null || user.getId().equals(userToDelete.getId())) { return TgolKeyStore.ACCESS_DENIED_VIEW_NAME; } for (Contract contract : userToDelete.getContractSet()) { deleteAllAuditsFromContract(contract); } getUserDataService().delete(userToDelete.getId()); request.getSession().removeAttribute(TgolKeyStore.USER_ID_TO_DELETE_KEY); request.getSession().setAttribute(TgolKeyStore.DELETED_USER_NAME_KEY, userToDelete.getEmail1()); return TgolKeyStore.ADMIN_VIEW_REDIRECT_NAME; } /** * @param userId * @param request * @param response * @param model * @return */ @RequestMapping(value = TgolKeyStore.DELETE_USER_AUDITS_URL, method = RequestMethod.GET) @Secured(TgolKeyStore.ROLE_ADMIN_KEY) public String displayDeleteUserAuditsPage( @RequestParam(TgolKeyStore.USER_ID_KEY) String userId, HttpServletRequest request, HttpServletResponse response, Model model) { Long lUserId; try { lUserId = Long.valueOf(userId); } catch (NumberFormatException nfe) { throw new ForbiddenUserException(); } User userToDelete = getUserDataService().read(lUserId); model.addAttribute(TgolKeyStore.USER_NAME_TO_DELETE_KEY, userToDelete.getEmail1()); request.getSession().setAttribute(TgolKeyStore.USER_ID_TO_DELETE_KEY, userToDelete.getId()); return TgolKeyStore.DELETE_AUDITS_VIEW_NAME; } /** * @param request * @param response * @param model * @return the name of the view that displays the confirmation page * when trying to delete all the audits of a user */ @RequestMapping(value = TgolKeyStore.DELETE_USER_AUDITS_URL, method = RequestMethod.POST) @Secured(TgolKeyStore.ROLE_ADMIN_KEY) public String displayDeleteUserAuditsConfirmationPage( HttpServletRequest request, HttpServletResponse response, Model model) { Object userId = request.getSession().getAttribute(TgolKeyStore.USER_ID_TO_DELETE_KEY); Long lUserId; if (userId instanceof Long) { lUserId = (Long) userId; } else { try { lUserId = Long.valueOf(userId.toString()); } catch (NumberFormatException nfe) { throw new ForbiddenUserException(); } } User userToDelete = getUserDataService().read(lUserId); for (Contract contract : userToDelete.getContractSet()) { deleteAllAuditsFromContract(contract); } request.getSession().removeAttribute(TgolKeyStore.USER_ID_TO_DELETE_KEY); request.getSession().setAttribute(TgolKeyStore.DELETED_USER_AUDITS_KEY, userToDelete.getEmail1()); return TgolKeyStore.ADMIN_VIEW_REDIRECT_NAME; } /** * @param request * @param response * @param model * @return The pages audit set-up form page */ @RequestMapping(value = TgolKeyStore.ADD_CONTRACT_URL, method = RequestMethod.GET) @Secured(TgolKeyStore.ROLE_ADMIN_KEY) public String displayAddContractAdminPage( HttpServletRequest request, HttpServletResponse response, Model model) { return prepateDataAndReturnCreateContractView( model, null, null, ContractOptionFormFieldHelper.getFreshContractOptionFormFieldMap(getContractOptionFormFieldBuilderMap()), TgolKeyStore.ADD_CONTRACT_VIEW_NAME); } /** * @param ccc the CreateContractCommand * @param result * @param request * @param response * @param model * @return The pages audit set-up form page */ @RequestMapping(value = TgolKeyStore.ADD_CONTRACT_URL, method = RequestMethod.POST) @Secured(TgolKeyStore.ROLE_ADMIN_KEY) public String submitAddContractAdminPage( @ModelAttribute(TgolKeyStore.CREATE_CONTRACT_COMMAND_KEY) CreateContractCommand ccc, BindingResult result, HttpServletRequest request, HttpServletResponse response, Model model) { Map<String, List<ContractOptionFormField>> optionFormFieldMap = ContractOptionFormFieldHelper.getFreshContractOptionFormFieldMap(getContractOptionFormFieldBuilderMap()); getCreateContractFormValidator().setContractOptionFormFieldMap(optionFormFieldMap); // We check whether the form is valid getCreateContractFormValidator().validateMultipleUsers(ccc, result); if (result.hasErrors()) { return displayFormWithErrors( model, ccc, null, null, optionFormFieldMap, TgolKeyStore.ADD_CONTRACT_VIEW_NAME); } Collection<User> userList = ccc.getUserList(); StringBuilder strb = new StringBuilder(); for (User user : userList) { if (user != null) { Contract contract = getContractDataService().create(); contract.setUser(user); contract = CreateContractCommandFactory.getInstance().updateContractFromCommand( ccc, contract); getContractDataService().saveOrUpdate(contract); strb.append(user.getEmail1()); strb.append(", "); } } request.getSession().setAttribute(TgolKeyStore.ADDED_CONTRACT_NAME_KEY,ccc.getLabel()); request.getSession().setAttribute(TgolKeyStore.ADDED_CONTRACT_USERS_NAME_KEY,strb.toString()); return TgolKeyStore.ADMIN_VIEW_REDIRECT_NAME; } }
package edu.northwestern.bioinformatics.studycalendar.web; import edu.northwestern.bioinformatics.studycalendar.dao.SiteDao; import edu.northwestern.bioinformatics.studycalendar.dao.UserDao; import edu.northwestern.bioinformatics.studycalendar.domain.Role; import static edu.northwestern.bioinformatics.studycalendar.domain.Role.*; import edu.northwestern.bioinformatics.studycalendar.domain.Site; import edu.northwestern.bioinformatics.studycalendar.domain.User; import edu.northwestern.bioinformatics.studycalendar.domain.UserRole; import edu.northwestern.bioinformatics.studycalendar.service.UserRoleService; import edu.northwestern.bioinformatics.studycalendar.service.UserService; import edu.northwestern.bioinformatics.studycalendar.web.osgi.InstalledAuthenticationSystem; import edu.nwu.bioinformatics.commons.spring.Validatable; import org.apache.commons.lang.StringUtils; import org.apache.commons.validator.GenericValidator; import org.springframework.validation.Errors; import org.acegisecurity.Authentication; import org.acegisecurity.context.SecurityContextHolder; import java.io.Serializable; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; public class CreateUserCommand implements Validatable, Serializable { private String password; private String emailAddress; private String rePassword; private boolean passwordModified; private User user; private Map<Site, Map<Role, RoleCell>> rolesGrid; private boolean userActiveFlag; private UserService userService; private SiteDao siteDao; private UserRoleService userRoleService; private UserDao userDao; private InstalledAuthenticationSystem installedAuthenticationSystem; private Boolean initialAdministrator = false; public CreateUserCommand( User user, SiteDao siteDao, UserService userService, UserDao userDao, UserRoleService userRoleService, InstalledAuthenticationSystem installedAuthenticationSystem ) { this.user = user == null ? new User() : user; this.siteDao = siteDao; this.userService = userService; this.userDao = userDao; this.userRoleService = userRoleService; this.installedAuthenticationSystem = installedAuthenticationSystem; this.passwordModified = false; this.emailAddress = this.user.getId() == null ? null : userService.getEmailAddresssForUser(user); buildRolesGrid(this.user.getUserRoles()); } private void buildRolesGrid(Set<UserRole> userRoles) { boolean selected; rolesGrid = new LinkedHashMap<Site, Map<Role, RoleCell>>(); for (Site site : siteDao.getAll()) { for (Role role : values()) { selected = false; for (UserRole userRole : userRoles) { if (userRole.getRole().equals(role) && (!role.isSiteSpecific() || userRole.getSites().contains(site))) { selected = true; break; } } if (!rolesGrid.containsKey(site)) { rolesGrid.put(site, new HashMap<Role, RoleCell>()); } rolesGrid.get(site).put(role, createRoleCell(selected, role.isSiteSpecific())); } } } public void validate(Errors errors) { if (user != null) { if (user.getName() == null || StringUtils.isEmpty(user.getName())) { errors.rejectValue("user.name", "error.user.name.not.specified"); } else { if (user.getId() == null && userDao.getByName(user.getName()) != null) { errors.rejectValue("user.name", "error.user.name.already.exists"); } } //For the case where emails are not set, this shouldn't be a stopping point to edit a particular user if (user.getId() == null) { if (emailAddress == null || StringUtils.isEmpty(emailAddress)) { errors.rejectValue("emailAddress", "error.user.email.not.specified"); } else if (!GenericValidator.isEmail(emailAddress)) { errors.rejectValue("emailAddress", "error.user.email.invalid"); } } if (updatePassword() && installedAuthenticationSystem.getAuthenticationSystem().usesLocalPasswords()) { if (password == null || StringUtils.isBlank(password)) { errors.rejectValue("password", "error.user.password.not.specified"); } else { if (!password.equals(rePassword)) { errors.rejectValue("rePassword", "error.user.repassword.does.not.match.password"); } } } } for (Site site : getRolesGrid().keySet()) { // prevent the removal of the last site coordinator for a site that has assignments if (site.hasAssignments()) { List<User> siteCoords = userDao.getSiteCoordinators(site); if (siteCoords.size() == 1 && siteCoords.contains(getUser())) { if (!getRolesGrid().get(site).get(SITE_COORDINATOR).isSelected()) { errors.rejectValue(gridFieldName(site, SITE_COORDINATOR), "error.user.last-site-coordinator", new Object[]{getUser().getName(), site.getName()}, "Last site coordinator"); } } } // prevent the removal of subject coordinators with assignments if (!getRolesGrid().get(site).get(SUBJECT_COORDINATOR).isSelected()) { if (getUser().hasAssignment(site)) { errors.rejectValue( gridFieldName(site, SUBJECT_COORDINATOR), "error.user.subject-coordinator-has-subjects", new Object[]{getUser().getName(), site.getName()}, "Subject coordinator has subjects" ); } } } } private String gridFieldName(Site site, Role role) { return String.format("rolesGrid[%d][%s].selected", site.getId(), role); } public User apply() throws Exception { if (updatePassword()) { user.setActiveFlag(isUserActiveFlag()); userService.saveUser(user, getOrCreatePassword(), getEmailAddress()); } else { if (user!= null && !userService.getEmailAddresssForUser(user).equals(getEmailAddress())) { userService.saveUser(user, getPassword(), getEmailAddress()); } // must be update only //make sure user has not updated email address user.setActiveFlag(isUserActiveFlag()); userDao.save(user); } if (initialAdministrator) { userRoleService.assignUserRole(user, Role.SYSTEM_ADMINISTRATOR, null); } else { assignUserRolesFromRolesGrid(); } refreshUser(user); return user; } private boolean updatePassword() { return passwordModified || user.getId() == null; } private void refreshUser(User user) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { User authenticatedUser = (User) authentication.getPrincipal(); if (user != null && user.getName().equals(authenticatedUser.getName())) { installedAuthenticationSystem.reloadAuthorities(); } } } // generate a random password when creating a new user in a regime that doesn't use the internal passwords private String getOrCreatePassword() { if (installedAuthenticationSystem.getAuthenticationSystem().usesLocalPasswords()) { return getPassword(); } else { int length = 16 + (int) Math.round(16 * Math.random()); StringBuilder generated = new StringBuilder(); while (generated.length() < length) { generated.append((char) (' ' + Math.round(('~' - ' ') * Math.random()))); } return generated.toString(); } } protected void assignUserRolesFromRolesGrid() throws Exception { for (Site site : rolesGrid.keySet()) { for (Role role : rolesGrid.get(site).keySet()) { if (role.isSiteSpecific()) { if (rolesGrid.get(site).get(role).isSelected()) { userRoleService.assignUserRole(user, role, site); } else { userRoleService.removeUserRoleAssignment(user, role, site); } } } } Set<Role> roleList = rolesGrid.values().iterator().next().keySet(); for (Role role : roleList) { if (!role.isSiteSpecific()) { int selected = 0; int notSelected = 0; for (Site innerSite : rolesGrid.keySet()) { if (!rolesGrid.get(innerSite).get(role).isSelected()) notSelected++; if (rolesGrid.get(innerSite).get(role).isSelected()) selected++; } if (selected == notSelected) { if (user.getUserRole(role) == null) { userRoleService.assignUserRole(user, role); } else { userRoleService.removeUserRoleAssignment(user, role); } } else if (selected == 1) { userRoleService.assignUserRole(user, role); } else if (notSelected == 1) { userRoleService.removeUserRoleAssignment(user, role); } else if (selected > notSelected) { userRoleService.assignUserRole(user, role); } else if (notSelected > selected) { userRoleService.removeUserRoleAssignment(user, role); } } } } public static class RoleCell implements Serializable { private boolean selected; private boolean siteSpecific; public RoleCell(boolean selected, boolean siteSpecific) { this.selected = selected; this.siteSpecific = siteSpecific; } public boolean isSelected() { return selected; } public boolean isSiteSpecific() { return siteSpecific; } public void setSelected(boolean selected) { this.selected = selected; } public void setSiteSpecific(boolean siteSpecific) { this.siteSpecific = siteSpecific; } } protected static RoleCell createRoleCell(boolean selected, boolean siteSpecific) { return new RoleCell(selected, siteSpecific); } ////// BOUND PROPERTIES public User getUser() { return user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRePassword() { return rePassword; } public void setRePassword(String rePassword) { this.rePassword = rePassword; } public Map<Site, Map<Role, RoleCell>> getRolesGrid() { return rolesGrid; } public boolean isPasswordModified() { return passwordModified; } public void setPasswordModified(boolean passwordModified) { this.passwordModified = passwordModified; } public void setUserActiveFlag(boolean userActiveFlag) { this.userActiveFlag = userActiveFlag; } public boolean isUserActiveFlag() { return userActiveFlag; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(final String emailAddress) { this.emailAddress = emailAddress; } public void setInitialAdministrator(Boolean initialAdministrator) { this.initialAdministrator = initialAdministrator; } }
package uk.ac.ebi.biosamples.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.MediaTypes; import org.springframework.hateoas.Resource; import org.springframework.hateoas.Resources; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import uk.ac.ebi.biosamples.model.Sample; import uk.ac.ebi.biosamples.model.filter.Filter; import uk.ac.ebi.biosamples.model.ga4gh.Ga4ghSample; import uk.ac.ebi.biosamples.service.GA4GHFilterBuilder; import uk.ac.ebi.biosamples.service.Ga4ghSampleResourceAssembler; import uk.ac.ebi.biosamples.service.SampleToGa4ghSampleConverter; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; @RestController @RequestMapping(value = "samples/ga4gh", produces = "application/json") public class GA4GHSampeSearchController { private GA4GHFilterBuilder filterBuilder; private SamplesRestController restController; private SampleToGa4ghSampleConverter mapper; private Ga4ghSampleResourceAssembler resourceAssembler; @Autowired public GA4GHSampeSearchController(GA4GHFilterBuilder filterBuilder, SamplesRestController controller, SampleToGa4ghSampleConverter mapper, Ga4ghSampleResourceAssembler resourceAssembler) { this.filterBuilder = filterBuilder; this.restController = controller; this.mapper = mapper; this.resourceAssembler = resourceAssembler; } @RequestMapping(method = RequestMethod.GET, produces = {MediaTypes.HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody public ResponseEntity<Resources<Resource<Ga4ghSample>>> searchSample(@RequestParam(name = "disease") String disease, @RequestParam(name = "page") int page) { Collection<Filter> filters = filterBuilder.getFilters(); List<String> filtersAsText = filters.parallelStream() .map( Filter::getSerialization ) .collect(Collectors.toList()); String[] filtersAsTextArray = new String[1]; filtersAsTextArray = filtersAsText.toArray(filtersAsTextArray); ResponseEntity<Resources<Resource<Sample>>> response = restController.searchHal(disease, filtersAsTextArray, null, page, null, null, null); Resources<Resource<Sample>> samples = response.getBody(); List<Resource<Ga4ghSample>> ga4ghSamples = samples.getContent().stream() .map( i -> { Sample sample = i.getContent(); Ga4ghSample ga4ghSample = mapper.convert(sample); return resourceAssembler.toResource(ga4ghSample); } ) .collect(Collectors.toList()); Resources<Resource<Ga4ghSample>> resources = new Resources<>(ga4ghSamples); return new ResponseEntity<>(resources, HttpStatus.OK); } }
package cfvbaibai.cardfantasy.engine.feature; import java.util.ArrayList; import java.util.List; import cfvbaibai.cardfantasy.data.Feature; import cfvbaibai.cardfantasy.engine.CardInfo; import cfvbaibai.cardfantasy.engine.FeatureEffect; import cfvbaibai.cardfantasy.engine.FeatureEffectType; import cfvbaibai.cardfantasy.engine.FeatureInfo; import cfvbaibai.cardfantasy.engine.FeatureResolver; import cfvbaibai.cardfantasy.engine.HeroDieSignal; import cfvbaibai.cardfantasy.engine.OnAttackBlockingResult; import cfvbaibai.cardfantasy.engine.OnDamagedResult; public final class EnergyDrainFeature { public static void apply(FeatureInfo featureInfo, FeatureResolver resolver, CardInfo attacker, CardInfo defender, OnAttackBlockingResult result, OnDamagedResult damagedResult) throws HeroDieSignal { if (result.getDamage() == 0 || defender == null) { return; } Feature feature = featureInfo.getFeature(); int adjAT = attacker.getLevel1AT() * feature.getImpact() / 100; List<CardInfo> victims = new ArrayList<CardInfo>(); victims.add(attacker); //resolver.getStage().getUI().useSkill(defender, attacker, feature, true); int totalAttackWeakened = WeakenFeature.weakenCard(resolver, featureInfo, adjAT, defender, victims); //resolver.getStage().getUI().adjustAT(defender, attacker, adjAT, feature); //attacker.addEffect(new FeatureEffect(FeatureEffectType.ATTACK_CHANGE, featureInfo, totalAttackWeakened, true)); if (!defender.isDead()) { resolver.getStage().getUI().adjustAT(defender, defender, totalAttackWeakened, feature); defender.addEffect(new FeatureEffect(FeatureEffectType.ATTACK_CHANGE, featureInfo, totalAttackWeakened, true)); } if (damagedResult != null) { // Null on magical attack. Only sweep is affected by damaged result. damagedResult.originalDamage -= totalAttackWeakened; } } }
package fi.vrk.xroad.catalog.collector.util; import fi.vrk.xroad.catalog.collector.wsimport.*; import fi.vrk.xroad.catalog.persistence.CatalogService; import fi.vrk.xroad.catalog.persistence.entity.ErrorLog; import lombok.extern.slf4j.Slf4j; import org.apache.cxf.endpoint.Client; import org.apache.cxf.frontend.ClientProxy; import org.apache.cxf.message.Attachment; import org.apache.cxf.message.Message; import org.apache.cxf.transport.http.HTTPConduit; import javax.activation.DataHandler; import javax.xml.ws.BindingProvider; import javax.xml.ws.Holder; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.Collection; import java.util.List; import java.util.UUID; /** * WS client */ @Slf4j public class XRoadClient { final MetaServicesPort metaServicesPort; final XRoadClientIdentifierType clientId; public XRoadClient(XRoadClientIdentifierType clientId, URL serverUrl) { this.metaServicesPort = getMetaServicesPort(serverUrl); final XRoadClientIdentifierType tmp = new XRoadClientIdentifierType(); copyIdentifierType(tmp, clientId); this.clientId = tmp; } /** * Calls the service using JAX-WS endpoints that have been generated from wsdl */ public List<XRoadServiceIdentifierType> getMethods(XRoadClientIdentifierType member, CatalogService catalogService) { XRoadServiceIdentifierType serviceIdentifierType = new XRoadServiceIdentifierType(); copyIdentifierType(serviceIdentifierType, member); XRoadClientIdentifierType tmpClientId = new XRoadClientIdentifierType(); copyIdentifierType(tmpClientId, clientId); serviceIdentifierType.setServiceCode("listMethods"); serviceIdentifierType.setServiceVersion("v1"); serviceIdentifierType.setObjectType(XRoadObjectType.SERVICE); // ListMethodsResponse response = null; // try { ListMethodsResponse response = metaServicesPort.listMethods(new ListMethods(), holder(tmpClientId), holder(serviceIdentifierType), userId(), queryId(), protocolVersion()); // } catch(Exception e) { // log.error("Fetch of SOAP services failed: " + e.getMessage()); // ErrorLog errorLog = ErrorLog.builder() // .created(LocalDateTime.now()) // .message("Fetch of SOAP services failed: " + e.getMessage()) // .code("500") // .xRoadInstance(member.getXRoadInstance()) // .memberClass(member.getMemberClass()) // .memberCode(member.getMemberCode()) // .groupCode(member.getGroupCode()) // .securityCategoryCode(member.getSecurityCategoryCode()) // .serverCode(member.getServerCode()) // .serviceCode(member.getServiceCode()) // .serviceVersion(member.getServiceVersion()) // .subsystemCode(member.getSubsystemCode()) // .build(); // catalogService.saveErrorLog(errorLog); return response.getService(); } public String getWsdl(XRoadServiceIdentifierType service, CatalogService catalogService) { XRoadServiceIdentifierType serviceIdentifierType = new XRoadServiceIdentifierType(); copyIdentifierType(serviceIdentifierType, service); XRoadClientIdentifierType tmpClientId = new XRoadClientIdentifierType(); copyIdentifierType(tmpClientId, clientId); serviceIdentifierType.setServiceCode("getWsdl"); serviceIdentifierType.setServiceVersion("v1"); serviceIdentifierType.setObjectType(XRoadObjectType.SERVICE); final GetWsdl getWsdl = new GetWsdl(); getWsdl.setServiceCode(service.getServiceCode()); getWsdl.setServiceVersion(service.getServiceVersion()); final Holder<GetWsdlResponse> response = new Holder<>(); final Holder<byte[]> wsdl = new Holder<>(); try { metaServicesPort.getWsdl(getWsdl, holder(tmpClientId), holder(serviceIdentifierType), userId(), queryId(), protocolVersion(), response, wsdl); } catch(Exception e) { log.error("Fetch of WSDL failed: " + e.getMessage()); ErrorLog errorLog = ErrorLog.builder() .created(LocalDateTime.now()) .message("Fetch of WSDL failed: " + e.getMessage()) .code("500") .xRoadInstance(service.getXRoadInstance()) .memberClass(service.getMemberClass()) .memberCode(service.getMemberCode()) .groupCode(service.getGroupCode()) .securityCategoryCode(service.getSecurityCategoryCode()) .serverCode(service.getServerCode()) .serviceCode(service.getServiceCode()) .serviceVersion(service.getServiceVersion()) .subsystemCode(service.getSubsystemCode()) .build(); catalogService.saveErrorLog(errorLog); } if (!(wsdl.value instanceof byte[])) { // Apache CXF does not map the attachment returned by the security server to the wsdl // output parameter due to missing Content-Id header. Extract the attachment from the // response context. DataHandler dh = null; final Client client = ClientProxy.getClient(metaServicesPort); final Collection<Attachment> attachments = (Collection<Attachment>)client.getResponseContext().get(Message.ATTACHMENTS); if (attachments != null && attachments.size() == 1) { dh = attachments.iterator().next().getDataHandler(); } else { log.error("Expected one WSDL attachment"); ErrorLog errorLog = ErrorLog.builder() .created(LocalDateTime.now()) .message("Expected one WSDL attachment") .code("500") .xRoadInstance(service.getXRoadInstance()) .memberClass(service.getMemberClass()) .memberCode(service.getMemberCode()) .groupCode(service.getGroupCode()) .securityCategoryCode(service.getSecurityCategoryCode()) .serverCode(service.getServerCode()) .serviceCode(service.getServiceCode()) .serviceVersion(service.getServiceVersion()) .subsystemCode(service.getSubsystemCode()) .build(); catalogService.saveErrorLog(errorLog); } try (ByteArrayOutputStream buf = new ByteArrayOutputStream()) { dh.writeTo(buf); return buf.toString(StandardCharsets.UTF_8.name()); } catch (IOException e) { log.error("Error downloading WSDL: ", e.getMessage()); ErrorLog errorLog = ErrorLog.builder() .created(LocalDateTime.now()) .message("Error downloading WSDL: " + e.getMessage()) .code("500") .xRoadInstance(service.getXRoadInstance()) .memberClass(service.getMemberClass()) .memberCode(service.getMemberCode()) .groupCode(service.getGroupCode()) .securityCategoryCode(service.getSecurityCategoryCode()) .serverCode(service.getServerCode()) .serviceCode(service.getServiceCode()) .serviceVersion(service.getServiceVersion()) .subsystemCode(service.getSubsystemCode()) .build(); catalogService.saveErrorLog(errorLog); } } else { return new String(wsdl.value, StandardCharsets.UTF_8); } return null; } public String getOpenApi(XRoadServiceIdentifierType service, String host, CatalogService catalogService) { ClientType clientType = new ClientType(); XRoadClientIdentifierType xRoadClientIdentifierType = new XRoadClientIdentifierType(); xRoadClientIdentifierType.setXRoadInstance(service.getXRoadInstance()); xRoadClientIdentifierType.setMemberClass(service.getMemberClass()); xRoadClientIdentifierType.setMemberCode(service.getMemberCode()); xRoadClientIdentifierType.setSubsystemCode(service.getSubsystemCode()); xRoadClientIdentifierType.setGroupCode(service.getGroupCode()); xRoadClientIdentifierType.setServiceCode(service.getServiceCode()); xRoadClientIdentifierType.setServiceVersion(service.getServiceVersion()); xRoadClientIdentifierType.setSecurityCategoryCode(service.getSecurityCategoryCode()); xRoadClientIdentifierType.setServerCode(service.getServerCode()); xRoadClientIdentifierType.setObjectType(service.getObjectType()); clientType.setId(xRoadClientIdentifierType); return MethodListUtil.openApiFromResponse(clientType, host, catalogService); } private static Holder<String> queryId() { return holder("xroad-catalog-collector-" + UUID.randomUUID()); } private static Holder<String> protocolVersion() { return holder("4.0"); } private static Holder<String> userId() { return holder("xroad-catalog-collector"); } private static <T> Holder<T> holder(T value) { return new Holder<>(value); } /** * MetaServicesPort for url */ private static MetaServicesPort getMetaServicesPort(URL url) { ProducerPortService service = new ProducerPortService(); MetaServicesPort port = service.getMetaServicesPortSoap11(); BindingProvider bindingProvider = (BindingProvider) port; bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url.toString()); final HTTPConduit conduit = (HTTPConduit) ClientProxy.getClient(port).getConduit(); conduit.getClient().setConnectionTimeout(30000); conduit.getClient().setReceiveTimeout(60000); return port; } private static void copyIdentifierType(XRoadIdentifierType target, XRoadIdentifierType source) { target.setGroupCode(source.getGroupCode()); target.setObjectType(source.getObjectType()); target.setMemberCode(source.getMemberCode()); target.setServiceVersion(source.getServiceVersion()); target.setMemberClass(source.getMemberClass()); target.setServiceCode(source.getServiceCode()); target.setSecurityCategoryCode(source.getSecurityCategoryCode()); target.setServerCode(source.getServerCode()); target.setXRoadInstance(source.getXRoadInstance()); target.setSubsystemCode(source.getSubsystemCode()); } }
package com.salesforce.dva.argus.service.monitor; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.persist.Transactional; import com.salesforce.dva.argus.entity.Alert; import com.salesforce.dva.argus.entity.Dashboard; import com.salesforce.dva.argus.entity.Metric; import com.salesforce.dva.argus.entity.Notification; import com.salesforce.dva.argus.entity.PrincipalUser; import com.salesforce.dva.argus.entity.ServiceManagementRecord; import com.salesforce.dva.argus.entity.ServiceManagementRecord.Service; import com.salesforce.dva.argus.entity.Trigger; import com.salesforce.dva.argus.entity.Trigger.TriggerType; import com.salesforce.dva.argus.inject.SLF4JTypeListener; import com.salesforce.dva.argus.service.AlertService; import com.salesforce.dva.argus.service.DashboardService; import com.salesforce.dva.argus.service.MonitorService; import com.salesforce.dva.argus.service.ServiceManagementService; import com.salesforce.dva.argus.service.TSDBService; import com.salesforce.dva.argus.service.UserService; import com.salesforce.dva.argus.service.alert.notifier.AuditNotifier; import com.salesforce.dva.argus.service.jpa.DefaultJPAService; import com.salesforce.dva.argus.service.metric.transform.TransformFactory.Function; import com.salesforce.dva.argus.system.SystemAssert; import com.salesforce.dva.argus.system.SystemConfiguration; import com.salesforce.dva.argus.system.SystemException; import com.sun.management.OperatingSystemMXBean; import com.sun.management.UnixOperatingSystemMXBean; import org.slf4j.Logger; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import static com.salesforce.dva.argus.system.SystemAssert.requireArgument; /** * Default implementation of the monitor service. * * @author Tom Valine (tvaline@salesforce.com) * @author Bhinav Sura (bhinav.sura@salesforce.com) */ @Singleton public class DefaultMonitorService extends DefaultJPAService implements MonitorService { private static final String NOTIFICATION_NAME = "monitor_notification"; private static final String PHYSICAL_MEMORY_ALERT = "physical_memory"; private static final String SWAP_SPACE_ALERT = "swap_space"; private static final String FILE_DESCRIPTORS_ALERT = "file_descriptors"; private static final String ALERT_NAME_PREFIX = "monitor-"; private static final String HOSTNAME; private static long TIME_BETWEEN_RECORDINGS = 60 * 1000; static { HOSTNAME = SystemConfiguration.getHostname(); } @SLF4JTypeListener.InjectLogger private Logger _logger; private final TSDBService _tsdbService; private final UserService _userService; private final AlertService _alertService; private final ServiceManagementService _serviceManagementService; private final DashboardService _dashboardService; private final Map<Metric, Double> _metrics = new ConcurrentHashMap<>(); private final PrincipalUser _adminUser; private Thread _monitorThread; /** * Creates a new DefaultMonitorService object. * * @param tsdbService The TSDB service. Cannot be null. * @param userService The user service. Cannot be null. * @param alertService The alert service. Cannot be null. * @param serviceManagementService The service management service. Cannot be null. * @param dashboardService The dashboard service. Cannot be null. * @param _sysConfig Service properties. */ @Inject public DefaultMonitorService(TSDBService tsdbService, UserService userService, AlertService alertService, ServiceManagementService serviceManagementService, DashboardService dashboardService, SystemConfiguration _sysConfig) { super(null, _sysConfig); requireArgument(tsdbService != null, "TSDB service cannot be null."); requireArgument(userService != null, "User service cannot be null."); requireArgument(alertService != null, "Alert service cannot be null."); requireArgument(serviceManagementService != null, "Service management service cannot be null."); requireArgument(dashboardService != null, "Dashboard service cannot be null."); _tsdbService = tsdbService; _userService = userService; _alertService = alertService; _serviceManagementService = serviceManagementService; _dashboardService = dashboardService; _adminUser = _userService.findAdminUser(); } private static String _constructAlertName(String type) { return ALERT_NAME_PREFIX + type + "-" + HOSTNAME; } private static Metric _constructCounterKey(String metricName, Map<String, String> tags) { SystemAssert.requireArgument(metricName != null, "Cannot create a Metric with null metric name"); Counter counter = Counter.fromMetricName(metricName); String scope = counter == null ? "argus.custom" : counter.getScope(); Metric metric = new Metric(scope, metricName); metric.setTags(tags); metric.setTag("host", HOSTNAME); return metric; } @Override @Transactional public synchronized void enableMonitoring() { requireNotDisposed(); _logger.info("Globally enabling all system monitoring."); _setServiceEnabled(true); _checkAlertExistence(true); _logger.info("All system monitoring globally enabled."); } @Override @Transactional public synchronized void disableMonitoring() { requireNotDisposed(); _logger.info("Globally disabling all system monitoring."); _setServiceEnabled(false); _checkAlertExistence(false); _logger.info("All system monitoring globally disabled."); } @Override @Transactional public synchronized void startRecordingCounters() { requireNotDisposed(); if (_monitorThread != null && _monitorThread.isAlive()) { _logger.info("Request to start system monitoring aborted as it is already running."); } else { _logger.info("Starting system monitor thread."); _checkAlertExistence(true); _monitorThread = new MonitorThread("system-monitor"); _monitorThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { _logger.error("Uncaught exception occured while pushing monitor counters for {}. Reason: {}", HOSTNAME, e.getMessage()); t.interrupt(); } }); _monitorThread.start(); _logger.info("System monitor thread started."); } } @Override @Transactional public synchronized void stopRecordingCounters() { requireNotDisposed(); if (_monitorThread != null && _monitorThread.isAlive()) { _logger.info("Stopping system monitoring."); _monitorThread.interrupt(); _logger.info("System monitor thread interrupted."); try { _logger.info("Waiting for system monitor thread to terminate."); _monitorThread.join(); } catch (InterruptedException ex) { _logger.warn("System monitoring was interrupted while shutting down."); } _checkAlertExistence(false); _logger.info("System monitoring stopped."); } else { _logger.info("Requested shutdown of system monitoring aborted as it is not yet running."); } } @Override public void updateCustomCounter(String name, double value, Map<String, String> tags) { requireNotDisposed(); requireArgument(name != null && !name.isEmpty(), "Cannot update a counter with null or empty name."); Metric metric = _constructCounterKey(name, tags); _logger.debug("Updating {} counter for {} to {}.", name, tags, value); _metrics.put(metric, value); } @Override public void updateCounter(Counter counter, double value, Map<String, String> tags) { requireNotDisposed(); requireArgument(counter != null, "Cannot update a null counter."); requireArgument(!"argus.jvm".equalsIgnoreCase(counter.getScope()), "Cannot update JVM counters"); updateCustomCounter(counter.getMetric(), value, tags); } @Override public double modifyCustomCounter(String name, double delta, Map<String, String> tags) { requireNotDisposed(); SystemAssert.requireArgument(name != null && !name.isEmpty(), "Cannot modify a counter with null or empty name."); Metric key = _constructCounterKey(name, tags); synchronized (_metrics) { Double value = _metrics.get(key); double newValue = value == null ? delta : value + delta; _logger.debug("Modifying {} counter for {} to {}.", name, tags, newValue); _metrics.put(key, newValue); return newValue; } } @Override public double modifyCounter(Counter counter, double delta, Map<String, String> tags) { requireNotDisposed(); requireArgument(counter != null, "Cannot modify a null counter."); requireArgument(!"argus.jvm".equalsIgnoreCase(counter.getScope()), "Cannot modify JVM counters"); return modifyCustomCounter(counter.getMetric(), delta, tags); } @Override public double getCounter(Counter counter, Map<String, String> tags) { requireArgument(counter != null, "Cannot get value for a null counter."); return getCustomCounter(counter.getMetric(), tags); } @Override public double getCustomCounter(String name, Map<String, String> tags) { requireNotDisposed(); requireArgument(name != null && !name.isEmpty(), "Cannot update a counter with null or empty name."); Metric metric = _constructCounterKey(name, tags); Double value; synchronized (_metrics) { value = _metrics.get(metric); if (value == null) { value = Double.NaN; } } _logger.debug("Value for {} counter having tags {} is {}.", name, tags, value); return value; } @Override public void resetCustomCounters() { requireNotDisposed(); _resetCountersForScope("argus.custom"); } @Override public void resetSystemCounters() { requireNotDisposed(); _resetCountersForScope("argus.core"); } @Override public void resetRuntimeCounters() { requireNotDisposed(); _resetCountersForScope("argus.jvm"); } @Override @Transactional public Dashboard getSystemDashboard() { requireNotDisposed(); return _getDashboardForScope("System Dashboard", "argus.core"); } @Override @Transactional public Dashboard getRuntimeDashboard() { requireNotDisposed(); return _getDashboardForScope("Runtime Dashboard", "argus.jvm"); } @Override public synchronized void dispose() { stopRecordingCounters(); super.dispose(); _userService.dispose(); _dashboardService.dispose(); _alertService.dispose(); _serviceManagementService.dispose(); // _tsdbService.dispose(); } private void _setServiceEnabled(boolean enabled) { synchronized (_serviceManagementService) { ServiceManagementRecord record = _serviceManagementService.findServiceManagementRecord(Service.MONITORING); if (record == null) { record = new ServiceManagementRecord(_userService.findAdminUser(), Service.MONITORING, enabled); } record.setEnabled(enabled); _serviceManagementService.updateServiceManagementRecord(record); } } private boolean _isMonitoringServiceEnabled() { return _serviceManagementService.isServiceEnabled(Service.MONITORING); } private void _resetCountersForScope(String scope) { assert (scope != null) : "Scope can not be null."; _logger.info("Resetting {} counters.", scope); List<Metric> toRemove = new LinkedList<>(); synchronized (_metrics) { for (Metric metric : _metrics.keySet()) { if (scope.equalsIgnoreCase(metric.getScope())) { toRemove.add(metric); } } for (Metric metric : toRemove) { _logger.debug("Resetting counter {}.", metric); _metrics.remove(metric); } } } private void _updateJVMStatsCounters() { Counter[] counters = Counter.values(); List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); List<MemoryPoolMXBean> memoryPoolBeans = ManagementFactory.getMemoryPoolMXBeans(); OperatingSystemMXBean osBean = ((OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()); for (Counter counter : counters) { if ("argus.jvm".equalsIgnoreCase(counter.getScope())) { Double value = null; String units = "count"; switch (counter) { case ACTIVE_CORES: value = (double) Runtime.getRuntime().availableProcessors(); break; case LOADED_CLASSES: value = (double) ManagementFactory.getClassLoadingMXBean().getLoadedClassCount(); break; case UNLOAED_CLASSES: value = (double) ManagementFactory.getClassLoadingMXBean().getUnloadedClassCount(); break; case MARKSWEEP_COUNT: for (GarbageCollectorMXBean bean : gcBeans) { if (bean.getName().toLowerCase().contains("mark")) { value = (double) bean.getCollectionCount(); break; } } break; case SCAVENGE_COUNT: for (GarbageCollectorMXBean bean : gcBeans) { if (bean.getName().toLowerCase().contains("scavenge")) { value = (double) bean.getCollectionCount(); break; } } break; case HEAP_USED: value = (double) ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); units = "bytes"; break; case NONHEAP_USED: value = (double) ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed(); units = "bytes"; break; case CODECACHE_USED: for (MemoryPoolMXBean bean : memoryPoolBeans) { if (bean.getName().toLowerCase().contains("code")) { value = (double) bean.getUsage().getUsed(); units = "bytes"; break; } } break; case EDEN_USED: for (MemoryPoolMXBean bean : memoryPoolBeans) { if (bean.getName().toLowerCase().contains("eden")) { value = (double) bean.getUsage().getUsed(); units = "bytes"; break; } } break; case OLDGEN_USED: for (MemoryPoolMXBean bean : memoryPoolBeans) { if (bean.getName().toLowerCase().contains("old")) { value = (double) bean.getUsage().getUsed(); units = "bytes"; break; } } break; case PERMGEN_USED: for (MemoryPoolMXBean bean : memoryPoolBeans) { if (bean.getName().toLowerCase().contains("perm")) { value = (double) bean.getUsage().getUsed(); units = "bytes"; break; } } break; case SURVIVOR_USED: for (MemoryPoolMXBean bean : memoryPoolBeans) { if (bean.getName().toLowerCase().contains("survivor")) { value = (double) bean.getUsage().getUsed(); units = "bytes"; break; } } break; case FREE_PHYSICAL_MEM: value = (double) osBean.getFreePhysicalMemorySize(); units = "bytes"; break; case FREE_SWAP_SPACE: value = (double) osBean.getFreeSwapSpaceSize(); units = "bytes"; break; case MAX_PHYSICAL_MEM: value = (double) osBean.getTotalPhysicalMemorySize(); units = "bytes"; break; case MAX_SWAP_SPACE: value = (double) osBean.getTotalSwapSpaceSize(); units = "bytes"; break; case OPEN_DESCRIPTORS: if (osBean instanceof UnixOperatingSystemMXBean) { value = (double) ((UnixOperatingSystemMXBean) osBean).getOpenFileDescriptorCount(); } break; case MAX_DESCRIPTORS: value = (double) ((UnixOperatingSystemMXBean) osBean).getMaxFileDescriptorCount(); break; case THREADS: value = (double) ManagementFactory.getThreadMXBean().getThreadCount(); break; case PEAK_THREADS: value = (double) ManagementFactory.getThreadMXBean().getPeakThreadCount(); break; case DAEMON_THREADS: value = (double) ManagementFactory.getThreadMXBean().getDaemonThreadCount(); break; default: throw new IllegalArgumentException("Unexpected Counter: This should never happen"); } // end switch if (value != null) { Metric metric = _constructCounterKey(counter.getMetric(), Collections.<String, String>emptyMap()); metric.setUnits(units); _metrics.put(metric, value); } } // end if } // end for } private Dashboard _getDashboardForScope(String name, String scope) { String dashboardName = name + HOSTNAME; Dashboard dashboard; synchronized (_dashboardService) { dashboard = _dashboardService.findDashboardByNameAndOwner(dashboardName, _adminUser); } if (dashboard == null) { dashboard = new Dashboard(_adminUser, dashboardName, _adminUser); /* @todo: create dashboard content. */ synchronized (_dashboardService) { dashboard = _dashboardService.updateDashboard(dashboard); } } return dashboard; } /** * Determines if an alert exists, creates it if it doesn't and then sets it to be enabled or disabled, as required. * * @param enabled Enables or disables the alert. * * @throws SystemException If an error creating the alert occurs. */ @Transactional protected synchronized void _checkAlertExistence(boolean enabled) { for (String alertName : new String[] { FILE_DESCRIPTORS_ALERT, PHYSICAL_MEMORY_ALERT, SWAP_SPACE_ALERT }) { if (_alertService.findAlertByNameAndOwner(_constructAlertName(alertName), _adminUser) == null) { String metricExpression = null; TriggerType triggerType = null; String triggerName = null; double triggerThreshold = Double.NaN; switch (alertName) { case FILE_DESCRIPTORS_ALERT: String openFileDescMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.OPEN_DESCRIPTORS.getScope(), Counter.OPEN_DESCRIPTORS.getMetric(), HOSTNAME); String maxFileDescMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.MAX_DESCRIPTORS.getScope(), Counter.MAX_DESCRIPTORS.getMetric(), HOSTNAME); metricExpression = MessageFormat.format("{0}({1}, {2})", Function.DIVIDE.getName(), openFileDescMetricExp, maxFileDescMetricExp); triggerType = TriggerType.GREATER_THAN; triggerName = "Open FD > 95% of Max FD"; triggerThreshold = 0.95; break; case PHYSICAL_MEMORY_ALERT: String freeMemMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.FREE_PHYSICAL_MEM.getScope(), Counter.FREE_PHYSICAL_MEM.getMetric(), HOSTNAME); String maxMemMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.MAX_PHYSICAL_MEM.getScope(), Counter.MAX_PHYSICAL_MEM.getMetric(), HOSTNAME); metricExpression = MessageFormat.format("{0}({1}, {2})", Function.DIVIDE.getName(), freeMemMetricExp, maxMemMetricExp); triggerType = TriggerType.LESS_THAN; triggerName = "Free Mem < 5% of Tot Mem"; triggerThreshold = 0.05; break; case SWAP_SPACE_ALERT: String freeSSMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.FREE_SWAP_SPACE.getScope(), Counter.FREE_SWAP_SPACE.getMetric(), HOSTNAME); String maxSSMetricExp = MessageFormat.format("-1h:{0}:{1}'{'host={2}'}':avg", Counter.MAX_SWAP_SPACE.getScope(), Counter.MAX_SWAP_SPACE.getMetric(), HOSTNAME); metricExpression = MessageFormat.format("{0}({1}, {2})", Function.DIVIDE.getName(), freeSSMetricExp, maxSSMetricExp); triggerType = TriggerType.LESS_THAN; triggerName = "Free Swap Space < 5% of Tot Swap Space"; triggerThreshold = 0.05; break; default: throw new SystemException("Attempting to create an unsupported monitoring alert" + alertName); } requireArgument(metricExpression != null && triggerType != null & triggerName != null, "Unsupported monitor alert " + alertName); Alert alert = new Alert(_adminUser, _adminUser, _constructAlertName(alertName), metricExpression, "0 * * * *"); Notification notification = new Notification(NOTIFICATION_NAME, alert, AuditNotifier.class.getName(), new ArrayList<String>(), 60000L); Trigger trigger = new Trigger(alert, triggerType, triggerName, triggerThreshold, 0); List<Trigger> triggers = Arrays.asList(new Trigger[] { trigger }); notification.setTriggers(triggers); alert.setNotifications(Arrays.asList(new Notification[] { notification })); alert.setTriggers(triggers); alert.setEnabled(enabled); _alertService.updateAlert(alert); } else { // end if Alert alert = _alertService.findAlertByNameAndOwner(_constructAlertName(alertName), _adminUser); alert.setEnabled(enabled); _alertService.updateAlert(alert); } // end if-else } // end for } /** * Monitoring thread. * * @author Tom Valine (tvaline@salesforce.com) */ private class MonitorThread extends Thread { /** * Creates a new SchedulingThread object. * * @param name The thread name. */ public MonitorThread(String name) { super(name); } @Override public void run() { while (!isInterrupted()) { _sleepForPollPeriod(); if (!isInterrupted() && _isMonitoringServiceEnabled()) { try { _pushCounters(); } catch (Exception ex) { _logger.error("Error occured while pushing monitor counters for {}. Reason: {}", HOSTNAME, ex.getMessage()); } } } } private void _pushCounters() { _logger.debug("Pushing monitor service counters for {}.", HOSTNAME); Map<Metric, Double> counters = new HashMap<>(); _updateJVMStatsCounters(); synchronized (_metrics) { counters.putAll(_metrics); _metrics.clear(); } long timestamp = (System.currentTimeMillis() / 60000) * 60000L; for (Entry<Metric, Double> entry : counters.entrySet()) { Map<Long, String> dataPoints = new HashMap<>(1); dataPoints.put(timestamp, String.valueOf(entry.getValue())); entry.getKey().setDatapoints(dataPoints); } if (!isDisposed()) { _tsdbService.putMetrics(new ArrayList<>(counters.keySet())); } } private void _sleepForPollPeriod() { try { _logger.info("Sleeping for {}s before pushing counters.", TIME_BETWEEN_RECORDINGS / 1000); sleep(TIME_BETWEEN_RECORDINGS); } catch (InterruptedException ex) { _logger.warn("System monitoring was interrupted."); interrupt(); } } } }
package com.intellij.ide.scopeView; import com.intellij.ide.projectView.ProjectView; import com.intellij.ide.projectView.PsiClassChildrenSource; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.packageDependencies.ui.DependencyNodeComparator; import com.intellij.packageDependencies.ui.DirectoryNode; import com.intellij.packageDependencies.ui.FileNode; import com.intellij.packageDependencies.ui.PackageDependenciesNode; import com.intellij.psi.*; import com.intellij.util.ui.tree.TreeUtil; import javax.swing.*; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeWillExpandListener; import javax.swing.tree.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ScopeTreeViewExpander implements TreeWillExpandListener { private JTree myTree; private Project myProject; public ScopeTreeViewExpander(final JTree tree, final Project project) { myTree = tree; myProject = project; } public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException { ProjectView projectView = ProjectView.getInstance(myProject); final TreePath path = myTree.getPathForRow(myTree.getRowForPath(event.getPath())); if (path == null) return; final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); if (node instanceof DirectoryNode) { Set<ClassNode> classNodes = null; for (int i = node.getChildCount() - 1; i >= 0; i final TreeNode childNode = node.getChildAt(i); if (childNode instanceof FileNode) { final FileNode fileNode = (FileNode)childNode; final PsiElement file = fileNode.getPsiElement(); if (file instanceof PsiJavaFile) { final VirtualFile virtualFile = ((PsiJavaFile)file).getVirtualFile(); if (virtualFile == null || (virtualFile.getFileType() != StdFileTypes.JAVA && virtualFile.getFileType() != StdFileTypes.CLASS)) return; final PsiClass[] psiClasses = ((PsiJavaFile)file).getClasses(); if (classNodes == null) { classNodes = new HashSet<ClassNode>(); } for (final PsiClass psiClass : psiClasses) { if (psiClass != null && psiClass.isValid()) { final ClassNode classNode = new ClassNode(psiClass); classNodes.add(classNode); if (projectView.isShowMembers(ScopeViewPane.ID)){ final List<PsiElement> result = new ArrayList<PsiElement>(); PsiClassChildrenSource.DEFAULT_CHILDREN.addChildren(psiClass, result); for (PsiElement psiElement : result) { psiElement.accept(new PsiElementVisitor() { public void visitClass(PsiClass aClass) { classNode.add(new ClassNode(aClass)); } public void visitMethod(PsiMethod method) { classNode.add(new MethodNode(method)); } public void visitField(PsiField field) { classNode.add(new FieldNode(field)); } public void visitReferenceExpression(PsiReferenceExpression expression) { } }); } } } } node.remove(fileNode); } } } if (classNodes != null){ for (ClassNode classNode : classNodes) { node.add(classNode); } } TreeUtil.sort(node, new DependencyNodeComparator()); ((DefaultTreeModel)myTree.getModel()).reload(node); } } public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException { final TreePath path = myTree.getPathForRow(myTree.getRowForPath(event.getPath())); if (path == null) return; final DefaultMutableTreeNode node = (PackageDependenciesNode)path.getLastPathComponent(); if (node instanceof DirectoryNode){ Set<FileNode> fileNodes = null; for (int i = node.getChildCount() - 1; i >= 0; i final TreeNode childNode = node.getChildAt(i); if (childNode instanceof ClassNode) { final ClassNode classNode = (ClassNode)childNode; final PsiElement psiElement = classNode.getPsiElement(); if (psiElement != null && psiElement.isValid()){ if (fileNodes == null){ fileNodes = new HashSet<FileNode>(); } fileNodes.add(new FileNode(psiElement.getContainingFile(), true)); } node.remove(classNode); } } if (fileNodes != null){ for (FileNode fileNode : fileNodes) { node.add(fileNode); } } TreeUtil.sort(node, new DependencyNodeComparator()); ((DefaultTreeModel)myTree.getModel()).reload(node); } } }
package velir.intellij.cq5.jcr.model; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Computable; import velir.intellij.cq5.jcr.Connection; import javax.jcr.*; import java.util.*; public class VNodeDefinition { public static final String JCR_AUTOCREATED = "jcr:autoCreated"; public static final String JCR_DEFAULTPRIMARYTYPE = "jcr:defaultPrimaryType"; public static final String JCR_ISMIXIN = "jcr:isMixin"; public static final String JCR_NAME = "jcr:name"; public static final String JCR_NODETYPENAME = "jcr:nodeTypeName"; public static final String JCR_ONPARENTVERSION = "jcr:onParentVersion"; public static final String JCR_SUPERTYPES = "jcr:supertypes"; public static final String NT_CHILDNODEDEFINITION = "nt:childNodeDefinition"; public static final String NT_PROPERTYDEFINITION = "nt:propertyDefinition"; public static final String CQ_COMPONENT = "cq:Component"; public static final String CQ_ISCONTAINER = "cq:isContainer"; public static final String CQ_DIALOG = "cq:Dialog"; public static final String JCR_TITLE = "jcr:title"; public static final String ALLOWED_PARENTS = "allowedParents"; public static final String COMPONENT_GROUP = "componentGroup"; private static final Logger log = com.intellij.openapi.diagnostic.Logger.getInstance(VNodeDefinition.class); private static Map<String,VNodeDefinition> allNodes; private Map<String,VPropertyDefinitionI> properties; private Set<String> supertypes; private Map<String,String> childSuggestions; private boolean canAddProperties; private boolean isMixin; private String name; public VNodeDefinition (Node node) throws RepositoryException { name = node.getProperty(JCR_NODETYPENAME).getString(); // do properties properties = new HashMap<String, VPropertyDefinitionI>(); childSuggestions = new HashMap<String, String>(); NodeIterator nodeIterator = node.getNodes(); while (nodeIterator.hasNext()) { Node definitionNode = nodeIterator.nextNode(); String nodeType = definitionNode.getProperty(VNode.JCR_PRIMARYTYPE).getString(); // do a property if (NT_PROPERTYDEFINITION.equals(nodeType)) { String propertyName = "*"; // default to wildcard name if (definitionNode.hasProperty(JCR_NAME)) { // only add non-autogenerated properties if (! definitionNode.getProperty(JCR_AUTOCREATED).getBoolean()) { propertyName = definitionNode.getProperty(JCR_NAME).getString(); properties.put(propertyName, new VPropertyDefinition(definitionNode)); } } else { // property with no name means this node can accept custom properties canAddProperties = true; } } // do a child suggestion if (NT_CHILDNODEDEFINITION.equals(nodeType)) { String childName = "*"; // only do well-defined childnodedefinitions with the following 2 jcr properties if (definitionNode.hasProperty(JCR_NAME) && definitionNode.hasProperty(JCR_DEFAULTPRIMARYTYPE)) { childSuggestions.put(definitionNode.getProperty(JCR_NAME).getString(), definitionNode.getProperty(JCR_DEFAULTPRIMARYTYPE).getString()); } } } // do supertypes supertypes = new HashSet<String>(); if (node.hasProperty(JCR_SUPERTYPES)) { for (Value value : node.getProperty(JCR_SUPERTYPES).getValues()) { supertypes.add(value.getString()); } } // set mixin status isMixin = node.hasProperty(JCR_ISMIXIN) && node.getProperty(JCR_ISMIXIN).getBoolean(); } public Map<String, Object> getPropertiesMap (boolean includePrimaryType) { Map<String,Object> propertiesMap = new HashMap<String, Object>(); for (Map.Entry<String, VPropertyDefinitionI> entry : properties.entrySet()) { propertiesMap.put(entry.getKey(), entry.getValue().getDefaultValue()); } if (includePrimaryType) propertiesMap.put(VNode.JCR_PRIMARYTYPE, name); // also get supertype properties for (String supertype : supertypes) { VNodeDefinition vNodeDefinition = VNodeDefinition.getDefinition(supertype); if (vNodeDefinition != null) propertiesMap.putAll(vNodeDefinition.getPropertiesMap(false)); else { log.error("Could not get definition for " + supertype ); } } return propertiesMap; } public Map<String, String> getChildSuggestions() { return childSuggestions; } public static void buildDefinitions () { log.info("started building node definitions"); Session session = null; String nodeName = ""; try { allNodes = new HashMap<String, VNodeDefinition>(); session = Connection.getSession(); Node rootNode = session.getNode("/jcr:system/jcr:nodeTypes"); NodeIterator nodeIterator = rootNode.getNodes(); while (nodeIterator.hasNext()) { Node node = nodeIterator.nextNode(); nodeName = node.getName(); VNodeDefinition vNodeDefinition = new VNodeDefinition(node); customizeDefinition(vNodeDefinition); //possibly customize this definition allNodes.put(nodeName, vNodeDefinition); } log.info("finished building nodes"); } catch (RepositoryException re) { log.error("Could not build node definitions, died at " + nodeName, re); } finally { if (session != null) session.logout(); } } // extend the lacking JCR definitions public static void customizeDefinition (VNodeDefinition vNodeDefinition) { String name = vNodeDefinition.name; if (CQ_COMPONENT.equals(name)) { vNodeDefinition.properties.put(ALLOWED_PARENTS, new VPropertyDefinitionI() { public Object getDefaultValue() { return "*/parsys"; } }); vNodeDefinition.properties.put(COMPONENT_GROUP, new VPropertyDefinitionI() { public Object getDefaultValue() { return "General"; } }); vNodeDefinition.childSuggestions.put("dialog", CQ_DIALOG); vNodeDefinition.childSuggestions.put("design_dialog", CQ_DIALOG); } } public static boolean hasDefinitions () { return ! allNodes.isEmpty(); } // only include non-mixin types public static String[] getNodeTypeNames () { // filter mixins out Set<String> keySet = allNodes.keySet(); Set<String> copySet = new HashSet<String>(); for (String s : keySet) copySet.add(s); // do I really need to do this, java? for (String s : keySet) { if (getDefinition(s).isMixin) copySet.remove(s); } String[] options = new String[copySet.size()]; options = copySet.toArray(options); Arrays.sort(options); return options; } public static VNodeDefinition getDefinition (String name) { return allNodes.get(name); } }
package com.kb.mylibs.Android; import java.io.IOException; import java.io.InputStream; import android.content.res.AssetManager; import android.app.Activity; public class MyAssetManager { protected AssetManager mAssetManager; public MyAssetManager() { } public void setActivity(Activity activity) { if (null != activity) { this.mAssetManager = activity.getAssets(); } else { System.out.print("activity is none"); } } public void setNativeAssetManager(AssetManager assetManager) { if (null != assetManager) { this.mAssetManager = assetManager; } else { System.out.print("assetManager is none"); } } public boolean isFileExist(String filePathStartAfterAssets) { try { boolean ret = false; String[] fileNameList = this.mAssetManager.list(""); for (int index = 0; index < fileNameList.length; ++index) { if(filePathStartAfterAssets == fileNameList[index]) { ret = true; break; } } return ret; } catch(IOException e) { e.printStackTrace(); System.out.print("isFileExist error"); return false; } } public String readText(String filePathStartAfterAssets) { InputStream input; try { input = this.mAssetManager.open(filePathStartAfterAssets); int size = input.available(); byte[] buffer = new byte[size]; input.read(buffer); input.close(); String text = new String(buffer); return text; } catch (IOException e) { e.printStackTrace(); System.out.print("readText error"); return ""; } } public byte[] readBytes(String filePathStartAfterAssets) { InputStream input; try { input = this.mAssetManager.open(filePathStartAfterAssets); int size = input.available(); byte[] buffer = new byte[size]; input.read(buffer); input.close(); return buffer; } catch (IOException e) { e.printStackTrace(); System.out.print("readBytes error"); return null; } } public void reset(String filePathStartAfterAssets) { InputStream input; try { input = this.mAssetManager.open(filePathStartAfterAssets); // mark mark reset input.mark(0); if(input.markSupported()) { input.reset(); } input.close(); } catch (IOException e) { e.printStackTrace(); System.out.print("readBytes error"); } } }
package edu.mit.scansite.server.updater; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.SQLException; import java.util.LinkedList; import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ibm.icu.util.Calendar; import edu.mit.scansite.server.ServiceLocator; import edu.mit.scansite.server.dataaccess.DaoFactory; import edu.mit.scansite.server.dataaccess.databaseconnector.DbConnector; import edu.mit.scansite.server.dataaccess.file.Downloader; import edu.mit.scansite.server.updater.transliterator.FileTransliterator; import edu.mit.scansite.shared.DataAccessException; import edu.mit.scansite.shared.transferobjects.DataSource; import edu.mit.scansite.shared.util.Formatter; /** * @author Tobieh * @author Konstantin Krismer * @author Thomas Bernwinkler */ public abstract class DbUpdater implements Runnable { private static final String TEMP_PREFIX = "temp_"; private static final String TXT_SUFFIX = ".txt"; protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected DataSourceMetaInfo dataSourceMetaInfo; protected DaoFactory fac; private List<URL> dbDownloadUrls = new LinkedList<>(); protected URL versionFileDownloadUrl; private File tempDir; private List<String> dbFileNames = new LinkedList<>(); private List<BufferedReader> readers = new LinkedList<>(); protected String errFileName; protected String tempFileName; public DbUpdater() { } public void init(String tempDirPath, String invalidFilePrefix, DataSourceMetaInfo dataSourceMetaInfo) throws ScansiteUpdaterException { try { this.dataSourceMetaInfo = dataSourceMetaInfo; this.dbDownloadUrls.add(new URL(dataSourceMetaInfo.getUrl())); try { this.versionFileDownloadUrl = (dataSourceMetaInfo.getVersionUrl() == null || dataSourceMetaInfo.getVersionUrl().isEmpty()) ? null : new URL(dataSourceMetaInfo.getVersionUrl()); } catch (Exception e) { logger.error(e.getMessage(), e); this.versionFileDownloadUrl = null; } String db = dataSourceMetaInfo.getDataSource().getShortName(); this.errFileName = invalidFilePrefix + "_" + db + TXT_SUFFIX; this.tempFileName = TEMP_PREFIX + db + TXT_SUFFIX; Formatter formatter = new Formatter(); this.tempDir = new File(formatter.formatFilePath(tempDirPath)); if (!this.tempDir.exists()) { if (!tempDir.mkdir()) { if (!tempDir.mkdirs()) { logger.error("Given temporary directory does not exist and could not be created"); throw new ScansiteUpdaterException( "Given temporary directory does not exist and could not be created"); } } } fac = ServiceLocator.getDaoFactory(); } catch (MalformedURLException e) { logger.error("Given URLs are invalid: " + e.getMessage(), e); throw new ScansiteUpdaterException("Given URLs are invalid: " + e.getMessage(), e); } catch (DataAccessException e) { logger.error("Can not create DaoFactory: " + e.getMessage(), e); throw new ScansiteUpdaterException("Can not create DaoFactory: " + e.getMessage(), e); } } /** * - download files - transliterate files to temporary scansite-specific files * (extracting information) - create temporary tables - transliterate * scansite-specific files to temporary table in database - update taxa in * histograms - rename old table, rename temp table - clean up (remove temporary * files and remove old tables) * * @throws ScansiteUpdaterException * Is thrown if any of the tasks encounters a problem. */ private void runUpdate() throws ScansiteUpdaterException { logger.info("setting data source version"); dataSourceMetaInfo.getDataSource().setVersion(getVersion()); logger.info("data source version set"); logger.info("download files unless already loaded"); String tempFilePath = getFilePath(tempFileName); File f = new File(tempFilePath); if (!f.exists()) { downloadDbFiles(dbDownloadUrls); } logger.info("download finished"); logger.info("transliterating files to temporary scansite-specific files (extracting information)"); if (!f.exists()) { for (String dbFileName : dbFileNames) { logger.info("Transliterating file: {}", dbFileName); initReader(dbFileName); FileTransliterator transliterator = getDbFileTransliterator(tempFilePath, getFilePath(errFileName)); transliterator.transliterate(); } try { logger.info( "Reestablishing database connection to be on the safe side (long download and transliteration times may cause issues)"); DbConnector.getInstance().resetConnections(); } catch (SQLException e) { logger.error("Failed to reestablish the database connection after long period timeout", e); } } logger.info("Prepare file transliterator to transfer data to database"); initReader(tempFileName); logger.info("Deleting downloaded files after processing to plain text file..."); for (String dbFileName : dbFileNames) { try { Files.deleteIfExists(Paths.get(getFilePath(dbFileName))); } catch (IOException e) { logger.error("Could not delete downloaded files after transliterating"); } } FileTransliterator ssTransliterator = getScansiteFileTransliterator(getFilePath("DB_" + errFileName)); try { logger.info("transliterate scansite-specific files to temporary table in database"); logger.info("disables auto-commit, unique and foreign key checks"); fac.getDataSourceDao().disableChecks(); logger.info("creating temp tables for inserts"); createTables(); logger.info("saving data source entry in dataSources table"); saveDataSource(dataSourceMetaInfo.getDataSource()); logger.info("transliterating to database: {}", tempFileName); ssTransliterator.transliterate(); logger.info("update histograms so that they are consistent with the new tables"); try { logger.info("updating histogram data {}", dataSourceMetaInfo.getDataSource().getDisplayName()); updateHistogramData(); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); // if it fails, the database is probably set up the first time } logger.info("renaming tables {}", dataSourceMetaInfo.getDataSource().getDisplayName()); renameTables(); logger.info("enabling auto-commit, unique and foreign key checks"); fac.getDataSourceDao().enableChecks(); logger.info("successful"); } catch (ScansiteUpdaterException e) { logger.error(e.getMessage()); e.printStackTrace(); dropTempTables(); throw e; } // clean up, remove old tables and delete temporary files cleanup(f); } private void saveDataSource(DataSource dataSource) { try { fac.getDataSourceDao().addOrUpdate(dataSource); } catch (DataAccessException e) { logger.error(e.getMessage()); } } protected abstract FileTransliterator getScansiteFileTransliterator(String errorFilePath) throws ScansiteUpdaterException; /** * This method is called if a version download URI is given in the * configuration. What needs to be done here is to fetch the version from the * given URI and return it. If null is returned, the current date is used as * version name. * * @return A string describing the current version, or NULL. * @throws ScansiteUpdaterException */ protected abstract String doGetVersion() throws ScansiteUpdaterException; /** * Instantiate a file transliterator that can be used for the downloaded public * database file and return it. * * @param tempFilePath * the path to the temporary file. * @param errorFilePath * the path to the error-file (file that contains invalid / failed * entries) * @return A file transliterator that reads / parses and transliterates the * downloaded files. * @throws ScansiteUpdaterException */ protected abstract FileTransliterator getDbFileTransliterator(String tempFilePath, String errorFilePath) throws ScansiteUpdaterException; /** * Prepare the URIs of the files that have to be downloaded. This can either be * a list containing the file that is given in the configuration file (most * simple case), or a list of files that is determined by accessing the given * URI. * * @param dbDownloadUrl * the URI given in the configuration file. * @return A list of files to download (defined by their URIs). * @throws ScansiteUpdaterException */ protected abstract List<URL> prepareDownloadUrls(List<URL> dbDownloadUrl) throws ScansiteUpdaterException; protected abstract void createTables() throws ScansiteUpdaterException; protected abstract void renameTables() throws ScansiteUpdaterException; protected abstract void dropOldTables() throws ScansiteUpdaterException; protected abstract void dropTempTables() throws ScansiteUpdaterException; protected abstract void updateHistogramData() throws ScansiteUpdaterException; private String getVersion() throws ScansiteUpdaterException { String version = null; if (versionFileDownloadUrl != null) { try { version = doGetVersion(); } catch (Exception e) { } } if (version == null || version.isEmpty()) { Calendar cal = Calendar.getInstance(); String month = String.valueOf(cal.get(Calendar.MONTH) + 1); String year = String.valueOf(cal.get(Calendar.YEAR)); String day = String.valueOf(cal.get(Calendar.DAY_OF_MONTH)); version = year + "/" + month + "/" + day; } return version; } /** * Initializes the reader that is used for accessing the given file. * * @throws ScansiteUpdaterException * Is thrown if the downloaded file can not be accessed. */ private void initReader(String fileName) throws ScansiteUpdaterException { File f = new File(getFilePath(fileName)); try { if (!readers.isEmpty()) { for (BufferedReader reader : readers) { reader.close(); } readers.clear(); } if (f.toString().endsWith(".gz")) { GZIPInputStream gzIn = new GZIPInputStream(new FileInputStream(f)); if (dataSourceMetaInfo.getEncoding() != null && !dataSourceMetaInfo.getEncoding().isEmpty()) { readers.add(new BufferedReader(new InputStreamReader(gzIn, dataSourceMetaInfo.getEncoding()))); } else { readers.add(new BufferedReader(new InputStreamReader(gzIn))); } } else if (f.toString().endsWith(".zip")) { ZipInputStream zis = new ZipInputStream(new FileInputStream(f)); ZipEntry zippedFile = zis.getNextEntry(); while (zippedFile != null) { File newFile = new File(tempDir + File.separator + dataSourceMetaInfo.getDataSource().getShortName() + "_" + zippedFile.getName()); FileOutputStream outputStream = new FileOutputStream(newFile); int len; byte[] buffer = new byte[1024]; while ((len = zis.read(buffer)) > 0) { outputStream.write(buffer, 0, len); } outputStream.close(); zippedFile = zis.getNextEntry(); readers.add(new BufferedReader(new FileReader(newFile))); } zis.closeEntry(); zis.close(); } else { readers.add(new BufferedReader(new FileReader(f))); } } catch (Exception e) { logger.error("Local file " + f + " can not be accessed: " + e.getMessage(), e); throw new ScansiteUpdaterException("Local file " + f + " can not be accessed!", e); } } /** * Performs the update. **/ @Override public void run() { try { runUpdate(); } catch (ScansiteUpdaterException e) { logger.error("failed at " + dataSourceMetaInfo.getDataSource().getShortName() + "): " + e.getMessage(), e); e.printStackTrace(); } } /** * Deletes all the files that have been created before. * * @param f */ protected void cleanup(File f) { try { for (BufferedReader reader : readers) { reader.close(); } readers.clear(); dropOldTables(); } catch (Exception e) { logger.error(e.getMessage(), e); } // Moved to DataInsertionManager // File dir; // if (f.isDirectory()){ // dir = f; // } else { // dir = f.getParentFile(); // f.delete(); // try { // FileUtils.deleteDirectory(dir); // } catch (IOException e) { // logger.warn(e.getMessage()); // logger.warn("Could not delete the temporary directory [" + // dir.getAbsolutePath() + "]! Please do so manually!"); } protected String getFilePath(String filename) { return tempDir + "/" + filename; } /** * Downloads the files that are needed. * * @throws ScansiteUpdaterException * Is thrown if one of the files can not be downloaded. */ private void downloadDbFiles(List<URL> dbDownloadUrls) throws ScansiteUpdaterException { this.dbDownloadUrls = prepareDownloadUrls(dbDownloadUrls); for (URL dbDownloadUrl : this.dbDownloadUrls) { String dbFileName = dataSourceMetaInfo.getDataSource().getShortName() + "_" + getFileNameFromURL(dbDownloadUrl.toString()); this.dbFileNames.add(dbFileName); String path = getFilePath(dbFileName); File f = new File(path); if (!f.exists()) { logger.info("download necessary, starting to download"); downloadFile(dbDownloadUrl, path); } else { logger.info("download not necessary, file already downloaded"); } } } private void downloadFile(URL from, String to) throws ScansiteUpdaterException { Downloader downloader = new Downloader(); downloader.downloadFile(from, to); } /** * Returns the filename of the given URL. * * @param url * The url. If "/var/www/poop.txt" is given, "poop.txt" is returned * @return The filename of the given URL. */ private String getFileNameFromURL(String url) { return url.substring(url.lastIndexOf('/') + 1, url.length()); } protected List<BufferedReader> getReaders() { return readers; } protected File getTempDir() { return tempDir; } protected DataSourceMetaInfo getDatabase() { return dataSourceMetaInfo; } protected URL getVersionFileDownloadUrl() { return versionFileDownloadUrl; } }
package org.jetel.graph; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.net.URL; import java.util.Arrays; import java.util.concurrent.Future; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.graph.runtime.EngineInitializer; import org.jetel.graph.runtime.GraphRuntimeContext; import org.jetel.main.runGraph; import org.jetel.test.CloverTestCase; import org.jetel.util.file.FileUtils; import org.jetel.util.string.StringUtils; public class ResetTest extends CloverTestCase { private final static String SCENARIOS_RELATIVE_PATH = "../cloveretl.test.scenarios/"; private final static String[] EXAMPLE_PATH = { "../cloveretl.examples/SimpleExamples/", "../cloveretl.examples/AdvancedExamples/", "../cloveretl.examples/CTL1FunctionsTutorial/", "../cloveretl.examples/CTL2FunctionsTutorial/", "../cloveretl.examples/DataProfiling/", "../cloveretl.examples/DataSampling/", "../cloveretl.examples/ExtExamples/", "../cloveretl.test.scenarios/", "../cloveretl.examples.commercial/", "../cloveretl.examples/CompanyTransactionsTutorial/" }; private final static String[] NEEDS_SCENARIOS_CONNECTION = { "graphRevenues.grf", "graphDBExecuteMsSql.grf", "graphDBExecuteMySql.grf", "graphDBExecuteOracle.grf", "graphDBExecutePostgre.grf", "graphDBExecuteSybase.grf", "graphInfobrightDataWriterRemote.grf", "graphLdapReaderWriter.grf" }; private final static String[] NEEDS_SCENARIOS_LIB = { "graphDBExecuteOracle.grf", "graphDBExecuteSybase.grf", "graphLdapReaderWriter.grf" }; private final static String GRAPHS_DIR = "graph"; private final static String TRANS_DIR = "trans"; private final static String[] OUT_DIRS = {"data-out/", "data-tmp/", "seq/"}; private final String basePath; private final File graphFile; private final boolean batchMode; private boolean cleanUp = true; private static Log logger = LogFactory.getLog(ResetTest.class); public static Test suite() { final TestSuite suite = new TestSuite(); for (int i = 0; i < EXAMPLE_PATH.length; i++) { logger.info("Testing graphs in " + EXAMPLE_PATH[i]); final File graphsDir = new File(EXAMPLE_PATH[i], GRAPHS_DIR); if(!graphsDir.exists()){ throw new IllegalStateException("Graphs directory " + graphsDir.getAbsolutePath() +" not found"); } File[] graphFiles =graphsDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().endsWith(".grf") && !pathname.getName().startsWith("TPCH")// ok, performance tests - last very long && !pathname.getName().contains("Performance")// ok, performance tests - last very long && !pathname.getName().equals("graphJoinData.grf") // ok, uses class file that is not created && !pathname.getName().equals("graphJoinHash.grf") // ok, uses class file that is not created && !pathname.getName().equals("graphOrdersReformat.grf") // ok, uses class file that is not created && !pathname.getName().equals("graphDataGeneratorExt.grf") // ok, uses class file that is not created && !pathname.getName().equals("graphApproximativeJoin.grf") // ok, uses class file that is not created && !pathname.getName().equals("graphDBJoin.grf") // ok, uses class file that is not created && !pathname.getName().equals("conversionNum2num.grf") // ok, should fail && !pathname.getName().equals("outPortWriting.grf") // ok, should fail && !pathname.getName().equals("graphDb2Load.grf") // ok, can only work with db2 client && !pathname.getName().equals("graphMsSqlDataWriter.grf") // ok, can only work with MsSql client && !pathname.getName().equals("graphMysqlDataWriter.grf") // ok, can only work with MySql client && !pathname.getName().equals("graphOracleDataWriter.grf") // ok, can only work with Oracle client && !pathname.getName().equals("graphPostgreSqlDataWriter.grf") // ok, can only work with postgre client && !pathname.getName().equals("graphInformixDataWriter.grf") // ok, can only work with informix server && !pathname.getName().equals("graphInfobrightDataWriter.grf") // ok, can only work with infobright server && !pathname.getName().equals("graphSystemExecuteWin.grf") // ok, graph for Windows && !pathname.getName().equals("graphLdapReader_Uninett.grf") // ok, invalid server && !pathname.getName().equals("graphSequenceChecker.grf") // ok, is to fail && !pathname.getName().equals("FixedData.grf") // ok, is to fail && !pathname.getName().equals("xpathReaderStates.grf") // ok, is to fail && !pathname.getName().equals("graphDataPolicy.grf") // ok, is to fail && !pathname.getName().equals("conversionDecimal2integer.grf") // ok, is to fail && !pathname.getName().equals("conversionDecimal2long.grf") // ok, is to fail && !pathname.getName().equals("conversionDouble2integer.grf") // ok, is to fail && !pathname.getName().equals("conversionDouble2long.grf") // ok, is to fail && !pathname.getName().equals("conversionLong2integer.grf") // ok, is to fail && !pathname.getName().equals("nativeSortTestGraph.grf") // ok, invalid paths && !pathname.getName().equals("mountainsInformix.grf") // see issue 2550 && !pathname.getName().equals("SystemExecuteWin_EchoFromFile.grf") // graph for windows && !pathname.getName().equals("XLSEncryptedFail.grf") // ok, is to fail && !pathname.getName().equals("XLSXEncryptedFail.grf") // ok, is to fail && !pathname.getName().equals("XLSInvalidFile.grf") // ok, is to fail && !pathname.getName().equals("XLSReaderOrderMappingFail.grf") // ok, is to fail && !pathname.getName().equals("XLSXReaderOrderMappingFail.grf") // ok, is to fail && !pathname.getName().equals("XLSWildcardStrict.grf") // ok, is to fail && !pathname.getName().equals("XLSXWildcardStrict.grf") // ok, is to fail && !pathname.getName().equals("XLSWildcardControlled1.grf") // ok, is to fail && !pathname.getName().equals("XLSXWildcardControlled1.grf") // ok, is to fail && !pathname.getName().equals("XLSWildcardControlled7.grf") // ok, is to fail && !pathname.getName().equals("XLSXWildcardControlled7.grf") // ok, is to fail && !pathname.getName().equals("SSWRITER_MultilineInsertIntoTemplate.grf") // uses graph parameter definition from after-commit.ts && !pathname.getName().equals("SSWRITER_FormatInMetadata.grf") // uses graph parameter definition from after-commit.ts && !pathname.getName().equals("WSC_NamespaceBindingsDefined.grf") // ok, is to fail && !pathname.getName().equals("FailingGraph.grf") // ok, is to fail && !pathname.getName().equals("RunGraph_FailWhenUnderlyingGraphFails.grf") // probably should fail, recheck after added to after-commit.ts && !pathname.getName().equals("DataIntersection_order_check_A.grf") // ok, is to fail && !pathname.getName().equals("DataIntersection_order_check_B.grf") // ok, is to fail && !pathname.getName().equals("UDR_Logging_SFTP_CL1469.grf") // ok, is to fail && !pathname.getName().startsWith("AddressDoctor") //wrong path to db file, try to fix when AD installed on jenkins machines && !pathname.getName().equals("EmailReader_Local.grf") // remove after CL-2167 solved && !pathname.getName().equals("EmailReader_Server.grf") // remove after CLD-3437 solved (or mail.javlin.eu has valid certificate) && !pathname.getName().contains("firebird") // remove after CL-2170 solved && !pathname.getName().startsWith("ListOfRecords_Functions_02_") // remove after CL-2173 solved && !pathname.getName().equals("UDR_FileURL_OneZipMultipleFilesUnspecified.grf") // remove after CL-2174 solved && !pathname.getName().equals("UDR_FileURL_OneZipOneFileUnspecified.grf") // remove after CL-2174 solved && !pathname.getName().startsWith("MapOfRecords_Functions_01_Compiled_") // remove after CL-2175 solved && !pathname.getName().startsWith("MapOfRecords_Functions_01_Interpreted_") // remove after CL-2176 solved && !pathname.getName().equals("manyRecords.grf") // remove after CL-1825 implemented && !pathname.getName().equals("packedDecimal.grf") // remove after CL-1811 solved && !pathname.getName().equals("SimpleZipWrite.grf") // used by ArchiveFlushTest.java, doesn't make sense to run it separately && !pathname.getName().equals("XMLExtract_TKLK_003_Back.grf") // needs output from XMLWriter_LKTW_003.grf && !pathname.getName().equals("SQLDataParser_precision_CL2187.grf") // ok, is to fail && !pathname.getName().equals("incrementalReadingDB_explicitMapping.grf") // remove after CL-2239 solved && !pathname.getName().equals("HTTPConnector_get_bodyparams.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_get_error_unknownhost.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_get_error_unknownprotocol.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_get_inputfield.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_get_inputfileURL.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_get_requestcontent.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_post_error_unknownhost.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_post_error_unknownprotocol.grf") // ok, is to fail && !pathname.getName().equals("HTTPConnector_inputmapping_null_values.grf") // ok, is to fail && !pathname.getName().equals("HttpConnector_errHandlingNoRedir.grf") // ok, is to fail && !pathname.getName().equals("XMLExtract_fileURL_not_xml.grf") // ok, is to fail && !pathname.getName().equals("XMLExtract_charset_invalid.grf") // ok, is to fail && !pathname.getName().equals("XMLExtract_mappingURL_missing.grf") // ok, is to fail && !pathname.getName().equals("XMLExtract_fileURL_not_exists.grf") // ok, is to fail && !pathname.getName().equals("XMLExtract_charset_not_default_fail.grf") // ok, is to fail && !pathname.getName().equals("RunGraph_differentOutputMetadataFail.grf") // ok, is to fail && !pathname.getName().equals("LUTPersistent_wrong_metadata.grf") // ok, is to fail && !pathname.getName().equals("UDW_nonExistingDir_fail_CL-2478.grf") // ok, is to fail && !pathname.getName().equals("CTL_lookup_put_fail.grf") // ok, is to fail && !pathname.getName().equals("SystemExecute_printBatchFile.grf") // ok, is to fail && !pathname.getName().startsWith("Proxy_") // allowed to run only on virt-cyan as proxy tests && !pathname.getName().equals("SandboxOperationHandlerTest.grf") // runs only on server && !pathname.getName().equals("DenormalizerWithoutInputFile.grf") // probably subgraph not supposed to be executed separately && !pathname.getName().equals("SimpleSequence_longValue.grf") // needs the sequence to be reset on start && !pathname.getName().equals("BeanWriterReader_employees.grf"); // remove after CL-2474 solved } }); Arrays.sort(graphFiles); for( int j = 0; j < graphFiles.length; j++){ suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], false, false)); suite.addTest(new ResetTest(EXAMPLE_PATH[i], graphFiles[j], true, j == graphFiles.length - 1 ? true : false)); } } return suite; } @Override protected void setUp() throws Exception { super.setUp(); initEngine(); } protected static String getTestName(String basePath, File graphFile, boolean batchMode) { final StringBuilder ret = new StringBuilder(); final String n = graphFile.getName(); int lastDot = n.lastIndexOf('.'); if (lastDot == -1) { ret.append(n); } else { ret.append(n.substring(0, lastDot)); } if (batchMode) { ret.append("-batch"); } else { ret.append("-nobatch"); } return ret.toString(); } protected ResetTest(String basePath, File graphFile, boolean batchMode, boolean cleanup) { super(getTestName(basePath, graphFile, batchMode)); this.basePath = basePath; this.graphFile = graphFile; this.batchMode = batchMode; this.cleanUp = cleanup; } @Override protected void runTest() throws Throwable { final String beseAbsolutePath = new File(basePath).getAbsolutePath().replace('\\', '/'); logger.info("Project dir: " + beseAbsolutePath); logger.info("Analyzing graph " + graphFile.getPath()); logger.info("Batch mode: " + batchMode); final GraphRuntimeContext runtimeContext = new GraphRuntimeContext(); runtimeContext.setUseJMX(false); runtimeContext.setContextURL(FileUtils.getFileURL(basePath)); // absolute path in PROJECT parameter is required for graphs using Derby database runtimeContext.addAdditionalProperty("PROJECT", beseAbsolutePath); if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_CONNECTION) != -1) { final String connDir = new File(SCENARIOS_RELATIVE_PATH + "conn").getAbsolutePath(); runtimeContext.addAdditionalProperty("CONN_DIR", connDir); logger.info("CONN_DIR set to " + connDir); } if (StringUtils.findString(graphFile.getName(), NEEDS_SCENARIOS_LIB) != -1) {// set LIB_DIR to jdbc drivers directory final String libDir = new File(SCENARIOS_RELATIVE_PATH + "lib").getAbsolutePath(); runtimeContext.addAdditionalProperty("LIB_DIR", libDir); logger.info("LIB_DIR set to " + libDir); } // for scenarios graphs, add the TRANS dir to the classpath if (basePath.contains("cloveretl.test.scenarios")) { runtimeContext.setRuntimeClassPath(new URL[] {FileUtils.getFileURL(FileUtils.appendSlash(beseAbsolutePath) + TRANS_DIR + "/")}); runtimeContext.setCompileClassPath(runtimeContext.getRuntimeClassPath()); } runtimeContext.setBatchMode(batchMode); final TransformationGraph graph = TransformationGraphXMLReaderWriter.loadGraph(new FileInputStream(graphFile), runtimeContext); try { graph.setDebugMode(false); EngineInitializer.initGraph(graph); for (int i = 0; i < 3; i++) { final Future<Result> futureResult = runGraph.executeGraph(graph, runtimeContext); Result result = Result.N_A; result = futureResult.get(); switch (result) { case FINISHED_OK: // everything O.K. logger.info("Execution of graph successful !"); break; case ABORTED: // execution was ABORTED !! logger.info("Execution of graph failed !"); fail("Execution of graph failed !"); break; default: logger.info("Execution of graph failed !"); fail("Execution of graph failed !"); } } } catch (Throwable e) { throw new IllegalStateException("Error executing grap " + graphFile, e); } finally { if (cleanUp) { cleanupData(); } logger.info("Transformation graph is freeing.\n"); graph.free(); } } private void cleanupData() { for (String outDir : OUT_DIRS) { File outDirFile = new File(basePath, outDir); File[] file = outDirFile.listFiles(new FileFilter() { @Override public boolean accept(File f) { return f.isFile(); } }); for (int i = 0; i < file.length; i++) { final boolean drt = file[i].delete(); if (drt) { logger.info("Cleanup: deleted file " + file[i].getAbsolutePath()); } else { logger.info("Cleanup: error delete file " + file[i].getAbsolutePath()); } } } } }
package com.gallatinsystems.survey.device.service; import java.net.URLEncoder; import java.util.Timer; import java.util.TimerTask; import android.app.Service; import android.content.Intent; import android.content.res.Resources; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.os.IBinder; import android.util.Log; import com.gallatinsystems.survey.device.R; import com.gallatinsystems.survey.device.dao.SurveyDbAdapter; import com.gallatinsystems.survey.device.exception.PersistentUncaughtExceptionHandler; import com.gallatinsystems.survey.device.util.ConstantUtil; import com.gallatinsystems.survey.device.util.HttpUtil; import com.gallatinsystems.survey.device.util.PropertyUtil; import com.gallatinsystems.survey.device.util.StatusUtil; /** * service for sending location beacons on a set interval to the server. This * can be disabled via the properties menu * * @author Christopher Fagiani * */ public class LocationService extends Service { private static Timer timer; private LocationManager locMgr; private Criteria locationCriteria; private static final long INITIAL_DELAY = 60000; private static final long INTERVAL = 300000; private static boolean sendBeacon = true; private static final String BEACON_SERVICE_PATH = "/locationBeacon?action=beacon&phoneNumber="; private static final String VER = "&ver="; private static final String LAT = "&lat="; private static final String LON = "&lon="; private static final String ACC = "&acc="; private static final String DEV_ID = "&devId="; private static final String TAG = "LocationService"; private String version; private String deviceId; private PropertyUtil props; public IBinder onBind(Intent intent) { return null; } /** * life cycle method for the service. This is called by the system when the * service is started. It will schedule a timerTask that will periodically * check the current location and send it to the server */ public int onStartCommand(final Intent intent, int flags, int startid) { // we only need to check this on command start since we'll explicitly // call endService if they change the preference to false after we're // already // started SurveyDbAdapter database = new SurveyDbAdapter(this); database.open(); String val = database .findPreference(ConstantUtil.LOCATION_BEACON_SETTING_KEY); deviceId = database.findPreference(ConstantUtil.DEVICE_IDENT_KEY); if (val != null) { sendBeacon = Boolean.parseBoolean(val); } Resources resources = getResources(); version = resources.getString(R.string.appversion); String serverBase = database .findPreference(ConstantUtil.SERVER_SETTING_KEY); if (serverBase != null && serverBase.trim().length() > 0) { serverBase = resources.getStringArray(R.array.servers)[Integer .parseInt(serverBase)]; } else { serverBase = props.getProperty(ConstantUtil.SERVER_BASE); } final String server = serverBase; database.close(); if (timer == null && sendBeacon) { timer = new Timer(true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (sendBeacon) { String provider = locMgr.getBestProvider( locationCriteria, true); if (provider != null) { sendLocation(server, locMgr .getLastKnownLocation(provider)); } } } }, INITIAL_DELAY, INTERVAL); } return Service.START_STICKY; } public void onCreate() { super.onCreate(); Thread .setDefaultUncaughtExceptionHandler(PersistentUncaughtExceptionHandler .getInstance()); locMgr = (LocationManager) getSystemService(LOCATION_SERVICE); locationCriteria = new Criteria(); locationCriteria.setAccuracy(Criteria.NO_REQUIREMENT); props = new PropertyUtil(getResources()); } /** * sends the location beacon to the server * * @param loc */ private void sendLocation(String serverBase, Location loc) { try { String phoneNumber = StatusUtil.getPhoneNumber(this); if (loc != null) { if (phoneNumber != null) { String url = serverBase + BEACON_SERVICE_PATH + URLEncoder.encode(phoneNumber, "UTF-8") + LAT + loc.getLatitude() + LON + loc.getLongitude() + ACC + loc.getAccuracy() + VER + version; if (deviceId != null) { url += DEV_ID + URLEncoder.encode(deviceId, "UTF-8"); } HttpUtil.httpGet(url); } } else { // if location is null, send an update anyway, just without // lat/lon HttpUtil.httpGet(serverBase + BEACON_SERVICE_PATH + URLEncoder.encode(phoneNumber, "UTF-8") + VER + version); } } catch (Exception e) { Log.e(TAG, "Could not send location beacon", e); PersistentUncaughtExceptionHandler.recordException(e); } } public void onDestroy() { super.onDestroy(); if (timer != null) { timer.cancel(); timer = null; } } }
package net.wayward_realms.waywardcharacters; import net.wayward_realms.waywardlib.character.Character; import net.wayward_realms.waywardlib.character.CharacterPlugin; import net.wayward_realms.waywardlib.character.Gender; import net.wayward_realms.waywardlib.character.Race; import net.wayward_realms.waywardlib.classes.ClassesPlugin; import net.wayward_realms.waywardlib.classes.Stat; import net.wayward_realms.waywardlib.combat.CombatPlugin; import net.wayward_realms.waywardlib.events.EventsPlugin; import net.wayward_realms.waywardlib.util.file.filter.YamlFileFilter; import org.bukkit.*; import org.bukkit.block.Biome; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.serialization.ConfigurationSerialization; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.io.IOException; import java.util.*; public class WaywardCharacters extends JavaPlugin implements CharacterPlugin { private Map<String, Gender> genders = new HashMap<>(); private Map<String, Race> races = new HashMap<>(); @Override public void onEnable() { ConfigurationSerialization.registerClass(CharacterImpl.class); ConfigurationSerialization.registerClass(GenderImpl.class); ConfigurationSerialization.registerClass(RaceImpl.class); ConfigurationSerialization.registerClass(RaceKit.class); saveDefaultConfig(); registerListeners(new EntityDamageListener(this), new EntityRegainHealthListener(this), new FoodLevelChangeListener(this), new PlayerItemConsumeListener(this), new PlayerInteractListener(this), new PlayerInteractEntityListener(this), new PlayerJoinListener(this), new PlayerLoginListener(this), new PlayerRespawnListener(this), new SignChangeListener(this), new PlayerEditBookListener(this)); getCommand("character").setExecutor(new CharacterCommand(this)); getCommand("racekit").setExecutor(new RaceKitCommand(this)); getCommand("stats").setExecutor(new StatsCommand(this)); getCommand("skillpoints").setExecutor(new SkillPointsCommand(this)); getCommand("togglethirst").setExecutor(new ToggleThirstCommand(this)); setupRegen(); setupHungerSlowdown(); } private void setupRegen() { getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { @Override public void run() { Random random = new Random(); for (Player player : getServer().getOnlinePlayers()) { if (player.getGameMode() != GameMode.CREATIVE) { Character character = getActiveCharacter(player); int decreaseChance = checkBiome(player.getLocation().getBlock().getBiome()); if (!isThirstDisabled(player)) { if (character.getThirst() > 0 && random.nextInt(100) <= decreaseChance) { character.setThirst(character.getThirst() - 1); player.sendMessage(getPrefix() + ChatColor.RED + "Thirst: -1" + ChatColor.GRAY + " (Total: " + character.getThirst() + ")"); } if (character.getThirst() < 5 && character.getHealth() > 1) { character.setHealth(character.getHealth() - 1); player.sendMessage(getPrefix() + ChatColor.RED + "You are very thirsty, be sure to drink something soon! " + ChatColor.GRAY + "(Health: -1)"); } } RegisteredServiceProvider<CombatPlugin> combatPluginProvider = Bukkit.getServer().getServicesManager().getRegistration(CombatPlugin.class); if (combatPluginProvider != null) { CombatPlugin combatPlugin = combatPluginProvider.getProvider(); if (combatPlugin.getActiveFight(character) != null) { continue; } } int manaRegen = Math.min(character.getMana() + Math.max(character.getMaxMana() / 50, 1), character.getMaxMana()) - character.getMana(); character.setMana(Math.min(character.getMana() + Math.max(character.getMaxMana() / 50, 1), character.getMaxMana())); if (manaRegen > 0) { player.sendMessage(getPrefix() + ChatColor.GREEN + "Mana regenerated: " + manaRegen); } if (player.getFoodLevel() >= 15) { double healthRegen; if (player.isSleeping()) { healthRegen = Math.min(character.getHealth() + (character.getMaxHealth() / 5), character.getMaxHealth()) - character.getHealth(); character.setHealth(Math.min(character.getHealth() + (character.getMaxHealth() / 5), character.getMaxHealth())); } else { healthRegen = Math.min(character.getHealth() + (character.getMaxHealth() / 20), character.getMaxHealth()) - character.getHealth(); character.setHealth(Math.min(character.getHealth() + (character.getMaxHealth() / 20), character.getMaxHealth())); } if (healthRegen > 0) { player.sendMessage(getPrefix() + ChatColor.GREEN + "Health regenerated: " + healthRegen); } } player.setMaxHealth(character.getMaxHealth()); player.setHealth(Math.max(character.getHealth(), 0)); } } } }, 500L, 500L); } private void setupHungerSlowdown() { float hungerModifier = -4F; float newExhaustStartLevel = 0.0F; if (hungerModifier > 0.0F) { newExhaustStartLevel = 4.0F / hungerModifier * (hungerModifier - 1.0F); } if (hungerModifier < 0.0F) { newExhaustStartLevel = hungerModifier * 4.0F - 1.0F; } final float finalNewExhaustStartLevel = newExhaustStartLevel; getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { public void run() { for (Player player : getServer().getOnlinePlayers()) { float currentExhaustion = player.getExhaustion(); if (((currentExhaustion > -1.0F ? 1 : 0) & (currentExhaustion < 0.0F ? 1 : 0)) != 0) { player.setExhaustion(4.0F); } if (((currentExhaustion > 0.0F ? 1 : 0) & (currentExhaustion < 4.0F ? 1 : 0)) != 0) { player.setExhaustion(finalNewExhaustStartLevel); } } } }, 0L, 1L); } @Override public void onDisable() { saveState(); } private void registerListeners(Listener... listeners) { for (Listener listener : listeners) { this.getServer().getPluginManager().registerEvents(listener, this); } } @Override public String getPrefix() { //return "" + ChatColor.DARK_GRAY + ChatColor.MAGIC + "|" + ChatColor.RESET + ChatColor.BLUE + "WaywardCharacters" + ChatColor.DARK_GRAY + ChatColor.MAGIC + "| " + ChatColor.RESET; return ""; } @SuppressWarnings("unchecked") @Override public void loadState() { // Genders File gendersFile = new File(getDataFolder(), "genders.yml"); if (gendersFile.exists()) { YamlConfiguration gendersConfig = new YamlConfiguration(); try { gendersConfig.load(gendersFile); for (String section : gendersConfig.getKeys(false)) { genders.put(section, (GenderImpl) gendersConfig.get(section)); } } catch (IOException | InvalidConfigurationException exception) { exception.printStackTrace(); } } if (genders.isEmpty()) { getLogger().info("There are no genders, creating defaults."); genders.put("UNKNOWN", new GenderImpl("UNKNOWN")); genders.put("MALE", new GenderImpl("MALE")); genders.put("FEMALE", new GenderImpl("FEMALE")); genders.put("AGENDER", new GenderImpl("AGENDER")); genders.put("ANDROGYNE", new GenderImpl("ANDROGYNE")); genders.put("BIGENDER", new GenderImpl("BIGENDER")); genders.put("CISGENDER", new GenderImpl("CISGENDER")); genders.put("CISSEXUAL", new GenderImpl("CISSEXUAL")); genders.put("GENDERQUEER", new GenderImpl("GENDERQUEER")); genders.put("HIJRA", new GenderImpl("HIJRA")); genders.put("PANGENDER", new GenderImpl("PANGENDER")); genders.put("TRANS_MAN", new GenderImpl("TRANS_MAN")); genders.put("TRANS_WOMAN", new GenderImpl("TRANS_WOMAN")); genders.put("TRIGENDER", new GenderImpl("TRIGENDER")); genders.put("TWO_SPIRIT", new GenderImpl("TWO_SPIRIT")); } // Races File racesFile = new File(getDataFolder(), "races.yml"); if (racesFile.exists()) { YamlConfiguration racesConfig = new YamlConfiguration(); try { racesConfig.load(racesFile); for (String section : racesConfig.getKeys(false)) { races.put(section, (RaceImpl) racesConfig.get(section)); } } catch (IOException | InvalidConfigurationException exception) { exception.printStackTrace(); } } if (races.isEmpty()) { getLogger().info("There are no races, creating defaults."); races.put("UNKNOWN", new RaceImpl("Unknown")); races.put("HUMAN", new RaceImpl("Human")); RaceKit arrows = new RaceKit(); arrows.addItem(new ItemStack(Material.ARROW, 4)); Map<Stat, Integer> statBonuses = new EnumMap<>(Stat.class); statBonuses.put(Stat.SPEED, 2); statBonuses.put(Stat.MELEE_DEFENCE, -2); races.put("ELF", new RaceImpl("Elf", arrows, statBonuses)); } // Characters // Old character conversion File oldCharacterDirectory = new File(getDataFolder(), "characters"); if (oldCharacterDirectory.exists()) { for (File file : oldCharacterDirectory.listFiles(new YamlFileFilter())) { YamlConfiguration oldcharacterSave = YamlConfiguration.loadConfiguration(file); if (oldcharacterSave.get("character") != null) { if (oldcharacterSave.get("character") instanceof CharacterImpl) { oldcharacterSave.get("character"); } } } delete(oldCharacterDirectory); } File characterDirectory = new File(getDataFolder(), "characters-new"); if (characterDirectory.exists()) { for (File file : characterDirectory.listFiles(new YamlFileFilter())) { int id = Integer.parseInt(file.getName().replace(".yml", "")); if (id > CharacterImpl.getNextId()) CharacterImpl.setNextId(id); } } } private void delete(File file) { if (file.isDirectory()) { for (File childFile : file.listFiles()) { delete(childFile); } } file.delete(); } @Override public void saveState() { // Genders File gendersFile = new File(getDataFolder().getPath() + File.separator + "genders.yml"); YamlConfiguration gendersConfig = new YamlConfiguration(); for (String genderName : genders.keySet()) { gendersConfig.set(genderName, genders.get(genderName)); } try { gendersConfig.save(gendersFile); } catch (IOException exception) { exception.printStackTrace(); } // Races File racesFile = new File(getDataFolder().getPath() + File.separator + "races.yml"); YamlConfiguration racesConfig = new YamlConfiguration(); for (String raceName : races.keySet()) { racesConfig.set(raceName, races.get(raceName)); } try { racesConfig.save(racesFile); } catch (IOException exception) { exception.printStackTrace(); } } @Override public Character getActiveCharacter(OfflinePlayer player) { File playerDirectory = new File(getDataFolder(), "players"); File playerFile = new File(playerDirectory, player.getName() + ".yml"); YamlConfiguration playerSave = YamlConfiguration.loadConfiguration(playerFile); if (playerSave.get("active-character") == null) { return null; } return getCharacter(playerSave.getInt("active-character")); } @Override public Set<Character> getCharacters(OfflinePlayer player) { YamlConfiguration playerSave = YamlConfiguration.loadConfiguration(new File(new File(getDataFolder(), "players"), player.getName() + ".yml")); if (playerSave.get("characters") == null) { playerSave.set("characters", new HashSet<Integer>()); } Set<Character> characters = new HashSet<>(); for (int cid : (Set<Integer>) playerSave.get("characters")) { characters.add(getCharacter(cid)); } return characters; } @Override public void addCharacter(OfflinePlayer player, Character character) { YamlConfiguration playerSave = YamlConfiguration.loadConfiguration(new File(new File(getDataFolder(), "players"), player.getName() + ".yml")); character.setPlayer(player); if (playerSave.get("characters") == null) { playerSave.set("characters", new HashSet<Integer>()); } Set<Integer> cids = (Set<Integer>) playerSave.get("characters"); cids.add(character.getId()); playerSave.set("characters", cids); try { playerSave.save(new File(new File(getDataFolder(), "players"), player.getName() + ".yml")); } catch (IOException exception) { exception.printStackTrace(); } } @Override public void removeCharacter(OfflinePlayer player, Character character) { YamlConfiguration playerSave = YamlConfiguration.loadConfiguration(new File(new File(getDataFolder(), "players"), player.getName() + ".yml")); character.setPlayer(player); if (playerSave.get("characters") == null) { playerSave.set("characters", new HashSet<Integer>()); } Set<Integer> cids = (Set<Integer>) playerSave.get("characters"); cids.remove(character.getId()); playerSave.set("characters", cids); try { playerSave.save(new File(new File(getDataFolder(), "players"), player.getName() + ".yml")); } catch (IOException exception) { exception.printStackTrace(); } } @Override public void removeCharacter(Character character) { throw new UnsupportedOperationException("Removing a character breaks stuff! Don't do it!"); } @Override public void setActiveCharacter(Player player, Character character) { if (getActiveCharacter(player) != null) { Character activeCharacter = getActiveCharacter(player); activeCharacter.setHelmet(player.getInventory().getHelmet()); activeCharacter.setChestplate(player.getInventory().getChestplate()); activeCharacter.setLeggings(player.getInventory().getLeggings()); activeCharacter.setBoots(player.getInventory().getBoots()); activeCharacter.setInventoryContents(player.getInventory().getContents()); activeCharacter.setLocation(player.getLocation()); activeCharacter.setHealth(player.getHealth()); activeCharacter.setFoodLevel(player.getFoodLevel()); } addCharacter(player, character); File playerDirectory = new File(getDataFolder(), "players"); File playerFile = new File(playerDirectory, player.getName() + ".yml"); YamlConfiguration playerSave = YamlConfiguration.loadConfiguration(playerFile); playerSave.set("active-character", character.getId()); try { playerSave.save(playerFile); } catch (IOException exception) { exception.printStackTrace(); } player.getInventory().setHelmet(character.getHelmet()); player.getInventory().setChestplate(character.getChestplate()); player.getInventory().setLeggings(character.getLeggings()); player.getInventory().setBoots(character.getBoots()); player.getInventory().setContents(character.getInventoryContents()); player.teleport(character.getLocation()); player.setDisplayName(character.isNameHidden() ? ChatColor.MAGIC + character.getName() + ChatColor.RESET : character.getName()); player.setMaxHealth(character.getMaxHealth()); player.setHealth(Math.max(character.getHealth(), 0)); player.setFoodLevel(character.getFoodLevel()); RegisteredServiceProvider<ClassesPlugin> classesPluginProvider = Bukkit.getServer().getServicesManager().getRegistration(ClassesPlugin.class); if (classesPluginProvider != null) { ClassesPlugin classesPlugin = classesPluginProvider.getProvider(); player.setExp((float) classesPlugin.getExperienceTowardsNextLevel(player) / (float) classesPlugin.getExpToNextLevel(classesPlugin.getLevel(player))); player.setLevel(classesPlugin.getLevel(player)); } } @Override public Character getCharacter(int id) { File newCharacterDirectory = new File(getDataFolder(), "characters-new"); File newCharacterFile = new File(newCharacterDirectory, id + ".yml"); if (newCharacterFile.exists()) { return new CharacterImpl(newCharacterFile); } else { RegisteredServiceProvider<EventsPlugin> eventsPluginProvider = getServer().getServicesManager().getRegistration(EventsPlugin.class); if (eventsPluginProvider != null) { EventsPlugin eventsPlugin = eventsPluginProvider.getProvider(); return eventsPlugin.getEventCharacter(id); } } return null; } @Override public Collection<Gender> getGenders() { return genders.values(); } @Override public Gender getGender(String name) { return genders.get(name); } @Override public void addGender(Gender gender) { genders.put(gender.getName(), gender); } @Override public void removeGender(Gender gender) { genders.remove(gender.getName()); } @Override public int getNextAvailableId() { return CharacterImpl.getNextId(); } @Override public void setNextAvailableId(int id) { CharacterImpl.setNextId(id); } @Override public void incrementNextAvailableId() { CharacterImpl.nextAvailableId(); } @Override public Collection<Race> getRaces() { return races.values(); } @Override public Race getRace(String name) { return races.get(name.toUpperCase()); } @Override public void addRace(Race race) { races.put(race.getName(), race); } @Override public void removeRace(Race race) { races.remove(race.getName()); } @Override public CharacterImpl createNewCharacter(OfflinePlayer player) { return new CharacterImpl(this, player); } public long getRaceKitClaim(OfflinePlayer player) { YamlConfiguration raceKitClaimSave = YamlConfiguration.loadConfiguration(new File("racekitclaims.yml")); return raceKitClaimSave.getLong(player.getName()); } public void setRaceKitClaim(OfflinePlayer player) { File raceKitClaimFile = new File("racekitclaims.yml"); YamlConfiguration raceKitClaimSave = YamlConfiguration.loadConfiguration(new File("racekitclaims.yml")); raceKitClaimSave.set(player.getName(), System.currentTimeMillis()); try { raceKitClaimSave.save(raceKitClaimFile); } catch (IOException exception) { exception.printStackTrace(); } } public boolean canClaimRaceKit(OfflinePlayer player) { YamlConfiguration raceKitClaimSave = YamlConfiguration.loadConfiguration(new File("racekitclaims.yml")); return raceKitClaimSave.get(player.getName()) == null || System.currentTimeMillis() - raceKitClaimSave.getLong(player.getName()) > 86400000L; } public boolean isThirstDisabled(OfflinePlayer player) { File thirstDisabledFile = new File(getDataFolder(), "thirst-disabled.yml"); YamlConfiguration thirstDisabledConfig = YamlConfiguration.loadConfiguration(thirstDisabledFile); return thirstDisabledConfig.getStringList("disabled").contains(player.getName()); } public void setThirstDisabled(OfflinePlayer player, boolean disabled) { File thirstDisabledFile = new File(getDataFolder(), "thirst-disabled.yml"); YamlConfiguration thirstDisabledConfig = YamlConfiguration.loadConfiguration(thirstDisabledFile); List<String> thirstDisabled = thirstDisabledConfig.getStringList("disabled"); if (disabled) thirstDisabled.add(player.getName()); else thirstDisabled.remove(player.getName()); thirstDisabledConfig.set("disabled", thirstDisabled); try { thirstDisabledConfig.save(thirstDisabledFile); } catch (IOException exception) { exception.printStackTrace(); } } private int checkBiome(Biome biome) { switch (biome) { case DESERT: case DESERT_HILLS: case DESERT_MOUNTAINS: return 8; case HELL: return 16; case JUNGLE: case JUNGLE_EDGE: case JUNGLE_EDGE_MOUNTAINS: case JUNGLE_HILLS: case JUNGLE_MOUNTAINS: return 6; case MESA: case MESA_BRYCE: case MESA_PLATEAU: case MESA_PLATEAU_FOREST: case MESA_PLATEAU_FOREST_MOUNTAINS: case MESA_PLATEAU_MOUNTAINS: return 8; case SAVANNA: case SAVANNA_MOUNTAINS: case SAVANNA_PLATEAU: case SAVANNA_PLATEAU_MOUNTAINS: return 6; default: return 4; } } private Biome convertBiomeFromString(String biome){ switch (biome){ default: return Biome.PLAINS; case "BEACH": return Biome.BEACH; case "BIRCH_FOREST": return Biome.BIRCH_FOREST; case "BIRCH_FOREST_HILLS": return Biome.BIRCH_FOREST_HILLS; case "BIRCH_FOREST_HILLS_MOUNTAINS": return Biome.BIRCH_FOREST_HILLS_MOUNTAINS; case "BIRCH_FOREST_MOUNTAINS": return Biome.BIRCH_FOREST_MOUNTAINS; case "COLD_BEACH": return Biome.COLD_BEACH; case "COLD_TAIGA": return Biome.COLD_TAIGA; case "COLD_TAIGA_HILLS": return Biome.COLD_TAIGA_HILLS; case "COLD_TAIGA_MOUNTAINS": return Biome.COLD_TAIGA_MOUNTAINS; case "DEEP_OCEAN": return Biome.DEEP_OCEAN; case "DESERT": return Biome.DESERT; case "DESERT_HILLS": return Biome.DESERT_HILLS; case "DESERT_MOUNTAINS": return Biome.DESERT_MOUNTAINS; case "EXTREME_HILLS": return Biome.EXTREME_HILLS; case "EXTREME_HILLS_MOUNTAINS": return Biome.EXTREME_HILLS_MOUNTAINS; case "EXTREME_HILLS_PLUS": return Biome.EXTREME_HILLS_PLUS; case "EXTREME_HILLS_PLUS_MOUNTAINS": return Biome.EXTREME_HILLS_PLUS_MOUNTAINS; case "FLOWER_FOREST": return Biome.FLOWER_FOREST; case "FOREST": return Biome.FOREST; case "FOREST_HILLS": return Biome.FOREST_HILLS; case "FROZEN_OCEAN": return Biome.FROZEN_OCEAN; case "FROZEN_RIVER": return Biome.FROZEN_RIVER; case "HELL": return Biome.HELL; case "ICE_MOUNTAINS": return Biome.ICE_MOUNTAINS; case "ICE_PLAINS": return Biome.ICE_PLAINS; case "ICE_PLAINS_SPIKES": return Biome.ICE_PLAINS_SPIKES; case "JUNGLE": return Biome.JUNGLE; case "JUNGLE_EDGE": return Biome.JUNGLE_EDGE; case "JUNGLE_EDGE_MOUNTAINS": return Biome.JUNGLE_EDGE_MOUNTAINS; case "JUNGLE_HILLS": return Biome.JUNGLE_HILLS; case "JUNGLE_MOUNTAINS": return Biome.JUNGLE_MOUNTAINS; case "MEGA_SPRUCE_TAIGA": return Biome.MEGA_SPRUCE_TAIGA; case "MEGA_SPRUCE_TAIGA_HILLS": return Biome.MEGA_SPRUCE_TAIGA_HILLS; case "MEGA_TAIGA": return Biome.MEGA_TAIGA; case "MEGA_TAIGA_HILLS": return Biome.MEGA_TAIGA_HILLS; case "MESA": return Biome.MESA; case "MESA_BRYCE": return Biome.MESA_BRYCE; case "MESA_PLATEAU": return Biome.MESA_PLATEAU; case "MESA_PLATEAU_FOREST": return Biome.MESA_PLATEAU_FOREST; case "MESA_PLATEAU_FOREST_MOUNTAINS": return Biome.MESA_PLATEAU_FOREST_MOUNTAINS; case "MESA_PLATEAU_MOUNTAINS": return Biome.MESA_PLATEAU_MOUNTAINS; case "MUSHROOM_ISLAND": return Biome.MUSHROOM_ISLAND; case "MUSHROOM_SHORE": return Biome.MUSHROOM_SHORE; case "OCEAN": return Biome.OCEAN; case "PLAINS": return Biome.PLAINS; case "RIVER": return Biome.RIVER; case "ROOFED_FOREST": return Biome.ROOFED_FOREST; case "ROOFED_FOREST_MOUNTAINS": return Biome.ROOFED_FOREST_MOUNTAINS; case "SAVANNA": return Biome.SAVANNA; case "SAVANNA_MOUNTAINS": return Biome.SAVANNA_MOUNTAINS; case "SAVANNA_PLATEAU": return Biome.SAVANNA_PLATEAU; case "SAVANNA_PLATEAU_MOUNTAINS": return Biome.SAVANNA_PLATEAU_MOUNTAINS; case "SKY": return Biome.SKY; case "SMALL_MOUNTAINS": return Biome.SMALL_MOUNTAINS; case "STONE_BEACH": return Biome.STONE_BEACH; case "SUNFLOWER_PLAINS": return Biome.SUNFLOWER_PLAINS; case "SWAMPLAND": return Biome.SWAMPLAND; case "SWAMPLAND_MOUNTAINS": return Biome.SWAMPLAND_MOUNTAINS; case "TAIGA": return Biome.TAIGA; case "TAIGA_HILLS": return Biome.TAIGA_HILLS; case "TAIGA_MOUNTAINS": return Biome.TAIGA_MOUNTAINS; } } }
package org.intermine.web; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.intermine.objectstore.query.ConstraintOp; /** * Action to handle button presses on the main tile * @author Mark Woodbridge */ public class MainAction extends Action { /** * Method called when user has finished updating a constraint * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception if the application business logic throws * an exception */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY); MainForm mf = (MainForm) form; PathNode node = (PathNode) query.getNodes().get(mf.getPath()); if (request.getParameter("attribute") != null) { ConstraintOp constraintOp = ConstraintOp. getOpForIndex(Integer.valueOf(mf.getAttributeOp())); Object constraintValue = mf.getParsedAttributeValue(); node.getConstraints().add(new Constraint(constraintOp, constraintValue)); } if (request.getParameter("bag") != null) { ConstraintOp constraintOp = ConstraintOp. getOpForIndex(Integer.valueOf(mf.getBagOp())); Object constraintValue = mf.getBagValue(); node.getConstraints().add(new Constraint(constraintOp, constraintValue)); } if (request.getParameter ("loop") != null) { ConstraintOp constraintOp = ConstraintOp. getOpForIndex(Integer.valueOf(mf.getLoopQueryOp())); Object constraintValue = mf.getLoopQueryValue(); node.getConstraints().add(new Constraint(constraintOp, constraintValue)); } if (request.getParameter("subclass") != null) { node.setType(mf.getSubclassValue()); session.setAttribute("path", mf.getSubclassValue()); } mf.reset(mapping, request); return mapping.findForward("query"); } }
package mod._sc; import java.io.PrintWriter; import lib.StatusException; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; import util.SOfficeFactory; import com.sun.star.beans.XPropertySet; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.sheet.XNamedRanges; import com.sun.star.sheet.XSpreadsheetDocument; import com.sun.star.table.CellAddress; import com.sun.star.table.CellRangeAddress; import com.sun.star.uno.AnyConverter; import com.sun.star.uno.Type; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; /** * Test for object which is represented by service * <code>com.sun.star.sheet.NamedRange</code>. <p> * Object implements the following interfaces : * <ul> * <li> <code>com::sun::star::container::XNamed</code></li> * <li> <code>com::sun::star::sheet::XNamedRange</code></li> * <li> <code>com::sun::star::sheet::XCellRangeReferrer</code></li> * </ul> * @see com.sun.star.sheet.NamedRange * @see com.sun.star.container.XNamed * @see com.sun.star.sheet.XNamedRange * @see com.sun.star.sheet.XCellRangeReferrer * @see ifc.container._XNamed * @see ifc.sheet._XNamedRange * @see ifc.sheet._XCellRangeReferrer */ public class ScNamedRangeObj extends TestCase { static XSpreadsheetDocument xSheetDoc = null; /** * Creates Spreadsheet document. */ protected void initialize( TestParameters tParam, PrintWriter log ) { SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)tParam.getMSF() ); try { log.println( "creating a Spreadsheet document" ); xSheetDoc = SOF.createCalcDoc(null); } catch ( com.sun.star.uno.Exception e ) { // Some exception occures.FAILED e.printStackTrace( log ); throw new StatusException( "Couldn't create document", e ); } } /** * Disposes Spreadsheet document. */ protected void cleanup( TestParameters tParam, PrintWriter log ) { log.println( " disposing xSheetDoc " ); XComponent oComp = (XComponent) UnoRuntime.queryInterface(XComponent.class, xSheetDoc) ; util.DesktopTools.closeDoc(oComp); } /** * Creating a Testenvironment for the interfaces to be tested. * Retrieves a collection of spreadsheets from a document * and takes one of them. Obtains the value of the property * <code>'NamedRanges'</code> that is the collection of named ranges. * Creates and adds new range to the collection. This new range is the instance of the * service <code>com.sun.star.sheet.NamedRange</code>. * Object relations created : * <ul> * <li> <code>'DATAAREA'</code> for * {@link ifc.sheet._XCellRangeReferrer} (the cell range address of the * created range) </li> * </ul> */ protected synchronized TestEnvironment createTestEnvironment(TestParameters Param, PrintWriter log) { XInterface oObj = null; // creation of testobject here // first we write what we are intend to do to log file log.println( "Creating a test environment" ); log.println("Getting test object ") ; // Getting named ranges. XPropertySet docProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xSheetDoc); Object ranges = null; try { ranges = docProps.getPropertyValue("NamedRanges"); } catch(com.sun.star.lang.WrappedTargetException e){ e.printStackTrace(log); throw new StatusException("Couldn't get NamedRanges", e); } catch(com.sun.star.beans.UnknownPropertyException e){ e.printStackTrace(log); throw new StatusException("Couldn't get NamedRanges", e); } XNamedRanges xNamedRanges = (XNamedRanges) UnoRuntime.queryInterface(XNamedRanges.class, ranges); CellRangeAddress DataArea = new CellRangeAddress((short)0, 0, 0, 1, 1); CellAddress base = new CellAddress(DataArea.Sheet, DataArea.StartColumn, DataArea.StartRow); if (xNamedRanges.hasByName("ANamedRange")) { xNamedRanges.removeByName("ANamedRange"); } xNamedRanges.addNewByName("ANamedRange", "A1:B2", base, 0); CellAddress listOutputPosition = new CellAddress((short)0, 1, 1); xNamedRanges.outputList(listOutputPosition); try { oObj = (XInterface) AnyConverter.toObject( new Type(XInterface.class),xNamedRanges.getByName("ANamedRange")); } catch(com.sun.star.lang.WrappedTargetException e){ e.printStackTrace(log); throw new StatusException("Couldn't get by name", e); } catch(com.sun.star.container.NoSuchElementException e){ e.printStackTrace(log); throw new StatusException("Couldn't get by name", e); } catch(com.sun.star.lang.IllegalArgumentException e){ e.printStackTrace(log); throw new StatusException("Couldn't get by name", e); } TestEnvironment tEnv = new TestEnvironment( oObj ); // Other parameters required for interface tests tEnv.addObjRelation("DATAAREA", DataArea); return tEnv; } }
package com.rtr.alchemy.service.resources; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.rtr.alchemy.dto.models.AllocationDto; import com.rtr.alchemy.dto.models.TreatmentDto; import com.rtr.alchemy.dto.requests.UpdateTreatmentRequest; import org.junit.Test; import javax.annotation.Nullable; import javax.ws.rs.core.Response.Status; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class TreatmentsResourceTest extends ResourceTest { private static final String TREATMENTS_ENDPOINT = "/experiments/{experimentName}/treatments"; private static final String TREATMENT_ENDPOINT = "/experiments/{experimentName}/treatments/{treatment}"; private static final String ALLOCATIONS_ENDPOINT = "/experiments/{experimentName}/allocations"; @Test public void testGetTreatments() { get(TREATMENTS_ENDPOINT, EXPERIMENT_BAD) .assertStatus(Status.NOT_FOUND); final Iterable<TreatmentDto> expected = MAPPER.toDto(experiment(EXPERIMENT_1).getTreatments(), TreatmentDto.class); final Iterable<TreatmentDto> actual = get(TREATMENTS_ENDPOINT, EXPERIMENT_1) .assertStatus(Status.OK) .result(iterable(TreatmentDto.class)); assertEquals(expected, actual); } @Test public void testGetTreatment() { get(TREATMENT_ENDPOINT, EXPERIMENT_BAD, EXP_1_TREATMENT_1) .assertStatus(Status.NOT_FOUND); get(TREATMENT_ENDPOINT, EXPERIMENT_1, TREATMENT_BAD) .assertStatus(Status.NOT_FOUND); final TreatmentDto expected = MAPPER.toDto(experiment(EXPERIMENT_1).getTreatment(EXP_1_TREATMENT_1), TreatmentDto.class); final TreatmentDto actual = get(TREATMENT_ENDPOINT, EXPERIMENT_1, EXP_1_TREATMENT_1) .assertStatus(Status.OK) .result(TreatmentDto.class); assertEquals(expected, actual); } @Test public void testAddTreatment() { final TreatmentDto expected = new TreatmentDto("new_treatment", "this is a new treatment"); put(TREATMENTS_ENDPOINT, EXPERIMENT_BAD) .entity(expected) .assertStatus(Status.NOT_FOUND); put(TREATMENTS_ENDPOINT, EXPERIMENT_1) .entity(expected) .assertStatus(Status.CREATED); final TreatmentDto actual = MAPPER.toDto(experiment(EXPERIMENT_1).getTreatment(expected.getName()), TreatmentDto.class); assertEquals(expected, actual); } @Test public void testRemoveTreamtment() { delete(TREATMENT_ENDPOINT, EXPERIMENT_BAD, EXP_1_TREATMENT_1) .assertStatus(Status.NOT_FOUND); delete(TREATMENT_ENDPOINT, EXPERIMENT_1, TREATMENT_BAD) .assertStatus(Status.NOT_FOUND); assertNotNull(experiment(EXPERIMENT_1).getTreatment(EXP_1_TREATMENT_1)); delete(TREATMENT_ENDPOINT, EXPERIMENT_1, EXP_1_TREATMENT_1) .assertStatus(Status.NO_CONTENT); assertNull(experiment(EXPERIMENT_1).getTreatment(EXP_1_TREATMENT_1)); } @Test public void testUpdateTreatment() { final UpdateTreatmentRequest request = new UpdateTreatmentRequest(Optional.of("new description")); post(TREATMENT_ENDPOINT, EXPERIMENT_BAD, EXP_1_TREATMENT_1) .entity(request) .assertStatus(Status.NOT_FOUND); post(TREATMENT_ENDPOINT, EXPERIMENT_1, TREATMENT_BAD) .entity(request) .assertStatus(Status.NOT_FOUND); post(TREATMENT_ENDPOINT, EXPERIMENT_1, EXP_1_TREATMENT_1) .entity(request) .assertStatus(Status.NO_CONTENT); final TreatmentDto treatment = get(TREATMENT_ENDPOINT, EXPERIMENT_1, EXP_1_TREATMENT_1) .assertStatus(Status.OK) .result(TreatmentDto.class); assertEquals(request.getDescription().orNull(), treatment.getDescription()); final Iterable<AllocationDto> allocations = get(ALLOCATIONS_ENDPOINT, EXPERIMENT_1) .assertStatus(Status.OK) .result(iterable(AllocationDto.class)); // Make sure we didn't lose our allocations for this treatment assertNotNull( Iterables.find(allocations, new Predicate<AllocationDto>() { @Override public boolean apply(@Nullable AllocationDto input) { return input != null && input.getTreatment().equals(EXP_1_TREATMENT_1); } }) ); } @Test public void testClearTreatments() { delete(TREATMENTS_ENDPOINT, EXPERIMENT_BAD) .assertStatus(Status.NOT_FOUND); assertNotNull(experiment(EXPERIMENT_1).getTreatment(EXP_1_TREATMENT_1)); assertNotNull(experiment(EXPERIMENT_1).getTreatment(EXP_1_TREATMENT_2)); assertNotNull(experiment(EXPERIMENT_1).getTreatment(EXP_1_TREATMENT_3)); delete(TREATMENTS_ENDPOINT, EXPERIMENT_1) .assertStatus(Status.NO_CONTENT); assertNull(experiment(EXPERIMENT_1).getTreatment(EXP_1_TREATMENT_1)); assertNull(experiment(EXPERIMENT_1).getTreatment(EXP_1_TREATMENT_2)); assertNull(experiment(EXPERIMENT_1).getTreatment(EXP_1_TREATMENT_3)); } }
package com.nestedworld.nestedworld.network.http.implementation; import com.nestedworld.nestedworld.BuildConfig; import com.nestedworld.nestedworld.network.NetworkConstant; public final class HttpEndPoint { private final static String API_VERSION = "v1/"; private final static String DEV_URL = "http://nestedworld-dev.kokakiwi.net/"; private final static String PROD_URL = "dev.nestedworld.com"; private final static String BASE_URL = (BuildConfig.ENVIRONMENT == NetworkConstant.Environement.DEV) ? DEV_URL : (BuildConfig.ENVIRONMENT == NetworkConstant.Environement.PROD) ? PROD_URL : DEV_URL; public final static String BASE_END_POINT = BASE_URL + API_VERSION; //Monster related endpoint private final static String MONSTERS_PREFIX = "monsters"; public final static String MONSTERS_LIST = MONSTERS_PREFIX; public final static String MONSTER_ATTACK = MONSTERS_PREFIX + "/{monsterId}/attacks"; //Place related endpoint private final static String PLACES_PREFIX = "places"; public final static String PLACES_LIST = PLACES_PREFIX; public final static String REGIONS_LIST = PLACES_PREFIX + "/regions"; //User related endpoint private final static String USER_PREFIX = "users/"; public final static String USER_INFO = USER_PREFIX; public final static String USER_FRIENDS = USER_PREFIX + "friends/"; public final static String USER_MONSTERS = USER_PREFIX + "monsters"; //Auth related endpoint private final static String AUTH_PREFIX = USER_INFO + "auth/"; public final static String USER_SIGN_IN = AUTH_PREFIX + "login/simple"; public final static String USER_REGISTER = AUTH_PREFIX + "register"; public final static String USER_PASSWORD = AUTH_PREFIX + "resetpassword"; public final static String USER_LOGOUT = AUTH_PREFIX + "logout"; //Attack related endpoint private final static String ATTACK_PREFIX = "attacks/"; public final static String ATTACK_LIST = ATTACK_PREFIX; private HttpEndPoint() { //Empty constructor for avoiding this class to be construct } }
package uk.org.sappho.code.change.management.app; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Module; import uk.org.sappho.configuration.Configuration; import uk.org.sappho.configuration.ConfigurationException; @RunWith(MockitoJUnitRunner.class) public class CodeChangeManagementAppTest { @Mock private Configuration config; private List<String> actions; private List<String> returnedActions; @Before public void setupFakeWiringConfiguration() throws ConfigurationException { String engineModuleName = "modules.engine"; List<String> returnedModuleNames = new ArrayList<String>(); returnedModuleNames.add(engineModuleName); List<String> moduleNames = config.getPropertyList("module"); when(moduleNames).thenReturn(returnedModuleNames); Module engineModule = config.getGuiceModule(engineModuleName); when(engineModule).thenReturn(new FakeEngineModule()); returnedActions = new ArrayList<String>(); actions = config.getPropertyList("app.run.action"); } @Test public void shouldRunSomeActions() throws Throwable { returnedActions.add("scan"); returnedActions.add("validate"); returnedActions.add("save"); returnedActions.add("load"); returnedActions.add("refresh"); returnedActions.add("process"); when(actions).thenReturn(returnedActions); new CodeChangeManagementApp().run(config); } @Test(expected = ConfigurationException.class) public void shouldFailDueToInvalidAction() throws Throwable { returnedActions.add("snafu"); when(actions).thenReturn(returnedActions); new CodeChangeManagementApp().run(config); } }
package im.actor.model.android.providers; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.media.SoundPool; import android.support.v4.app.NotificationCompat; import android.support.v4.graphics.drawable.RoundedBitmapDrawable; import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory; import android.text.SpannableStringBuilder; import android.text.style.StyleSpan; import java.util.List; import im.actor.messenger.R; import im.actor.messenger.app.Intents; import im.actor.messenger.app.activity.MainActivity; import im.actor.messenger.app.util.Screen; import im.actor.messenger.app.view.AvatarPlaceholderDrawable; import im.actor.model.Messenger; import im.actor.model.NotificationProvider; import im.actor.model.entity.Avatar; import im.actor.model.entity.Notification; import im.actor.model.entity.Peer; import im.actor.model.entity.PeerType; import im.actor.model.files.FileSystemReference; import im.actor.model.viewmodel.FileVMCallback; import static im.actor.messenger.app.Core.groups; import static im.actor.messenger.app.Core.messenger; import static im.actor.messenger.app.Core.users; public class AndroidNotifications implements NotificationProvider { private static final int NOTIFICATION_ID = 1; private SoundPool soundPool; private int soundId; private Peer visiblePeer; private Context context; public AndroidNotifications(Context context) { this.context = context; soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); soundId = soundPool.load(context, R.raw.notification, 1); } @Override public void onMessageArriveInApp(Messenger messenger) { soundPool.play(soundId, 1.0f, 1.0f, 0, 0, 1.0f); } @Override public void onNotification(Messenger messenger, List<Notification> topNotifications, int messagesCount, int conversationsCount, boolean silentUpdate, boolean isInApp) { // Android ignores isInApp argument because it is ok to send normal notification // instead in-app final NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setAutoCancel(true); builder.setSmallIcon(R.drawable.ic_app_notify); builder.setPriority(NotificationCompat.PRIORITY_HIGH); builder.setCategory(NotificationCompat.CATEGORY_MESSAGE); int defaults = NotificationCompat.DEFAULT_LIGHTS; if (messenger().isNotificationSoundEnabled()) { defaults |= NotificationCompat.DEFAULT_SOUND; } if (messenger().isNotificationVibrationEnabled()) { defaults |= NotificationCompat.DEFAULT_VIBRATE; } if (silentUpdate) { defaults = 0; } builder.setDefaults(defaults); // Wearable // builder.extend(new NotificationCompat.WearableExtender() // .setBackground(((BitmapDrawable) AppContext.getContext().getResources().getDrawable(R.drawable.wear_bg)).getBitmap()) // .setHintHideIcon(true)); final Notification topNotification = topNotifications.get(0); if (!silentUpdate) { builder.setTicker(getNotificationTextFull(topNotification)); } android.app.Notification result; if (messagesCount == 1) { // Single message notification final String sender = getNotificationSender(topNotification); final CharSequence text = getNotificationText(topNotification); visiblePeer = topNotification.getPeer(); Avatar avatar =null; int id = 0; switch (visiblePeer.getPeerType()){ case PRIVATE: avatar = users().get(visiblePeer.getPeerId()).getAvatar().get(); id = users().get(visiblePeer.getPeerId()).getId(); break; case GROUP: avatar = groups().get(visiblePeer.getPeerId()).getAvatar().get(); id = groups().get(visiblePeer.getPeerId()).getId(); break; } Drawable avatarDrawable = new AvatarPlaceholderDrawable(sender, id, 12, context, false); result = buildSingleMessageNotification(avatarDrawable, builder, sender, text, topNotification); NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(NOTIFICATION_ID, result); if(avatar!=null)messenger().bindFile(avatar.getSmallImage().getFileReference(), true, new FileVMCallback() { @Override public void onNotDownloaded() { } @Override public void onDownloading(float progress) { } @Override public void onDownloaded(FileSystemReference reference) { RoundedBitmapDrawable d = RoundedBitmapDrawableFactory.create(context.getResources(), reference.getDescriptor()); d.setCornerRadius(d.getIntrinsicHeight()/2); d.setAntiAlias(true); android.app.Notification result = buildSingleMessageNotification(d, builder, sender, text, topNotification); NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(NOTIFICATION_ID, result); } }); } else if (conversationsCount == 1) { // Single conversation notification String sender = getNotificationSender(topNotification); builder.setContentTitle(sender); builder.setContentText(messagesCount + " messages"); visiblePeer = topNotification.getPeer(); builder.setContentIntent(PendingIntent.getActivity(context, 0, Intents.openDialog(topNotification.getPeer(), false, context), PendingIntent.FLAG_UPDATE_CURRENT)); final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); for (Notification n : topNotifications) { if (topNotification.getPeer().getPeerType() == PeerType.GROUP) { inboxStyle.addLine(getNotificationTextFull(n)); } else { inboxStyle.addLine(getNotificationText(n)); } } inboxStyle.setSummaryText(messagesCount + " messages"); Avatar avatar =null; int id = 0; switch (visiblePeer.getPeerType()){ case PRIVATE: avatar = users().get(visiblePeer.getPeerId()).getAvatar().get(); id = users().get(visiblePeer.getPeerId()).getId(); break; case GROUP: avatar = groups().get(visiblePeer.getPeerId()).getAvatar().get(); id = groups().get(visiblePeer.getPeerId()).getId(); break; } Drawable avatarDrawable = new AvatarPlaceholderDrawable(sender, id, 12, context, false); result = buildSingleConversationNotification(builder, inboxStyle, avatarDrawable); NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(NOTIFICATION_ID, result); if(avatar!=null)messenger().bindFile(avatar.getSmallImage().getFileReference(), true, new FileVMCallback() { @Override public void onNotDownloaded() { } @Override public void onDownloading(float progress) { } @Override public void onDownloaded(FileSystemReference reference) { RoundedBitmapDrawable d = RoundedBitmapDrawableFactory.create(context.getResources(), reference.getDescriptor()); d.setCornerRadius(d.getIntrinsicHeight() / 2); d.setAntiAlias(true); android.app.Notification result = buildSingleConversationNotification(builder, inboxStyle, d); NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(NOTIFICATION_ID, result); } }); } else { // Multiple conversations notification builder.setContentTitle(context.getString(R.string.app_name)); builder.setContentText(messagesCount + " messages in " + conversationsCount + " chats"); visiblePeer = null; builder.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT)); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); for (Notification n : topNotifications) { inboxStyle.addLine(getNotificationTextFull(n)); } inboxStyle.setSummaryText(messagesCount + " messages in " + conversationsCount + " chats"); result = builder .setStyle(inboxStyle) .build(); NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(NOTIFICATION_ID, result); } } private android.app.Notification buildSingleConversationNotification(NotificationCompat.Builder builder, NotificationCompat.InboxStyle inboxStyle, Drawable avatarDrawable) { return builder .setLargeIcon(drawableToBitmap(avatarDrawable)) .setStyle(inboxStyle) .build(); } private android.app.Notification buildSingleMessageNotification(Drawable d, NotificationCompat.Builder builder, String sender, CharSequence text, Notification topNotification) { return builder .setContentTitle(sender) .setContentText(text) .setLargeIcon(drawableToBitmap(d)) .setContentIntent(PendingIntent.getActivity(context, 0, Intents.openDialog(topNotification.getPeer(), false, context), PendingIntent.FLAG_UPDATE_CURRENT)) .setStyle(new NotificationCompat.BigTextStyle().bigText(text)) .build(); } public static Bitmap drawableToBitmap(Drawable drawable) { int height = drawable.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(height > 0 ? height : Screen.dp(42), height > 0 ? height : Screen.dp(42), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } @Override public void hideAllNotifications() { NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); manager.cancel(NOTIFICATION_ID); } private CharSequence getNotificationTextFull(Notification notification) { SpannableStringBuilder res = new SpannableStringBuilder(); if (!messenger().getFormatter().isLargeDialogMessage(notification.getContentDescription().getContentType())) { res.append(getNotificationSender(notification)); res.append(": "); res.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, res.length(), 0); } res.append(getNotificationText(notification)); return res; } private String getNotificationSender(Notification pendingNotification) { String sender; if (pendingNotification.getPeer().getPeerType() == PeerType.GROUP) { sender = users().get(pendingNotification.getSender()).getName().get(); sender += "@"; sender += groups().get(pendingNotification.getPeer().getPeerId()).getName().get(); } else { sender = users().get(pendingNotification.getSender()).getName().get(); } return sender; } private CharSequence getNotificationText(Notification pendingNotification) { return messenger().getFormatter().formatContentDialogText(pendingNotification.getSender(), pendingNotification.getContentDescription().getContentType(), pendingNotification.getContentDescription().getText(), pendingNotification.getContentDescription().getRelatedUser()); } }
package org.ovirt.engine.core.bll; import org.ovirt.engine.core.common.queries.GetVmPoolByIdParameters; public class GetVmPoolByIdQuery<P extends GetVmPoolByIdParameters> extends QueriesCommandBase<P> { public GetVmPoolByIdQuery(P parameters) { super(parameters); } @Override protected void executeQueryCommand() { getQueryReturnValue().setReturnValue( getDbFacade().getVmPoolDAO() .get(getParameters().getPoolId(), getUserID(), getParameters().isFiltered())); } }
package org.intermine.bio.dataconversion; import java.io.File; import java.io.IOException; import java.io.Reader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStoreException; import org.intermine.xml.full.Item; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Loads disease name and identifier from orphanet. the annotations are set in the OMIM source. * * @author Julie Sullivan */ public class OrphanetConverter extends BioFileConverter { private static final String DATASET_TITLE = "Orphanet data set"; private static final String DATA_SOURCE_NAME = "Orphanet"; private static final String PREFIX = "ORPHANET:"; /** * Constructor * @param writer the ItemWriter used to handle the resultant items * @param model the Model */ public OrphanetConverter(ItemWriter writer, Model model) { super(writer, model, DATA_SOURCE_NAME, DATASET_TITLE); } /** * * * {@inheritDoc} */ public void process(Reader reader) throws Exception { File currentFile = getCurrentFile(); if ("en_product1.xml".equals(currentFile.getName())) { processXML(currentFile); } else { throw new RuntimeException("Don't know how to process file: " + currentFile.getName()); } } private void processXML(File file) throws SAXException, IOException, ParserConfigurationException, ObjectStoreException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(file); doc.getDocumentElement().normalize(); NodeList entryList = doc.getElementsByTagName("Disorder"); for (int i = 0; i < entryList.getLength(); i++) { Element entry = (Element) entryList.item(i); String orphaNumber = entry.getElementsByTagName("OrphaNumber").item(0).getTextContent(); String diseaseName = entry.getElementsByTagName("Name").item(0).getTextContent(); Item item = createItem("Disease"); item.setAttribute("identifier", PREFIX + orphaNumber); item.setAttribute("name", diseaseName); store(item); } } }
package org.biojava.nbio.structure.io.mmtf; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.TestStructureCrossReferences; import org.biojava.nbio.structure.io.PDBFileParser; import org.biojava.nbio.structure.io.mmcif.AllChemCompProvider; import org.biojava.nbio.structure.io.mmcif.ChemCompGroupFactory; import org.biojava.nbio.structure.io.mmcif.ChemCompProvider; import org.junit.Test; import org.rcsb.mmtf.dataholders.MmtfStructure; import org.rcsb.mmtf.decoder.ReaderUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.zip.GZIPInputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class TestMmtfPerformance { private static final Logger logger = LoggerFactory.getLogger(TestMmtfPerformance.class); private static final int NUMBER_OF_REPEATS = 10; // Returns the contents of the file in a byte array. public static byte[] getBytesFromFile(File file) throws IOException { // Get the size of the file long length = file.length(); // You cannot create an array using a long type. // It needs to be an int type. // Before converting to an int type, check // to ensure that file is not larger than Integer.MAX_VALUE. if (length > Integer.MAX_VALUE) { // File is too large throw new IOException("File is too large!"); } // Create the byte array to hold the data byte[] bytes = new byte[(int)length]; // Read in the bytes int offset = 0; int numRead = 0; InputStream is = new FileInputStream(file); try { while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { offset += numRead; } } finally { is.close(); } // Ensure all the bytes have been read in if (offset < bytes.length) { throw new IOException("Could not completely read file "+file.getName()); } return bytes; } static String convertStreamToString(java.io.InputStream is) { java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } public byte[] getByteArrayFromInputStream(InputStream is) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toByteArray(); } @Test public void test3HBX() throws Exception{ String pdbId = "3HBX"; URL url = new URL("https://files.rcsb.org/download/"+pdbId+".pdb.gz"); String pdbFile = convertStreamToString(new GZIPInputStream(url.openStream())); long pdbStart = System.currentTimeMillis(); PDBFileParser parser = new PDBFileParser(); for ( int i =0 ; i< NUMBER_OF_REPEATS ; i++) { Structure pdbStructure = parser.parsePDBFile(new ByteArrayInputStream(pdbFile.getBytes())); } long pdbEnd = System.currentTimeMillis(); URL mmtfURL = new URL("https://mmtf.rcsb.org/v1.0/full/" + pdbId + ".mmtf.gz"); byte[] mmtfdata = getByteArrayFromInputStream(new GZIPInputStream((mmtfURL.openStream()))); long mmtfStart = System.currentTimeMillis(); for ( int i =0 ; i< NUMBER_OF_REPEATS ; i++) { Structure mmtfStructure = MmtfActions.readFromInputStream(new ByteArrayInputStream(mmtfdata)); } long mmtfEnd = System.currentTimeMillis(); long timeMMTF = (mmtfEnd-mmtfStart); long timePDB = (pdbEnd-pdbStart); logger.warn("average time to parse mmtf: " + (timeMMTF/NUMBER_OF_REPEATS)); logger.warn("average time to parse PDB : " + (timePDB/NUMBER_OF_REPEATS)); assertTrue( "It should not be the case, but it is faster to parse a PDB file ("+timePDB+" ms.) than MMTF ("+( timeMMTF)+" ms.)!",( timePDB) > ( timeMMTF)); } }
package org.jnect.demo.incquery; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.viatra2.emf.incquery.runtime.exception.IncQueryException; import org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete.misc.DeltaMonitor; import org.jnect.core.KinectManager; import bodymodel.jump.JumpMatcher; import bodymodel.righthandabovehead.RightHandAboveHeadMatch; import bodymodel.righthandabovehead.RightHandAboveHeadMatcher; /** * * @author istvanrath * */ public class StartIncQueryDemoHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { if (KinectManager.INSTANCE.isSkeletonTrackingStarted()) { // move head to 0,0 KinectManager.INSTANCE.getSkeletonModel().getHead().setX(0); KinectManager.INSTANCE.getSkeletonModel().getHead().setY(0); try { RightHandAboveHeadMatcher matcher = RightHandAboveHeadMatcher.factory() .getMatcher(KinectManager.INSTANCE.getSkeletonModel()); final DeltaMonitor<RightHandAboveHeadMatch> dm = matcher.newDeltaMonitor(true); matcher.addCallbackAfterUpdates(new Runnable() { @Override public void run() { for (RightHandAboveHeadMatch m : dm.matchFoundEvents) { System.out.println("New match found:" + m.toString()); // colorize head and right hand m.getH().setColor_r(255); m.getRH().setColor_r(255); } for (RightHandAboveHeadMatch m : dm.matchLostEvents) { System.out.println("Lost match found:" + m.toString()); // decolorize m.getH().setColor_r(0); m.getRH().setColor_r(0); } dm.clear(); } }); } catch (IncQueryException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { System.out.println("Start skeleton simulator first!"); } return null; } }
package VASSAL.tools.image.tilecache; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.concurrent.ExecutorService; import VASSAL.tools.lang.Callback; /** * Slices an image into tiles. * * @since 3.2.0 * @author Joel Uckelman */ public interface TileSlicer { /** * Slices an image into tiles. * * @param src the source image * @param iname the basename for the tiles * @param tpath the path for the tiles * @param tw the tile width * @param th the tile height * @param exec the executor in which to run tasks * @param progress a callback for indicating progress */ public void slice( BufferedImage src, String iname, String tpath, int tw, int th, ExecutorService exec, Callback<Void> progress ) throws IOException; }
package machine_specific_tests; import org.junit.Before; import com.spun.util.SystemUtils; public class MachineSpecificTest { private static boolean DISPLAYED = false; @Before public void beforeMethod() { if (!MachineSpecific.isMachineConfiguredForTesting()) { displayMessage(); org.junit.Assume.assumeTrue(false); } } private void displayMessage() { if (!DISPLAYED) { DISPLAYED = true; String message = String.format( "This machine isn't configured to run machine_specific_tests.\n" + "To run these either\n" + " 1) Set machine_specific_tests.MachineSpecific.FORCE_RUN=true\n" + " 2) Add \"%s\" to machine_specific_tests.MachineSpecific.MACHINES", SystemUtils.getComputerName()); System.out.println(message); } } }