answer
stringlengths
17
10.2M
package mat.server.simplexml.hqmf; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import mat.model.clause.MeasureExport; import mat.server.util.XmlProcessor; import mat.shared.MatConstants; import mat.shared.UUIDUtilClient; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Comment; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; // TODO: Auto-generated Javadoc /** * The Class HQMFClauseLogicGenerator. */ public class HQMFClauseLogicGenerator implements Generator { /** The Constant GROUPER_CRITERIA. */ private static final String GROUPER_CRITERIA = "grouperCriteria"; /** The Constant CONJUNCTION_CODE. */ private static final String CONJUNCTION_CODE = "conjunctionCode"; /** The Constant LOCAL_VARIABLE_NAME. */ private static final String LOCAL_VARIABLE_NAME = "localVariableName"; /** The Constant CRITERIA_REFERENCE. */ private static final String CRITERIA_REFERENCE = "criteriaReference"; /** The Constant ROLE. */ private static final String ROLE = "role"; /** The Constant PARTICIPATION. */ private static final String PARTICIPATION = "participation"; /** The Constant EXCERPT. */ private static final String EXCERPT = "excerpt"; /** The Constant SEQUENCE_NUMBER. */ private static final String SEQUENCE_NUMBER = "sequenceNumber"; /** The Constant GROUPER. */ private static final String GROUPER = "grouper"; /** The Constant ENTRY. */ private static final String ENTRY = "entry"; /** The Constant DATA_CRITERIA_SECTION. */ private static final String DATA_CRITERIA_SECTION = "dataCriteriaSection"; /** The sub tree node map. */ Map<String, Node> subTreeNodeMap = new HashMap<String,Node>(); /** The measure export. */ MeasureExport measureExport; /** The Constant logger. */ private static final Log logger = LogFactory .getLog(HQMFClauseLogicGenerator.class); /** * MAP of Functional Ops NON Subset Type. */ private static final Map<String, String> FUNCTIONAL_OPS_NON_SUBSET = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); /** * MAP of Functional Ops Subset Type. */ private static final Map<String, String> FUNCTIONAL_OPS_SUBSET = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); static { FUNCTIONAL_OPS_NON_SUBSET.put(MatConstants.FIRST, "1"); FUNCTIONAL_OPS_NON_SUBSET.put(MatConstants.SECOND, "2"); FUNCTIONAL_OPS_NON_SUBSET.put(MatConstants.THIRD, "3"); FUNCTIONAL_OPS_NON_SUBSET.put(MatConstants.FOURTH, "4"); FUNCTIONAL_OPS_NON_SUBSET.put(MatConstants.FIFTH, "5"); FUNCTIONAL_OPS_SUBSET.put(MatConstants.MOST_RECENT, "QDM_LAST"); FUNCTIONAL_OPS_SUBSET.put(MatConstants.COUNT, "QDM_SUM"); FUNCTIONAL_OPS_SUBSET.put(MatConstants.MIN, "QDM_MIN"); FUNCTIONAL_OPS_SUBSET.put(MatConstants.MAX, "QDM_MAX"); FUNCTIONAL_OPS_SUBSET.put(MatConstants.SUM, "QDM_SUM"); FUNCTIONAL_OPS_SUBSET.put(MatConstants.MEDIAN, "QDM_MEDIAN"); FUNCTIONAL_OPS_SUBSET.put(MatConstants.AVG, "QDM_AVERAGE"); } /** The Constant populations. */ private static final List<String> POPULATION_NAME_LIST = new ArrayList<String>(); static{ POPULATION_NAME_LIST.add("initialPopulation"); POPULATION_NAME_LIST.add("denominator"); POPULATION_NAME_LIST.add("denominatorExclusions"); POPULATION_NAME_LIST.add("denominatorExceptions"); POPULATION_NAME_LIST.add("numerator"); POPULATION_NAME_LIST.add("numeratorExclusions"); POPULATION_NAME_LIST.add("measurePopulation"); POPULATION_NAME_LIST.add("measurePopulationExclusions"); POPULATION_NAME_LIST.add("stratum"); } /** The sub tree node in mo map. */ Map<String, Node> subTreeNodeInMOMap = new HashMap<String,Node>(); /** The sub tree node in pop map. */ Map<String, Node> subTreeNodeInPOPMap = new HashMap<String,Node>(); /** The sub tree node in RA map. */ Map<String, Node> subTreeNodeInRAMap = new HashMap<String,Node>(); /** The Constant FUNCTIONAL_OP_RULES_IN_POP. */ private static final Map<String, List<String>> FUNCTIONAL_OP_RULES_IN_POP = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER); /** The Constant FUNCTIONAL_OP_RULES_IN_MO. */ private static final Map<String, List<String>> FUNCTIONAL_OP_RULES_IN_MO = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER); static { FUNCTIONAL_OP_RULES_IN_POP.put("MEDIAN", getFunctionalOpFirstChild("MEDIAN")); FUNCTIONAL_OP_RULES_IN_POP.put("AVG", getFunctionalOpFirstChild("AVG")); FUNCTIONAL_OP_RULES_IN_POP.put("MAX", getFunctionalOpFirstChild("MAX")); FUNCTIONAL_OP_RULES_IN_POP.put("MIN", getFunctionalOpFirstChild("MIN")); FUNCTIONAL_OP_RULES_IN_POP.put("SUM", getFunctionalOpFirstChild("SUM")); FUNCTIONAL_OP_RULES_IN_POP.put("COUNT", getFunctionalOpFirstChild("COUNT")); FUNCTIONAL_OP_RULES_IN_POP.put("FIRST", getFunctionalOpFirstChild("FIRST")); FUNCTIONAL_OP_RULES_IN_POP.put("SECOND", getFunctionalOpFirstChild("SECOND")); FUNCTIONAL_OP_RULES_IN_POP.put("THIRD", getFunctionalOpFirstChild("THIRD")); FUNCTIONAL_OP_RULES_IN_POP.put("FOURTH", getFunctionalOpFirstChild("FOURTH")); FUNCTIONAL_OP_RULES_IN_POP.put("FIFTH", getFunctionalOpFirstChild("FIFTH")); FUNCTIONAL_OP_RULES_IN_POP.put("MOST RECENT", getFunctionalOpFirstChild("MOST RECENT")); FUNCTIONAL_OP_RULES_IN_POP.put("AGE AT", getFunctionalOpFirstChild("AGE AT")); /* Rules for Functions in Measure Observations*/ FUNCTIONAL_OP_RULES_IN_MO.put("MEDIAN", getFunctionalOpFirstChildInMO("MEDIAN")); FUNCTIONAL_OP_RULES_IN_MO.put("AVERAGE", getFunctionalOpFirstChildInMO("AVERAGE")); FUNCTIONAL_OP_RULES_IN_MO.put("MIN", getFunctionalOpFirstChildInMO("MIN")); FUNCTIONAL_OP_RULES_IN_MO.put("SUM", getFunctionalOpFirstChildInMO("SUM")); FUNCTIONAL_OP_RULES_IN_MO.put("COUNT", getFunctionalOpFirstChildInMO("COUNT")); FUNCTIONAL_OP_RULES_IN_MO.put("DATETIMEDIFF", getFunctionalOpFirstChildInMO("DATETIMEDIFF")); } /* (non-Javadoc) * @see mat.server.simplexml.hqmf.Generator#generate(mat.model.clause.MeasureExport) */ @Override public String generate(MeasureExport me) throws Exception { measureExport = me; //creating Map for Populations and Measure Observations. createUsedSubTreeRefMap(); generateSubTreeXML(); return null; } /** * Generate sub tree xml. * * @throws XPathExpressionException the x path expression exception */ private void generateSubTreeXML() throws XPathExpressionException { String xpath = "/measure/subTreeLookUp/subTree[not(@instance)]"; NodeList subTreeNodeList = measureExport.getSimpleXMLProcessor().findNodeList(measureExport.getSimpleXMLProcessor().getOriginalDoc(), xpath); for(int i=0;i<subTreeNodeList.getLength();i++){ Node subTreeNode = subTreeNodeList.item(i); String clauseName = subTreeNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue(); String uuid = subTreeNode.getAttributes().getNamedItem(UUID).getNodeValue(); if((subTreeNodeInPOPMap.containsKey(uuid)&&subTreeNodeInMOMap.containsKey(uuid)) || subTreeNodeInPOPMap.containsKey(uuid) || subTreeNodeInRAMap.containsKey(uuid)){ generateSubTreeXML(subTreeNode, false); } } String xpathOccurrence = "/measure/subTreeLookUp/subTree[(@instance)]"; NodeList occurrenceSubTreeNodeList = measureExport.getSimpleXMLProcessor().findNodeList(measureExport.getSimpleXMLProcessor().getOriginalDoc(), xpathOccurrence); for(int i=0;i<occurrenceSubTreeNodeList.getLength();i++){ Node subTreeNode = occurrenceSubTreeNodeList.item(i); generateOccHQMF(subTreeNode); } } /** * Generate sub tree xml. * @param subTreeNode the sub tree node * @throws XPathExpressionException the x path expression exception */ protected Node generateSubTreeXML( Node subTreeNode, boolean msrObsDateTimeDiffSubTree) throws XPathExpressionException { /** * If this is an empty or NULL clause, return right now. */ if((subTreeNode == null) || !subTreeNode.hasChildNodes()){ return null; } /** * If this is a Occurrence clause then we need to find the base clause and generate HQMF for the base clause. * Then we need to generate Occurrence HQMF for the occurrence clause. */ if (subTreeNode.getAttributes().getNamedItem(INSTANCE_OF) != null) { String baseClauseUUID = subTreeNode.getAttributes().getNamedItem(INSTANCE_OF).getNodeValue(); String xpath = "/measure/subTreeLookUp/subTree[@uuid = '"+baseClauseUUID+"']"; Node baseSubTreeNode = measureExport.getSimpleXMLProcessor().findNode(measureExport.getSimpleXMLProcessor().getOriginalDoc(), xpath); generateSubTreeXML(baseSubTreeNode, false); generateOccHQMF(subTreeNode); } String subTreeUUID = subTreeNode.getAttributes().getNamedItem(UUID).getNodeValue(); String clauseName = subTreeNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue(); Boolean isRAV = isRiskAdjustmentVariable(subTreeUUID, clauseName); /** * Check the 'subTreeNodeMap' to make sure the clause isnt already generated. */ if(subTreeNodeMap.containsKey(subTreeUUID) && !msrObsDateTimeDiffSubTree){ logger.info("HQMF for Clause "+clauseName + " is already generated. Skipping."); return null; } //get the first child of the subTreeNode Node firstChild = subTreeNode.getFirstChild(); String firstChildName = firstChild.getNodeName(); logger.info("Generating HQMF for clause:'"+clauseName+"' with first child named:'"+firstChildName+"'."); XmlProcessor hqmfXmlProcessor = measureExport.getHQMFXmlProcessor(); Element dataCriteriaSectionElem = (Element) hqmfXmlProcessor.getOriginalDoc().getElementsByTagName(DATA_CRITERIA_SECTION).item(0); //generate comment //Comment comment = hqmfXmlProcessor.getOriginalDoc().createComment("Clause '"+clauseName+"'"); //dataCriteriaSectionElem.appendChild(comment); if(isRAV){ Comment RAComment = hqmfXmlProcessor.getOriginalDoc().createComment("Risk Adjustment Variable"); dataCriteriaSectionElem.appendChild(RAComment); } Node entryElement = null; switch (firstChildName) { case SET_OP: entryElement = generateSetOpHQMF(firstChild,dataCriteriaSectionElem, clauseName); break; case ELEMENT_REF: entryElement = generateElementRefHQMF(firstChild,dataCriteriaSectionElem, clauseName); break; case SUB_TREE_REF: entryElement = generateSubTreeHQMF(firstChild,dataCriteriaSectionElem, clauseName); break; case RELATIONAL_OP: entryElement = generateRelOpHQMF(firstChild, dataCriteriaSectionElem, clauseName); break; case FUNCTIONAL_OP: entryElement = generateFunctionalOpHQMF(firstChild,dataCriteriaSectionElem, clauseName); break; default: //Dont do anything break; } if(isRAV){ Node temp = hqmfXmlProcessor.getOriginalDoc().createAttribute(RAV); temp.setNodeValue("true"); entryElement.getAttributes().setNamedItem(temp); } /** * The clause is generated now. Make an entry in the 'subTreeNodeMap' to keep track of its generation. */ subTreeNodeMap.put(subTreeUUID, subTreeNode); return entryElement; } /** * This method is used to discover weither a given class name and UUID is a risk adjustment variable * @param subTreeUUID * @param clauseName * @return */ private Boolean isRiskAdjustmentVariable(String subTreeUUID, String clauseName) { String xPath = "/measure/riskAdjustmentVariables/subTreeRef[@displayName=\"" + clauseName + "\" and @id='" + subTreeUUID + "']"; boolean RAV = false; try { Node RA = measureExport.getSimpleXMLProcessor().findNode(measureExport.getSimpleXMLProcessor().getOriginalDoc(), xPath); if(RA != null){ RAV = true; } } catch (XPathExpressionException e) { // TODO Auto-generated catch block e.printStackTrace(); } return RAV; } /** * Generate occ hqmf. * * @param subTreeNode the sub tree node * @throws XPathExpressionException the x path expression exception */ private void generateOccHQMF( Node subTreeNode) throws XPathExpressionException { /** * If this is an empty or NULL clause, return right now. */ if((subTreeNode == null) || (subTreeNode.getAttributes().getNamedItem(INSTANCE_OF)==null)){ return; } XmlProcessor hqmfXmlProcessor = measureExport.getHQMFXmlProcessor(); String occSubTreeUUID = subTreeNode.getAttributes().getNamedItem(UUID).getNodeValue(); String qdmVariableSubTreeUUID = subTreeNode.getAttributes().getNamedItem(INSTANCE_OF).getNodeValue(); String clauseName = subTreeNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue(); Boolean isRAV = isRiskAdjustmentVariable(qdmVariableSubTreeUUID, clauseName); /** * Check the 'subTreeNodeMap' to make sure the occ clause isnt already generated. */ if(subTreeNodeMap.containsKey(occSubTreeUUID)){ logger.info("HQMF for Occ Clause "+clauseName + " is already generated. Skipping."); return; } if(!subTreeNodeMap.containsKey(qdmVariableSubTreeUUID)){ logger.info("HQMF for Clause "+clauseName + " is not already generated. Skipping."); return; } String xpath = "/measure/subTreeLookUp/subTree[@uuid = '"+qdmVariableSubTreeUUID+"']"; Node baseSubTreeNode = measureExport.getSimpleXMLProcessor().findNode(measureExport.getSimpleXMLProcessor().getOriginalDoc(), xpath); Node baseFirstChild = baseSubTreeNode.getFirstChild(); String baseExt = baseFirstChild.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue(); Node firstChild = subTreeNode.getFirstChild(); String firstChildName = firstChild.getNodeName(); String ext = firstChild.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue(); // Local Variable Name. String localVarName = clauseName.replace("$", "") + "_" + UUIDUtilClient.uuid(5); String root = subTreeNode.getAttributes().getNamedItem(INSTANCE_OF).getNodeValue(); // Check for Element Ref as first CHild. if (firstChildName.equalsIgnoreCase(ELEMENT_REF)) { ext = getElementRefExt(firstChild, measureExport.getSimpleXMLProcessor()); baseExt = getElementRefExt(baseFirstChild, measureExport.getSimpleXMLProcessor()); }else if(RELATIONAL_OP.equals(firstChildName) || FUNCTIONAL_OP.equals(firstChildName) || SET_OP.equals(firstChildName)){ ext += "_" + firstChild.getAttributes().getNamedItem(UUID).getNodeValue(); baseExt += "_" + baseFirstChild.getAttributes().getNamedItem(UUID).getNodeValue(); } if(FUNCTIONAL_OP.equals(firstChildName)){ if(firstChild.getFirstChild() != null) { Node functionChild = firstChild.getFirstChild(); Node baseFunctionChild = baseFirstChild.getFirstChild(); if(functionChild != null) { if (functionChild.getNodeName().equalsIgnoreCase(SUB_TREE_REF)) { ext = functionChild.getAttributes() .getNamedItem(ID).getNodeValue(); baseExt = baseFunctionChild.getAttributes() .getNamedItem(ID).getNodeValue(); }else if(functionChild.getNodeName().equalsIgnoreCase(ELEMENT_REF)){ ext = getElementRefExt(functionChild, measureExport.getSimpleXMLProcessor()); baseExt = getElementRefExt(baseFunctionChild, measureExport.getSimpleXMLProcessor()); }else{ ext = (StringUtils.deleteWhitespace(functionChild.getAttributes() .getNamedItem(DISPLAY_NAME).getNodeValue() + "_" + functionChild.getAttributes().getNamedItem(UUID).getNodeValue()) .replaceAll(":", "_")); baseExt = (StringUtils.deleteWhitespace(baseFunctionChild.getAttributes() .getNamedItem(DISPLAY_NAME).getNodeValue() + "_" + baseFunctionChild.getAttributes().getNamedItem(UUID).getNodeValue()) .replaceAll(":", "_")); } } } } String isQdmVariable = subTreeNode.getAttributes().getNamedItem(QDM_VARIABLE).getNodeValue(); if (isQdmVariable.equalsIgnoreCase(TRUE)) { ext = "qdm_var_" + StringUtils.deleteWhitespace(ext); baseExt = "qdm_var_" + StringUtils.deleteWhitespace(baseExt); localVarName = "qdm_var_" + StringUtils.deleteWhitespace(localVarName); } String extForOccurrenceNode = "occ" + subTreeNode.getAttributes().getNamedItem( "instance").getNodeValue() + "of_"+ext; ext = StringUtils.deleteWhitespace(ext); localVarName = StringUtils.deleteWhitespace(localVarName); logger.info("generateOccHQMF "+"//entry/*/id[@root='" + root + "'][@extension=\"" + baseExt + "\"]"); Node idNodeQDM = hqmfXmlProcessor.findNode(hqmfXmlProcessor.getOriginalDoc(), "//entry/*/id[@root='" + root + "'][@extension=\"" + baseExt + "\"]"); logger.info("idNodeQDM == null?"+(idNodeQDM == null)); if (idNodeQDM != null) { //Add code here which will create a replica of the entry elem of 'idNodeQDM' and assign it an extension //which has "Occ_X" string in it. Node cloneMainEntryNode = idNodeQDM.getParentNode().getParentNode().cloneNode(true); Node cloneIDNode = findNode(cloneMainEntryNode, "ID"); if (cloneMainEntryNode != null) { Node localVariableNode = cloneMainEntryNode.getFirstChild(); if (localVariableNode.getAttributes().getNamedItem("value") !=null) { localVariableNode.getAttributes().getNamedItem("value").setNodeValue(localVarName); } } cloneIDNode.getAttributes().getNamedItem(EXTENSION).setNodeValue(extForOccurrenceNode); Element dataCriteriaSectionElem = (Element) hqmfXmlProcessor.getOriginalDoc() .getElementsByTagName(DATA_CRITERIA_SECTION).item(0); //Comment occComment = hqmfXmlProcessor.getOriginalDoc().createComment("Clause (Main entry)'"+clauseName+"'"); //dataCriteriaSectionElem.appendChild(occComment); dataCriteriaSectionElem.appendChild(cloneMainEntryNode); Node parentNode = cloneIDNode.getParentNode().cloneNode(false); //Comment comment = hqmfXmlProcessor.getOriginalDoc().createComment("Clause '"+clauseName+"'"); if(isRAV){ Comment RAComment = hqmfXmlProcessor.getOriginalDoc().createComment("Risk Adjustment Variable"); dataCriteriaSectionElem.appendChild(RAComment); } //dataCriteriaSectionElem.appendChild(comment); Element entryElem = hqmfXmlProcessor.getOriginalDoc().createElement(ENTRY); entryElem.setAttribute(TYPE_CODE, "DRIV"); Element idElement = hqmfXmlProcessor.getOriginalDoc().createElement(ID); idElement.setAttribute(ROOT, subTreeNode.getAttributes().getNamedItem(UUID).getNodeValue()); idElement.setAttribute(EXTENSION, extForOccurrenceNode); parentNode.appendChild(idElement); Element outboundRelElem = hqmfXmlProcessor.getOriginalDoc().createElement(OUTBOUND_RELATIONSHIP); outboundRelElem.setAttribute(TYPE_CODE, "OCCR"); Element criteriaRefElem = hqmfXmlProcessor.getOriginalDoc().createElement(CRITERIA_REFERENCE); String refClassCodeValue = parentNode.getAttributes().getNamedItem(CLASS_CODE) .getNodeValue(); String refMoodValue = parentNode.getAttributes().getNamedItem(MOOD_CODE) .getNodeValue(); criteriaRefElem.setAttribute(CLASS_CODE, refClassCodeValue); criteriaRefElem.setAttribute(MOOD_CODE, refMoodValue); Element idRelElem = hqmfXmlProcessor.getOriginalDoc().createElement(ID); idRelElem.setAttribute(ROOT, root); idRelElem.setAttribute(EXTENSION, extForOccurrenceNode); criteriaRefElem.appendChild(idRelElem); outboundRelElem.appendChild(criteriaRefElem); parentNode.appendChild(outboundRelElem); entryElem.appendChild(parentNode); dataCriteriaSectionElem.appendChild(entryElem); /** * The occ clause is generated now. Make an entry in the 'subTreeNodeMap' to keep track of its generation. */ subTreeNodeMap.put(occSubTreeUUID, subTreeNode); } } /** * Generate functional op hqmf. * * @param functionalNode the functional node * @param dataCriteriaSectionElem the data criteria section elem * @return the node * @throws XPathExpressionException the x path expression exception */ private Node generateFunctionalOpHQMF(Node functionalNode, Element dataCriteriaSectionElem , String clauseName) throws XPathExpressionException { Node node = null; if(functionalNode.getChildNodes() != null){ Node firstChildNode = functionalNode.getFirstChild(); String firstChildName = firstChildNode.getNodeName(); switch (firstChildName) { case SET_OP: String functionOpType = functionalNode.getAttributes().getNamedItem(TYPE).getNodeValue(); if (FUNCTIONAL_OPS_NON_SUBSET.containsKey(functionOpType.toUpperCase()) || FUNCTIONAL_OPS_SUBSET.containsKey(functionOpType.toUpperCase())) { node = generateSetOpHQMF(firstChildNode, dataCriteriaSectionElem, clauseName); } break; case ELEMENT_REF: node = generateElementRefHQMF(firstChildNode, dataCriteriaSectionElem, clauseName); break; case RELATIONAL_OP: node = generateRelOpHQMF(firstChildNode, dataCriteriaSectionElem, clauseName); break; case FUNCTIONAL_OP: //findFunctionalOpChild(firstChildNode, dataCriteriaSectionElem); break; case SUB_TREE_REF: node = generateSubTreeHQMFInFunctionalOp(firstChildNode, dataCriteriaSectionElem, clauseName); break; default: //Dont do anything break; } //NamedNodeMap attribMap = functionalNode.getAttributes(); //String funcDisplayName = StringUtils.deleteWhitespace(attribMap.getNamedItem(DISPLAY_NAME).getNodeValue()); //String relUUID = attribMap.getNamedItem(UUID).getNodeValue(); //String localVarName = "localVar_"+funcDisplayName+"_"+relUUID; String localVarName = clauseName; localVarName = localVarName.replace("$", ""); Node parentNode = functionalNode.getParentNode(); if (parentNode != null) { if (parentNode.getNodeName().equalsIgnoreCase("subTree")) { if (parentNode.getAttributes().getNamedItem(QDM_VARIABLE) != null) { String isQdmVariable = parentNode.getAttributes() .getNamedItem(QDM_VARIABLE).getNodeValue(); if (TRUE.equalsIgnoreCase(isQdmVariable)) { localVarName = localVarName.replace("$", ""); localVarName = "qdm_var_" + localVarName; } } localVarName = localVarName + "_" + UUIDUtilClient.uuid(5); localVarName = StringUtils.deleteWhitespace(localVarName); updateLocalVar(node, localVarName); } } } return node; } /** * Method to generate HQMF for function Ops with first child as subTreeRef. In this case grouperCriteria will be generated for * SubTreeRef with Excerpt entry inside it for functional Op. * * @param firstChildNode - SubTreeRef Node. * @param dataCriteriaSectionElem - Data Criteria Element. * @return the node * @throws XPathExpressionException the x path expression exception */ private Node generateSubTreeHQMFInFunctionalOp(Node firstChildNode, Element dataCriteriaSectionElem, String clauseName) throws XPathExpressionException { Node parentNode = firstChildNode.getParentNode(); //temp node. String subTreeUUID = firstChildNode.getAttributes().getNamedItem(ID).getNodeValue(); String xpath = "/measure/subTreeLookUp/subTree[@uuid='"+subTreeUUID+"']"; Node subTreeNode = measureExport.getSimpleXMLProcessor().findNode(measureExport.getSimpleXMLProcessor().getOriginalDoc(), xpath); String firstChildNameOfSubTree = subTreeNode.getFirstChild().getNodeName(); if(FUNCTIONAL_OP.equals(firstChildNameOfSubTree)){ String firstChildNodeName = parentNode.getAttributes().getNamedItem(TYPE).getNodeValue(); if(!SATISFIES_ALL.equalsIgnoreCase(firstChildNodeName)||!SATISFIES_ANY.equalsIgnoreCase(firstChildNodeName) || !AGE_AT.equals(firstChildNodeName)){ return null; } } Element root = measureExport.getHQMFXmlProcessor().getOriginalDoc().createElement("temp"); generateSubTreeHQMF(firstChildNode, root, clauseName); Element entryElement = (Element) root.getFirstChild(); Node firstChild = entryElement.getFirstChild(); if("localVariableName".equals(firstChild.getNodeName())){ firstChild = firstChild.getNextSibling(); } Element excerpt = generateExcerptEntryForFunctionalNode(parentNode, null, measureExport.getHQMFXmlProcessor(), entryElement); if(excerpt != null) { //create comment node //Comment comment = measureExport.getHQMFXmlProcessor().getOriginalDoc(). // createComment("entry for " + parentNode.getAttributes().getNamedItem("displayName").getNodeValue()); //firstChild.appendChild(comment); firstChild.appendChild(excerpt); } dataCriteriaSectionElem.appendChild(entryElement); return entryElement; } /** * This will take care of the use case where a user can create a Clause with only one * QDM elementRef inside it. * We will make a copy of the original entry for QDM and update the id@root and id@extension * for it. This will server as an entry for the Clause. * * @param elementRefNode the element ref node * @param parentNode the parent node * @return the node * @throws XPathExpressionException the x path expression exception */ private Node generateElementRefHQMF(Node elementRefNode, Node parentNode, String clauseName) throws XPathExpressionException { XmlProcessor hqmfXmlProcessor = measureExport.getHQMFXmlProcessor(); Node node = null; String ext = getElementRefExt(elementRefNode, measureExport.getSimpleXMLProcessor()); String root = elementRefNode.getAttributes().getNamedItem(ID).getNodeValue(); String localVariableName = clauseName; Node idNodeQDM = hqmfXmlProcessor.findNode(hqmfXmlProcessor.getOriginalDoc(), "//entry/*/id[@root='"+root+"'][@extension=\""+ext+"\"]"); if(idNodeQDM != null){ Node entryElem = idNodeQDM.getParentNode().getParentNode().cloneNode(true); Node newIdNode = getTagFromEntry(entryElem, ID); if(newIdNode == null){ return null; } String idroot = "0"; Node parNode = elementRefNode.getParentNode(); if((parNode != null) && SUB_TREE.equals(parNode.getNodeName())){ idroot = parNode.getAttributes().getNamedItem(UUID).getNodeValue(); // Added logic to show qdm_variable in extension if clause is of qdm variable type. String isQdmVariable = parNode.getAttributes().getNamedItem(QDM_VARIABLE).getNodeValue(); if(isQdmVariable.equalsIgnoreCase(TRUE)) { String occText = null; // Handled Occurrence Of QDM Variable. if(parNode.getAttributes().getNamedItem(INSTANCE_OF) != null){ occText = "occ"+parNode.getAttributes().getNamedItem(INSTANCE).getNodeValue()+"of_"; } if (occText != null) { ext = occText + "qdm_var_"+ext; } else { ext = "qdm_var_"+ext; localVariableName = "qdm_var_"+localVariableName; } } localVariableName = localVariableName + "_" + UUIDUtilClient.uuid(5); localVariableName = StringUtils.deleteWhitespace(localVariableName); ((Element)newIdNode).setAttribute(ROOT, idroot); ((Element)newIdNode).setAttribute(EXTENSION, ext); Node localVariableNode = entryElem.getFirstChild(); if (localVariableNode.getAttributes().getNamedItem("value") !=null) { localVariableNode.getAttributes().getNamedItem("value").setNodeValue(localVariableName); } parentNode.appendChild(entryElem); node = entryElem; } else { //if the the parentNode for ElementRef is other than SubTreeNode Element excerptElement = null; Node subTreeParentNode = checkIfSubTree(parNode); if(subTreeParentNode != null){ root = subTreeParentNode.getAttributes().getNamedItem(UUID).getNodeValue(); if (subTreeParentNode.getAttributes().getNamedItem(QDM_VARIABLE) != null) { String isQdmVariable = subTreeParentNode.getAttributes() .getNamedItem(QDM_VARIABLE).getNodeValue(); if (TRUE.equalsIgnoreCase(isQdmVariable)) { String occText = null; // Handled Occurrence Of QDM Variable. if(subTreeParentNode.getAttributes().getNamedItem(INSTANCE_OF) != null){ occText = "occ"+subTreeParentNode.getAttributes().getNamedItem("instance").getNodeValue()+"of_"; } if (occText != null) { ext = occText + "qdm_var_"+ext; } else { ext = "qdm_var_"+ext; } } } }else{ root = UUIDUtilClient.uuid(); } Node entryNodeForElementRef = idNodeQDM.getParentNode().getParentNode(); Node clonedEntryNodeForElementRef = entryNodeForElementRef.cloneNode(true); NodeList idChildNodeList = ((Element)clonedEntryNodeForElementRef).getElementsByTagName(ID); if((idChildNodeList != null) && (idChildNodeList.getLength() > 0)){ Node idChildNode = idChildNodeList.item(0); idChildNode.getAttributes().getNamedItem(EXTENSION).setNodeValue(ext); idChildNode.getAttributes().getNamedItem(ROOT).setNodeValue(root); } Node firstChild = clonedEntryNodeForElementRef.getFirstChild(); if(LOCAL_VARIABLE_NAME.equals(firstChild.getNodeName())){ firstChild = firstChild.getNextSibling(); } //Added logic to show qdm_variable in extension if clause is of qdm variable type. if (FUNCTIONAL_OP.equals(parNode.getNodeName())) { excerptElement = generateExcerptEntryForFunctionalNode(parNode, elementRefNode, hqmfXmlProcessor, clonedEntryNodeForElementRef); } if(excerptElement != null){ //Comment comment = hqmfXmlProcessor.getOriginalDoc().createComment("excerpt for "+parNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); //firstChild.appendChild(comment); firstChild.appendChild(excerptElement); } //create comment node //Comment comment = hqmfXmlProcessor.getOriginalDoc().createComment("entry for "+elementRefNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); //parentNode.appendChild(comment); parentNode.appendChild(clonedEntryNodeForElementRef); // clonedEntryNodeForElementRef.appendChild(excerptElement); node = clonedEntryNodeForElementRef; } updateLocalVar(node, ext); } return node; } /** * This will take care of the use case where a user can create a Clause with only one * child Clause inside it. * If HQMF for the child clause is already generated, then since we have no way of referencing * this child clause using <outBoundRelationShip> directly, we are * adding it to a default UNION grouper. * * If it isnt generated then we generate it and then add a criteriaRef to it inside a default UNION. * * @param subTreeRefNode the sub tree ref node * @param parentNode the parent node * @throws XPathExpressionException the x path expression exception */ private Node generateSubTreeHQMF(Node subTreeRefNode, Node parentNode, String clauseName) throws XPathExpressionException { String subTreeUUID = subTreeRefNode.getAttributes().getNamedItem(ID).getNodeValue(); /** * Check if the Clause has already been generated. * If it is not generated yet, then generate it by * calling the 'generateSubTreeXML' method. */ if(!subTreeNodeMap.containsKey(subTreeUUID)){ String xpath = "/measure/subTreeLookUp/subTree[@uuid='"+subTreeUUID+"']"; Node subTreeNode = measureExport.getSimpleXMLProcessor().findNode(measureExport.getSimpleXMLProcessor().getOriginalDoc(), xpath); generateSubTreeXML( subTreeNode, false); } XmlProcessor hqmfXmlProcessor = measureExport.getHQMFXmlProcessor(); // creating Entry Tag Element entryElem = hqmfXmlProcessor.getOriginalDoc().createElement(ENTRY); entryElem.setAttribute(TYPE_CODE, "DRIV"); String root = "0"; String ext = subTreeRefNode.getAttributes().getNamedItem(ID).getNodeValue(); String localVarName = clauseName; localVarName = localVarName.replace("$", ""); /*Node parNode = subTreeRefNode.getParentNode();*/ Node parNode = checkIfSubTree(subTreeRefNode.getParentNode()); if(parNode != null){ root = parNode.getAttributes().getNamedItem(UUID).getNodeValue(); if (parNode.getAttributes().getNamedItem(QDM_VARIABLE) != null) { String isQdmVariable = parNode.getAttributes() .getNamedItem(QDM_VARIABLE).getNodeValue(); if (TRUE.equalsIgnoreCase(isQdmVariable)) { //ext = "qdm_var_" + ext; String occText = null; // Handled Occurrence Of QDM Variable. if(parNode.getAttributes().getNamedItem(INSTANCE_OF) != null){ occText = "occ"+parNode.getAttributes().getNamedItem(INSTANCE).getNodeValue()+"of_"; } if (occText != null) { ext = occText + "qdm_var_"+ext; } else { ext = "qdm_var_"+ext; localVarName = "qdm_var_" + localVarName; } } } } Node grouperElem = generateEmptyGrouper(hqmfXmlProcessor, root, ext); //generate comment Comment comment = hqmfXmlProcessor.getOriginalDoc().createComment("outBoundRelationship for "+subTreeRefNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); grouperElem.appendChild(comment); //generate outboundRelationship Element outboundRelElem = generateEmptyOutboundElem(hqmfXmlProcessor); Element conjunctionCodeElem = hqmfXmlProcessor.getOriginalDoc().createElement(CONJUNCTION_CODE); conjunctionCodeElem.setAttribute(CODE, "OR"); outboundRelElem.appendChild(conjunctionCodeElem); generateCritRefForNode(outboundRelElem, subTreeRefNode, clauseName); grouperElem.appendChild(outboundRelElem); Element localVarElem = hqmfXmlProcessor.getOriginalDoc().createElement(LOCAL_VARIABLE_NAME); localVarName = localVarName + "_" + UUIDUtilClient.uuid(5); localVarName = StringUtils.deleteWhitespace(localVarName); localVarElem.setAttribute(VALUE, localVarName); entryElem.appendChild(localVarElem); entryElem.appendChild(grouperElem); parentNode.appendChild(entryElem); return entryElem; } /** * This method wil generate HQMF code for setOp (UNION,INTERSECTION). * * @param setOpNode the set op node * @param parentNode the parent node * @return the node * @throws XPathExpressionException the x path expression exception */ private Node generateSetOpHQMF( Node setOpNode, Node parentNode, String clauseName) throws XPathExpressionException { XmlProcessor hqmfXmlProcessor = measureExport.getHQMFXmlProcessor(); //DISPLAY NAME is used instead of type as it is in Title case. String setOpType = setOpNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue(); String conjunctionType = "OR"; if("union".equalsIgnoreCase(setOpType) || SATISFIES_ANY.equalsIgnoreCase(setOpType)){ conjunctionType = "OR"; }else if("intersection".equalsIgnoreCase(setOpType) || SATISFIES_ALL.equalsIgnoreCase(setOpType)){ conjunctionType = "AND"; } // creating Entry Tag Element entryElem = hqmfXmlProcessor.getOriginalDoc().createElement(ENTRY); entryElem.setAttribute(TYPE_CODE, "DRIV"); //creating grouperCriteria element String root = "0"; //String ext = setOpType.toUpperCase(); String ext = setOpType + "_" + setOpNode.getAttributes().getNamedItem(UUID).getNodeValue(); String localVariableName = clauseName + "_" + setOpNode.getAttributes().getNamedItem(UUID).getNodeValue(); Node subTreeParentNode = checkIfSubTree(setOpNode.getParentNode()); if (subTreeParentNode != null) { root = subTreeParentNode.getAttributes().getNamedItem(UUID).getNodeValue(); if (subTreeParentNode.getAttributes().getNamedItem(QDM_VARIABLE) != null) { String isQdmVariable = subTreeParentNode.getAttributes() .getNamedItem(QDM_VARIABLE).getNodeValue(); if (TRUE.equalsIgnoreCase(isQdmVariable)) { String occText = null; // Handled Occurrence Of QDM Variable. if(subTreeParentNode.getAttributes().getNamedItem(INSTANCE_OF) != null){ occText = "occ"+subTreeParentNode.getAttributes().getNamedItem(INSTANCE).getNodeValue()+"of_"; } if (occText != null) { ext = occText + "qdm_var_"+ext; } else { ext = "qdm_var_"+ext; } localVariableName = "qdm_var_" + localVariableName; } } } else { root = UUIDUtilClient.uuid(); } Node grouperElem = generateEmptyGrouper(hqmfXmlProcessor, root, ext); Node templateIdNode = getTemplateIdForSatisfies(hqmfXmlProcessor, setOpType); if(templateIdNode != null){ grouperElem.insertBefore(templateIdNode, grouperElem.getFirstChild()); } NodeList childNodes = setOpNode.getChildNodes(); for(int i=0;i<childNodes.getLength();i++){ Node childNode = childNodes.item(i); String childName = childNode.getNodeName(); if("comment".equals(childName)){ continue; } //generate comment Comment comment = hqmfXmlProcessor.getOriginalDoc().createComment("outBoundRelationship for "+childNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); grouperElem.appendChild(comment); //generate outboundRelationship Element outboundRelElem = generateEmptyOutboundElem(hqmfXmlProcessor); Element conjunctionCodeElem = hqmfXmlProcessor.getOriginalDoc().createElement(CONJUNCTION_CODE); conjunctionCodeElem.setAttribute(CODE, conjunctionType); outboundRelElem.appendChild(conjunctionCodeElem); if (ELEMENT_REF.equals(childName) || SUB_TREE_REF.equals(childName)) { generateCritRefForNode(outboundRelElem, childNode, clauseName); } else { switch (childName) { case SET_OP: generateCritRefSetOp(parentNode, hqmfXmlProcessor, childNode, outboundRelElem , clauseName); break; case RELATIONAL_OP: generateCritRefRelOp(parentNode, hqmfXmlProcessor, childNode, outboundRelElem , clauseName); break; case FUNCTIONAL_OP: generateCritRefFunctionalOp(childNode, outboundRelElem, clauseName); break; default: //Dont do anything break; } } grouperElem.appendChild(outboundRelElem); } //Added logic to show qdm_variable in extension if clause is of qdm variable type. Node grouperEntryNode = grouperElem.cloneNode(true); if (FUNCTIONAL_OP.equals(setOpNode.getParentNode().getNodeName())) { Element excerptElement = generateExcerptEntryForFunctionalNode(setOpNode.getParentNode(), null, hqmfXmlProcessor, grouperEntryNode); //Comment comment = hqmfXmlProcessor.getOriginalDoc().createComment("excerpt for "+setOpNode.getParentNode().getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); //grouperElem.appendChild(comment); grouperElem.appendChild(excerptElement); } Element localVarElem = hqmfXmlProcessor.getOriginalDoc().createElement(LOCAL_VARIABLE_NAME); localVarElem.setAttribute(VALUE, StringUtils.deleteWhitespace(localVariableName)); entryElem.appendChild(localVarElem); entryElem.appendChild(grouperElem); parentNode.appendChild(entryElem); return entryElem; } /** * Generate crit ref functional op. * * @param childNode -Node * @param outboundRelElem - outBoundElement * @throws XPathExpressionException -Exception */ private void generateCritRefFunctionalOp(Node childNode, Element outboundRelElem, String clauseName) throws XPathExpressionException { Element dataCriteriaSectionElem = (Element) measureExport.getHQMFXmlProcessor(). getOriginalDoc().getElementsByTagName(DATA_CRITERIA_SECTION).item(0); Node entryNode = generateFunctionalOpHQMF(childNode, dataCriteriaSectionElem, clauseName); if ((entryNode != null) && entryNode.getNodeName().equals(ENTRY)) { Node fChild = entryNode.getFirstChild(); if (LOCAL_VARIABLE_NAME.equals(fChild.getNodeName())) { fChild = fChild.getNextSibling(); } //create criteriaRef Element criteriaReference = measureExport.getHQMFXmlProcessor().getOriginalDoc().createElement(CRITERIA_REFERENCE); criteriaReference.setAttribute(CLASS_CODE, fChild.getAttributes().getNamedItem(CLASS_CODE).getNodeValue()); criteriaReference.setAttribute(MOOD_CODE, fChild.getAttributes().getNamedItem(MOOD_CODE).getNodeValue()); NodeList childNodeList = fChild.getChildNodes(); for (int j = 0; j < childNodeList.getLength(); j++) { Node entryChildNodes = childNodeList.item(j); if (entryChildNodes.getNodeName().equalsIgnoreCase(ID)) { Element id = measureExport.getHQMFXmlProcessor().getOriginalDoc().createElement(ID); id.setAttribute(ROOT, entryChildNodes.getAttributes().getNamedItem(ROOT).getNodeValue()); id.setAttribute(EXTENSION, entryChildNodes.getAttributes() .getNamedItem(EXTENSION).getNodeValue()); criteriaReference.appendChild(id); outboundRelElem.appendChild(criteriaReference); break; } } } } /** * This method is used to create a <templateId> tag for SATISFIES ALL/SATISFIES ANY * functionalOps. * These are functionalOp's but are converted to setOps and treated as Groupers. * * @param hqmfXmlProcessor the hqmf xml processor * @param type the type * @return the template id for satisfies */ private Node getTemplateIdForSatisfies(XmlProcessor hqmfXmlProcessor, String type) { Node templateIdNode = null; if(SATISFIES_ALL.equalsIgnoreCase(type) || SATISFIES_ANY.equalsIgnoreCase(type)){ templateIdNode = hqmfXmlProcessor.getOriginalDoc().createElement(TEMPLATE_ID); Element itemNode = hqmfXmlProcessor.getOriginalDoc().createElement(ITEM); //initialize rootOID with the OID for SATISFIES ALL String rootOID = "2.16.840.1.113883.10.20.28.3.109"; //if we are dealing with SATISFIES ANY change the OID if(SATISFIES_ANY.equalsIgnoreCase(type)){ rootOID = "2.16.840.1.113883.10.20.28.3.108"; } itemNode.setAttribute(ROOT, rootOID); templateIdNode.appendChild(itemNode); } return templateIdNode; } /** * Generate rel op hqmf. * * @param relOpNode the rel op node * @param dataCriteriaSectionElem the data criteria section elem * @return the node * @throws XPathExpressionException the x path expression exception */ private Node generateRelOpHQMF( Node relOpNode, Node dataCriteriaSectionElem, String clauseName) throws XPathExpressionException { Node finalNode = null; if(relOpNode.getChildNodes().getLength() == 2){ Node lhsNode = relOpNode.getFirstChild(); Node rhsNode = relOpNode.getLastChild(); String lhsName = lhsNode.getNodeName(); //NamedNodeMap attribMap = relOpNode.getAttributes(); //String relDisplayName = StringUtils.deleteWhitespace(attribMap.getNamedItem(DISPLAY_NAME).getNodeValue()); // String relUUID = attribMap.getNamedItem(UUID).getNodeValue(); //String localVarName = "localVar_"+relDisplayName+"_"+relUUID; String localVarName = clauseName; Node parentNode = relOpNode.getParentNode(); if(parentNode != null){ if(parentNode.getNodeName().equalsIgnoreCase("subTree")){ if (parentNode.getAttributes().getNamedItem(QDM_VARIABLE) != null) { String isQdmVariable = parentNode.getAttributes() .getNamedItem(QDM_VARIABLE).getNodeValue(); if (TRUE.equalsIgnoreCase(isQdmVariable)) { localVarName = localVarName.replace("$", ""); localVarName = "qdm_var_" + localVarName; } } } } localVarName = localVarName + "_" + UUIDUtilClient.uuid(5); localVarName = StringUtils.deleteWhitespace(localVarName); if (ELEMENT_REF.equals(lhsName)) { finalNode = getrelOpLHSQDM(relOpNode, dataCriteriaSectionElem,lhsNode, rhsNode, clauseName); } else if (RELATIONAL_OP.equals(lhsName)){ finalNode = getrelOpLHSRelOp(relOpNode, dataCriteriaSectionElem,lhsNode, rhsNode,clauseName); Node relOpParentNode = relOpNode.getParentNode(); if(relOpParentNode.getNodeName().equalsIgnoreCase(FUNCTIONAL_OP)) { Element excerptElement = generateExcerptEntryForFunctionalNode(relOpNode.getParentNode() , lhsNode, measureExport.getHQMFXmlProcessor(), finalNode); if(excerptElement != null){ Node firstNode = finalNode.getFirstChild(); if(LOCAL_VARIABLE_NAME.equals(firstNode.getNodeName())){ firstNode = firstNode.getNextSibling(); } //Comment comment = measureExport.getHQMFXmlProcessor().getOriginalDoc().createComment("entry for "+relOpNode.getParentNode().getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); //firstNode.appendChild(comment); firstNode.appendChild(excerptElement); } } //return finalNode; }else if(SET_OP.equals(lhsName)){ finalNode = getrelOpLHSSetOp( relOpNode, dataCriteriaSectionElem,lhsNode, rhsNode, clauseName); Node relOpParentNode = relOpNode.getParentNode(); if(relOpParentNode.getNodeName().equalsIgnoreCase(FUNCTIONAL_OP)) { Element excerptElement = generateExcerptEntryForFunctionalNode(relOpNode.getParentNode() , lhsNode, measureExport.getHQMFXmlProcessor(), finalNode); if(excerptElement != null){ Node firstNode = finalNode.getFirstChild(); if(LOCAL_VARIABLE_NAME.equals(firstNode.getNodeName())){ firstNode = firstNode.getNextSibling(); } //Comment comment = measureExport.getHQMFXmlProcessor().getOriginalDoc().createComment("entry for "+relOpNode.getParentNode().getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); //firstNode.appendChild(comment); firstNode.appendChild(excerptElement); } } //return finalNode; }else if(SUB_TREE_REF.equals(lhsName) || FUNCTIONAL_OP.equalsIgnoreCase(lhsName)){ Node functionalOpNodeWithChildQDM = checkLHSFunctionalOpWithChildQDM(lhsNode); if(functionalOpNodeWithChildQDM != null){ //Do something godawful here. Node functionEntryNode = generateFunctionalOpHQMF(functionalOpNodeWithChildQDM, (Element) dataCriteriaSectionElem,clauseName); dataCriteriaSectionElem.appendChild(functionEntryNode); finalNode = createSpecialGrouperForRelOp(relOpNode, functionEntryNode, rhsNode, dataCriteriaSectionElem, clauseName); } else if(FUNCTIONAL_OP.equalsIgnoreCase(lhsName)){ finalNode = getFunctionalOpLHS(relOpNode, dataCriteriaSectionElem, lhsNode, rhsNode, clauseName); }else{ finalNode = getrelOpLHSSubtree(relOpNode, dataCriteriaSectionElem,lhsNode, rhsNode,clauseName); } } // else if(FUNCTIONAL_OP.equalsIgnoreCase(lhsName)) { // finalNode = getFunctionalOpLHS(relOpNode, dataCriteriaSectionElem, lhsNode, rhsNode, clauseName); if(parentNode.getNodeName().equalsIgnoreCase("subTree")){ updateLocalVar(finalNode, localVarName); } }else{ logger.info("Relational Op:"+relOpNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()+" does not have exactly 2 children. Skipping HQMF for it."); } return finalNode; } /** * When we have a case of "First:(Encounter,Performed:Inpatient) During Measurement Period"; we * need to generate a entry with Grouper * @param relOpNode * @param functionEntryNode * @param rhsNode * @param dataCriteriaSectionElem * @param clauseName */ private Node createSpecialGrouperForRelOp(Node relOpNode, Node functionEntryNode, Node rhsNode, Node dataCriteriaSectionElem, String clauseName) throws XPathExpressionException { XmlProcessor hqmfXmlProcessor = measureExport.getHQMFXmlProcessor(); // creating Entry Tag Element entryElem = hqmfXmlProcessor.getOriginalDoc().createElement(ENTRY); entryElem.setAttribute(TYPE_CODE, "DRIV"); String localVariableName = relOpNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue(); Element localVarElem = hqmfXmlProcessor.getOriginalDoc().createElement(LOCAL_VARIABLE_NAME); localVariableName = localVariableName + "_" + UUIDUtilClient.uuid(5); localVariableName = StringUtils.deleteWhitespace(localVariableName); localVarElem.setAttribute(VALUE, localVariableName); entryElem.appendChild(localVarElem); String root = relOpNode.getAttributes().getNamedItem(UUID).getNodeValue(); String ext = StringUtils.deleteWhitespace(relOpNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue() + "_" + relOpNode.getAttributes().getNamedItem(UUID).getNodeValue()); Node grouperElem = generateEmptyGrouper(hqmfXmlProcessor, root, ext); entryElem.appendChild(grouperElem); if(entryElem != null) { Node subTreeParentNode = checkIfSubTree(relOpNode.getParentNode()); Node idNode = findNode(entryElem,"ID"); if((idNode != null) && (subTreeParentNode != null)) { String idExtension = idNode.getAttributes().getNamedItem(EXTENSION).getNodeValue(); String idRoot = idNode.getAttributes().getNamedItem(ROOT).getNodeValue(); root = subTreeParentNode.getAttributes().getNamedItem(UUID).getNodeValue(); ext = StringUtils.deleteWhitespace(relOpNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue() + "_" + relOpNode.getAttributes().getNamedItem(UUID).getNodeValue()); if (subTreeParentNode.getAttributes().getNamedItem(QDM_VARIABLE) != null) { String isQdmVariable = subTreeParentNode.getAttributes() .getNamedItem(QDM_VARIABLE).getNodeValue(); if (TRUE.equalsIgnoreCase(isQdmVariable)) { String occText = null; // Handled Occurrence Of QDM Variable. if(subTreeParentNode.getAttributes().getNamedItem(INSTANCE_OF) != null){ occText = "occ"+subTreeParentNode.getAttributes().getNamedItem(INSTANCE).getNodeValue()+"of_"; } if (occText != null) { ext = occText + "qdm_var_"+ext; } else { ext = "qdm_var_"+ext; } } } idNode.getAttributes().getNamedItem(ROOT).setNodeValue(root); idNode.getAttributes().getNamedItem(EXTENSION).setNodeValue(ext); // Updated Excerpt tag idNode root and extension. //String hqmfXmlString = measureExport.getHQMFXmlProcessor().getOriginalXml(); Node idNodeExcerpt = measureExport.getHQMFXmlProcessor().findNode( measureExport.getHQMFXmlProcessor().getOriginalDoc(), "//entry/*/excerpt/*/id[@root='"+idRoot+"'][@extension=\""+idExtension+"\"]"); if(idNodeExcerpt!=null){ idNodeExcerpt.getAttributes().getNamedItem(ROOT).setNodeValue(root); idNodeExcerpt.getAttributes().getNamedItem(EXTENSION).setNodeValue(ext); } } //Element temporallyRelatedInfoNode = createBaseTemporalNode(relOpNode, measureExport.getHQMFXmlProcessor()); Element temporallyRelatedInfoNode = null; if(!FULFILLS.equalsIgnoreCase(relOpNode.getAttributes().getNamedItem(TYPE).getNodeValue())) { temporallyRelatedInfoNode = createBaseTemporalNode(relOpNode, measureExport.getHQMFXmlProcessor()); } else { temporallyRelatedInfoNode = measureExport.getHQMFXmlProcessor().getOriginalDoc().createElement(OUTBOUND_RELATIONSHIP); temporallyRelatedInfoNode.setAttribute(TYPE_CODE, "FLFS"); } handleRelOpRHS(dataCriteriaSectionElem, rhsNode, temporallyRelatedInfoNode,clauseName); Node firstChild = entryElem.getFirstChild(); if(LOCAL_VARIABLE_NAME.equals(firstChild.getNodeName())){ firstChild = firstChild.getNextSibling(); } NodeList outBoundList = ((Element)firstChild).getElementsByTagName(OUTBOUND_RELATIONSHIP); if((outBoundList != null) && (outBoundList.getLength() > 0)){ Node outBound = outBoundList.item(0); firstChild.insertBefore(temporallyRelatedInfoNode, outBound); }else{ NodeList excerptList = ((Element)firstChild).getElementsByTagName(EXCERPT); if((excerptList != null) && (excerptList.getLength() > 0)){ Node excerptNode = excerptList.item(0); firstChild.insertBefore(temporallyRelatedInfoNode, excerptNode); }else{ firstChild.appendChild(temporallyRelatedInfoNode); } } //Add a outBound Relationship for the 'functionEntryNode' passed above. Element outBoundForFunction = measureExport.getHQMFXmlProcessor().getOriginalDoc().createElement(OUTBOUND_RELATIONSHIP); outBoundForFunction.setAttribute(TYPE_CODE, "COMP"); Node idNodeForFunctionEntryNode = findNode(functionEntryNode,"ID"); Node excerptNodeForFunctionEntryNode = findNode(functionEntryNode,"excerpt"); Node idNodeInExcerptNode = findNode(excerptNodeForFunctionEntryNode, "id"); String newExtension = StringUtils.deleteWhitespace(clauseName) + "_" + idNodeForFunctionEntryNode.getAttributes().getNamedItem(EXTENSION).getNodeValue(); idNodeForFunctionEntryNode.getAttributes().getNamedItem(EXTENSION).setNodeValue(newExtension); idNodeInExcerptNode.getAttributes().getNamedItem(EXTENSION).setNodeValue(newExtension); if(idNodeForFunctionEntryNode != null){ Node firstChildOfFunctionEntryElem = functionEntryNode.getFirstChild(); if(LOCAL_VARIABLE_NAME.equals(firstChildOfFunctionEntryElem.getNodeName())){ firstChildOfFunctionEntryElem = firstChildOfFunctionEntryElem.getNextSibling(); } NamedNodeMap criteriaNodeAttributeMap = firstChildOfFunctionEntryElem.getAttributes(); if(criteriaNodeAttributeMap.getNamedItem(CLASS_CODE) != null && criteriaNodeAttributeMap.getNamedItem(MOOD_CODE) != null){ //create criteriaRef Element criteriaReference = hqmfXmlProcessor.getOriginalDoc().createElement(CRITERIA_REFERENCE); criteriaReference.setAttribute(CLASS_CODE, criteriaNodeAttributeMap.getNamedItem(CLASS_CODE).getNodeValue()); criteriaReference.setAttribute(MOOD_CODE, criteriaNodeAttributeMap.getNamedItem(MOOD_CODE).getNodeValue()); Node idNodeForFunctionEntryNode_Clone = idNodeForFunctionEntryNode.cloneNode(true); criteriaReference.appendChild(idNodeForFunctionEntryNode_Clone); outBoundForFunction.appendChild(criteriaReference); grouperElem.appendChild(outBoundForFunction); } } dataCriteriaSectionElem.appendChild(entryElem); } return entryElem; } /** * This is to be called when you want to check If the node passed is a FunctionOp with it's child being an elementRef/QDM. * If the node passed is a SubTree/Clause node then this will "recursively" look into the child of that SubTree/Clause * node to see if that child is a FunctionOp with child being an elementRef/QDM. * @param lhsNode * @return * @throws XPathExpressionException */ private Node checkLHSFunctionalOpWithChildQDM(Node node) throws XPathExpressionException { Node returnFunctionalNode = null; String nodeName = node.getNodeName(); if(FUNCTIONAL_OP.equalsIgnoreCase(nodeName)){ returnFunctionalNode = node; /*Node childNode = node.getFirstChild(); if(childNode != null && ELEMENT_REF.equals(childNode.getNodeName())){ returnFunctionalNode = node; }*/ }else if(SUB_TREE_REF.equals(nodeName)){ String subTreeUUID = node.getAttributes().getNamedItem(ID).getNodeValue(); String xpath = "/measure/subTreeLookUp/subTree[@uuid='"+subTreeUUID+"']"; Node subTreeNode = measureExport.getSimpleXMLProcessor().findNode(measureExport.getSimpleXMLProcessor().getOriginalDoc(), xpath); Node childNode = subTreeNode.getFirstChild(); if(childNode != null){ returnFunctionalNode = checkLHSFunctionalOpWithChildQDM(childNode); } } return returnFunctionalNode; } /** * Gets the functional op lhs. * * @param relOpNode the rel op node * @param dataCriteriaSectionElem the data criteria section elem * @param lhsNode the lhs node * @param rhsNode the rhs node * @return the functional op lhs * @throws XPathExpressionException the x path expression exception */ private Node getFunctionalOpLHS(Node relOpNode, Node dataCriteriaSectionElem, Node lhsNode, Node rhsNode, String clauseName) throws XPathExpressionException { Node entryNode = generateFunctionalOpHQMF(lhsNode, (Element) dataCriteriaSectionElem,clauseName); //Comment comment = measureExport.getHQMFXmlProcessor().getOriginalDoc().createComment("entry for "+relOpNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); //dataCriteriaSectionElem.appendChild(comment); if(entryNode != null) { Node subTreeParentNode = checkIfSubTree(relOpNode.getParentNode()); Node idNode = findNode(entryNode,"ID"); if((idNode != null) && (subTreeParentNode != null)) { String idExtension = idNode.getAttributes().getNamedItem(EXTENSION).getNodeValue(); String idRoot = idNode.getAttributes().getNamedItem(ROOT).getNodeValue(); String root = subTreeParentNode.getAttributes().getNamedItem(UUID).getNodeValue(); String ext = StringUtils.deleteWhitespace(relOpNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue() + "_" + relOpNode.getAttributes().getNamedItem(UUID).getNodeValue()); if (subTreeParentNode.getAttributes().getNamedItem(QDM_VARIABLE) != null) { String isQdmVariable = subTreeParentNode.getAttributes() .getNamedItem(QDM_VARIABLE).getNodeValue(); if (TRUE.equalsIgnoreCase(isQdmVariable)) { String occText = null; // Handled Occurrence Of QDM Variable. if(subTreeParentNode.getAttributes().getNamedItem(INSTANCE_OF) != null){ occText = "occ"+subTreeParentNode.getAttributes().getNamedItem(INSTANCE).getNodeValue()+"of_"; } if (occText != null) { ext = occText + "qdm_var_"+ext; } else { ext = "qdm_var_"+ext; } } } idNode.getAttributes().getNamedItem(ROOT).setNodeValue(root); idNode.getAttributes().getNamedItem(EXTENSION).setNodeValue(ext); // Updated Excerpt tag idNode root and extension. //String hqmfXmlString = measureExport.getHQMFXmlProcessor().getOriginalXml(); Node idNodeExcerpt = measureExport.getHQMFXmlProcessor().findNode( measureExport.getHQMFXmlProcessor().getOriginalDoc(), "//entry/*/excerpt/*/id[@root='"+idRoot+"'][@extension=\""+idExtension+"\"]"); if(idNodeExcerpt!=null){ idNodeExcerpt.getAttributes().getNamedItem(ROOT).setNodeValue(root); idNodeExcerpt.getAttributes().getNamedItem(EXTENSION).setNodeValue(ext); } } //Element temporallyRelatedInfoNode = createBaseTemporalNode(relOpNode, measureExport.getHQMFXmlProcessor()); Element temporallyRelatedInfoNode = null; if(!FULFILLS.equalsIgnoreCase(relOpNode.getAttributes().getNamedItem(TYPE).getNodeValue())) { temporallyRelatedInfoNode = createBaseTemporalNode(relOpNode, measureExport.getHQMFXmlProcessor()); } else { temporallyRelatedInfoNode = measureExport.getHQMFXmlProcessor().getOriginalDoc().createElement(OUTBOUND_RELATIONSHIP); temporallyRelatedInfoNode.setAttribute(TYPE_CODE, "FLFS"); } handleRelOpRHS(dataCriteriaSectionElem, rhsNode, temporallyRelatedInfoNode,clauseName); Node firstChild = entryNode.getFirstChild(); if(LOCAL_VARIABLE_NAME.equals(firstChild.getNodeName())){ firstChild = firstChild.getNextSibling(); } NodeList outBoundList = ((Element)firstChild).getElementsByTagName(OUTBOUND_RELATIONSHIP); if((outBoundList != null) && (outBoundList.getLength() > 0)){ Node outBound = outBoundList.item(0); firstChild.insertBefore(temporallyRelatedInfoNode, outBound); }else{ NodeList excerptList = ((Element)firstChild).getElementsByTagName(EXCERPT); if((excerptList != null) && (excerptList.getLength() > 0)){ Node excerptNode = excerptList.item(0); firstChild.insertBefore(temporallyRelatedInfoNode, excerptNode); }else{ firstChild.appendChild(temporallyRelatedInfoNode); } } dataCriteriaSectionElem.appendChild(entryNode); } /*else{ Comment commnt = measureExport.getHQMFXmlProcessor().getOriginalDoc().createComment("CHECK:Could not find an entry for functionalOp:"+lhsNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); dataCriteriaSectionElem.appendChild(commnt); }*/ return entryNode; } /** * @param criteriaNodeInEntry * @return idNode */ private Node findNode(Node criteriaNodeInEntry, String nodeName) { Node idNode = null; for (int i = 0; i < criteriaNodeInEntry.getChildNodes().getLength(); i++) { Node childNode = criteriaNodeInEntry.getChildNodes().item(i); String childNodeName = childNode.getNodeName(); if (childNodeName.contains("Criteria")) { NodeList criteriaChildNodes = childNode.getChildNodes(); for(int j = 0; j < criteriaChildNodes.getLength(); j++){ Node criteriaChildNode = criteriaChildNodes.item(j); if(nodeName.equalsIgnoreCase(criteriaChildNode.getNodeName())) { idNode = criteriaChildNode; break; } } break; } } return idNode; } /** * Gets the rel op lhs subtree. * * @param relOpNode the rel op node * @param dataCriteriaSectionElem the data criteria section elem * @param lhsNode the lhs node * @param rhsNode the rhs node * @return the rel op lhs subtree */ private Node getrelOpLHSSubtree( Node relOpNode, Node dataCriteriaSectionElem, Node lhsNode, Node rhsNode, String clauseName) { try{ String subTreeUUID = lhsNode.getAttributes().getNamedItem(ID).getNodeValue(); String root = subTreeUUID; Node relOpParentNode = relOpNode.getParentNode(); String xpath = "/measure/subTreeLookUp/subTree[@uuid='"+subTreeUUID+"']"; Node subTreeNode = measureExport.getSimpleXMLProcessor().findNode(measureExport.getSimpleXMLProcessor().getOriginalDoc(), xpath); if(subTreeNode != null ) { /** * Check if the Clause has already been generated. * If it is not generated yet, then generate it by * calling the 'generateSubTreeXML' method. */ if(!subTreeNodeMap.containsKey(subTreeUUID)){ generateSubTreeXML(subTreeNode, false); } String isQdmVariable = subTreeNode.getAttributes() .getNamedItem(QDM_VARIABLE).getNodeValue(); Node firstChild = subTreeNode.getFirstChild(); String firstChildName = firstChild.getNodeName(); String ext = StringUtils.deleteWhitespace(firstChild.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); if(FUNCTIONAL_OP.equals(firstChildName) || RELATIONAL_OP.equals(firstChildName) || SET_OP.equals(firstChildName)){ ext += "_" + firstChild.getAttributes().getNamedItem(UUID).getNodeValue(); } if(ELEMENT_REF.equals(firstChildName)){ ext = getElementRefExt(firstChild, measureExport.getSimpleXMLProcessor()); } else if(FUNCTIONAL_OP.equals(firstChildName)){ if(firstChild.getFirstChild() != null) { Node functionChild = firstChild.getFirstChild(); if(functionChild != null) { if (functionChild.getNodeName().equalsIgnoreCase(SUB_TREE_REF)) { ext = functionChild.getAttributes() .getNamedItem(ID).getNodeValue(); }else if(functionChild.getNodeName().equalsIgnoreCase(ELEMENT_REF)){ ext = getElementRefExt(functionChild, measureExport.getSimpleXMLProcessor()); } else{ ext = (StringUtils.deleteWhitespace(functionChild.getAttributes() .getNamedItem(DISPLAY_NAME).getNodeValue() + "_" + functionChild.getAttributes().getNamedItem(UUID).getNodeValue()) .replaceAll(":", "_")); } } } } if(TRUE.equalsIgnoreCase(isQdmVariable)){ String occText = null; // Handled Occurrence Of QDM Variable. if(subTreeNode.getAttributes().getNamedItem(INSTANCE_OF) != null){ occText = "occ"+subTreeNode.getAttributes().getNamedItem("instance").getNodeValue()+"of_"; } if (occText != null) { ext = occText + "qdm_var_"+ext; } else { ext = "qdm_var_"+ext; } } Node idNodeQDM = measureExport.getHQMFXmlProcessor().findNode(measureExport.getHQMFXmlProcessor().getOriginalDoc(), "//entry/*/id[@root='"+root+"'][@extension=\""+ext+"\"]"); if(idNodeQDM != null){ String newExt = StringUtils.deleteWhitespace(relOpNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue() + "_" + relOpNode.getAttributes().getNamedItem(UUID).getNodeValue()); if((relOpParentNode != null) && SUB_TREE.equals(relOpParentNode.getNodeName())){ root = relOpParentNode.getAttributes().getNamedItem(UUID).getNodeValue(); Node qdmVarNode = relOpParentNode.getAttributes().getNamedItem(QDM_VARIABLE); if (qdmVarNode != null) { String isQdmVar = relOpParentNode.getAttributes() .getNamedItem(QDM_VARIABLE).getNodeValue(); if (TRUE.equalsIgnoreCase(isQdmVar)) { String occText = null; // Handled Occurrence Of QDM Variable. if(relOpParentNode.getAttributes().getNamedItem(INSTANCE_OF) != null){ occText = "occ"+relOpParentNode.getAttributes().getNamedItem("instance").getNodeValue()+"of_"; } if (occText != null) { newExt = occText + "qdm_var_"+newExt; } else { newExt = "qdm_var_"+newExt; } } } } else { Node tempParentNode = checkIfParentSubTree(relOpParentNode); if(tempParentNode != null){ root = tempParentNode.getAttributes().getNamedItem(UUID).getNodeValue(); } } Node parent = idNodeQDM.getParentNode(); Node isOcc = subTreeNode.getAttributes().getNamedItem(INSTANCE_OF); Node newEntryNode = null; if(TRUE.equals(isQdmVariable) && (isOcc == null)){ XmlProcessor hqmfXmlProcessor = measureExport.getHQMFXmlProcessor(); // creating Entry Tag Element entryElem = hqmfXmlProcessor.getOriginalDoc().createElement(ENTRY); entryElem.setAttribute(TYPE_CODE, "DRIV"); // create empty grouperCriteria Node grouperElem = generateEmptyGrouper(hqmfXmlProcessor, root, newExt); //generate outboundRelationship Element outboundRelElem = generateEmptyOutboundElem(hqmfXmlProcessor); NamedNodeMap attribMap = parent.getAttributes(); String classCode = attribMap.getNamedItem(CLASS_CODE).getNodeValue(); String moodCode = attribMap.getNamedItem(MOOD_CODE).getNodeValue(); //create criteriaRef Element criteriaReference = hqmfXmlProcessor.getOriginalDoc().createElement(CRITERIA_REFERENCE); criteriaReference.setAttribute(CLASS_CODE, classCode); criteriaReference.setAttribute(MOOD_CODE, moodCode); Element id = hqmfXmlProcessor.getOriginalDoc().createElement(ID); id.setAttribute(ROOT, subTreeUUID); id.setAttribute(EXTENSION, ext); criteriaReference.appendChild(id); outboundRelElem.appendChild(criteriaReference); Element localVarElem = hqmfXmlProcessor.getOriginalDoc().createElement(LOCAL_VARIABLE_NAME); localVarElem.setAttribute(VALUE, ext); entryElem.appendChild(localVarElem); grouperElem.appendChild(outboundRelElem); entryElem.appendChild(grouperElem); newEntryNode = entryElem; }else{ Node entryNodeForSubTree = idNodeQDM.getParentNode().getParentNode(); newEntryNode = entryNodeForSubTree.cloneNode(true); NodeList idChildNodeList = ((Element)newEntryNode).getElementsByTagName(ID); if((idChildNodeList != null) && (idChildNodeList.getLength() > 0)){ Node idChildNode = idChildNodeList.item(0); idChildNode.getAttributes().getNamedItem(EXTENSION).setNodeValue(newExt); idChildNode.getAttributes().getNamedItem(ROOT).setNodeValue(root); } } //Element temporallyRelatedInfoNode = createBaseTemporalNode(relOpNode, measureExport.getHQMFXmlProcessor()); Element temporallyRelatedInfoNode = null; if(!FULFILLS.equalsIgnoreCase(relOpNode.getAttributes().getNamedItem(TYPE).getNodeValue())) { temporallyRelatedInfoNode = createBaseTemporalNode(relOpNode, measureExport.getHQMFXmlProcessor()); } else { temporallyRelatedInfoNode = measureExport.getHQMFXmlProcessor().getOriginalDoc().createElement(OUTBOUND_RELATIONSHIP); temporallyRelatedInfoNode.setAttribute(TYPE_CODE, "FLFS"); } handleRelOpRHS( dataCriteriaSectionElem, rhsNode, temporallyRelatedInfoNode,clauseName); Node firstNode = newEntryNode.getFirstChild(); if(LOCAL_VARIABLE_NAME.equals(firstNode.getNodeName())){ firstNode = firstNode.getNextSibling(); } NodeList outBoundList = ((Element)firstNode).getElementsByTagName(OUTBOUND_RELATIONSHIP); if((outBoundList != null) && (outBoundList.getLength() > 0)){ Node outBound = outBoundList.item(0); firstNode.insertBefore(temporallyRelatedInfoNode, outBound); }else{ firstNode.appendChild(temporallyRelatedInfoNode); } // Entry for Functional Op. if (FUNCTIONAL_OP.equals(relOpParentNode.getNodeName())) { Element excerptElement = generateExcerptEntryForFunctionalNode(relOpParentNode, lhsNode, measureExport.getHQMFXmlProcessor(), firstNode.getParentNode()); if(excerptElement != null) { //Comment comment = measureExport.getHQMFXmlProcessor().getOriginalDoc().createComment("entry for "+relOpParentNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); //firstNode.appendChild(comment); firstNode.appendChild(excerptElement); } } //create comment node //Comment comment = measureExport.getHQMFXmlProcessor().getOriginalDoc().createComment("entry for "+relOpNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); //dataCriteriaSectionElem.appendChild(comment); dataCriteriaSectionElem.appendChild(newEntryNode); return newEntryNode; } } }catch(Exception e){ e.printStackTrace(); } return null; } /** * Gets the rel op lhs set op. * * @param relOpNode the rel op node * @param dataCriteriaSectionElem the data criteria section elem * @param lhsNode the lhs node * @param rhsNode the rhs node * @return the rel op lhs set op */ private Node getrelOpLHSSetOp(Node relOpNode, Node dataCriteriaSectionElem, Node lhsNode, Node rhsNode , String clauseName) { XmlProcessor hqmfXmlProcessor = measureExport.getHQMFXmlProcessor(); //Node relOpParentNode = relOpNode.getParentNode(); try{ Node setOpEntryNode = generateSetOpHQMF(lhsNode, dataCriteriaSectionElem, clauseName); //Element temporallyRelatedInfoNode = createBaseTemporalNode(relOpNode, hqmfXmlProcessor); Node relOpParentNode = checkIfSubTree(relOpNode.getParentNode()); if((relOpParentNode != null)) { NodeList idChildNodeList = ((Element)setOpEntryNode).getElementsByTagName(ID); if((idChildNodeList != null) && (idChildNodeList.getLength() > 0)){ Node idChildNode = idChildNodeList.item(0); String root = relOpParentNode.getAttributes().getNamedItem(UUID).getNodeValue(); String ext = StringUtils.deleteWhitespace(relOpNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue() + "_" + relOpNode.getAttributes().getNamedItem(UUID).getNodeValue()); if (relOpParentNode.getAttributes().getNamedItem(QDM_VARIABLE) != null) { String isQdmVariable = relOpParentNode.getAttributes() .getNamedItem(QDM_VARIABLE).getNodeValue(); if (TRUE.equalsIgnoreCase(isQdmVariable)) { String occText = null; // Handled Occurrence Of QDM Variable. if(relOpParentNode.getAttributes().getNamedItem(INSTANCE_OF) != null){ occText = "occ"+relOpParentNode.getAttributes().getNamedItem(INSTANCE).getNodeValue()+"of_"; } if (occText != null) { ext = occText + "qdm_var_"+ext; } else { ext = "qdm_var_"+ext; } } } idChildNode.getAttributes().getNamedItem(EXTENSION).setNodeValue(ext); idChildNode.getAttributes().getNamedItem(ROOT).setNodeValue(root); } } Element temporallyRelatedInfoNode = null; if(!FULFILLS.equalsIgnoreCase(relOpNode.getAttributes().getNamedItem(TYPE).getNodeValue())) { temporallyRelatedInfoNode = createBaseTemporalNode(relOpNode, hqmfXmlProcessor); } else { temporallyRelatedInfoNode = hqmfXmlProcessor.getOriginalDoc().createElement(OUTBOUND_RELATIONSHIP); temporallyRelatedInfoNode.setAttribute(TYPE_CODE, "FLFS"); } handleRelOpRHS(dataCriteriaSectionElem, rhsNode, temporallyRelatedInfoNode,clauseName); Node firstChild = setOpEntryNode.getFirstChild(); if(LOCAL_VARIABLE_NAME.equals(firstChild.getNodeName())){ firstChild = firstChild.getNextSibling(); } NodeList outBoundList = ((Element)firstChild).getElementsByTagName(OUTBOUND_RELATIONSHIP); if((outBoundList != null) && (outBoundList.getLength() > 0)){ Node outBound = outBoundList.item(0); firstChild.insertBefore(temporallyRelatedInfoNode, outBound); }else{ firstChild.appendChild(temporallyRelatedInfoNode); } //create comment node //Comment comment = hqmfXmlProcessor.getOriginalDoc().createComment("entry for "+relOpNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); //dataCriteriaSectionElem.appendChild(comment); dataCriteriaSectionElem.appendChild(setOpEntryNode); return setOpEntryNode; }catch(Exception e){ e.printStackTrace(); } return null; } /** * Gets the rel op lhs rel op. * * @param relOpNode the rel op node * @param dataCriteriaSectionElem the data criteria section elem * @param lhsNode the lhs node * @param rhsNode the rhs node * @return the rel op lhs rel op * @throws XPathExpressionException the x path expression exception */ private Node getrelOpLHSRelOp( Node relOpNode, Node dataCriteriaSectionElem, Node lhsNode, Node rhsNode, String clauseName) throws XPathExpressionException { XmlProcessor hqmfXmlProcessor = measureExport.getHQMFXmlProcessor(); //Node relOpParentNode = relOpNode.getParentNode(); try{ Node relOpEntryNode = generateRelOpHQMF( lhsNode, dataCriteriaSectionElem,clauseName); /*Element temporallyRelatedInfoNode = createBaseTemporalNode(relOpNode, hqmfXmlProcessor);*/ Node relOpParentNode = checkIfSubTree(relOpNode.getParentNode()); if((relOpParentNode != null)) { NodeList idChildNodeList = ((Element)relOpEntryNode).getElementsByTagName(ID); if((idChildNodeList != null) && (idChildNodeList.getLength() > 0)){ Node idChildNode = idChildNodeList.item(0); String root = relOpParentNode.getAttributes().getNamedItem(UUID).getNodeValue(); String ext = StringUtils.deleteWhitespace(relOpNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue() + "_" + relOpNode.getAttributes().getNamedItem(UUID).getNodeValue()); if (relOpParentNode.getAttributes().getNamedItem(QDM_VARIABLE) != null) { String isQdmVariable = relOpParentNode.getAttributes() .getNamedItem(QDM_VARIABLE).getNodeValue(); if (TRUE.equalsIgnoreCase(isQdmVariable)) { String occText = null; // Handled Occurrence Of QDM Variable. if(relOpParentNode.getAttributes().getNamedItem(INSTANCE_OF) != null){ occText = "occ"+relOpParentNode.getAttributes().getNamedItem("instance").getNodeValue()+"of_"; } if (occText != null) { ext = occText + "qdm_var_"+ext; } else { ext = "qdm_var_"+ext; } } } idChildNode.getAttributes().getNamedItem(EXTENSION).setNodeValue(ext); idChildNode.getAttributes().getNamedItem(ROOT).setNodeValue(root); } } Element temporallyRelatedInfoNode = null; if(!FULFILLS.equalsIgnoreCase(relOpNode.getAttributes().getNamedItem(TYPE).getNodeValue())) { temporallyRelatedInfoNode = createBaseTemporalNode(relOpNode, hqmfXmlProcessor); } else { temporallyRelatedInfoNode = hqmfXmlProcessor.getOriginalDoc().createElement(OUTBOUND_RELATIONSHIP); temporallyRelatedInfoNode.setAttribute(TYPE_CODE, "FLFS"); } handleRelOpRHS(dataCriteriaSectionElem, rhsNode, temporallyRelatedInfoNode,clauseName); Node firstChild = relOpEntryNode.getFirstChild(); if(LOCAL_VARIABLE_NAME.equals(firstChild.getNodeName())){ firstChild = firstChild.getNextSibling(); } NodeList outBoundList = ((Element)firstChild).getElementsByTagName(OUTBOUND_RELATIONSHIP); if((outBoundList != null) && (outBoundList.getLength() > 0)){ Node outBound = outBoundList.item(0); firstChild.insertBefore(temporallyRelatedInfoNode, outBound); }else{ firstChild.appendChild(temporallyRelatedInfoNode); } //create comment node //Comment comment = hqmfXmlProcessor.getOriginalDoc().createComment("entry for "+relOpNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); //dataCriteriaSectionElem.appendChild(comment); dataCriteriaSectionElem.appendChild(relOpEntryNode); return relOpEntryNode; }catch(Exception e){ e.printStackTrace(); } return null; } /** * Gets the rel op lhsqdm. * * @param relOpNode the rel op node * @param dataCriteriaSectionElem the data criteria section elem * @param lhsNode the lhs node * @param rhsNode the rhs node * @return the rel op lhsqdm * @throws XPathExpressionException the x path expression exception */ private Node getrelOpLHSQDM(Node relOpNode, Node dataCriteriaSectionElem, Node lhsNode, Node rhsNode, String clauseName) throws XPathExpressionException { String ext = getElementRefExt(lhsNode, measureExport.getSimpleXMLProcessor()); String root = lhsNode.getAttributes().getNamedItem(ID).getNodeValue(); XmlProcessor hqmfXmlProcessor = measureExport.getHQMFXmlProcessor(); Node relOpParentNode = relOpNode.getParentNode(); Element excerptElement = null; Node idNodeQDM = hqmfXmlProcessor.findNode(hqmfXmlProcessor.getOriginalDoc(), "//entry/*/id[@root='"+root+"'][@extension=\""+ext+"\"]"); if ((relOpParentNode != null) && (idNodeQDM != null)) { ext = StringUtils.deleteWhitespace(relOpNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue() + "_" + relOpNode.getAttributes().getNamedItem(UUID).getNodeValue()) ; Node subTreeParentNode = checkIfSubTree(relOpParentNode); if(subTreeParentNode != null){ root = subTreeParentNode.getAttributes().getNamedItem(UUID).getNodeValue(); if (subTreeParentNode.getAttributes().getNamedItem(QDM_VARIABLE) != null) { String isQdmVariable = subTreeParentNode.getAttributes() .getNamedItem(QDM_VARIABLE).getNodeValue(); if (TRUE.equalsIgnoreCase(isQdmVariable)) { String occText = null; // Handled Occurrence Of QDM Variable. if(relOpParentNode.getAttributes().getNamedItem(INSTANCE_OF) != null){ occText = "occ"+relOpParentNode.getAttributes().getNamedItem("instance").getNodeValue()+"of_"; } if (occText != null) { ext = occText + "qdm_var_"+ext; } else { ext = "qdm_var_"+ext; } } } } Node entryNodeForElementRef = idNodeQDM.getParentNode().getParentNode(); Node clonedEntryNodeForElementRef = entryNodeForElementRef.cloneNode(true); /*Element localVarName = (Element) ((Element)clonedEntryNodeForElementRef).getElementsByTagName("localVariableName").item(0); localVarName.setAttribute(VALUE,findSubTreeDisplayName(lhsNode));*/ NodeList idChildNodeList = ((Element)clonedEntryNodeForElementRef).getElementsByTagName(ID); updateLocalVar(clonedEntryNodeForElementRef, ext); if((idChildNodeList != null) && (idChildNodeList.getLength() > 0)){ Node idChildNode = idChildNodeList.item(0); idChildNode.getAttributes().getNamedItem(EXTENSION).setNodeValue(ext); idChildNode.getAttributes().getNamedItem(ROOT).setNodeValue(root); } //Added logic to show qdm_variable in extension if clause is of qdm variable type. if (FUNCTIONAL_OP.equals(relOpParentNode.getNodeName())) { excerptElement = generateExcerptEntryForFunctionalNode(relOpParentNode, lhsNode, hqmfXmlProcessor, clonedEntryNodeForElementRef); } Element temporallyRelatedInfoNode = null; if(!FULFILLS.equalsIgnoreCase(relOpNode.getAttributes().getNamedItem(TYPE).getNodeValue())) { temporallyRelatedInfoNode = createBaseTemporalNode(relOpNode, hqmfXmlProcessor); generateTemporalAttribute(hqmfXmlProcessor, lhsNode,temporallyRelatedInfoNode, clonedEntryNodeForElementRef, true); } else { temporallyRelatedInfoNode = hqmfXmlProcessor.getOriginalDoc().createElement(OUTBOUND_RELATIONSHIP); temporallyRelatedInfoNode.setAttribute(TYPE_CODE, "FLFS"); } handleRelOpRHS(dataCriteriaSectionElem, rhsNode, temporallyRelatedInfoNode,clauseName); Node firstChild = clonedEntryNodeForElementRef.getFirstChild(); if(LOCAL_VARIABLE_NAME.equals(firstChild.getNodeName())){ firstChild = firstChild.getNextSibling(); } NodeList outBoundList = ((Element)firstChild).getElementsByTagName(OUTBOUND_RELATIONSHIP); if((outBoundList != null) && (outBoundList.getLength() > 0)){ Node outBound = outBoundList.item(0); firstChild.insertBefore(temporallyRelatedInfoNode, outBound); }else{ firstChild.appendChild(temporallyRelatedInfoNode); } if(excerptElement != null){ //Comment comment = hqmfXmlProcessor.getOriginalDoc().createComment("excerpt for "+relOpParentNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); //firstChild.appendChild(comment); firstChild.appendChild(excerptElement); } //create comment node //Comment comment = hqmfXmlProcessor.getOriginalDoc().createComment("entry for "+relOpNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); //dataCriteriaSectionElem.appendChild(comment); dataCriteriaSectionElem.appendChild(clonedEntryNodeForElementRef); return clonedEntryNodeForElementRef; } return null; } /** * Handle rel op rhs. * * @param dataCriteriaSectionElem the data criteria section elem * @param rhsNode the rhs node * @param temporallyRelatedInfoNode the temporally related info node * @throws XPathExpressionException the x path expression exception */ private void handleRelOpRHS( Node dataCriteriaSectionElem, Node rhsNode, Element temporallyRelatedInfoNode, String clauseName) throws XPathExpressionException { XmlProcessor hqmfXmlProcessor = measureExport.getHQMFXmlProcessor(); String rhsName = rhsNode.getNodeName(); Node dataCritSectionNode = hqmfXmlProcessor.findNode(temporallyRelatedInfoNode.getOwnerDocument(), "//dataCriteriaSection"); if(ELEMENT_REF.equals(rhsName)){ Node entryNode = generateCritRefElementRef(temporallyRelatedInfoNode, rhsNode, measureExport.getHQMFXmlProcessor()); generateTemporalAttribute(hqmfXmlProcessor, rhsNode,temporallyRelatedInfoNode, entryNode, false); }else if(SUB_TREE_REF.equals(rhsName)){ generateCritRefForNode(temporallyRelatedInfoNode, rhsNode, clauseName); }else{ switch (rhsName) { case SET_OP: generateCritRefSetOp(dataCritSectionNode, hqmfXmlProcessor, rhsNode, temporallyRelatedInfoNode, clauseName); break; case RELATIONAL_OP: generateRelOpHQMF(rhsNode,temporallyRelatedInfoNode, clauseName); Node lastChild = temporallyRelatedInfoNode.getLastChild(); if(lastChild.getNodeName().equals(ENTRY)){ temporallyRelatedInfoNode.removeChild(lastChild); Node fChild = lastChild.getFirstChild(); if(LOCAL_VARIABLE_NAME.equals(fChild.getNodeName())){ fChild = fChild.getNextSibling(); } Node criteriaNode = fChild; //temporallyRelatedInfoNode.appendChild(criteriaNode); dataCritSectionNode.appendChild(lastChild); //create criteriaRef Element criteriaReference = hqmfXmlProcessor.getOriginalDoc().createElement(CRITERIA_REFERENCE); criteriaReference.setAttribute(CLASS_CODE, criteriaNode.getAttributes().getNamedItem(CLASS_CODE).getNodeValue()); criteriaReference.setAttribute(MOOD_CODE, criteriaNode.getAttributes().getNamedItem(MOOD_CODE).getNodeValue()); NodeList childNodeList = criteriaNode.getChildNodes(); for(int i =0; i< childNodeList.getLength();i++) { Node childNode = childNodeList.item(i); if(childNode.getNodeName().equalsIgnoreCase(ID)){ Element id = hqmfXmlProcessor.getOriginalDoc().createElement(ID); id.setAttribute(ROOT, childNode.getAttributes().getNamedItem(ROOT).getNodeValue()); id.setAttribute(EXTENSION, childNode.getAttributes().getNamedItem(EXTENSION).getNodeValue()); criteriaReference.appendChild(id); temporallyRelatedInfoNode.appendChild(criteriaReference); break; } } NodeList childTemporalNodeList = ((Element)criteriaNode).getElementsByTagName("temporallyRelatedInformation"); if((childTemporalNodeList != null) && (childTemporalNodeList.getLength() > 0)){ Node childTemporalNode = childTemporalNodeList.item(0); Node temporalInfoNode = childTemporalNode.getFirstChild(); //find sourceAttribute NodeList childs = temporalInfoNode.getChildNodes(); for(int c=0;c<childs.getLength();c++){ Node child = childs.item(c); String childName = child.getNodeName(); if("qdm:sourceAttribute".equals(childName)){ Node cloneAttNode = child.cloneNode(true); temporallyRelatedInfoNode.getFirstChild().appendChild(cloneAttNode); hqmfXmlProcessor.getOriginalDoc().renameNode(cloneAttNode, "", "qdm:targetAttribute"); break; } } } } break; case FUNCTIONAL_OP : Node entryNode = generateFunctionalOpHQMF(rhsNode , (Element) dataCritSectionNode,clauseName); if ((entryNode !=null) && entryNode.getNodeName().equals(ENTRY)) { Node fChild = entryNode.getFirstChild(); if (LOCAL_VARIABLE_NAME.equals(fChild.getNodeName())) { fChild = fChild.getNextSibling(); } //create criteriaRef Element criteriaReference = hqmfXmlProcessor.getOriginalDoc().createElement(CRITERIA_REFERENCE); criteriaReference.setAttribute(CLASS_CODE, fChild.getAttributes().getNamedItem(CLASS_CODE).getNodeValue()); criteriaReference.setAttribute(MOOD_CODE, fChild.getAttributes().getNamedItem(MOOD_CODE).getNodeValue()); NodeList childNodeList = fChild.getChildNodes(); for(int i =0; i< childNodeList.getLength();i++) { Node childNode = childNodeList.item(i); if(childNode.getNodeName().equalsIgnoreCase(ID)){ Element id = hqmfXmlProcessor.getOriginalDoc().createElement(ID); id.setAttribute(ROOT, childNode.getAttributes().getNamedItem(ROOT).getNodeValue()); id.setAttribute(EXTENSION, childNode.getAttributes().getNamedItem(EXTENSION).getNodeValue()); criteriaReference.appendChild(id); temporallyRelatedInfoNode.appendChild(criteriaReference); break; } } } break; default: //Dont do anything break; } } } /** * Generate temporal attribute. * * @param hqmfXmlProcessor the hqmf xml processor * @param rhsNode the rhs node * @param temporallyRelatedInfoNode the temporally related info node * @param entryNode the entry node * @param isSource the is source * @return the node */ private Node generateTemporalAttribute(XmlProcessor hqmfXmlProcessor, Node rhsNode, Element temporallyRelatedInfoNode, Node entryNode, boolean isSource) { if(entryNode != null){ Element entryElement = (Element)entryNode; if(!rhsNode.hasChildNodes()){ return null; }else{ Node child = rhsNode.getFirstChild(); if(!"attribute".equals(child.getNodeName())){ return null; } String value = child.getAttributes().getNamedItem(NAME).getNodeValue(); List<String> validAttribNames = new ArrayList<String>(); validAttribNames.add("incision datetime"); validAttribNames.add("facility location arrival datetime"); validAttribNames.add("facility location departure datetime"); validAttribNames.add("recorded datetime"); validAttribNames.add("signed datetime"); validAttribNames.add("start datetime"); validAttribNames.add("stop datetime"); if(!validAttribNames.contains(value)){ return null; } if("start datetime".equals(value) || "stop datetime".equals(value)){ String dataType = rhsNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue(); if(!dataType.endsWith("Order")){ return null; } } //create sourceAttribute/targetAttribute String attribName = "qdm:sourceAttribute"; if(!isSource){ attribName = "qdm:targetAttribute"; } Element attribute = hqmfXmlProcessor.getOriginalDoc().createElement(attribName); attribute.setAttribute(NAME, value); String boundValue = "effectiveTime.low"; if("incision datetime".equals(value)){ NodeList nodeList = entryElement.getElementsByTagName(OUTBOUND_RELATIONSHIP); if((nodeList != null) && (nodeList.getLength() > 0)){ //Always get the last outBoundRelationShip tag, because this is the one //which will represent the Node outBoundNode = nodeList.item(nodeList.getLength()-1); Node criteriaNode = outBoundNode.getFirstChild(); NodeList idNodeList = ((Element)criteriaNode).getElementsByTagName(ID); if((idNodeList != null) && (idNodeList.getLength() > 0)){ Node idNode = idNodeList.item(0); Element qdmId = hqmfXmlProcessor.getOriginalDoc().createElement("qdm:id"); qdmId.setAttribute(ROOT, idNode.getAttributes().getNamedItem(ROOT).getNodeValue()); qdmId.setAttribute(EXTENSION, idNode.getAttributes().getNamedItem(EXTENSION).getNodeValue()); attribute.appendChild(qdmId); } } }else{ NodeList nodeList = entryElement.getElementsByTagName(PARTICIPATION); if((nodeList != null) && (nodeList.getLength() > 0)){ //Always get the last outBoundRelationShip tag, because this is the one //which will represent the Node participationNode = nodeList.item(nodeList.getLength()-1); Node roleNode = ((Element)participationNode).getElementsByTagName(ROLE).item(0); NodeList idNodeList = ((Element)roleNode).getElementsByTagName(ID); if((idNodeList != null) && (idNodeList.getLength() > 0)){ Node idNode = idNodeList.item(0); Node itemNode = idNode.getFirstChild(); Element qdmId = hqmfXmlProcessor.getOriginalDoc().createElement("qdm:id"); qdmId.setAttribute(ROOT, itemNode.getAttributes().getNamedItem(ROOT).getNodeValue()); qdmId.setAttribute(EXTENSION, itemNode.getAttributes().getNamedItem(EXTENSION).getNodeValue()); attribute.appendChild(qdmId); if("facility location departure datetime".equals(value) || "stop datetime".equals(value) || "signed datetime".equals(value) || "recorded datetime".equals(value)){ boundValue = "effectiveTime.high"; } } } } attribute.setAttribute("bound", boundValue); Node temporalInformation = temporallyRelatedInfoNode.getFirstChild(); if(temporallyRelatedInfoNode.getElementsByTagName("qdm:delta").item(0)!=null){ Node qdmDeltaNode = temporallyRelatedInfoNode.getElementsByTagName("qdm:delta").item(0); temporalInformation.insertBefore(attribute, qdmDeltaNode); } else { temporalInformation.appendChild(attribute); } return attribute; } } return null; } /** * Generate Excerpt for Functional Op used with timing/Relationship. * * @param functionalOpNode the functional op node * @param lhsNode the lhs node * @param hqmfXmlProcessor the hqmf xml processor * @param clonedNodeToAppendExcerpt the cloned node to append excerpt * @return the element * @throws XPathExpressionException the x path expression exception */ private Element generateExcerptEntryForFunctionalNode(Node functionalOpNode, Node lhsNode, XmlProcessor hqmfXmlProcessor, Node clonedNodeToAppendExcerpt) throws XPathExpressionException { Element excerptElement = hqmfXmlProcessor.getOriginalDoc().createElement(EXCERPT); String functionalOpName = functionalOpNode.getAttributes().getNamedItem(TYPE).getNodeValue(); Element criteriaElement = null; if (FUNCTIONAL_OPS_NON_SUBSET.containsKey(functionalOpName)) { Element sequenceElement = hqmfXmlProcessor.getOriginalDoc().createElement(SEQUENCE_NUMBER); sequenceElement.setAttribute(VALUE, FUNCTIONAL_OPS_NON_SUBSET.get(functionalOpName.toUpperCase())); excerptElement.appendChild(sequenceElement); if (clonedNodeToAppendExcerpt != null) { if(clonedNodeToAppendExcerpt.getNodeName().contains(GROUPER)) { criteriaElement = generateCriteriaElementForSetOpExcerpt(hqmfXmlProcessor, clonedNodeToAppendExcerpt); excerptElement.appendChild(criteriaElement); } else { NodeList entryChildNodes = clonedNodeToAppendExcerpt.getChildNodes(); criteriaElement = generateCriteriaElementForExcerpt(hqmfXmlProcessor, entryChildNodes); excerptElement.appendChild(criteriaElement); } } } else if (FUNCTIONAL_OPS_SUBSET.containsKey(functionalOpName)) { NamedNodeMap attributeMap = functionalOpNode.getAttributes(); if(clonedNodeToAppendExcerpt.getNodeName().contains(GROUPER)) { criteriaElement = generateCriteriaElementForSetOpExcerpt(hqmfXmlProcessor, clonedNodeToAppendExcerpt); excerptElement.appendChild(criteriaElement); } else { NodeList entryChildNodes = clonedNodeToAppendExcerpt.getChildNodes(); criteriaElement = generateCriteriaElementForExcerpt(hqmfXmlProcessor, entryChildNodes); excerptElement.appendChild(criteriaElement); } if (clonedNodeToAppendExcerpt != null) { if ("count".equalsIgnoreCase(functionalOpName)) { createRepeatNumberTagForCountFuncttion(hqmfXmlProcessor, attributeMap, criteriaElement); Element qdmSubSetElement = hqmfXmlProcessor.getOriginalDoc().createElement("qdm:subsetCode"); qdmSubSetElement.setAttribute(CODE, FUNCTIONAL_OPS_SUBSET.get(functionalOpName.toUpperCase())); Element subSetCodeElement = hqmfXmlProcessor.getOriginalDoc().createElement("subsetCode"); subSetCodeElement.setAttribute(CODE, "SUM"); excerptElement.appendChild(subSetCodeElement); excerptElement.appendChild(qdmSubSetElement); excerptElement.appendChild(criteriaElement); } else { if ((attributeMap.getNamedItem(OPERATOR_TYPE) != null) && (lhsNode != null)) { String lhsNodeType = lhsNode.getNodeName(); if (ELEMENT_REF.equalsIgnoreCase(lhsNodeType)) { String qdmUUID = lhsNode.getAttributes().getNamedItem(ID).getNodeValue(); String xPath = "/measure/elementLookUp/qdm[@uuid ='"+qdmUUID+"']"; Node node = measureExport.getSimpleXMLProcessor().findNode(measureExport.getSimpleXMLProcessor().getOriginalDoc(), xPath); if((node != null) && lhsNode.hasChildNodes()){ Node qdmNode = node.cloneNode(true); Node attributeNode = lhsNode.getFirstChild().cloneNode(true); attributeNode.setUserData(ATTRIBUTE_NAME, attributeNode.getAttributes().getNamedItem(NAME).getNodeValue(), null); attributeNode.setUserData(ATTRIBUTE_MODE,attributeMap.getNamedItem(OPERATOR_TYPE).getNodeValue(), null); attributeNode.setUserData(ATTRIBUTE_UUID, attributeNode.getAttributes().getNamedItem(ATTR_UUID).getNodeValue(), null); Element attributeElement = (Element) attributeNode; attributeElement.setAttribute(MODE, attributeMap.getNamedItem(OPERATOR_TYPE).getNodeValue()); if(attributeElement.getAttributes().getNamedItem(ATTR_DATE) != null){ attributeNode.setUserData(ATTRIBUTE_DATE, attributeMap.getNamedItem(QUANTITY).getNodeValue(),null); } else { attributeElement.setAttribute(COMPARISON_VALUE, attributeMap.getNamedItem(QUANTITY).getNodeValue()); } if(attributeMap.getNamedItem(UNIT) != null){ attributeElement.setAttribute(UNIT, attributeMap.getNamedItem(UNIT).getNodeValue()); } else { if(attributeElement.getAttributes().getNamedItem(UNIT) != null){ attributeElement.removeAttribute(UNIT); } } attributeNode = attributeElement; //HQMFDataCriteriaElementGenerator hqmfDataCriteriaElementGenerator = new HQMFDataCriteriaElementGenerator(); //hqmfDataCriteriaElementGenerator.generateAttributeTagForFunctionalOp(measureExport,qdmNode, criteriaElement, attributeNode); HQMFAttributeGenerator attributeGenerator = new HQMFAttributeGenerator(); attributeGenerator.generateAttributeTagForFunctionalOp(measureExport,qdmNode, criteriaElement, attributeNode); } } } Element qdmSubSetElement = hqmfXmlProcessor.getOriginalDoc().createElement("qdm:subsetCode"); qdmSubSetElement.setAttribute(CODE, FUNCTIONAL_OPS_SUBSET.get(functionalOpName.toUpperCase())); if("sum".equalsIgnoreCase(functionalOpName)){ Element subSetCodeElement = hqmfXmlProcessor.getOriginalDoc().createElement("subsetCode"); subSetCodeElement.setAttribute(CODE, "SUM"); excerptElement.appendChild(subSetCodeElement); } excerptElement.appendChild(qdmSubSetElement); excerptElement.appendChild(criteriaElement); } } } return excerptElement; } /** * Check if parent sub tree. * * @param parentNode the parent node * @return the node */ protected Node checkIfParentSubTree(Node parentNode){ Node returnNode = null; if(parentNode!=null){ String parentName = parentNode.getNodeName(); if(SUB_TREE.equals(parentName)){ returnNode = parentNode; } else { returnNode = checkIfParentSubTree(parentNode.getParentNode()); } } return returnNode; } /** * Generates RepeatNumber tags for Count Function. * @param hqmfXmlProcessor - XmlProcessor. * @param attributeMap - NamedNodeMap. * @param criteriaElement - Element. */ private void createRepeatNumberTagForCountFuncttion(XmlProcessor hqmfXmlProcessor, NamedNodeMap attributeMap, Element criteriaElement) { Element repeatNumberElement = hqmfXmlProcessor.getOriginalDoc().createElement("repeatNumber"); Element lowNode = hqmfXmlProcessor.getOriginalDoc().createElement("low"); Element highNode = hqmfXmlProcessor.getOriginalDoc().createElement("high"); if (attributeMap.getNamedItem(OPERATOR_TYPE) != null) { String operatorType = attributeMap.getNamedItem(OPERATOR_TYPE).getNodeValue(); String quantity = attributeMap.getNamedItem(QUANTITY).getNodeValue(); if (operatorType.startsWith("Greater Than")) { lowNode.setAttribute(VALUE, quantity); highNode.setAttribute(NULL_FLAVOR, "PINF"); if ("Greater Than or Equal To".equals(operatorType)) { repeatNumberElement.setAttribute("lowClosed", TRUE); } } else if ("Equal To".equals(operatorType)) { repeatNumberElement.setAttribute("lowClosed", TRUE); repeatNumberElement.setAttribute("highClosed", TRUE); lowNode.setAttribute(VALUE, quantity); highNode.setAttribute(VALUE, quantity); } else if (operatorType.startsWith("Less Than")) { repeatNumberElement.setAttribute("lowClosed", TRUE); lowNode.setAttribute(VALUE, "0"); highNode.setAttribute(VALUE, quantity); if ("Less Than or Equal To".equals(operatorType)) { repeatNumberElement.setAttribute("highClosed", TRUE); } } repeatNumberElement.appendChild(lowNode); repeatNumberElement.appendChild(highNode); criteriaElement.appendChild(repeatNumberElement); } } /** * Generate criteria element for excerpt. * * @param hqmfXmlProcessor the hqmf xml processor * @param entryChildNodes the entry child nodes * @return the element */ private Element generateCriteriaElementForExcerpt(XmlProcessor hqmfXmlProcessor, NodeList entryChildNodes) { Element criteriaElement = null; for (int i = 0; i < entryChildNodes.getLength(); i++) { Node childNode = entryChildNodes.item(i); String childNodeName = childNode.getNodeName(); if (childNodeName.contains("Criteria")) { criteriaElement = hqmfXmlProcessor.getOriginalDoc().createElement(childNodeName); criteriaElement.setAttribute(CLASS_CODE, childNode.getAttributes().getNamedItem(CLASS_CODE).getNodeValue()); criteriaElement.setAttribute(MOOD_CODE, childNode.getAttributes().getNamedItem(MOOD_CODE).getNodeValue()); NodeList criteriaChildNodes = childNode.getChildNodes(); for(int j = 0; j < criteriaChildNodes.getLength(); j++){ Node criteriaChildNode = criteriaChildNodes.item(j); if(ID.equalsIgnoreCase(criteriaChildNode.getNodeName())) { Element idElement = hqmfXmlProcessor.getOriginalDoc().createElement(ID); idElement.setAttribute(ROOT, criteriaChildNode.getAttributes().getNamedItem(ROOT).getNodeValue()); idElement.setAttribute(EXTENSION, criteriaChildNode.getAttributes().getNamedItem(EXTENSION).getNodeValue()); criteriaElement.appendChild(idElement); break; } } break; } } return criteriaElement; } /** * Generate criteria element for set op excerpt. * * @param hqmfXmlProcessor the hqmf xml processor * @param clonedNodeToAppendExcerpt the cloned node to append excerpt * @return the element */ private Element generateCriteriaElementForSetOpExcerpt(XmlProcessor hqmfXmlProcessor, Node clonedNodeToAppendExcerpt) { Element criteriaElement = null; for (int i = 0; i < clonedNodeToAppendExcerpt.getChildNodes().getLength(); i++) { Node childNode = clonedNodeToAppendExcerpt.getChildNodes().item(i); if(ID.equalsIgnoreCase(childNode.getNodeName())) { Node criteriaNode = generateEmptyGrouper(hqmfXmlProcessor, childNode.getAttributes().getNamedItem(ROOT).getNodeValue() , childNode.getAttributes().getNamedItem(EXTENSION).getNodeValue()); criteriaElement = (Element) criteriaNode; break; } } return criteriaElement; } /** * Creates the base temporal node. * * @param relOpNode the rel op node * @param hqmfXmlProcessor the hqmf xml processor * @return the element */ private Element createBaseTemporalNode(Node relOpNode, XmlProcessor hqmfXmlProcessor) { NamedNodeMap attribMap = relOpNode.getAttributes(); Element temporallyRelatedInfoNode = hqmfXmlProcessor.getOriginalDoc().createElement("temporallyRelatedInformation"); temporallyRelatedInfoNode.setAttribute(TYPE_CODE, attribMap.getNamedItem(TYPE).getNodeValue().toUpperCase()); Element temporalInfoNode = hqmfXmlProcessor.getOriginalDoc().createElement("qdm:temporalInformation"); String precisionUnit = "min"; //use min by default if(attribMap.getNamedItem(OPERATOR_TYPE) != null){ String operatorType = attribMap.getNamedItem(OPERATOR_TYPE).getNodeValue(); String quantity = attribMap.getNamedItem(QUANTITY).getNodeValue(); String unit = attribMap.getNamedItem(UNIT).getNodeValue(); if("seconds".equals(unit)){ precisionUnit = "s"; unit = "s"; } else if("hours".equals(unit)) { unit = "h"; } else if ("minutes".equals(unit)){ unit = "min"; } else { precisionUnit = "d"; if("days".equals(unit)){ unit = "d"; }else if("weeks".equals(unit)){ unit = "wk"; }else if("months".equals(unit)){ unit = "mo"; }else if("years".equals(unit)){ unit = "a"; } } Element deltaNode = hqmfXmlProcessor.getOriginalDoc().createElement("qdm:delta"); Element lowNode = hqmfXmlProcessor.getOriginalDoc().createElement("low"); lowNode.setAttribute(UNIT, unit); Element highNode = hqmfXmlProcessor.getOriginalDoc().createElement("high"); highNode.setAttribute(UNIT, unit); if(operatorType.startsWith("Greater Than")){ lowNode.setAttribute(VALUE, quantity); highNode.removeAttribute(UNIT); highNode.setAttribute(NULL_FLAVOR, "PINF"); if("Greater Than or Equal To".equals(operatorType)){ deltaNode.setAttribute("lowClosed", TRUE); } }else if("Equal To".equals(operatorType)){ deltaNode.setAttribute("lowClosed", TRUE); deltaNode.setAttribute("highClosed", TRUE); lowNode.setAttribute(VALUE, quantity); highNode.setAttribute(VALUE, quantity); }else if(operatorType.startsWith("Less Than")){ deltaNode.setAttribute("lowClosed", TRUE); lowNode.setAttribute(VALUE, "0"); highNode.setAttribute(VALUE, quantity); if("Less Than or Equal To".equals(operatorType)){ deltaNode.setAttribute("highClosed", TRUE); } } deltaNode.appendChild(lowNode); deltaNode.appendChild(highNode); temporalInfoNode.appendChild(deltaNode); } temporalInfoNode.setAttribute("precisionUnit", precisionUnit); temporallyRelatedInfoNode.appendChild(temporalInfoNode); return temporallyRelatedInfoNode; } /** * Generate crit ref rel op. * * @param parentNode the parent node * @param hqmfXmlProcessor the hqmf xml processor * @param childNode the child node * @param outboundRelElem the outbound rel elem * @throws XPathExpressionException the x path expression exception */ private void generateCritRefRelOp( Node parentNode, XmlProcessor hqmfXmlProcessor, Node childNode, Node outboundRelElem, String clauseName) throws XPathExpressionException { Node relOpEntryNode = generateRelOpHQMF(childNode,parentNode, clauseName); if(relOpEntryNode != null){ Node idNode = getTagFromEntry(relOpEntryNode, ID); //Node critNode = relOpEntryNode.getFirstChild(); //NodeList nodeList = ((Element)critNode).getElementsByTagName(ID); //if(nodeList != null && nodeList.getLength() > 0){ if(idNode != null){ //Node idNode = nodeList.item(0); NamedNodeMap idAttribMap = idNode.getAttributes(); String idRoot = idAttribMap.getNamedItem(ROOT).getNodeValue(); String idExt = idAttribMap.getNamedItem(EXTENSION).getNodeValue(); Node parent = idNode.getParentNode(); NamedNodeMap attribMap = parent.getAttributes(); String classCode = attribMap.getNamedItem(CLASS_CODE).getNodeValue(); String moodCode = attribMap.getNamedItem(MOOD_CODE).getNodeValue(); //create criteriaRef Element criteriaReference = hqmfXmlProcessor.getOriginalDoc().createElement(CRITERIA_REFERENCE); criteriaReference.setAttribute(CLASS_CODE, classCode); criteriaReference.setAttribute(MOOD_CODE, moodCode); Element id = hqmfXmlProcessor.getOriginalDoc().createElement(ID); id.setAttribute(ROOT, idRoot); id.setAttribute(EXTENSION, idExt); criteriaReference.appendChild(id); outboundRelElem.appendChild(criteriaReference); } } } /** * Generate crit ref set op. * * @param parentNode the parent node * @param hqmfXmlProcessor the hqmf xml processor * @param childNode the child node * @param outboundRelElem the outbound rel elem * @throws XPathExpressionException the x path expression exception */ private void generateCritRefSetOp( Node parentNode, XmlProcessor hqmfXmlProcessor, Node childNode, Node outboundRelElem, String clauseName) throws XPathExpressionException { Node setOpEntry = generateSetOpHQMF(childNode,parentNode, clauseName); NodeList childList = setOpEntry.getChildNodes(); for(int j=0;j<childList.getLength();j++){ Node child = childList.item(j); if(GROUPER_CRITERIA.equals(child.getNodeName())){ NodeList idChildList = ((Element)child).getElementsByTagName(ID); if(idChildList.getLength() > 0){ Node idChild = idChildList.item(0); NamedNodeMap attribMap = idChild.getAttributes(); String idRoot = attribMap.getNamedItem(ROOT).getNodeValue(); String idExt = attribMap.getNamedItem(EXTENSION).getNodeValue(); //create criteriaRef Element criteriaReference = hqmfXmlProcessor.getOriginalDoc().createElement(CRITERIA_REFERENCE); criteriaReference.setAttribute(CLASS_CODE, "GROUPER"); criteriaReference.setAttribute(MOOD_CODE, "EVN"); Element id = hqmfXmlProcessor.getOriginalDoc().createElement(ID); id.setAttribute(ROOT, idRoot); id.setAttribute(EXTENSION, idExt); criteriaReference.appendChild(id); outboundRelElem.appendChild(criteriaReference); } } } } /** * Generate crit ref for node. * * @param outboundRelElem the outbound rel elem * @param childNode the child node * @throws XPathExpressionException the x path expression exception */ private void generateCritRefForNode(Node outboundRelElem, Node childNode , String clauseName) throws XPathExpressionException { XmlProcessor hqmfXmlProcessor = measureExport.getHQMFXmlProcessor(); String childName = childNode.getNodeName(); switch(childName){ case ELEMENT_REF: generateCritRefElementRef( outboundRelElem, childNode,hqmfXmlProcessor); break; case SUB_TREE_REF: generateCritRefSubTreeRef(outboundRelElem, childNode, hqmfXmlProcessor, true); break; default: break; } } /** * This method will basically create a <criteriaReference> with classCode='GROUPER' and moodCode='EVN' * and have the <id> tag pointing to the <grouperCriteria> for the referenced subTree/clause. * * @param outboundRelElem the outbound rel elem * @param subTreeRefNode the sub tree ref node * @param hqmfXmlProcessor the hqmf xml processor * @throws XPathExpressionException the x path expression exception */ protected void generateCritRefSubTreeRef(Node outboundRelElem, Node subTreeRefNode, XmlProcessor hqmfXmlProcessor) throws XPathExpressionException { generateCritRefSubTreeRef(outboundRelElem, subTreeRefNode, hqmfXmlProcessor, false); } /** * This method will basically create a <criteriaReference> with classCode='GROUPER' and moodCode='EVN' * and have the <id> tag pointing to the <grouperCriteria> for the referenced subTree/clause. * * @param outboundRelElem the outbound rel elem * @param subTreeRefNode the sub tree ref node * @param hqmfXmlProcessor the hqmf xml processor * @param checkExisting check in the map if already existing * @throws XPathExpressionException the x path expression exception */ protected void generateCritRefSubTreeRef( Node outboundRelElem, Node subTreeRefNode, XmlProcessor hqmfXmlProcessor, boolean checkExisting) throws XPathExpressionException { String subTreeUUID = subTreeRefNode.getAttributes().getNamedItem(ID).getNodeValue(); String root = subTreeUUID; String xpath = "/measure/subTreeLookUp/subTree[@uuid='"+subTreeUUID+"']"; Node subTreeNode = measureExport.getSimpleXMLProcessor().findNode(measureExport.getSimpleXMLProcessor().getOriginalDoc(), xpath); if(subTreeNode != null ) { String isQdmVariable = subTreeNode.getAttributes() .getNamedItem(QDM_VARIABLE).getNodeValue(); Node firstChild = subTreeNode.getFirstChild(); String firstChildName = firstChild.getNodeName(); String ext = StringUtils.deleteWhitespace(firstChild.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue()); if(FUNCTIONAL_OP.equals(firstChildName) || RELATIONAL_OP.equals(firstChildName) || SET_OP.equals(firstChildName)){ ext += "_" + firstChild.getAttributes().getNamedItem(UUID).getNodeValue(); } String occText = null; // Handled Occurrence Of QDM Variable. if(subTreeNode.getAttributes().getNamedItem(INSTANCE_OF) != null){ occText = "occ"+subTreeNode.getAttributes().getNamedItem(INSTANCE).getNodeValue()+"of_"; } //if(subTreeNode.getAttributes().getNamedItem(INSTANCE_OF) == null) { if(ELEMENT_REF.equals(firstChildName) ){ ext = getElementRefExt(firstChild, measureExport.getSimpleXMLProcessor()); } else if(FUNCTIONAL_OP.equals(firstChildName)){ if(firstChild.getFirstChild() != null) { Node functionChild = firstChild.getFirstChild(); if(functionChild != null) { if (functionChild.getNodeName().equalsIgnoreCase(SUB_TREE_REF)) { ext = functionChild.getAttributes() .getNamedItem(ID).getNodeValue(); }else if(functionChild.getNodeName().equalsIgnoreCase(ELEMENT_REF)){ ext = getElementRefExt(functionChild, measureExport.getSimpleXMLProcessor()); }else{ ext = (StringUtils.deleteWhitespace(functionChild.getAttributes() .getNamedItem(DISPLAY_NAME).getNodeValue() + "_" + functionChild.getAttributes().getNamedItem(UUID).getNodeValue()) .replaceAll(":", "_")); } } } } if(TRUE.equalsIgnoreCase(isQdmVariable)){ if (occText != null) { ext = occText + "qdm_var_"+ext; } else { ext = "qdm_var_"+ext; } } /** * Check if the Clause has already been generated. * If it is not generated yet, then generate it by * calling the 'generateSubTreeXML' method. */ if(checkExisting && !subTreeNodeMap.containsKey(subTreeUUID)){ generateSubTreeXML( subTreeNode, false); } Node idNodeQDM = hqmfXmlProcessor.findNode(hqmfXmlProcessor.getOriginalDoc(), "//entry/*/id[@root='"+root+"'][@extension=\""+ext+"\"]"); if(idNodeQDM != null){ Node parent = idNodeQDM.getParentNode(); if(parent != null){ NamedNodeMap attribMap = parent.getAttributes(); String classCode = attribMap.getNamedItem(CLASS_CODE).getNodeValue(); String moodCode = attribMap.getNamedItem(MOOD_CODE).getNodeValue(); //create criteriaRef Element criteriaReference = hqmfXmlProcessor.getOriginalDoc().createElement(CRITERIA_REFERENCE); criteriaReference.setAttribute(CLASS_CODE, classCode); criteriaReference.setAttribute(MOOD_CODE, moodCode); Element id = hqmfXmlProcessor.getOriginalDoc().createElement(ID); id.setAttribute(ROOT, root); id.setAttribute(EXTENSION, ext); criteriaReference.appendChild(id); outboundRelElem.appendChild(criteriaReference); } }else{ Comment comment = hqmfXmlProcessor.getOriginalDoc().createComment("CHECK:Could not find an entry for subTree:"+"//entry/*/id[@root='"+root+"'][@extension='"+ext+"']"); outboundRelElem.appendChild(comment); } } } /** * Generate crit ref element ref. * * @param outboundRelElem the outbound rel elem * @param elementRefNode the element ref node * @param hqmfXmlProcessor the hqmf xml processor * @return the node * @throws XPathExpressionException the x path expression exception */ private Node generateCritRefElementRef( Node outboundRelElem, Node elementRefNode, XmlProcessor hqmfXmlProcessor) throws XPathExpressionException { String ext = getElementRefExt(elementRefNode, measureExport.getSimpleXMLProcessor()); String root = elementRefNode.getAttributes().getNamedItem(ID).getNodeValue(); Node idNodeQDM = hqmfXmlProcessor.findNode(hqmfXmlProcessor.getOriginalDoc(), "//entry/*/id[@root=\""+root+"\"][@extension=\""+ext+"\"]"); if(idNodeQDM != null){ Node parent = idNodeQDM.getParentNode(); if(parent != null){ NamedNodeMap attribMap = parent.getAttributes(); String classCode = attribMap.getNamedItem(CLASS_CODE).getNodeValue(); String moodCode = attribMap.getNamedItem(MOOD_CODE).getNodeValue(); //create criteriaRef Element criteriaReference = hqmfXmlProcessor.getOriginalDoc().createElement(CRITERIA_REFERENCE); criteriaReference.setAttribute(CLASS_CODE, classCode); criteriaReference.setAttribute(MOOD_CODE, moodCode); Element id = hqmfXmlProcessor.getOriginalDoc().createElement(ID); id.setAttribute(ROOT, root); id.setAttribute(EXTENSION, ext); criteriaReference.appendChild(id); outboundRelElem.appendChild(criteriaReference); //return <entry> element return parent.getParentNode(); } }else{ //check if this is a measurement period String displayName = elementRefNode.getAttributes().getNamedItem(DISPLAY_NAME).getNodeValue(); if("Measurement Period : Timing Element".equals(displayName)){ //create criteriaRef Element criteriaReference = hqmfXmlProcessor.getOriginalDoc().createElement(CRITERIA_REFERENCE); criteriaReference.setAttribute(CLASS_CODE, "OBS"); criteriaReference.setAttribute(MOOD_CODE, "EVN"); Element id = hqmfXmlProcessor.getOriginalDoc().createElement(ID); id.setAttribute(ROOT, elementRefNode.getAttributes().getNamedItem(ID).getNodeValue()); id.setAttribute(EXTENSION, "measureperiod"); criteriaReference.appendChild(id); outboundRelElem.appendChild(criteriaReference); } } return null; } /** * Generate item count element ref. * * @param me the me * @param populationTypeCriteriaElement the population type criteria element * @param elementRefNode the element ref node * @param hqmfXmlProcessor the hqmf xml processor * @throws XPathExpressionException the x path expression exception */ public void generateItemCountElementRef(MeasureExport me, Element populationTypeCriteriaElement, Node elementRefNode, XmlProcessor hqmfXmlProcessor) throws XPathExpressionException { String ext = getElementRefExt(elementRefNode, me.getSimpleXMLProcessor()); String root = elementRefNode.getAttributes().getNamedItem(ID).getNodeValue(); Node idNodeQDM = hqmfXmlProcessor.findNode(hqmfXmlProcessor.getOriginalDoc(), "//entry/*/id[@root='"+root+"'][@extension=\""+ext+"\"]"); if(idNodeQDM != null){ Node parent = idNodeQDM.getParentNode(); if(parent != null){ String classCode = parent.getAttributes().getNamedItem("classCode").getNodeValue(); String moodCode = parent.getAttributes().getNamedItem("moodCode").getNodeValue(); //item count Criteria Ref for Measure Observations if("measureObservationDefinition".equals(populationTypeCriteriaElement.getNodeName())){ Element componentOfElem = hqmfXmlProcessor.getOriginalDoc().createElement("componentOf"); componentOfElem.setAttribute(TYPE_CODE, "COMP"); Element criteriaRef = hqmfXmlProcessor.getOriginalDoc().createElement(CRITERIA_REFERENCE); criteriaRef.setAttribute(CLASS_CODE, classCode); criteriaRef.setAttribute(MOOD_CODE, moodCode); Element idElement = hqmfXmlProcessor.getOriginalDoc().createElement(ID); idElement.setAttribute(ROOT, root); idElement.setAttribute(EXTENSION, ext); criteriaRef.appendChild(idElement); componentOfElem.appendChild(criteriaRef); Comment comment = hqmfXmlProcessor.getOriginalDoc().createComment("Item Count "); populationTypeCriteriaElement.appendChild(comment); populationTypeCriteriaElement.appendChild(componentOfElem); } else { //item count Criteria Ref for Populations //create component for ItemCount ElmentRef Element componentElem = hqmfXmlProcessor.getOriginalDoc().createElement("component"); componentElem.setAttribute(TYPE_CODE, "COMP"); Element measureAttrElem = hqmfXmlProcessor.getOriginalDoc().createElement("measureAttribute"); componentElem.appendChild(measureAttrElem); Element codeElem = hqmfXmlProcessor.getOriginalDoc().createElement("code"); codeElem.setAttribute(CODE, "ITMCNT"); codeElem.setAttribute(CODE_SYSTEM, "2.16.840.1.113883.5.4"); codeElem.setAttribute(CODE_SYSTEM_NAME, "HL7 Observation Value"); Element displayNameElem = hqmfXmlProcessor.getOriginalDoc().createElement(DISPLAY_NAME); displayNameElem.setAttribute(VALUE, "Items to count"); codeElem.appendChild(displayNameElem); Element valueElem = hqmfXmlProcessor.getOriginalDoc().createElement(VALUE); valueElem.setAttribute("xsi:type", "II"); valueElem.setAttribute(ROOT, root); valueElem.setAttribute(EXTENSION, ext); measureAttrElem.appendChild(codeElem); measureAttrElem.appendChild(valueElem); populationTypeCriteriaElement.appendChild(componentElem); } } } } /** * Gets the element ref ext. * * @param elementRefNode the element ref node * @param simpleXmlProcessor the simple xml processor * @return the element ref ext * @throws XPathExpressionException the x path expression exception */ private String getElementRefExt(Node elementRefNode, XmlProcessor simpleXmlProcessor) throws XPathExpressionException { String extension = ""; if(elementRefNode.hasChildNodes()){ Node childNode = elementRefNode.getFirstChild(); if("attribute".equals(childNode.getNodeName())){ extension = childNode.getAttributes().getNamedItem(ATTR_UUID).getNodeValue(); } }else{ String id = elementRefNode.getAttributes().getNamedItem(ID).getNodeValue(); Node qdmNode = simpleXmlProcessor.findNode(simpleXmlProcessor.getOriginalDoc(), "/measure/elementLookUp/qdm[@uuid='"+id+"']"); if(qdmNode != null){ String dataType = qdmNode.getAttributes().getNamedItem(DATATYPE).getNodeValue(); String qdmName = qdmNode.getAttributes().getNamedItem(NAME).getNodeValue(); extension = qdmName + "_" + dataType; if(qdmNode.getAttributes().getNamedItem(INSTANCE) != null){ extension = qdmNode.getAttributes().getNamedItem(INSTANCE).getNodeValue() +"_" + extension; } } } return StringUtils.deleteWhitespace(extension); } /** * Generate empty grouper. * * @param hqmfXmlProcessor the hqmf xml processor * @param root the root * @param ext the ext * @return the node */ private Node generateEmptyGrouper(XmlProcessor hqmfXmlProcessor, String root, String ext) { Element grouperElem = hqmfXmlProcessor.getOriginalDoc().createElement(GROUPER_CRITERIA); grouperElem.setAttribute(CLASS_CODE, "GROUPER"); grouperElem.setAttribute(MOOD_CODE, "EVN"); Element idElem = hqmfXmlProcessor.getOriginalDoc().createElement(ID); idElem.setAttribute(ROOT, root); idElem.setAttribute(EXTENSION, StringUtils.deleteWhitespace(ext)); grouperElem.appendChild(idElem); return grouperElem; } /** * Generate empty outbound elem. * * @param hqmfXmlProcessor the hqmf xml processor * @return the element */ private Element generateEmptyOutboundElem(XmlProcessor hqmfXmlProcessor) { Element outboundRelElem = hqmfXmlProcessor.getOriginalDoc().createElement(OUTBOUND_RELATIONSHIP); outboundRelElem.setAttribute(TYPE_CODE, "COMP"); return outboundRelElem; } /** * Gets the tag from entry. * * @param entryElem the entry elem * @param tagName the tag name * @return the tag from entry */ private Node getTagFromEntry(Node entryElem, String tagName) { String entryElemName = entryElem.getNodeName(); if(ENTRY.equals(entryElemName)){ Node firstChild = entryElem.getFirstChild(); if(LOCAL_VARIABLE_NAME.equals(firstChild.getNodeName())){ NodeList nodeList = ((Element)firstChild.getNextSibling()).getElementsByTagName(tagName); if((nodeList != null) && (nodeList.getLength() > 0)){ return nodeList.item(0); } }else{ NodeList nodeList = ((Element)firstChild).getElementsByTagName(tagName); if((nodeList != null) && (nodeList.getLength() > 0)){ return nodeList.item(0); } } } return null; } /** * Check If the parentNode is a SUB_TREE node. * Or else, if parent is a 'functionalOp' then recursively check if the parentNode's parent * is a 'subTree'. * If yes, then return true. * * @param parentNode the parent node * @return boolean */ private Node checkIfSubTree(Node parentNode) { Node returnNode = null; if(parentNode != null){ String parentName = parentNode.getNodeName(); if(SUB_TREE.equals(parentName)){ returnNode = parentNode; }else if(FUNCTIONAL_OP.equals(parentName)){ returnNode = checkIfSubTree(parentNode.getParentNode()); } } return returnNode; } /** * Gets the firt child list. * * @param function the function * @return the firt child list */ public static List<String> getFunctionalOpFirstChild(String function) { List<String> childList = new ArrayList<String>(); if (AGE_AT.equalsIgnoreCase(function)) { childList.add(SUB_TREE_REF); childList.add(RELATIONAL_OP); childList.add(FUNCTIONAL_OP); childList.add(ELEMENT_REF); } else { childList.add(ELEMENT_REF); childList.add(SET_OP); childList.add(SUB_TREE_REF); childList.add(RELATIONAL_OP); } return childList; } /** * Gets the aggregate and instance function childs. * * @param typeChild the type child * @return the aggregate and instance function childs */ public static List<String> getAggregateAndInstanceFunctionChilds(String typeChild){ List<String> aggregateList = new ArrayList<String>(); aggregateList.add("FIRST"); aggregateList.add("SECOND"); aggregateList.add("THIRD"); aggregateList.add("FOURTH"); aggregateList.add("FIFTH"); aggregateList.add("MOST RECENT"); if ("AGGREGATE".equals(typeChild)) { aggregateList.add("DATETIMEDIFF"); } return aggregateList; } /** * Gets the functional op first child in mo. * * @param function the function * @return the functional op first child in mo */ public static List<String> getFunctionalOpFirstChildInMO(String function) { List<String> childList = new ArrayList<String>(); if ("DATETIMEDIFF".equalsIgnoreCase(function)) { childList.add(ELEMENT_REF); childList.add(SUB_TREE_REF); childList.add(RELATIONAL_OP); childList.addAll(getAggregateAndInstanceFunctionChilds("INSTANCE")); } else { childList.addAll(getFunctionalOpFirstChild(function)); childList.addAll(getAggregateAndInstanceFunctionChilds("AGGREGATE")); } return childList; } /** * Check for used Used sub tree ref Node map in Populations and Meausre Observations. */ private void createUsedSubTreeRefMap() { XmlProcessor simpleXmlProcessor = measureExport.getSimpleXMLProcessor(); String typeXpathString = ""; List<String> usedSubTreeRefIdsPop = new ArrayList<String>(); List<String> usedSubTreeRefIdsMO = new ArrayList<String>(); List<String> usedSubTreeRefIDsRA = new ArrayList<String>(); for (String typeString : POPULATION_NAME_LIST) { typeXpathString += "@type = '" + typeString + "' or"; } typeXpathString = typeXpathString.substring(0, typeXpathString.lastIndexOf(" or")); String xpathForSubTreeInPOPClause = "/measure/measureGrouping//clause[" + typeXpathString + "]//subTreeRef/@id"; String xpathForSubTreeInMOClause = "/measure/measureGrouping//clause[@type='measureObservation']//subTreeRef/@id"; String xpathForSubTreeInRAClause = "/measure//riskAdjustmentVariables/subTreeRef/@id"; try { //creating used Subtree Red Map in Populations NodeList populationsSubTreeNode = simpleXmlProcessor.findNodeList(simpleXmlProcessor.getOriginalDoc(), xpathForSubTreeInPOPClause); for(int i=0;i<populationsSubTreeNode.getLength();i++){ String uuid = populationsSubTreeNode.item(i).getNodeValue(); uuid = checkIfQDMVarInstanceIsPresent(uuid, simpleXmlProcessor); if(!usedSubTreeRefIdsPop.contains(uuid)){ usedSubTreeRefIdsPop.add(uuid); } } usedSubTreeRefIdsPop = checkUnUsedSubTreeRef(simpleXmlProcessor, usedSubTreeRefIdsPop); for (String uuid: usedSubTreeRefIdsPop) { Node subTreeNode = createUsedSubTreeRefMap(simpleXmlProcessor, uuid); subTreeNodeInPOPMap.put(uuid, subTreeNode); } //creating used Subtree Red Map in Measure Observations NodeList measureObsSubTreeNode = simpleXmlProcessor.findNodeList(simpleXmlProcessor.getOriginalDoc(), xpathForSubTreeInMOClause); for (int i=0;i<measureObsSubTreeNode.getLength();i++) { String uuid = measureObsSubTreeNode.item(i).getNodeValue(); uuid = checkIfQDMVarInstanceIsPresent(uuid, simpleXmlProcessor); if (!usedSubTreeRefIdsMO.contains(uuid)) { usedSubTreeRefIdsMO.add(uuid); } } usedSubTreeRefIdsMO = checkUnUsedSubTreeRef(simpleXmlProcessor, usedSubTreeRefIdsMO); for(String uuid: usedSubTreeRefIdsMO){ Node subTreeNode = createUsedSubTreeRefMap(simpleXmlProcessor, uuid); subTreeNodeInMOMap.put(uuid, subTreeNode); } //creating used Subtree Red in Risk Adjustment NodeList riskAdjSubTreeNode = simpleXmlProcessor.findNodeList(simpleXmlProcessor.getOriginalDoc(), xpathForSubTreeInRAClause); for (int i=0;i<riskAdjSubTreeNode.getLength();i++) { String uuid = riskAdjSubTreeNode.item(i).getNodeValue(); uuid = checkIfQDMVarInstanceIsPresent(uuid, simpleXmlProcessor); if (!usedSubTreeRefIDsRA.contains(uuid)) { usedSubTreeRefIDsRA.add(uuid); } } usedSubTreeRefIDsRA = checkUnUsedSubTreeRef(simpleXmlProcessor, usedSubTreeRefIDsRA); for(String uuid: usedSubTreeRefIDsRA){ Node subTreeNode = createUsedSubTreeRefMap(simpleXmlProcessor, uuid); subTreeNodeInRAMap.put(uuid, subTreeNode); } } catch (XPathExpressionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Creates the used sub tree ref map. * * @param simpleXmlProcessor the simple xml processor * @param uuid the uuid * @return the node */ private Node createUsedSubTreeRefMap(XmlProcessor simpleXmlProcessor, String uuid) { String xpathforUsedSubTreeMap ="/measure/subTreeLookUp/subTree[@uuid='"+uuid+"']"; Node subTreeNode = null; try { subTreeNode = simpleXmlProcessor.findNode(simpleXmlProcessor.getOriginalDoc(), xpathforUsedSubTreeMap); } catch (XPathExpressionException e) { e.printStackTrace(); } return subTreeNode; } /** * Check un used sub tree ref. * * @param xmlProcessor the xml processor * @param usedSubTreeRefIds the used sub tree ref ids * @return the list */ private List<String> checkUnUsedSubTreeRef(XmlProcessor xmlProcessor, List<String> usedSubTreeRefIds){ List<String> allSubTreeRefIds = new ArrayList<String>(); NodeList subTreeRefIdsNodeList; javax.xml.xpath.XPath xPath = XPathFactory.newInstance().newXPath(); try { subTreeRefIdsNodeList = xmlProcessor.findNodeList(xmlProcessor.getOriginalDoc(), "/measure//subTreeRef/@id"); for (int i = 0; i < subTreeRefIdsNodeList.getLength(); i++) { Node SubTreeRefIdAttributeNode = subTreeRefIdsNodeList.item(i); if (!allSubTreeRefIds.contains(SubTreeRefIdAttributeNode .getNodeValue())) { allSubTreeRefIds.add(SubTreeRefIdAttributeNode.getNodeValue()); } } allSubTreeRefIds.removeAll(usedSubTreeRefIds); for (int i = 0; i < usedSubTreeRefIds.size(); i++) { for (int j = 0; j < allSubTreeRefIds.size(); j++) { Node usedSubTreeRefNode = xmlProcessor.findNode(xmlProcessor.getOriginalDoc(), "/measure/subTreeLookUp/subTree[@uuid='" + usedSubTreeRefIds.get(i) + "']//subTreeRef[@id='" + allSubTreeRefIds.get(j) + "']"); if (usedSubTreeRefNode != null) { String subTreeUUID = usedSubTreeRefNode.getAttributes().getNamedItem(ID).getNodeValue(); String XPATH_IS_INSTANCE_OF = "//subTree [boolean(@instanceOf)]/@uuid ='" + subTreeUUID +"'"; boolean isOccurrenceNode = (Boolean) xPath.evaluate(XPATH_IS_INSTANCE_OF, xmlProcessor.getOriginalDoc(), XPathConstants.BOOLEAN); if(isOccurrenceNode) { String XPATH_PARENT_UUID = "//subTree [@uuid ='"+subTreeUUID +"']/@instanceOf"; String parentUUID = (String) xPath.evaluate(XPATH_PARENT_UUID, xmlProcessor.getOriginalDoc(), XPathConstants.STRING); if (!usedSubTreeRefIds.contains(parentUUID)) { usedSubTreeRefIds.add(parentUUID); } } if (!usedSubTreeRefIds.contains(allSubTreeRefIds.get(j))) { usedSubTreeRefIds.add(allSubTreeRefIds.get(j)); } } } } } catch (XPathExpressionException e) { // TODO Auto-generated catch block e.printStackTrace(); } return usedSubTreeRefIds; } /** * Validate sub tree ref in pop. * * @param subTreeNode the sub tree node * @param functionalOpNode the functional op node * @return true, if successful */ public boolean validateSubTreeRefInPOP(Node subTreeNode, Node functionalOpNode){ if(subTreeNodeInPOPMap.get(subTreeNode.getAttributes() .getNamedItem(UUID).getNodeValue())!=null){ String firstChildName = functionalOpNode.getFirstChild().getNodeName(); String functionalOpType = functionalOpNode.getAttributes().getNamedItem(TYPE).getNodeValue(); List<String> childsList = FUNCTIONAL_OP_RULES_IN_POP.get(functionalOpType); if(childsList.contains(firstChildName)){ return true; } } return false; } /** * Utility method which will try to find the tag "localVariableName" and set the given string value to its * VALUE attribute. * @param node * @param localVarName */ private void updateLocalVar(Node node, String localVarName) { if(node == null){ return; } NodeList localVarNodeList = ((Element)node).getElementsByTagName(LOCAL_VARIABLE_NAME); if((localVarNodeList != null) && (localVarNodeList.getLength() > 0)){ Element localVar = (Element) localVarNodeList.item(0); localVar.setAttribute(VALUE, localVarName); } } /** * Check if qdm var instance is present. * * @param usedSubtreeRefId the used subtree ref id * @param xmlProcessor the xml processor * @return the string */ private String checkIfQDMVarInstanceIsPresent(String usedSubtreeRefId, XmlProcessor xmlProcessor){ String XPATH_INSTANCE_QDM_VAR = "/measure/subTreeLookUp/subTree[@uuid='"+usedSubtreeRefId+"']/@instance"; String XPATH_INSTANCE_OF_QDM_VAR = "/measure/subTreeLookUp/subTree[@uuid='"+usedSubtreeRefId+"']/@instanceOf"; try { Node nodesSDE_SubTree = xmlProcessor.findNode(xmlProcessor.getOriginalDoc(), XPATH_INSTANCE_QDM_VAR); if(nodesSDE_SubTree!=null){ Node nodesSDE_SubTreeInstance = xmlProcessor.findNode(xmlProcessor.getOriginalDoc(), XPATH_INSTANCE_OF_QDM_VAR); usedSubtreeRefId = nodesSDE_SubTreeInstance.getNodeValue(); } } catch (XPathExpressionException e) { // TODO Auto-generated catch block e.printStackTrace(); } return usedSubtreeRefId; } /** * @return the subTreeNodeMap */ public Map<String, Node> getSubTreeNodeMap() { return subTreeNodeMap; } /** * @param subTreeNodeMap the subTreeNodeMap to set */ public void setSubTreeNodeMap(Map<String, Node> subTreeNodeMap) { this.subTreeNodeMap = subTreeNodeMap; } /** * @return the measureExport */ public MeasureExport getMeasureExport() { return measureExport; } /** * @param measureExport the measureExport to set */ public void setMeasureExport(MeasureExport measureExport) { this.measureExport = measureExport; } /** * @return the subTreeNodeInMOMap */ public Map<String, Node> getSubTreeNodeInMOMap() { return subTreeNodeInMOMap; } /** * @param subTreeNodeInMOMap the subTreeNodeInMOMap to set */ public void setSubTreeNodeInMOMap(Map<String, Node> subTreeNodeInMOMap) { this.subTreeNodeInMOMap = subTreeNodeInMOMap; } /** * @return the subTreeNodeInMOMap */ public Map<String, Node> getSubTreeNodeInRAMap() { return subTreeNodeInRAMap; } /** * @param subTreeNodeInMOMap the subTreeNodeInMOMap to set */ public void setSubTreeNodeInRAMap(Map<String, Node> subTreeNodeInRAMap) { this.subTreeNodeInRAMap = subTreeNodeInRAMap; } /** * @return the subTreeNodeInPOPMap */ public Map<String, Node> getSubTreeNodeInPOPMap() { return subTreeNodeInPOPMap; } /** * @param subTreeNodeInPOPMap the subTreeNodeInPOPMap to set */ public void setSubTreeNodeInPOPMap(Map<String, Node> subTreeNodeInPOPMap) { this.subTreeNodeInPOPMap = subTreeNodeInPOPMap; } }
package org.animotron.exist.interpreter; import org.animotron.Keywords; import org.animotron.Namespaces; import org.exist.dom.NewArrayNodeSet; import org.exist.dom.NodeProxy; import org.exist.dom.NodeSet; import org.exist.dom.QName; import org.exist.memtree.NodeImpl; import org.exist.xquery.XPathException; import org.exist.xquery.value.SequenceIterator; import org.exist.xquery.value.Type; import org.w3c.dom.Node; /** * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> * */ public class Animo { public NodeSet process(NodeSet flow) throws XPathException { return process(flow, null); } public NodeSet process(NodeSet flow, NodeSet context) throws XPathException { return process(flow, null, context, null, null); } private NodeSet process(NodeSet flow, NodeSet stackFlow, NodeSet context, NodeSet stackContext, NodeSet source) throws XPathException { NodeSet res = new NewArrayNodeSet(); SequenceIterator i = flow.iterate(); while (i.hasNext()) { NodeImpl input = (NodeImpl) i.nextItem(); NodeSet set = process(input, stackFlow, context, stackContext, source); res.addAll(set); } return res; } private NodeSet process(NodeImpl input, NodeSet stackFlow, NodeSet context, NodeSet stackContext, NodeSet source) throws XPathException { switch (input.getType()) { case Type.ELEMENT: { String ns = input.getNamespaceURI(); if (ns.equals(Namespaces.AN.namespace())) { String name = input.getLocalName(); if (name.equals(Keywords.AN_EMPTY.keyword())) { // TODO: process an:empty } else if (name.equals(Keywords.AN_SELF.keyword())) { // TODO: process an:self } else if (name.equals(Keywords.AN_CONTENT.keyword())) { // TODO: process an:content } else { // TODO: process an:* } } else if (ns.equals(Namespaces.ANY.namespace())) { // TODO: process any:* } else if (ns.equals(Namespaces.ALL.namespace())) { // TODO: process all:* } else if (ns.equals(Namespaces.PTRN.namespace())) { // TODO: process ptrn:* } else if (ns.equals(Namespaces.GET.namespace())) { // TODO: process get:* } else if (ns.equals(Namespaces.SELF.namespace())) { if (input.getLocalName().equals( Keywords.SELF_INSTANCE.keyword())) { // process self:instance // return local-name() as text() } else { // TODO: process self:* } } else if (ns.equals(Namespaces.IC.namespace())) { // skip ic:* // return input as is return (NodeSet) input; } else { QName keyword = input.getQName(); if (keyword.equals(Keywords.DO_SKIP.QName())) { // TODO: process do:skip } else if (keyword.equals(Keywords.DO_XQUERY.QName())) { // TODO: process do:xquery } else if (keyword.equals(Keywords.DO_XSLT.QName())) { // TODO: process do:xslt } else if (keyword.equals(Keywords.USE_FLOW_STACK.QName())) { // TODO: process use:flow-stack } else if (keyword.equals(Keywords.USE_CONTEXT_STACK.QName())) { // TODO: process use:stack } else if (keyword.equals(Keywords.USE_LOCAL_CONTEXT.QName())) { // TODO: process use:context } else if (keyword.equals(Keywords.USE_CONTEXT.QName())) { // TODO: process use:CONTEXT } else if (keyword.equals(Keywords.USE_GLOBAL_CONTEXT.QName())) { // TODO: process use:repository } else { // process element() Node node = input.getNode(); return process(node, stackFlow, context, stackContext, source); } } } default: // process node() return (NodeSet) input; } } private NodeSet process(Node input, NodeSet stackFlow, NodeSet context, NodeSet stackContext, NodeSet source) throws XPathException { return null; } }
package org.animotron.graph; import org.neo4j.graphdb.RelationshipType; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * */ public enum RelationshipTypes implements RelationshipType { REF, RESULT }
package org.neu.ccs.mechanical_turk; import java.applet.Applet; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.MouseInfo; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import javax.imageio.ImageIO; import javax.swing.JApplet; import javax.swing.JOptionPane; /** * * @author Yaseen Alkhafaji <alkhafaji.yaseen@gmail.com> * @author Michael Barbini * */ public class TurkApplet extends JApplet implements MouseListener { private Timer timer; private TimerTask task; private Point press, release; private URL imgURL; private BufferedImage img; private ArrayList<Pair> boxCoordinates; private ArrayList<String> queries; public void init() { timer = new Timer(); addMouseListener(this); boxCoordinates = new ArrayList<>(); queries = new ArrayList<>(); String urlParam; try { urlParam = getParameter("imgURL"); } catch (NullPointerException npe) { urlParam = null; } String defaultUrl = "http://images.media-allrecipes.com/userphotos/250x250/00/64/20/642001.jpg", url = (urlParam == null || urlParam.isEmpty() ? defaultUrl : urlParam); loadImage(url); //will we need to receive any parameters? } public void paint(Graphics g) { super.paint(g); drawImage(img, g); checkAndDrawRect(g); } @Override public void mouseClicked(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} @Override public void mousePressed(MouseEvent e) { press = getMousePosition(); task = new Updater(); timer.scheduleAtFixedRate(task, 0, 10); } @Override public void mouseReleased(MouseEvent e) { task.cancel(); String query = JOptionPane.showInputDialog(this, "Natural Language Query?"); queries.add(query); boxCoordinates.add(new Pair(press, release)); press = null; release = null; } private class Updater extends TimerTask { @Override public void run() { release = getMousePosition(); repaint(); } } private class Pair { private Point start; // starting point (not necessarily top left) private Point end; // ending point (not necessarily bottom right) public Pair(Point s, Point e) { start = s; end = e; } public Point getStart() { return start; } public Point getEnd() { return end; } } private void checkAndDrawRect(Graphics g) { g.setColor(Color.green); for (Pair rect : boxCoordinates) drawRect(g, rect.getStart(), rect.getEnd()); if (press != null && release != null) { drawRect(g, press, release); } } private void drawRect(Graphics g, Point start, Point end) { Point press = start, release = end; int topLeftX = (int) Math.min(press.getX(), release.getX()), topLeftY = (int) Math.min(press.getY(), release.getY()), width = (int) Math.abs(press.getX() - release.getX()), height = (int) Math.abs(press.getY() - release.getY()); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.drawRect(topLeftX, topLeftY, width, height); } private void loadImage(String URL) { try { imgURL = new URL(URL); img = ImageIO.read(imgURL); } catch (IOException e) { System.out.println("Image loading failed... Stack Trace below"); e.printStackTrace(); } } private void drawImage(BufferedImage img, Graphics g) { g.drawImage(img, 0, 0, null); } public void undo() { boxCoordinates.remove(boxCoordinates.size()-1); queries.remove(queries.size()-1); } public ArrayList<String> getQueries() { return queries; } public ArrayList<Pair> getBoxCoords() { return this.boxCoordinates; } }
package org.ethereum.db; import static org.iq80.leveldb.impl.Iq80DBFactory.factory; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.ethereum.config.SystemProperties; import org.iq80.leveldb.CompressionType; import org.iq80.leveldb.DB; import org.iq80.leveldb.DBIterator; import org.iq80.leveldb.Options; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DatabaseImpl implements Database { private static Logger logger = LoggerFactory.getLogger(DatabaseImpl.class); private DB db; private String name; public DatabaseImpl(String name) { // Initialize Database this.name = name; Options options = new Options(); options.createIfMissing(true); options.compressionType(CompressionType.NONE); try { logger.debug("Opening database"); File dbLocation = new File(System.getProperty("user.dir") + "/" + SystemProperties.CONFIG.databaseDir() + "/"); File fileLocation = new File(dbLocation, name); if(SystemProperties.CONFIG.databaseReset()) { destroyDB(fileLocation); } logger.debug("Initializing new or existing DB: '" + name + "'"); db = factory.open(fileLocation, options); // logger.debug("Showing database stats"); // String stats = DATABASE.getProperty("leveldb.stats"); // logger.debug(stats); } catch (IOException ioe) { logger.error(ioe.getMessage(), ioe); throw new RuntimeException("Can't initialize database"); } } public void destroyDB(File fileLocation) { logger.debug("Destroying existing DB"); Options options = new Options(); try { factory.destroy(fileLocation, options); } catch (IOException e) { logger.error(e.getMessage(), e); } } /** Get object (key) -> value */ public byte[] get(byte[] key) { return db.get(key); } /** Insert object(value) (key = sha3(value)) */ public void put(byte[] key, byte[] value) { db.put(key, value); } /** Delete object (key) from db **/ public void delete(byte[] key) { db.delete(key); } public DBIterator iterator() { return db.iterator(); } public DB getDb() { return this.db; } @Override public void close() { try { logger.info("Release DB: {}", name); db.close(); } catch (IOException e) { logger.error("failed to find the db file on the close: {} ", name); } } public List<ByteArrayWrapper> dumpKeys() { DBIterator iterator = getDb().iterator(); ArrayList<ByteArrayWrapper> keys = new ArrayList<ByteArrayWrapper>(); while (iterator.hasNext()) { ByteArrayWrapper key = new ByteArrayWrapper(iterator.next().getKey()); keys.add(key); } Collections.sort((List<ByteArrayWrapper>) keys); return keys; } }
package edu.wustl.query.action; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.hibernate.HibernateException; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.querysuite.queryobject.IParameterizedQuery; import edu.wustl.common.querysuite.queryobject.impl.ParameterizedQuery; import edu.wustl.common.security.PrivilegeCache; import edu.wustl.common.security.PrivilegeManager; import edu.wustl.common.security.PrivilegeUtility; import edu.wustl.common.util.Permissions; import edu.wustl.common.util.dbManager.HibernateUtility; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.query.actionForm.SaveQueryForm; import edu.wustl.query.flex.dag.DAGConstant; import edu.wustl.query.util.global.Constants; import gov.nih.nci.security.authorization.domainobjects.ProtectionElement; import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup; import gov.nih.nci.security.authorization.domainobjects.User; import gov.nih.nci.security.dao.ProtectionElementSearchCriteria; import gov.nih.nci.security.exceptions.CSException; import gov.nih.nci.security.exceptions.CSObjectNotFoundException; /** * @author chetan_patil * @created September 12, 2007, 10:24:05 PM */ public class RetrieveQueryAction extends Action { @Override public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward actionForward = null; String message = null; try { HttpSession session = request.getSession(); removeAttributesFromSession(session); SaveQueryForm saveQueryForm = (SaveQueryForm) actionForm; Collection<IParameterizedQuery> parameterizedQueryCollection = HibernateUtility .executeHQL(HibernateUtility.GET_PARAMETERIZED_QUERIES_DETAILS); PrivilegeCache privilegeCache = setPrivilegeCache(session); Collection<IParameterizedQuery> authorizedQueryCollection = new ArrayList<IParameterizedQuery>(); Collection<IParameterizedQuery> sharedQueryCollection = new ArrayList<IParameterizedQuery>(); message = initializeParameterizeQueryCollection(request, saveQueryForm, parameterizedQueryCollection, privilegeCache, authorizedQueryCollection, sharedQueryCollection); setErrorMessages(request, message); actionForward = setActionForward(actionMapping, (String) request.getAttribute("pageOf")); } catch (HibernateException hibernateException) { actionForward = actionMapping.findForward(Constants.FAILURE); } request.setAttribute(Constants.POPUP_MESSAGE, ApplicationProperties .getValue("query.confirmBox.message")); return actionForward; } private String initializeParameterizeQueryCollection(HttpServletRequest request, SaveQueryForm saveQueryForm, Collection<IParameterizedQuery> parameterizedQueryCollection, PrivilegeCache privilegeCache, Collection<IParameterizedQuery> authorizedQueryCollection, Collection<IParameterizedQuery> sharedQueryCollection) throws CSException, CSObjectNotFoundException { String message; if (parameterizedQueryCollection == null) { saveQueryForm.setParameterizedQueryCollection(new ArrayList<IParameterizedQuery>()); message = "No"; } else { checkExecuteQueryPrivilege(parameterizedQueryCollection, (String) request.getAttribute("pageOf"), privilegeCache, authorizedQueryCollection, sharedQueryCollection); setQueryCollectionToSaveQueryForm(saveQueryForm, (String) request.getAttribute("pageOf"), authorizedQueryCollection, sharedQueryCollection); message = authorizedQueryCollection.size() + ""; } return message; } private PrivilegeCache setPrivilegeCache(HttpSession session) throws CSException { SessionDataBean sessionDataBean = (SessionDataBean)session.getAttribute(Constants.SESSION_DATA); User user = new PrivilegeUtility().getUserProvisioningManager().getUser(sessionDataBean.getUserName()); sessionDataBean.setCsmUserId(user.getUserId().toString()); PrivilegeCache privilegeCache = PrivilegeManager.getInstance().getPrivilegeCache(sessionDataBean.getUserName()); return privilegeCache; } private ActionForward setActionForward(ActionMapping actionMapping, String pageOf) { ActionForward actionForward; actionForward = actionMapping.findForward(Constants.SUCCESS); //for displaying in work flow pop up if(pageOf!=null&&(Constants.MY_QUERIES_FOR_WORKFLOW.equals(pageOf) ||Constants.PUBLIC_QUERIES_FOR_WORKFLOW.equals(pageOf))) { actionForward = actionMapping.findForward(Constants.DISPLAY_QUERIES_IN_POPUP); } else if(pageOf!= null&& (Constants.PUBLIC_QUERY_PROTECTION_GROUP.equals(pageOf)|| Constants.PAGE_OF_MY_QUERIES.equals(pageOf))) { actionForward = actionMapping.findForward(Constants.MY_QUERIES); } return actionForward; } private void setErrorMessages(HttpServletRequest request, String message) { ActionMessages actionMessages = new ActionMessages(); ActionMessage actionMessage = new ActionMessage("query.resultFound.message", message); actionMessages.add(ActionMessages.GLOBAL_MESSAGE, actionMessage); saveMessages(request, actionMessages); } private void checkExecuteQueryPrivilege( Collection<IParameterizedQuery> parameterizedQueryCollection, String pageOf, PrivilegeCache privilegeCache, Collection<IParameterizedQuery> authorizedQueryCollection, Collection<IParameterizedQuery> sharedQueryCollection) throws CSException, CSObjectNotFoundException { for(IParameterizedQuery parameterizedQuery : parameterizedQueryCollection) { String objectId = ((ParameterizedQuery)parameterizedQuery).getObjectId(); if(privilegeCache.hasPrivilege(objectId, Permissions.EXECUTE_QUERY)) { boolean sharedQuery = setSharedQueriesCollection(sharedQueryCollection, parameterizedQuery, objectId); if(!sharedQuery) { authorizedQueryCollection.add(parameterizedQuery); } } } } private void removeAttributesFromSession(HttpSession session) { session.removeAttribute(Constants.SELECTED_COLUMN_META_DATA); session.removeAttribute(Constants.SAVE_GENERATED_SQL); session.removeAttribute(Constants.SAVE_TREE_NODE_LIST); session.removeAttribute(Constants.ID_NODES_MAP); session.removeAttribute(Constants.MAIN_ENTITY_MAP); session.removeAttribute(Constants.EXPORT_DATA_LIST); session.removeAttribute(Constants.ENTITY_IDS_MAP); session.removeAttribute(DAGConstant.TQUIMap); } private void setQueryCollectionToSaveQueryForm(SaveQueryForm saveQueryForm, String pageOf, Collection<IParameterizedQuery> authorizedQueryCollection, Collection<IParameterizedQuery> sharedQueryCollection) { if(pageOf !=null && (Constants.PUBLIC_QUERY_PROTECTION_GROUP.equals(pageOf)|| Constants.PUBLIC_QUERIES_FOR_WORKFLOW.equals(pageOf))) { saveQueryForm.setParameterizedQueryCollection(sharedQueryCollection); } else { saveQueryForm.setParameterizedQueryCollection(authorizedQueryCollection); } } private boolean setSharedQueriesCollection( Collection<IParameterizedQuery> sharedQueryCollection, IParameterizedQuery parameterizedQuery, String objectId) throws CSException, CSObjectNotFoundException { ProtectionElement pe = new ProtectionElement(); List<ProtectionElement> peList = new ArrayList<ProtectionElement>(); PrivilegeUtility privilegeUtility = new PrivilegeUtility(); pe.setObjectId(objectId); ProtectionElementSearchCriteria searchCriteria = new ProtectionElementSearchCriteria(pe); peList = privilegeUtility.getUserProvisioningManager().getObjects(searchCriteria); boolean sharedQuery = false; if (peList != null && !peList.isEmpty()) { pe = peList.get(0); } Set<ProtectionGroup> pgSet = privilegeUtility.getUserProvisioningManager().getProtectionGroups(pe.getProtectionElementId().toString()); sharedQuery = populateSharedQueryCollection(sharedQueryCollection, parameterizedQuery, pgSet); return sharedQuery; } private boolean populateSharedQueryCollection( Collection<IParameterizedQuery> sharedQueryCollection, IParameterizedQuery parameterizedQuery, Set<ProtectionGroup> pgSet) { boolean sharedQuery=false; for(ProtectionGroup pg : pgSet) { if(pg.getProtectionGroupName().equals(Constants.PUBLIC_QUERY_PROTECTION_GROUP)) { sharedQueryCollection.add(parameterizedQuery); sharedQuery = true; } } return sharedQuery; } }
package com.kuxhausen.huemore.net; import android.util.Pair; import com.kuxhausen.huemore.state.BulbState; import com.kuxhausen.huemore.state.Event; import com.kuxhausen.huemore.state.Group; import com.kuxhausen.huemore.state.Mood; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * used to store activity data about an ongoing mood and format the data for consumption by * visualizations/notifications */ public class PlayingMood { private Mood mMood; private String mMoodName; private Group mGroup; /** * In elapsed realtime milliseconds */ private long mStartTime; /** * In elapsed realtime milliseconds */ private long mLastTickedTime; /** * @param startTime in elapsed realtime milliseconds (may be negative) * @param dayStartTime in elapsed realtime milliseconds (may be negative) */ public PlayingMood(Mood m, String moodName, Group g, long startTime, long dayStartTime, Long internalProgress) { if (m == null || g == null) { throw new IllegalArgumentException(); } mMood = m; if (moodName != null) { mMoodName = moodName; } else { mMoodName = "?"; } mGroup = g; if (m.getTimeAddressingRepeatPolicy()) { mStartTime = dayStartTime; long[] lastTickedTimePerChannel = new long[m.getNumChannels()]; Arrays.fill(lastTickedTimePerChannel, dayStartTime - 1); for (int numCycles = -1; numCycles < 1; numCycles++) { for (Event e : m.getEvents()) { long adjustedEventTime = e.getMilliTime() + dayStartTime + (numCycles * m.getLoopMilliTime()); if (adjustedEventTime < lastTickedTimePerChannel[e.getChannel()]) { lastTickedTimePerChannel[e.getChannel()] = adjustedEventTime; } } } mLastTickedTime = dayStartTime - 1; for (long i : lastTickedTimePerChannel) { mLastTickedTime = Math.min(mLastTickedTime - 1, i); } } else { mStartTime = startTime; mLastTickedTime = startTime - 1; } if (internalProgress != null) { mLastTickedTime = internalProgress; } } public long getStartTime() { return mStartTime; } public long getInternalProgress() { return mLastTickedTime; } private List<Long> getChannelBulbIds(int channelNum) { ArrayList<Long> channel = new ArrayList<Long>(); List<Long> bulbBaseIds = mGroup.getNetworkBulbDatabaseIds(); for (int i = 0; i < bulbBaseIds.size(); i++) { if (i % mMood.getNumChannels() == channelNum) { channel.add(bulbBaseIds.get(i)); } } return channel; } public boolean hasFutureEvents() { if (mMood.getEvents().length == 0) { return false; } if (mMood.getTimeAddressingRepeatPolicy()) { return true; } if (mMood.isInfiniteLooping()) { return true; } if ((mMood.getEvents()[mMood.getEvents().length - 1].getMilliTime() + mStartTime) > mLastTickedTime) { return true; } return false; } /** * @return anticipated tme of the next event, calculated in elapsed realtime milliseconds */ public long getNextEventInCurrentMillis() { if (!hasFutureEvents()) { throw new IllegalStateException(); } if (mMood.isInfiniteLooping()) { long cycleStart = mStartTime + ((mLastTickedTime - mStartTime) / mMood.getLoopMilliTime()) * mMood.getLoopMilliTime(); for (int numCycles = 0; numCycles < 2; numCycles++) { for (Event e : mMood.getEvents()) { if (e.getMilliTime() + cycleStart + (numCycles * mMood.getLoopMilliTime()) > mLastTickedTime) { return e.getMilliTime() + cycleStart + (numCycles * mMood.getLoopMilliTime()); } } } } else { for (Event e : mMood.getEvents()) { if (e.getMilliTime() + mStartTime > mLastTickedTime) { return e.getMilliTime() + mStartTime; } } } throw new IllegalStateException(); } /** * @param sinceTime in elapsed realtime milliseconds * @param throughTime in elapsed realtime milliseconds */ public List<Pair<List<Long>, BulbState>> getEventsSinceThrough(long sinceTime, long throughTime) { List<Pair<List<Long>, BulbState>> result = new ArrayList<Pair<List<Long>, BulbState>>(); if (mMood.getTimeAddressingRepeatPolicy()) { int priorLoops = (int) Math.floor(((double) (sinceTime - mStartTime)) / mMood.getLoopMilliTime()); for (int numCycles = priorLoops; mStartTime + (numCycles * mMood.getLoopMilliTime()) <= throughTime; numCycles++) { for (Event e : mMood.getEvents()) { if (sinceTime < (e.getMilliTime() + mStartTime + (numCycles * mMood.getLoopMilliTime())) && (e.getMilliTime() + mStartTime + (numCycles * mMood.getLoopMilliTime())) <= throughTime) { result.add(new Pair<List<Long>, BulbState>(getChannelBulbIds(e.getChannel()), e.getBulbState())); } } } } else if (mMood.isInfiniteLooping()) { int priorLoops = (int) Math.max(0, (sinceTime - mStartTime) / mMood.getLoopMilliTime()); for (int numCycles = priorLoops; mStartTime + (numCycles * mMood.getLoopMilliTime()) <= throughTime; numCycles++) { for (Event e : mMood.getEvents()) { if (sinceTime < (e.getMilliTime() + mStartTime + (numCycles * mMood.getLoopMilliTime())) && (e.getMilliTime() + mStartTime + (numCycles * mMood.getLoopMilliTime())) <= throughTime) { result.add(new Pair<List<Long>, BulbState>(getChannelBulbIds(e.getChannel()), e.getBulbState())); } } } } else { for (Event e : mMood.getEvents()) { if (sinceTime < (e.getMilliTime() + mStartTime) && (e.getMilliTime() + mStartTime) <= throughTime) { result.add( new Pair<List<Long>, BulbState>(getChannelBulbIds(e.getChannel()), e.getBulbState())); } } } return result; } /** * @param throughTime in elapsed realtime milliseconds */ public List<Pair<List<Long>, BulbState>> tick(long throughTime) { if (throughTime < mLastTickedTime) { throw new IllegalArgumentException(); } long sinceT = mLastTickedTime; long throughT = throughTime; mLastTickedTime = throughTime; return getEventsSinceThrough(sinceT, throughT); } public String getMoodName() { return mMoodName; } public String getGroupName() { return mGroup.getName(); } public String toString() { return getGroupName() + " \u2190 " + getMoodName(); } public Group getGroup() { return mGroup; } public Mood getMood() { return mMood; } }
package org.basex.query.util.pkg; import static org.basex.query.QueryText.*; import static org.basex.query.util.Err.*; import static org.basex.util.Token.*; import java.lang.reflect.*; import java.net.*; import java.util.*; import org.basex.core.*; import org.basex.io.*; import org.basex.query.*; import org.basex.query.util.pkg.Package.Component; import org.basex.query.util.pkg.Package.Dependency; import org.basex.util.*; import org.basex.util.hash.*; public final class ModuleLoader { /** Default class loader. */ private static final ClassLoader LOADER = Thread.currentThread().getContextClassLoader(); /** Cached URLs to be added to the class loader. */ private final ArrayList<URL> urls = new ArrayList<URL>(); /** Current class loader. */ private ClassLoader loader = LOADER; /** Java modules. */ private HashMap<Object, ArrayList<Method>> javaModules; /** Database context. */ private final Context context; /** * Constructor. * @param ctx database context */ public ModuleLoader(final Context ctx) { context = ctx; } /** * Closes opened jar files. */ public void close() { if(loader instanceof JarLoader) ((JarLoader) loader).close(); } /** * Adds a package from the repository or a Java class. * @param uri module uri * @param ii input info * @param qp query parser * @return if the package has been found * @throws QueryException query exception */ public boolean addImport(final byte[] uri, final InputInfo ii, final QueryParser qp) throws QueryException { // add EXPath package final TokenSet pkgs = context.repo.nsDict().get(uri); if(pkgs != null) { Version ver = null; byte[] nm = null; for(final byte[] name : pkgs) { final Version v = new Version(Package.version(name)); if(ver == null || v.compareTo(ver) > 0) { ver = v; nm = name; } } if(nm != null) { addRepo(nm, new TokenSet(), new TokenSet(), ii, qp); return true; } } // search module in repository: rewrite URI to file path final boolean java = startsWith(uri, JAVAPREF); String uriPath = uri2path(string(java ? substring(uri, JAVAPREF.length) : uri)); if(uriPath == null) return false; if(!java) { // no "java:" prefix: first try to import module as XQuery final String path = context.mprop.get(MainProp.REPOPATH) + uriPath; // check for any file with XQuery suffix for(final String suf : IO.XQSUFFIXES) { if(addModule(new IOFile(path + suf), uri, qp)) return true; } } // "java:" prefix, or no XQuery package found: try to load Java module uriPath = capitalize(uriPath); final String path = context.mprop.get(MainProp.REPOPATH) + uriPath; final IOFile file = new IOFile(path + IO.JARSUFFIX); if(file.exists()) addURL(file); // try to create Java class instance addJava(uriPath, uri, ii); return true; } /** * Returns a reference to the specified class. * @param clz fully classified class name * @return found class, or {@code null} * @throws Throwable any exception or error: {@link ClassNotFoundException}, * {@link LinkageError} or {@link ExceptionInInitializerError}. */ public Class<?> findClass(final String clz) throws Throwable { // add cached URLs to class loader final int us = urls.size(); if(us != 0) { loader = new JarLoader(urls.toArray(new URL[us]), loader); urls.clear(); } // no external classes added: use default class loader return loader == LOADER ? Reflect.forName(clz) : Class.forName(clz, true, loader); } /** * Returns an instance of the specified Java module class. * @param clz class to be found * @return instance, or {@code null} */ public Object findImport(final String clz) { // check if class was imported as Java module if(javaModules != null) { for(final Object jm : javaModules.keySet()) { if(jm.getClass().getName().equals(clz)) return jm; } } return null; } public static String uri2path(final String uri) { try { final URI u = new URI(uri); final TokenBuilder tb = new TokenBuilder(); final String auth = u.getAuthority(); if(auth != null) { // reverse authority, replace dots by slashes final String[] comp = auth.split("\\."); for(int c = comp.length - 1; c >= 0; c--) tb.add('/').add(comp[c]); } else { tb.add('/'); } // add remaining path String path = u.getPath(); if(path == null) return null; path = path.replace('.', '/'); // add slash or path tb.add(path.isEmpty() ? "/" : path); final String pth = tb.toString(); // add "index" string return pth.endsWith("/") ? pth + "index" : pth; } catch(final URISyntaxException ex) { Util.debug(ex); return null; } } /** * Capitalizes the last path segment. * @param path input path * @return capitalized path */ public static String capitalize(final String path) { final int i = path.lastIndexOf('/'); return i == -1 || i + 1 >= path.length() ? path : path.substring(0, i + 1) + Character.toUpperCase(path.charAt(i + 1)) + path.substring(i + 2); } /** * Parses the specified file as module if it exists. * @param file file to be added * @param uri namespace uri * @param qp query parser * @return {@code true} if file exists and was successfully parsed * @throws QueryException query exception */ private static boolean addModule(final IOFile file, final byte[] uri, final QueryParser qp) throws QueryException { if(!file.exists()) return false; qp.module(token(file.path()), uri); return true; } /** * Loads a Java class. * @param path file path * @param uri original URI * @param ii input info * @throws QueryException query exception */ private void addJava(final String path, final byte[] uri, final InputInfo ii) throws QueryException { final String cp = path.replace('/', '.').substring(1); Class<?> clz = null; try { clz = findClass(cp); } catch(final ClassNotFoundException ex) { NOMODULE.thrw(ii, uri); // expected exception } catch(final Throwable th) { MODINIT.thrw(ii, th); } final boolean qm = clz.getSuperclass() == QueryModule.class; final Object jm = Reflect.get(clz); if(jm == null) NOINST.thrw(ii, cp); // add all public methods of the class (ignore methods from super classes) final ArrayList<Method> list = new ArrayList<Method>(); for(final Method m : clz.getMethods()) { // if class is inherited from {@link QueryModule}, no super methods are accepted if(!qm || m.getDeclaringClass() == clz) list.add(m); } // add class and its methods to module cache if(javaModules == null) javaModules = new HashMap<Object, ArrayList<Method>>(); javaModules.put(jm, list); } /** * Adds a package from the package repository. * @param name package name * @param toLoad list with packages to be loaded * @param loaded already loaded packages * @param ii input info * @param qp query parser * @throws QueryException query exception */ private void addRepo(final byte[] name, final TokenSet toLoad, final TokenSet loaded, final InputInfo ii, final QueryParser qp) throws QueryException { // return if package is already loaded if(loaded.contains(name)) return; // find package in package dictionary final byte[] pDir = context.repo.pkgDict().get(name); if(pDir == null) BXRE_NOTINST.thrw(ii, name); final IOFile pkgDir = context.repo.path(string(pDir)); // parse package descriptor final IO pkgDesc = new IOFile(pkgDir, PkgText.DESCRIPTOR); if(!pkgDesc.exists()) Util.debug(PkgText.MISSDESC, string(name)); final Package pkg = new PkgParser(context.repo, ii).parse(pkgDesc); // check if package contains a jar descriptor final IOFile jarDesc = new IOFile(pkgDir, PkgText.JARDESC); // add jars to classpath if(jarDesc.exists()) addJar(jarDesc, pkgDir, string(pkg.abbrev), ii); // package has dependencies -> they have to be loaded first => put package // in list with packages to be loaded if(pkg.dep.size() != 0) toLoad.add(name); for(final Dependency d : pkg.dep) { if(d.pkg != null) { // we consider only package dependencies here final byte[] depPkg = new PkgValidator(context.repo, ii).depPkg(d); if(depPkg == null) { BXRE_NOTINST.thrw(ii, string(d.pkg)); } else { if(toLoad.contains(depPkg)) CIRCMODULE.thrw(ii); addRepo(depPkg, toLoad, loaded, ii, qp); } } } for(final Component comp : pkg.comps) { final String p = new IOFile(new IOFile(pkgDir, string(pkg.abbrev)), string(comp.file)).path(); qp.module(token(p), comp.uri); } if(toLoad.id(name) != 0) toLoad.delete(name); loaded.add(name); } /** * Adds the jar files registered in jarDesc. * @param jarDesc jar descriptor * @param pkgDir package directory * @param modDir module directory * @param ii input info * @throws QueryException query exception */ private void addJar(final IOFile jarDesc, final IOFile pkgDir, final String modDir, final InputInfo ii) throws QueryException { // add new URLs final JarDesc desc = new JarParser(context, ii).parse(jarDesc); for(final byte[] u : desc.jars) { addURL(new IOFile(new IOFile(pkgDir, modDir), string(u))); } } /** * Adds a URL to the cache. * @param jar jar file to be added */ private void addURL(final IOFile jar) { try { urls.add(new URL(jar.url())); } catch(final MalformedURLException ex) { Util.errln(ex); } } }
package org.epoxide.commons.profiler; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; public class Profiler { private final Logger log; private final List<ProfileEntry> entries = new ArrayList<>(); private boolean enabled; public Profiler (String name) { this (Logger.getLogger(name)); } public Profiler (Logger log) { this.log = log; } public Profiler setEnabled(boolean enabled) { this.enabled = enabled; return this; } public boolean isEnabled() { return this.enabled; } public static class ProfileEntry { private final String name; private Long time; private boolean ended; public ProfileEntry (String name) { this.name = name; } } }
package org.jitsi.videobridge; import org.jitsi.util.*; import java.util.*; /** * Manages the set of <tt>Endpoint</tt>s whose video streams are being * forwarded to a specific <tt>VideoChannel</tt> (i.e. the * <tt>VideoChannel</tt>'s <tt>LastN</tt> set). * * @author Lyubomir Marinov * @author George Politis * @author Boris Grozev */ public class LastNController { /** * The <tt>Logger</tt> used by the <tt>VideoChannel</tt> class and its * instances to print debug information. */ private static final Logger logger = Logger.getLogger(LastNController.class); /** * An empty list instance. */ private static final List<String> INITIAL_EMPTY_LIST = Collections.unmodifiableList(new LinkedList<String>()); /** * The set of <tt>Endpoints</tt> whose video streams are currently being * forwarded. */ private List<String> forwardedEndpoints = INITIAL_EMPTY_LIST; /** * The list of all <tt>Endpoint</tt>s in the conference, ordered by the * last time they were elected dominant speaker. */ private List<String> conferenceSpeechActivityEndpoints = INITIAL_EMPTY_LIST; /** * The list of endpoints which have been explicitly marked as 'pinned' * and whose video streams should always be forwarded. */ private List<String> pinnedEndpoints = INITIAL_EMPTY_LIST; /** * The maximum number of endpoints whose video streams will be forwarded * to the endpoint. A value of {@code -1} means that there is no limit, and * all endpoints' video streams will be forwarded. */ private int lastN = -1; /** * Whether or not adaptive lastN is in use. */ private boolean adaptiveLastN = false; /** * Whether or not adaptive simulcast is in use. */ private boolean adaptiveSimulcast = false; /** * The {@link VideoChannel} which owns this {@link LastNController}. */ private final VideoChannel channel; /** * The ID of the endpoint of {@link #channel}. */ private String endpointId; /** * Initializes a new {@link LastNController} instance which is to belong * to a particular {@link VideoChannel}. * @param channel the owning {@link VideoChannel}. */ public LastNController(VideoChannel channel) { this.channel = channel; } /** * @return the maximum number of endpoints whose video streams will be * forwarded to the endpoint. A value of {@code -1} means that there is no * limit. */ public int getLastN() { return lastN; } /** * @return the set of <tt>Endpoints</tt> whose video streams are currently * being forwarded. */ public List<String> getForwardedEndpoints() { return forwardedEndpoints; } /** * Sets the value of {@code lastN}, that is, the maximum number of endpoints * whose video streams will be forwarded to the endpoint. A value of * {@code -1} means that there is no limit. * @param lastN the value to set. */ public void setLastN(int lastN) { if (logger.isDebugEnabled()) { logger.debug("Setting lastN=" + lastN); } List<String> endpointsToAskForKeyframe = null; synchronized (this) { // Since we have the lock anyway, call update() inside, so it // doesn't have to obtain it again. But keep the call to // askForKeyframes() outside. if (this.lastN != lastN) { // If we're just now enabling lastN, we don't need to ask for // keyframes as all streams were being forwarded already. boolean update = this.lastN != -1; this.lastN = lastN; if (update) { endpointsToAskForKeyframe = update(); } } } askForKeyframes(endpointsToAskForKeyframe); } /** * Sets the list of "pinned" endpoints (i.e. endpoints for which video * should always be forwarded, regardless of {@code lastN}). * @param newPinnedEndpointIds the list of endpoint IDs to set. */ public void setPinnedEndpointIds(List<String> newPinnedEndpointIds) { if (logger.isDebugEnabled()) { logger.debug("Setting pinned endpoints: " + newPinnedEndpointIds.toString()); } List<String> endpointsToAskForKeyframe = null; synchronized (this) { // Since we have the lock anyway, call update() inside, so it // doesn't have to obtain it again. But keep the call to // askForKeyframes() outside. if (!pinnedEndpoints.equals(newPinnedEndpointIds)) { pinnedEndpoints = Collections.unmodifiableList(newPinnedEndpointIds); endpointsToAskForKeyframe = update(); } } askForKeyframes(endpointsToAskForKeyframe); } /** * Checks whether RTP packets from {@code sourceChannel} should be forwarded * to {@link #channel}. * @param sourceChannel the channel. * @return {@code true} iff RTP packets from {@code sourceChannel} should * be forwarded to {@link #channel}. */ public boolean isForwarded(Channel sourceChannel) { if (lastN < 0) { // If Last-N is disabled, we forward everything. return true; } if (sourceChannel == null) { logger.warn("Invalid sourceChannel: null."); return false; } Endpoint channelEndpoint = sourceChannel.getEndpoint(); if (channelEndpoint == null) { logger.warn("sourceChannel has no endpoint."); return false; } if (forwardedEndpoints == INITIAL_EMPTY_LIST) { // LastN is enabled, but we haven't yet initialized the list of // endpoints in the conference. initializeConferenceEndpoints(); } // This may look like a place to optimize, because we query an unordered // list (in O(n)) and it executes on each video packet if lastN is // enabled. However, the size of forwardedEndpoints is restricted to // lastN and so small enough that it is not worth optimizing. return forwardedEndpoints.contains(channelEndpoint.getID()); } /** * @return the number of streams currently being forwarded. */ public int getN() { return forwardedEndpoints.size(); } /** * @return the list of "pinned" endpoints. */ public List<String> getPinnedEndpoints() { return pinnedEndpoints; } /** * Notifies this instance that the ordered list of endpoints in the * conference has changed. * * @param endpoints the new ordered list of endpoints in the conference. * @return the list of endpoints which were added to the list of forwarded * endpoints as a result of the call, or {@code null} if none were added. */ public List<Endpoint> speechActivityEndpointsChanged( List<Endpoint> endpoints) { List<String> newEndpointIdList = getIDs(endpoints); List<String> enteringEndpointIds = speechActivityEndpointIdsChanged(newEndpointIdList); if (logger.isDebugEnabled()) { logger.debug( "New list of conference endpoints: " + newEndpointIdList.toString() + "; entering endpoints: " + (enteringEndpointIds == null ? "none" : enteringEndpointIds.toString())); } List<Endpoint> ret = new LinkedList<>(); if (enteringEndpointIds != null) { for (Endpoint endpoint : endpoints) { if (enteringEndpointIds.contains(endpoint.getID())) { ret.add(endpoint); } } } return ret; } /** * Notifies this instance that the ordered list of endpoints (specified * as a list of endpoint IDs) in the conference has changed. * * @param endpointIds the new ordered list of endpoints (specified as a list * of endpoint IDs) in the conference. * @return the list of IDs of endpoints which were added to the list of * forwarded endpoints as a result of the call. */ private synchronized List<String> speechActivityEndpointIdsChanged( List<String> endpointIds) { if (conferenceSpeechActivityEndpoints.equals(endpointIds)) { if (logger.isDebugEnabled()) { logger.debug("Conference endpoints have not changed."); } return null; } else { List<String> newEndpoints = new LinkedList<>(endpointIds); newEndpoints.removeAll(conferenceSpeechActivityEndpoints); conferenceSpeechActivityEndpoints = endpointIds; return update(newEndpoints); } } /** * Enables or disables the "adaptive last-n" mode, depending on the value of * {@code adaptiveLastN}. * @param adaptiveLastN {@code true} to enable, {@code false} to disable */ public void setAdaptiveLastN(boolean adaptiveLastN) { this.adaptiveLastN = adaptiveLastN; // TODO: actually enable/disable } /** * Enables or disables the "adaptive simulcast" mod, depending on the value * of {@code adaptiveLastN}. * @param adaptiveSimulcast {@code true} to enable, {@code false} to * disable. */ public void setAdaptiveSimulcast(boolean adaptiveSimulcast) { this.adaptiveSimulcast = adaptiveSimulcast; // TODO: actually enable/disable } /** * @return {@code true} iff the "adaptive last-n" mode is enabled. */ public boolean getAdaptiveLastN() { return adaptiveLastN; } /** * @return {@code true} iff the "adaptive simulcast" mode is enabled. */ public boolean getAdaptiveSimulcast() { return adaptiveSimulcast; } /** * Recalculates the list of forwarded endpoints based on the current values * of the various parameters of this instance ({@link #lastN}, * {@link #conferenceSpeechActivityEndpoints}, {@link #pinnedEndpoints}). * * @return the list of IDs of endpoints which were added to * {@link #forwardedEndpoints} (i.e. of endpoints * "entering last-n") as a * result of this call. Returns {@code null} if no endpoints were added. */ private synchronized List<String> update() { return update(null); } /** * Recalculates the list of forwarded endpoints based on the current values * of the various parameters of this instance ({@link #lastN}, * {@link #conferenceSpeechActivityEndpoints}, {@link #pinnedEndpoints}). * * @param newConferenceEndpoints A list of endpoints which entered the * conference since the last call to this method. They need not be asked * for keyframes, because they were never filtered by this * {@link #LastNController(VideoChannel)}. * * @return the list of IDs of endpoints which were added to * {@link #forwardedEndpoints} (i.e. of endpoints * "entering last-n") as a * result of this call. Returns {@code null} if no endpoints were added. */ private synchronized List<String> update(List<String> newConferenceEndpoints) { List<String> newForwardedEndpoints = new LinkedList<>(); String ourEndpointId = getEndpointId(); if (conferenceSpeechActivityEndpoints == INITIAL_EMPTY_LIST) { conferenceSpeechActivityEndpoints = getIDs(channel.getConferenceSpeechActivity().getEndpoints()); newConferenceEndpoints = conferenceSpeechActivityEndpoints; } if (lastN < 0) { // Last-N is disabled, we forward everything. newForwardedEndpoints.addAll(conferenceSpeechActivityEndpoints); if (ourEndpointId != null) { newForwardedEndpoints.remove(ourEndpointId); } } else { // Pinned endpoints are always forwarded. newForwardedEndpoints.addAll(getPinnedEndpoints()); // As long as they are still endpoints in the conference. newForwardedEndpoints.retainAll(conferenceSpeechActivityEndpoints); if (newForwardedEndpoints.size() > lastN) { // What do we want in this case? It looks like a contradictory // request from the client, but maybe it makes for a good API // on the client to allow the pinned to override last-n. // Unfortunately, this will not play well with Adaptive-Last-N // or changes to Last-N for other reasons. } else if (newForwardedEndpoints.size() < lastN) { for (String endpointId : conferenceSpeechActivityEndpoints) { if (newForwardedEndpoints.size() < lastN) { if (!endpointId.equals(ourEndpointId) && !newForwardedEndpoints.contains(endpointId)) { newForwardedEndpoints.add(endpointId); } } else { break; } } } } List<String> enteringEndpoints; if (forwardedEndpoints.equals(newForwardedEndpoints)) { // We want forwardedEndpoints != INITIAL_EMPTY_LIST forwardedEndpoints = newForwardedEndpoints; enteringEndpoints = null; } else { enteringEndpoints = new ArrayList<>(newForwardedEndpoints); enteringEndpoints.removeAll(forwardedEndpoints); if (logger.isDebugEnabled()) { logger.debug( "Forwarded endpoints changed: " + forwardedEndpoints.toString() + " -> " + newForwardedEndpoints.toString() + ". Entering: " + enteringEndpoints.toString()); } forwardedEndpoints = Collections.unmodifiableList(newForwardedEndpoints); // TODO: we may want to do this asynchronously. channel.sendLastNEndpointsChangeEventOnDataChannel( forwardedEndpoints, enteringEndpoints); } // If lastN is disabled, the endpoints entering forwardedEndpoints were // never filtered, so they don't need to be asked for keyframes. if (lastN < 0) { enteringEndpoints = null; } if (enteringEndpoints != null && newConferenceEndpoints != null) { // Endpoints just entering the conference need not be asked for // keyframes. enteringEndpoints.removeAll(newConferenceEndpoints); } return enteringEndpoints; } /** * Sends a keyframe request to the endpoints specified in * {@code endpointIds} * @param endpointIds the list of IDs of endpoints to which to send a * request for a keyframe. */ private void askForKeyframes(List<String> endpointIds) { // TODO: Execute asynchronously. if (endpointIds != null && !endpointIds.isEmpty()) { channel.getContent().askForKeyframesById(endpointIds); } } /** * @return the ID of the endpoint of our channel. */ private String getEndpointId() { if (endpointId == null) { Endpoint endpoint = channel.getEndpoint(); if (endpoint != null) { endpointId = endpoint.getID(); } } return endpointId; } /** * Initializes the local list of endpoints * ({@link #speechActivityEndpointsChanged(List)}) with the current * endpoints from the conference. */ private synchronized void initializeConferenceEndpoints() { speechActivityEndpointsChanged( channel.getConferenceSpeechActivity().getEndpoints()); if (logger.isDebugEnabled()) { logger.debug("Initialized the list of endpoints: " + conferenceSpeechActivityEndpoints.toString()); } } /** * Extracts a list of endpoint IDs from a list of {@link Endpoint}s. * @param endpoints the list of {@link Endpoint}s. * @return the list of IDs of endpoints in {@code endpoints}. */ private List<String> getIDs(List<Endpoint> endpoints) { if (endpoints != null && !endpoints.isEmpty()) { List<String> endpointIds = new LinkedList<>(); for (Endpoint endpoint : endpoints) { endpointIds.add(endpoint.getID()); } return endpointIds; } return null; } }
package org.jolokia.docker.maven.util; import java.io.*; import java.util.*; import java.util.regex.Pattern; import org.apache.maven.plugin.MojoExecutionException; import org.codehaus.plexus.util.StringUtils; import org.jolokia.docker.maven.AbstractDockerMojo; /** * Utility class for various (loosely) environment related tasks. * * @author roland * @since 04.04.14 */ public class EnvUtil { private EnvUtil() {} // Check both, url and env DOCKER_HOST (first takes precedence) public static String extractUrl(String dockerHost) { String connect = dockerHost != null ? dockerHost : System.getenv("DOCKER_HOST"); if (connect == null) { File unixSocket = new File("/var/run/docker.sock"); if (unixSocket.exists() && unixSocket.canRead() && unixSocket.canWrite()) { connect = "unix:///var/run/docker.sock"; } else { throw new IllegalArgumentException("No url given and no DOCKER_HOST environment variable set"); } } String protocol = connect.contains(":" + AbstractDockerMojo.DOCKER_HTTPS_PORT) ? "https:" : "http:"; return connect.replaceFirst("^tcp:", protocol); } public static String getCertPath(String certPath) { String path = certPath != null ? certPath : System.getenv("DOCKER_CERT_PATH"); if (path == null) { File dockerHome = new File(System.getProperty("user.home") + "/.docker"); if (dockerHome.isDirectory() && dockerHome.list(SuffixFileFilter.PEM_FILTER).length > 0) { return dockerHome.getAbsolutePath(); } } return path; } /** * Write out a property file * * @param props properties to write * @param portPropertyFile file name * @throws MojoExecutionException */ public static void writePortProperties(Properties props,String portPropertyFile) throws MojoExecutionException { File propFile = new File(portPropertyFile); try (OutputStream os = new FileOutputStream(propFile)) { props.store(os,"Docker ports"); } catch (IOException e) { throw new MojoExecutionException("Cannot write properties to " + portPropertyFile + ": " + e,e); } } /** * Splits every element in the given list on the last colon in the name and returns a list with * two elements: The left part before the colon and the right part after the colon. If the string doesnt contain * a colon, the value is used for both elements in the returned arrays. * * @param listToSplit list of strings to split * @return return list of 2-element arrays or an empty list if the given list is empty or null */ public static List<String[]> splitOnLastColon(List<String> listToSplit) { if (listToSplit != null) { List<String[]> ret = new ArrayList<>(); for (String element : listToSplit) { String[] p = element.split(":"); String rightValue = p[p.length - 1]; String[] nameParts = Arrays.copyOfRange(p, 0, p.length - 1); String leftValue = StringUtils.join(nameParts, ":"); if (leftValue.length() == 0) { leftValue = rightValue; } ret.add(new String[]{leftValue, rightValue}); } return ret; } return Collections.emptyList(); } public static String[] splitOnSpaceWithEscape(String toSplit) { String[] split = toSplit.split("(?<!" + Pattern.quote("\\") + ")\\s+"); String[] res = new String[split.length]; for (int i = 0; i < split.length; i++) { res[i] = split[i].replaceAll("\\\\ "," "); } return res; } /** * Join a list of objects to a string with a given separator by calling Object.toString() on the elements. * * @param list to join * @param separator separator to use * @return the joined string. */ public static String stringJoin(List list, String separator) { StringBuilder ret = new StringBuilder(); boolean first = true; for (Object o : list) { if (!first) { ret.append(separator); } ret.append(o); first = false; } return ret.toString(); } /** * Extract part of given properties as a map. The given prefix is used to find the properties, * the rest of the property name is used as key for the map. * * @param prefix prefix which specifies the part which should be extracted as map * @param properties properties to extract from * @return the extracted map or null if no such map exists */ public static Map<String, String> extractFromPropertiesAsMap(String prefix, Properties properties) { Map<String, String> ret = new HashMap<>(); Enumeration names = properties.propertyNames(); String prefixP = prefix + "."; while (names.hasMoreElements()) { String propName = (String) names.nextElement(); if (propMatchesPrefix(prefixP, propName)) { String mapKey = propName.substring(prefixP.length()); ret.put(mapKey, properties.getProperty(propName)); } } return ret.size() > 0 ? ret : null; } /** * Extract from given properties a list of string values. The prefix is used to determine the subset of the * given properties from which the list should be extracted, the rest is used as a numeric index. If the rest * is not numeric, the order is not determined (all those props are appended to the end of the list) * * @param prefix for selecting the properties from which the list should be extracted * @param properties properties from which to extract from * @return parsed list or null if no element with prefixes exists */ public static List<String> extractFromPropertiesAsList(String prefix, Properties properties) { TreeMap<Integer,String> orderedMap = new TreeMap<>(); List<String> rest = new ArrayList<>(); Enumeration names = properties.propertyNames(); String prefixP = prefix + "."; while (names.hasMoreElements()) { String key = (String) names.nextElement(); if (propMatchesPrefix(prefixP, key)) { String index = key.substring(prefixP.length()); String value = properties.getProperty(key); try { Integer nrIndex = Integer.parseInt(index); orderedMap.put(nrIndex,value); } catch (NumberFormatException exp) { rest.add(value); } } } List<String> ret = new ArrayList<>(orderedMap.values()); ret.addAll(rest); return ret.size() > 0 ? ret : null; } private static boolean propMatchesPrefix(String prefix, String key) { return key.startsWith(prefix) && key.length() >= prefix.length(); } public static String findRegistry(String ... checkFirst) { for (String registry : checkFirst) { if (registry != null) { return registry; } } // Check environment as last resort return System.getenv("DOCKER_REGISTRY"); } public static File prepareAbsoluteOutputDirPath(MojoParameters params, String dir, String path) { return prepareAbsolutePath(params, new File(params.getOutputDirectory(), dir).toString(), path); } public static File prepareAbsoluteSourceDirPath(MojoParameters params, String path) { return prepareAbsolutePath(params, params.getSourceDirectory(), path); } private static File prepareAbsolutePath(MojoParameters params, String directory, String path) { File file = new File(path); if (file.isAbsolute()) { return file; } return new File(new File(params.getProject().getBasedir(), directory), path); } }
package org.lightmare.libraries; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.log4j.Logger; import org.lightmare.libraries.loaders.EjbClassLoader; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.FileUtils; import org.lightmare.utils.reflect.MetaUtils; /** * Class for load jar or class files from specified path * * @author levan * */ public class LibraryLoader { private static final String ADD_URL_METHOD_NAME = "addURL"; private static final String CLOSE_METHOD_NAME = "close"; private static final String LOADER_THREAD_NAME = "library-class-loader-thread"; private static Method addURLMethod; private static final Lock LOCK = new ReentrantLock(); private static final Logger LOG = Logger.getLogger(LibraryLoader.class); /** * {@link Callable}<ClassLoader> implementation to initialize * {@link ClassLoader} in separate thread * * @author levan * */ private static class LibraryLoaderInit implements Callable<ClassLoader> { private URL[] urls; private ClassLoader parent; public LibraryLoaderInit(final URL[] urls, final ClassLoader parent) { this.urls = urls; this.parent = parent; } @Override public ClassLoader call() throws Exception { ClassLoader loader = cloneContextClassLoader(urls, parent); return loader; } } private static Method getURLMethod() throws IOException { if (addURLMethod == null) { LOCK.lock(); try { if (addURLMethod == null) { addURLMethod = MetaUtils.getDeclaredMethod( URLClassLoader.class, ADD_URL_METHOD_NAME, URL.class); } } finally { LOCK.unlock(); } } return addURLMethod; } /** * If passed {@link ClassLoader} is instance of {@link URLClassLoader} then * gets {@link URL}[] of this {@link ClassLoader} calling * {@link URLClassLoader#getURLs()} method * * @param loader * @return {@link URL}[] */ private static URL[] getURLs(ClassLoader loader) { URL[] urls; if (loader instanceof URLClassLoader) { urls = ((URLClassLoader) loader).getURLs(); } else { urls = new URL[0]; } return urls; } /** * Initializes and returns enriched {@link ClassLoader} in separated * {@link Thread} to load bean and library classes * * @param urls * @return {@link ClassLoader} * @throws IOException */ public static ClassLoader initializeLoader(final URL[] urls) throws IOException { ClassLoader parent = getContextClassLoader(); LibraryLoaderInit initializer = new LibraryLoaderInit(urls, parent); FutureTask<ClassLoader> task = new FutureTask<ClassLoader>(initializer); Thread thread = new Thread(task); thread.setName(LOADER_THREAD_NAME); thread.setPriority(Thread.MAX_PRIORITY); thread.start(); ClassLoader ejbLoader; try { ejbLoader = task.get(); } catch (InterruptedException ex) { throw new IOException(ex); } catch (ExecutionException ex) { throw new IOException(ex); } return ejbLoader; } /** * Gets current {@link Thread}'s context {@link ClassLoader} object * * @return {@link ClassLoader} */ public static ClassLoader getContextClassLoader() { PrivilegedAction<ClassLoader> action = new PrivilegedAction<ClassLoader>() { public ClassLoader run() { Thread currentThread = Thread.currentThread(); ClassLoader classLoader = currentThread.getContextClassLoader(); return classLoader; } }; ClassLoader loader = AccessController.doPrivileged(action); return loader; } public static ClassLoader getEnrichedLoader(File file, Set<URL> urls) throws IOException { FileUtils.getSubfiles(file, urls); URL[] paths = ObjectUtils.toArray(urls, URL.class); ClassLoader parent = getContextClassLoader(); URLClassLoader urlLoader = URLClassLoader.newInstance(paths, parent); return urlLoader; } public static ClassLoader getEnrichedLoader(URL[] urls, ClassLoader parent) throws IOException { EjbClassLoader urlLoader = null; if (ObjectUtils.available(urls)) { if (parent == null) { parent = getContextClassLoader(); } urlLoader = EjbClassLoader.newInstance(urls, parent); } return urlLoader; } /** * Initializes new {@link ClassLoader} from loaded {@link URL}'s from * enriched {@link ClassLoader} for beans and libraries * * @param urls * @return {@link ClassLoader} * @throws IOException */ public static ClassLoader cloneContextClassLoader(final URL[] urls, ClassLoader parent) throws IOException { URLClassLoader loader = (URLClassLoader) getEnrichedLoader(urls, parent); try { // get all resources for cloning URL[] urlArray = loader.getURLs(); URL[] urlClone = urlArray.clone(); if (parent == null) { parent = getContextClassLoader(); } ClassLoader clone = EjbClassLoader.newInstance(urlClone, parent); return clone; } finally { closeClassLoader(loader); // dereference cloned class loader instance loader = null; } } /** * Merges two {@link ClassLoader}s * * @param newLoader * @param oldLoader * @return {@link ClassLoader} */ public static ClassLoader createCommon(ClassLoader newLoader, ClassLoader oldLoader) { URL[] urls = getURLs(oldLoader); URLClassLoader commonLoader = URLClassLoader.newInstance(urls, oldLoader); urls = getURLs(newLoader); commonLoader = URLClassLoader.newInstance(urls, newLoader); return commonLoader; } public static void loadCurrentLibraries(Thread thread, ClassLoader loader) { if (ObjectUtils.notNull(loader)) { thread.setContextClassLoader(loader); } } public static void loadCurrentLibraries(ClassLoader loader) { Thread thread = Thread.currentThread(); loadCurrentLibraries(thread, loader); } public static void loadURLToSystem(URL[] urls, Method method, URLClassLoader urlLoader) throws IOException { for (URL url : urls) { MetaUtils.invokePrivate(method, urlLoader, url); } } private static void loadLibraryFromPath(String libraryPath) throws IOException { File file = new File(libraryPath); if (file.exists()) { Set<URL> urls = new HashSet<URL>(); FileUtils.getSubfiles(file, urls); URL[] paths = ObjectUtils.toArray(urls, URL.class); URLClassLoader urlLoader = (URLClassLoader) ClassLoader .getSystemClassLoader(); Method method = getURLMethod(); loadURLToSystem(paths, method, urlLoader); } } /** * Loads jar or <code>.class</code> files to the current thread from * libraryPaths recursively * * @param libraryPaths * @throws IOException */ public static void loadLibraries(String... libraryPaths) throws IOException { if (ObjectUtils.available(libraryPaths)) { for (String libraryPath : libraryPaths) { loadLibraryFromPath(libraryPath); } } } /** * Loads passed classes to specified {@link ClassLoader} instance * * @param classes * @param loader */ public static void loadClasses(Collection<String> classes, ClassLoader loader) throws IOException { if (ObjectUtils.available(classes) && ObjectUtils.notNull(loader)) { for (String className : classes) { try { loader.loadClass(className); } catch (ClassNotFoundException ex) { throw new IOException(ex); } } } } /** * Loads passed classes to specified current {@link Thread}'s context class * loader * * @param classes */ public static void loadClasses(Collection<String> classes) throws IOException { ClassLoader loader = getContextClassLoader(); loadClasses(classes, loader); } /** * Closes passed {@link ClassLoader} if it is instance of * {@link URLClassLoader} class * * @param loader * @throws IOException */ public static void closeClassLoader(ClassLoader loader) throws IOException { if (ObjectUtils.notNull(loader) && loader instanceof URLClassLoader) { try { loader.clearAssertionStatus(); // Finds if loader associated class has "close" method if (MetaUtils.hasMethod(loader.getClass(), CLOSE_METHOD_NAME)) { ((URLClassLoader) loader).close(); } } catch (Throwable th) { LOG.error(th.getMessage(), th); } } } }
package org.lightmare.utils.reflect; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; /** * Class to use reflection {@link Method} calls and {@link Field} information * sets * * @author levan * */ public class MetaUtils { // default values for primitives private static byte byteDef = 0; private static boolean booleanDef = Boolean.FALSE; private static char charDef = '\u0000'; private static short shortDef = 0; private static int intDef; private static long longDef; private static float floatDef; private static double doubleDef; // default value for modifier private static final int DEFAULT_MODIFIER = 0; /** * Sets object accessible flag as true if it is not * * @param accessibleObject * @param accessible */ private static void setAccessible(AccessibleObject accessibleObject, boolean accessible) { if (ObjectUtils.notTrue(accessible)) { synchronized (accessibleObject) { if (ObjectUtils.notTrue(accessibleObject.isAccessible())) { accessibleObject.setAccessible(Boolean.TRUE); } } } } /** * Sets passed {@link AccessibleObject}'s accessible flag as passed * accessible boolean value if the last one is false * * @param accessibleObject * @param accessible */ private static void resetAccessible(AccessibleObject accessibleObject, boolean accessible) { if (ObjectUtils.notTrue(accessible)) { synchronized (accessibleObject) { if (accessibleObject.isAccessible()) { accessibleObject.setAccessible(accessible); } } } } /** * Makes accessible passed {@link Constructor}'s and invokes * {@link Constructor#newInstance(Object...)} method * * @param constructor * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T newInstance(Constructor<T> constructor, Object... parameters) throws IOException { T instance; boolean accessible = constructor.isAccessible(); try { setAccessible(constructor, accessible); instance = constructor.newInstance(parameters); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } finally { resetAccessible(constructor, accessible); } return instance; } /** * Gets declared constructor for given {@link Class} and given parameters * * @param type * @param parameterTypes * @return {@link Constructor} * @throws IOException */ public static <T> Constructor<T> getConstructor(Class<T> type, Class<?>... parameterTypes) throws IOException { Constructor<T> constructor; try { constructor = type.getDeclaredConstructor(parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return constructor; } /** * Instantiates class by {@link Constructor} (MetaUtils * {@link #newInstance(Constructor, Object...)}) after * {@link MetaUtils#getConstructor(Class, Class...)} method call * * @param type * @param parameterTypes * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T callConstructor(Class<T> type, Class<?>[] parameterTypes, Object... parameters) throws IOException { T instance; Constructor<T> constructor = getConstructor(type, parameterTypes); instance = newInstance(constructor, parameters); return instance; } /** * Loads class by name * * @param className * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className) throws IOException { Class<?> clazz = classForName(className, null); return clazz; } /** * Loads class by name with specific {@link ClassLoader} if it is not * <code>null</code> * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, ClassLoader loader) throws IOException { Class<?> clazz = classForName(className, Boolean.TRUE, loader); return clazz; } /** * Loads and if initialize parameter is true initializes class by name with * specific {@link ClassLoader} if it is not <code>null</code> * * @param className * @param initialize * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, boolean initialize, ClassLoader loader) throws IOException { Class<?> clazz; try { if (loader == null) { clazz = Class.forName(className); } else { clazz = Class.forName(className, initialize, loader); } } catch (ClassNotFoundException ex) { throw new IOException(ex); } return clazz; } /** * Loads class by name with current {@link Thread}'s {@link ClassLoader} and * initializes it * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> initClassForName(String className) throws IOException { Class<?> clazz; ClassLoader loader = LibraryLoader.getContextClassLoader(); clazz = classForName(className, Boolean.TRUE, loader); return clazz; } /** * Creates {@link Class} instance by {@link Class#newInstance()} method call * * @param clazz * @return */ public static <T> T instantiate(Class<T> clazz) throws IOException { T instance; try { instance = clazz.newInstance(); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } return instance; } /** * Gets declared method from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method getDeclaredMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws IOException { Method method; try { method = clazz.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return method; } /** * Gets all declared methods from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method[] getDeclaredMethods(Class<?> clazz) throws IOException { Method[] methods; try { methods = clazz.getDeclaredMethods(); } catch (SecurityException ex) { throw new IOException(ex); } return methods; } /** * Gets one modifier <code>int</code> value for passed collection * * @param modifiers * @return <code>int</code> */ private static int calculateModifier(int[] modifiers) { int modifier = DEFAULT_MODIFIER; if (ObjectUtils.notNull(modifiers)) { int length = modifiers.length; int modifierValue; for (int i = 0; i < length; i++) { modifierValue = modifiers[i]; modifier = modifier | modifierValue; } } return modifier; } /** * Finds if passed {@link Class} has declared public {@link Method} with * appropriated name * * @param clazz * @param modifiers * @param methodName * @return <code>boolean</code> * @throws IOException */ private static boolean classHasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { boolean found = Boolean.FALSE; Method[] methods = getDeclaredMethods(clazz); int length = methods.length; int modifier = calculateModifier(modifiers); Method method; for (int i = 0; i < length && ObjectUtils.notTrue(found); i++) { method = methods[i]; found = method.getName().equals(methodName); if (found && ObjectUtils.notEquals(modifier, DEFAULT_MODIFIER)) { found = ((method.getModifiers() & modifier) > DEFAULT_MODIFIER); } } return found; } /** * Finds if passed {@link Class} has {@link Method} with appropriated name * and modifiers * * @param clazz * @param methodName * @param modifiers * @return <code>boolean</code> * @throws IOException */ public static boolean hasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { boolean found = Boolean.FALSE; Class<?> superClass = clazz; while (ObjectUtils.notNull(superClass) && ObjectUtils.notTrue(found)) { found = MetaUtils.classHasMethod(superClass, methodName, modifiers); if (ObjectUtils.notTrue(found)) { superClass = superClass.getSuperclass(); } } return found; } /** * Finds if passed {@link Class} has public {@link Method} with appropriated * name * * @param clazz * @param methodName * @return <code>boolean</code> * @throws IOException */ public static boolean hasPublicMethod(Class<?> clazz, String methodName) throws IOException { boolean found = MetaUtils.hasMethod(clazz, methodName, Modifier.PUBLIC); return found; } /** * Gets declared field from passed class with specified name * * @param clazz * @param name * @return {@link Field} * @throws IOException */ public static Field getDeclaredField(Class<?> clazz, String name) throws IOException { Field field; try { field = clazz.getDeclaredField(name); } catch (NoSuchFieldException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return field; } /** * Returns passed {@link Field}'s modifier * * @param field * @return <code>int</code> */ public static int getModifiers(Field field) { return field.getModifiers(); } /** * Returns passed {@link Method}'s modifier * * @param method * @return <code>int</code> */ public static int getModifiers(Method method) { return method.getModifiers(); } /** * Returns type of passed {@link Field} invoking {@link Field#getType()} * method * * @param field * @return {@link Class}<?> */ public static Class<?> getType(Field field) { return field.getType(); } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invoke(Method method, Object data, Object... arguments) throws IOException { Object value; try { value = method.invoke(data, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invokePrivate(Method method, Object data, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { setAccessible(method, accessible); value = invoke(method, data, arguments); } finally { resetAccessible(method, accessible); } return value; } /** * Common method to invoke static {@link Method} with reflection * * @param method * @param arguments * @return * @throws IOException */ public static Object invokeStatic(Method method, Object... arguments) throws IOException { Object value; try { value = method.invoke(null, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke private static {@link Method} * * @param method * @param arguments * @return * @throws IOException */ public static Object invokePrivateStatic(Method method, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { setAccessible(method, accessible); value = invokeStatic(method, arguments); } finally { resetAccessible(method, accessible); } return value; } /** * Sets value to {@link Field} sets accessible Boolean.TRUE remporary if * needed * * @param field * @param value * @throws IOException */ public static void setFieldValue(Field field, Object data, Object value) throws IOException { boolean accessible = field.isAccessible(); try { setAccessible(field, accessible); field.set(data, value); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { resetAccessible(field, accessible); } } /** * Gets value of specific field in specific {@link Object} * * @param field * @param data * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field, Object data) throws IOException { Object value; boolean accessible = field.isAccessible(); try { setAccessible(field, accessible); value = field.get(data); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { resetAccessible(field, accessible); } return value; } /** * Gets value of specific static field * * @param field * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field) throws IOException { Object value = getFieldValue(field, null); return value; } /** * Gets {@link List} of all {@link Method}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Method> * @throws IOException */ public static List<Method> getAnnotatedMethods(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Method> methods = new ArrayList<Method>(); Method[] allMethods = getDeclaredMethods(clazz); for (Method method : allMethods) { if (method.isAnnotationPresent(annotationClass)) { methods.add(method); } } return methods; } /** * Gets {@link List} of all {@link Field}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Field> * @throws IOException */ public static List<Field> getAnnotatedFields(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Field> fields = new ArrayList<Field>(); Field[] allFields = clazz.getDeclaredFields(); for (Field field : allFields) { if (field.isAnnotationPresent(annotationClass)) { fields.add(field); } } return fields; } /** * Gets wrapper class if passed class is primitive type * * @param type * @return {@link Class}<T> */ public static <T> Class<T> getWrapper(Class<?> type) { Class<T> wrapper; if (type.isPrimitive()) { if (type.equals(byte.class)) { wrapper = ObjectUtils.cast(Byte.class); } else if (type.equals(boolean.class)) { wrapper = ObjectUtils.cast(Boolean.class); } else if (type.equals(char.class)) { wrapper = ObjectUtils.cast(Character.class); } else if (type.equals(short.class)) { wrapper = ObjectUtils.cast(Short.class); } else if (type.equals(int.class)) { wrapper = ObjectUtils.cast(Integer.class); } else if (type.equals(long.class)) { wrapper = ObjectUtils.cast(Long.class); } else if (type.equals(float.class)) { wrapper = ObjectUtils.cast(Float.class); } else if (type.equals(double.class)) { wrapper = ObjectUtils.cast(Double.class); } else { wrapper = ObjectUtils.cast(type); } } else { wrapper = ObjectUtils.cast(type); } return wrapper; } /** * Returns default values if passed class is primitive else returns null * * @param clazz * @return Object */ public static Object getDefault(Class<?> clazz) { Object value; if (clazz.isPrimitive()) { if (clazz.equals(byte.class)) { value = byteDef; } else if (clazz.equals(boolean.class)) { value = booleanDef; } else if (clazz.equals(char.class)) { value = charDef; } else if (clazz.equals(short.class)) { value = shortDef; } else if (clazz.equals(int.class)) { value = intDef; } else if (clazz.equals(long.class)) { value = longDef; } else if (clazz.equals(float.class)) { value = floatDef; } else if (clazz.equals(double.class)) { value = doubleDef; } else { value = null; } } else { value = null; } return value; } }
package org.lightmare.utils.shutdown; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.log4j.Logger; import org.lightmare.cache.ConnectionContainer; import org.lightmare.cache.MetaContainer; import org.lightmare.cache.RestContainer; import org.lightmare.cache.TmpResources; import org.lightmare.deploy.LoaderPoolManager; import org.lightmare.utils.CollectionUtils; /** * Runnable class for shut down hook * * @author levan * */ public class ShutDown implements Runnable { private List<TmpResources> resources; private static final String SHUTDOWN_MESSAGE = "Lightmare server is going to shut down"; // Boolean check if shutdown hook is set private static final AtomicBoolean HOOK_SET = new AtomicBoolean( Boolean.FALSE); private static final Logger LOG = Logger.getLogger(ShutDown.class); public ShutDown(TmpResources tmpResources) { getResources().add(tmpResources); } private List<TmpResources> getResources() { if (resources == null) { resources = new ArrayList<TmpResources>(); } return resources; } private void setTmpResources(TmpResources tmpResources) { getResources().add(tmpResources); } /** * Clears cache and closes all resources * * @throws IOException */ public static void clearAll() throws IOException { ConnectionContainer.clear(); MetaContainer.clear(); RestContainer.clear(); LoaderPoolManager.reload(); } @Override public void run() { try { if (CollectionUtils.valid(resources)) { for (TmpResources tmpResources : resources) { tmpResources.removeTempFiles(); } } clearAll(); } catch (IOException ex) { LOG.fatal(ex.getMessage(), ex); } LOG.info(SHUTDOWN_MESSAGE); } /** * Sets shut down hook for application * * @param tmpResources */ public static void setHook(TmpResources tmpResources) { // Checks if shutdown hook is set if (HOOK_SET.getAndSet(Boolean.TRUE)) { ShutDown shutDown = new ShutDown(tmpResources); Thread shutDownThread = new Thread(shutDown); Runtime runtime = Runtime.getRuntime(); runtime.addShutdownHook(shutDownThread); } } }
package org.made.neohabitat.mods; import org.elkoserver.foundation.json.JSONMethod; import org.elkoserver.foundation.json.OptBoolean; import org.elkoserver.foundation.json.OptInteger; import org.elkoserver.json.EncodeControl; import org.elkoserver.json.JSONLiteral; import org.elkoserver.server.context.User; import org.made.neohabitat.Copyable; import org.made.neohabitat.HabitatMod; import org.made.neohabitat.Openable; /** * Habitat Pawn_machine * * Recycles goods for tokens. * * @author Randy Farmer */ public class Pawn_machine extends Openable implements Copyable { public int HabitatClass() { return CLASS_PAWN_MACHINE; } public String HabitatModName() { return "Pawn_machine"; } public int capacity() { return 1; } public int pc_state_bytes() { return 3; }; public boolean known() { return true; } public boolean opaque_container() { return true; } public boolean changeable () { return true; } public boolean filler() { return false; } public static final int[] pawn_values = { 0, 0, 1, 0, 0, 0, 25, 10, 0, 0, 1, 20, 5, 40, 0, 0, 100, 100, 0, 0, 30000, 0, 0, 0, 0, 5, 800, 20, 0, 0, 11, 47, 0, 1, 0, 400, 0, 600, 0, 0, 0, 0, 1, 1, 200, 0, 100, 30, 0, 1, 0, 0, 5, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 800, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 150, 0, 400, 0, 0, 0, 0, 75, 0, 900, 0, 0, 0, 25, 0, 0, 0, 0, /* 100 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 109 */ /* 110 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 119 */ /* 120 */ 0, 0, 0, 0, 0, 0, 0, 10, 0, 400 }; /* 129 */ @JSONMethod({ "style", "x", "y", "orientation", "gr_state", "restricted", "open_flags", "key_hi", "key_lo" }) public Pawn_machine(OptInteger style, OptInteger x, OptInteger y, OptInteger orientation, OptInteger gr_state, OptBoolean restricted, OptInteger open_flags, OptInteger key_hi, OptInteger key_lo) { super(style, x, y, orientation, gr_state, restricted, open_flags, key_hi, key_lo); } public Pawn_machine(int style, int x, int y, int orientation, int gr_state, boolean restricted, boolean[] open_flags, int key_hi, int key_lo) { super(style, x, y, orientation, gr_state, restricted, open_flags, key_hi, key_lo); } @Override public HabitatMod copyThisMod() { return new Pawn_machine(style, x, y, orientation, gr_state, restricted, open_flags, key_hi, key_lo); } @Override public JSONLiteral encode(EncodeControl control) { JSONLiteral result = super.encodeOpenable(new JSONLiteral(HabitatModName(), control)); result.finish(); return result; } @JSONMethod public void MUNCH(User from) { HabitatMod recycle = contents(0); if (adjacent(this) && recycle != null) { if (TRUE == Tokens.pay_to(avatar(from), pawn_values[recycle.HabitatClass()])) { send_neighbor_msg(from, noid, "MUNCH$"); destroy_contents(); send_goaway_msg(recycle.noid); send_reply_success(from); return; } send_reply_err(from, noid, BOING_FAILURE); return; } this.send_reply_error(from, noid); } }
package org.opentripplanner.analyst; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonGenerator; import com.google.common.primitives.Ints; import java.io.IOException; import java.io.Serializable; import org.opentripplanner.analyst.core.WeightingFunction; /** * A pair of parallel histograms representing how many features are located at each amount of travel time * away from from a single origin. One array contains the raw counts of features (e.g. number of places of employment * M minutes from home) and the other array contains the weighted sums of those features accounting for their * magnitudes (e.g. the number of jobs in all places of employment M minutes away from home). * All time values are rounded down into 1-minute bins (0-60 seconds = minute 0, 61-120 = min 1, etc.) */ public class Histogram implements Serializable { /** * The weighting functions to be used, as an array. Generally this will be an array of 120 * functions, one to calculate cumulative accessibility for each minute in two hours. * But any additive function can be used, and the output of the functions will be places in * counts and sums parallel to this array. */ public static WeightingFunction[] weightingFunctions; /** * The steepness of the logistic rolloff, basically a smoothing parameter. * Must be negative or your results will be backwards (i.e. jobs nearby will be worth less than jobs far away). * * The larger it is in magnitude, the less smoothing. setting it to -2 / 60.0 yields a rolloff of about 5 minutes. */ // TODO: should not be final, but that means that we need to rebuild the weighting functions when it is changed. public static final double LOGISTIC_STEEPNESS = -2 / 60.0; static { weightingFunctions = new WeightingFunction[120]; for (int i = 0; i < 120; i++) { weightingFunctions[i] = new WeightingFunction.Logistic((i + 1) * 60, LOGISTIC_STEEPNESS); } } /** * The number features that can be reached within each one-minute bin. Index 0 is 0-1 minutes, index 50 is 50-51 * minutes, etc. The features are not weighted by their magnitudes, so values represent (for example) the number of * places of employment that can be reached rather than the total number of jobs in all those places of employment. */ public int[] counts; /** * The weighted sum of all features that can be reached within each one-minute bin. * Index 0 is 0-1 minutes, index 50 is 50-51 minutes, etc. * Features are weighted by their magnitudes, so values represent (for example) the total number of jobs in * all accessible places of employment, rather than the number of places of employment. */ public int[] sums; /** * Given parallel arrays of travel times and magnitudes for any number of destination features, construct * histograms that represent the distribution of individual features and total opportunities as a function of * travel time. The length of the arrays containing these histograms will be equal to the maximum travel time * specified in the original search request, in minutes. * @param times the time at which each destination is reached. The array will be destructively sorted in place. * @param weight the weight or magnitude of each destination reached. it is parallel to times. */ public Histogram (int[] times, int[] weight) { int size = weightingFunctions.length; // optimization: bin times and weights by seconds. // there will often be more than one destination in a seconds due to the pigeonhole principle: // there are a lot more destinations than there are seconds int maxSecs = Integer.MIN_VALUE; for (int time : times) { if (time == Integer.MAX_VALUE) continue; if (time > maxSecs) maxSecs = time; } int[] binnedCounts = new int[maxSecs + 1]; int[] binnedWeights = new int[maxSecs + 1]; for (int i = 0; i < times.length; i++) { if (times[i] == Integer.MAX_VALUE) continue; binnedCounts[times[i]] += 1; binnedWeights[times[i]] += weight[i]; } // we use logistic rolloff, so we want to compute the counts and sums using floating-point values before truncation double[] tmpCounts = new double[size]; double[] tmpSums = new double[size]; for (int i = 0; i < binnedCounts.length; i++) { for (int j = 0; j < weightingFunctions.length; j++) { double w = weightingFunctions[j].getWeight(i); tmpCounts[j] += w * binnedCounts[i]; tmpSums[j] += w * binnedWeights[i]; } } // convert to ints counts = new int[size]; sums = new int[size]; for (int i = 0; i < weightingFunctions.length; i++) { counts[i] = (int) Math.round(tmpCounts[i]); sums[i] = (int) Math.round(tmpSums[i]); } // make density rather than cumulative // note that counts[0] is already a density so we don't touch it for (int i = weightingFunctions.length - 1; i > 0; i counts[i] -= counts[i - 1]; sums[i] -= sums[i - 1]; } } /** no-arg constructor for serialization/deserialization */ public Histogram () {} /** * Serialize this pair of histograms out as a JSON document using the given JsonGenerator. The format is: * <pre> { * sums: [], * counts: [] * } </pre> */ public void writeJson(JsonGenerator jgen) throws JsonGenerationException, IOException { // The number of features reached during each minute, ignoring their magnitudes jgen.writeArrayFieldStart("sums"); { for(int sum : sums) { jgen.writeNumber(sum); } } jgen.writeEndArray(); // The total number of opportunities reached during each minute (the sum of the features' magnitudes) jgen.writeArrayFieldStart("counts"); { for(int count : counts) { jgen.writeNumber(count); } } jgen.writeEndArray(); } }
package org.osiam.storage.entities; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import com.google.common.collect.ImmutableSet; /** * User Entity */ @Entity @Table(name = "scim_user") public class UserEntity extends ResourceEntity { private static final String JOIN_COLUMN_NAME = "user_internal_id"; @Column(nullable = false, unique = true) private String userName; @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true) private NameEntity name; @Column private String nickName; @Column private String profileUrl; @Column private String title; @Column private String userType; @Column private String preferredLanguage; @Column private String locale; @Column private String timezone; @Column private Boolean active = Boolean.FALSE; @Column(nullable = false) private String password; @Column private String displayName; @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = JOIN_COLUMN_NAME) private Set<EmailEntity> emails = new HashSet<>(); @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = JOIN_COLUMN_NAME) private Set<PhoneNumberEntity> phoneNumbers = new HashSet<>(); @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = JOIN_COLUMN_NAME) private Set<ImEntity> ims = new HashSet<>(); @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = JOIN_COLUMN_NAME) private Set<PhotoEntity> photos = new HashSet<>(); @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = JOIN_COLUMN_NAME) private Set<AddressEntity> addresses = new HashSet<>(); @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = JOIN_COLUMN_NAME) private Set<EntitlementsEntity> entitlements = new HashSet<>(); @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = JOIN_COLUMN_NAME) private Set<RolesEntity> roles = new HashSet<>(); @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = JOIN_COLUMN_NAME) private Set<X509CertificateEntity> x509Certificates = new HashSet<>(); // TODO: fix relationship or delete it (it is not used right now) @OneToMany @JoinTable(name = "scim_user_scim_extension", joinColumns = { @JoinColumn(name = "scim_user_internal_id", referencedColumnName = "internal_id") }, inverseJoinColumns = { @JoinColumn(name = "registered_extensions_internal_id", referencedColumnName = "internal_id") }) private Set<ExtensionEntity> registeredExtensions = new HashSet<>(); @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = JOIN_COLUMN_NAME) private Set<ExtensionFieldValueEntity> extensionFieldValues = new HashSet<>(); public UserEntity() { getMeta().setResourceType("User"); } /** * @return the name entity */ public NameEntity getName() { return name; } /** * @param name * the name entity */ public void setName(NameEntity name) { this.name = name; } /** * @return the nick name */ public String getNickName() { return nickName; } /** * @param nickName * the nick name */ public void setNickName(String nickName) { this.nickName = nickName; } /** * @return the profile url */ public String getProfileUrl() { return profileUrl; } /** * @param profileUrl * the profile url */ public void setProfileUrl(String profileUrl) { this.profileUrl = profileUrl; } /** * @return the title */ public String getTitle() { return title; } /** * @param title * the title */ public void setTitle(String title) { this.title = title; } /** * @return the user type */ public String getUserType() { return userType; } /** * @param userType * the user type */ public void setUserType(String userType) { this.userType = userType; } /** * @return the preferred languages */ public String getPreferredLanguage() { return preferredLanguage; } /** * @param preferredLanguage * the preferred languages */ public void setPreferredLanguage(String preferredLanguage) { this.preferredLanguage = preferredLanguage; } /** * @return the locale */ public String getLocale() { return locale; } /** * @param locale * the locale */ public void setLocale(String locale) { this.locale = locale; } /** * @return the timezone */ public String getTimezone() { return timezone; } /** * @param timezone * the timezone */ public void setTimezone(String timezone) { this.timezone = timezone; } /** * @return the active status */ public Boolean getActive() { return active; } /** * @param active * the active status */ public void setActive(Boolean active) { this.active = active; } /** * @return the password */ public String getPassword() { return password; } /** * @param password * the password */ public void setPassword(String password) { this.password = password; } @Override public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getUserName() { return userName; } /** * @param userName * the user name */ public void setUserName(String userName) { this.userName = userName; } /** * Returns an immutable view of the list of emails * * @return the emails entity */ public Set<EmailEntity> getEmails() { return ImmutableSet.copyOf(emails); } /** * Adds a new email to this user * * @param email * the emai lto add */ public void addEmail(EmailEntity email) { emails.add(email); } /** * Removes the given email from this user * * @param email * the email to remove */ public void removeEmail(EmailEntity email) { emails.remove(email); } /** * @param emails * the emails entity * @deprecated */ @Deprecated public void setEmails(Set<EmailEntity> emails) { // Setting Foreign key in child entity because hibernate did it not automatically if (emails != null) { for (EmailEntity emailEntity : emails) { emailEntity.setUser(this); } } this.emails = emails; } /** * @return the extensions data of the user */ public Set<ExtensionFieldValueEntity> getUserExtensions() { if (extensionFieldValues == null) { extensionFieldValues = new HashSet<>(); } return extensionFieldValues; } /** * @param userExtensions * the extension data of the user */ public void setUserExtensions(Set<ExtensionFieldValueEntity> userExtensions) { if (userExtensions != null) { for (ExtensionFieldValueEntity extensionValue : userExtensions) { extensionValue.setUser(this); } } this.extensionFieldValues = userExtensions; } /** * @return the phone numbers entity */ public Set<PhoneNumberEntity> getPhoneNumbers() { return phoneNumbers; } /** * @param phoneNumbers * the phone numbers entity */ public void setPhoneNumbers(Set<PhoneNumberEntity> phoneNumbers) { // Setting Foreign key in child entity because hibernate did it not automatically if (phoneNumbers != null) { for (PhoneNumberEntity phoneNumberEntity : phoneNumbers) { phoneNumberEntity.setUser(this); } } this.phoneNumbers = phoneNumbers; } /** * @return the instant messaging entity */ public Set<ImEntity> getIms() { return ims; } /** * @param ims * the instant messaging entity */ public void setIms(Set<ImEntity> ims) { // Setting Foreign key in child entity because hibernate did it not automatically if (ims != null) { for (ImEntity imEntity : ims) { imEntity.setUser(this); } } this.ims = ims; } /** * @return the photos entity */ public Set<PhotoEntity> getPhotos() { return photos; } /** * @param photos * the photos entity */ public void setPhotos(Set<PhotoEntity> photos) { // Setting Foreign key in child entity because hibernate did it not automatically if (photos != null) { for (PhotoEntity photoEntity : photos) { photoEntity.setUser(this); } } this.photos = photos; } /** * @return the addresses entity */ public Set<AddressEntity> getAddresses() { return addresses; } /** * @param addresses * the addresses entity */ public void setAddresses(Set<AddressEntity> addresses) { this.addresses = addresses; } /** * @return the entitlements */ public Set<EntitlementsEntity> getEntitlements() { return entitlements; } /** * @param entitlements * the entitlements */ public void setEntitlements(Set<EntitlementsEntity> entitlements) { this.entitlements = entitlements; } /** * @return the roles */ public Set<RolesEntity> getRoles() { return roles; } /** * @param roles * the roles */ public void setRoles(Set<RolesEntity> roles) { this.roles = roles; } /** * @return the X509 certs */ public Set<X509CertificateEntity> getX509Certificates() { return x509Certificates; } /** * @param x509Certificates * the X509 certs */ public void setX509Certificates(Set<X509CertificateEntity> x509Certificates) { // Setting Foreign key in child entity because hibernate did it not automatically if (x509Certificates != null) { for (X509CertificateEntity certificateEntity : x509Certificates) { certificateEntity.setUser(this); } } this.x509Certificates = x509Certificates; } /** * Registers a new extension for this User. If the given extension is already registered, it will be ignored. * * @param extension * The extension to register */ public void registerExtension(ExtensionEntity extension) { if (extension == null) { throw new IllegalArgumentException("extension must not be null"); } registeredExtensions.add(extension); } /** * Read all registered user extensions. * * @return A set of all registered user extensions. Never null; */ public Set<ExtensionEntity> getRegisteredExtensions() { return registeredExtensions; } /** * Adds or updates an extension field value for this User. When updating, the old value of the extension field is * removed from this user and the new one will be added. * * @param extensionValue * The extension field value to add or update */ public void addOrUpdateExtensionValue(ExtensionFieldValueEntity extensionValue) { if (extensionValue == null) { throw new IllegalArgumentException("extensionValue must not be null"); } if (extensionFieldValues.contains(extensionValue)) { extensionFieldValues.remove(extensionValue); } extensionValue.setUser(this); extensionFieldValues.add(extensionValue); } @Override public String toString() { return "UserEntity{" + "UUID='" + getId() + "\', " + "userName='" + userName + '\'' + '}'; } }
package org.twdata.pkgscanner; import java.net.URL; import java.net.URLDecoder; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.io.IOException; import java.io.File; /** * Does the actual work of scanning the classloader */ class InternalScanner { private ClassLoader classloader; private PackageScanner.VersionMapping[] versionMappings; private OsgiVersionConverter versionConverter = new DefaultOsgiVersionConverter(); static interface Test { boolean matchesPackage(String pkg); boolean matchesJar(String name); } InternalScanner(ClassLoader cl, PackageScanner.VersionMapping[] versionMappings) { this.classloader = cl; this.versionMappings = versionMappings; } void setOsgiVersionConverter(OsgiVersionConverter converter) { this.versionConverter = converter; } Collection<ExportPackage> findInPackages(Test test, String... roots) { // weans out duplicates by choosing the winner as the last one to be discovered Map<String, ExportPackage> map = new HashMap<String,ExportPackage>(); for (String pkg : roots) { for (ExportPackage export : findInPackage(test, pkg)) { map.put(export.getPackageName(), export); } } // Let's be nice and sort the results by package return new TreeSet(map.values()); } Collection<ExportPackage> findInUrls(Test test, URL... urls) { // weans out duplicates by choosing the winner as the last one to be discovered Map<String, ExportPackage> map = new HashMap<String,ExportPackage>(); Vector<URL> list = new Vector<URL>(Arrays.asList(urls)); for (ExportPackage export : findInPackageWithUrls(test, "", list.elements())) { map.put(export.getPackageName(), export); } // Let's be nice and sort the results by package return new TreeSet(map.values()); } /** * Scans for classes starting at the package provided and descending into subpackages. * Each class is offered up to the Test as it is discovered, and if the Test returns * true the class is retained. * * @param test an instance of {@link Test} that will be used to filter classes * @param packageName the name of the package from which to start scanning for * classes, e.g. {@code net.sourceforge.stripes} */ List<ExportPackage> findInPackage(Test test, String packageName) { List<ExportPackage> localExports = new ArrayList<ExportPackage>(); packageName = packageName.replace('.', '/'); Enumeration<URL> urls; try { urls = classloader.getResources(packageName); } catch (IOException ioe) { System.err.println("Could not read package: " + packageName); return localExports; } return findInPackageWithUrls(test, packageName, urls); } List<ExportPackage> findInPackageWithUrls(Test test, String packageName, Enumeration<URL> urls) { List<ExportPackage> localExports = new ArrayList<ExportPackage>(); while (urls.hasMoreElements()) { try { URL url = urls.nextElement(); String urlPath = url.getPath(); // it's in a JAR, grab the path to the jar if (urlPath.lastIndexOf('!') > 0) { urlPath = urlPath.substring(0, urlPath.lastIndexOf('!')); } else if (!urlPath.startsWith("file:")) { urlPath = "file:"+urlPath; } //System.out.println("Scanning for classes in [" + urlPath + "] matching criteria: " + test); File file = new File(new URL(urlPath).toURI()); if (file.isDirectory()) { localExports.addAll(loadImplementationsInDirectory(test, packageName, file)); } else { if (test.matchesJar(file.getName())) { localExports.addAll(loadImplementationsInJar(test, packageName, file)); } } } catch (Exception ioe) { System.err.println("could not read entries: " + ioe); } } return localExports; } /** * Finds matches in a physical directory on a filesystem. Examines all * files within a directory - if the File object is not a directory, and ends with <i>.class</i> * the file is loaded and tested to see if it is acceptable according to the Test. Operates * recursively to find classes within a folder structure matching the package structure. * * @param test a Test used to filter the classes that are discovered * @param parent the package name up to this directory in the package hierarchy. E.g. if * /classes is in the classpath and we wish to examine files in /classes/org/apache then * the values of <i>parent</i> would be <i>org/apache</i> * @param location a File object representing a directory */ List<ExportPackage> loadImplementationsInDirectory(Test test, String parent, File location) { File[] files = location.listFiles(); StringBuilder builder = null; List<ExportPackage> localExports = new ArrayList<ExportPackage>(); Set scanned = new HashSet<String>(); for (File file : files) { builder = new StringBuilder(100); builder.append(parent).append("/").append(file.getName()); String packageOrClass = (parent == null ? file.getName() : builder.toString()); if (file.isDirectory()) { localExports.addAll(loadImplementationsInDirectory(test, packageOrClass, file)); // If the parent is empty, then assume the directory's jars should be searched } else if ("".equals(parent) && file.getName().endsWith(".jar") && test.matchesJar(file.getName())) { localExports.addAll(loadImplementationsInJar(test, "", file)); } else { String pkg = packageOrClass; int lastSlash = pkg.lastIndexOf('/'); if (lastSlash > 0) { pkg = pkg.substring(0, lastSlash); } pkg = pkg.replace("/", "."); if (!scanned.contains(pkg)) { if (test.matchesPackage(pkg)) { localExports.add(new ExportPackage(pkg, determinePackageVersion(null, pkg))); } scanned.add(pkg); } } } return localExports; } /** * Finds matching classes within a jar files that contains a folder structure * matching the package structure. If the File is not a JarFile or does not exist a warning * will be logged, but no error will be raised. * * @param test a Test used to filter the classes that are discovered * @param parent the parent package under which classes must be in order to be considered * @param file the jar file to be examined for classes */ List<ExportPackage> loadImplementationsInJar(Test test, String parent, File file) { List<ExportPackage> localExports = new ArrayList<ExportPackage>(); try { JarFile jarFile = new JarFile(file); Set scanned = new HashSet<String>(); for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements(); ) { JarEntry entry = e.nextElement(); String name = entry.getName(); if (!entry.isDirectory() && name.startsWith(parent)) { String pkg = name; int pos = pkg.lastIndexOf('/'); if (pos > -1) { pkg = pkg.substring(0, pos); } pkg = pkg.replace('/', '.'); if (!scanned.contains(pkg)) { if (test.matchesPackage(pkg)) { localExports.add(new ExportPackage(pkg, determinePackageVersion(file, pkg))); } scanned.add(pkg); } } } } catch (IOException ioe) { System.err.println("Could not search jar file '" + file + "' for classes matching criteria: " + test + " due to an IOException" + ioe); } return localExports; } String determinePackageVersion(File jar, String pkg) { // Look for an explicit mapping String version = null; for (PackageScanner.VersionMapping mapping : versionMappings) { if (mapping.matches(pkg)) { version = mapping.getVersion(); } } if (version == null && jar != null) { // TODO: Look for osgi headers if (version == null) { // Try to guess the version from the jar name String name = jar.getName(); return extractVersion(name); } } return version; } /** * Tries to guess the version by assuming it starts as the first number after a '-' or '_' sign, then converts * the version into an OSGi-compatible one. */ String extractVersion(String filename) { StringBuilder version = null; boolean lastWasSeparator = false; for (int x=0; x<filename.length(); x++) { char c = filename.charAt(x); if (c == '-' || c == '_') lastWasSeparator = true; else if (Character.isDigit(c) && lastWasSeparator && version == null) version = new StringBuilder(); if (version != null) version.append(c); } if (version != null) { if (".jar".equals(version.substring(version.length() - 4))) version.delete(version.length() - 4, version.length()); return versionConverter.getVersion(version.toString()); } else return null; } }
package org.voight.morse.morsepractice; import java.util.logging.Logger; import javax.sound.sampled.LineUnavailableException; /** * * @author Jeffrey Voight <jeff.voight@gmail.com> */ public class Symbol { protected static int DIT = 0; protected static int DAH = 1; protected static Logger log = Logger.getLogger(Symbol.class.getName()); protected int symbolDuration; // Duration in milliseconds protected int ditDuration; protected int dahDuration; // Three times as long protected int ditPause; protected int dahPause; protected int hz=700; protected Tone t; protected byte[] tone = new byte[0]; private String code=""; private char c; /** * * @param c * @param _code * @param _hz * @param _speed * @throws LineUnavailableException */ public Symbol(char c, String _code, int _hz, int _speed) throws LineUnavailableException { this.c=Character.toUpperCase(c); code=_code; setDurations(_speed); setHz(_hz); t = new Tone(); String display = ""; //log.info("Code: " + _code); int strLen = _code.length(); if (!" ".equals(_code)) { for (int i = 0; i < strLen; i++) { int bit = Integer.parseInt("" + _code.charAt(i)); if (bit == 0) { tone = addTone(DIT); tone = addPause(DIT); display = display.concat("0"); } else { tone = addTone(DAH); tone = addPause(DIT); display = display.concat("1"); } } } tone = addPause(DAH); // log.info(display); } public String getText(){ return ""+c; } public String getCode(){ return code; } /** * * @param _hz */ final public void setHz(int _hz){ if(_hz>1000){ log.severe("You've selected a tone Hz greater than 1000. RIP your hearing."); } hz=_hz; } private byte[] addTone(int _longOrShort) { int bytelen = tone.length; byte[] newbytes = t.getSineWave(hz, (_longOrShort == DIT ? ditDuration : dahDuration)); byte[] returnBytes = new byte[bytelen + newbytes.length]; System.arraycopy(tone, 0, returnBytes, 0, bytelen); System.arraycopy(newbytes, 0, returnBytes, bytelen, newbytes.length); return returnBytes; } private byte[] addPause(int _longOrShort) { int bytelen = tone.length; byte[] newbytes = t.getSineWave(00, (_longOrShort == DIT ? ditDuration : dahDuration)); byte[] returnBytes = new byte[bytelen + newbytes.length]; System.arraycopy(tone, 0, returnBytes, 0, bytelen); System.arraycopy(newbytes, 0, returnBytes, bytelen, newbytes.length); return returnBytes; } /** * Gets the duration of a DIT pulse based on the Groups Per Minute Groups * consist of 5 symbols each. The worst case scenario per symbol is DAH DAH * DAH DAH DAH plus a pause. * * @param _gpm * @return */ public static int getDit(int _gpm) { double symbolPerMinute=_gpm*5; double symbolDuration = 60/symbolPerMinute; // The longest duration a symbol can be at this rate in seconds // The longest symbol possible is 5 DAHs in a row plus a DAH pause at the end. // Including the DIT pauses between DITs and DAHs, that makes // 6*DAH + 4*DIT. Each DAH is 3*DIT. This means that the longest symbol is // 3 * 6 * DAH + 4 * DIT = (18 + 4) * DIT or 22*DIT. // Therefore, a DIT is longest/22. double ditDuration = symbolDuration/22; int ditDurationMilliseconds=(int)(ditDuration*1000); log.info("At " + _gpm + "GPM, DIT is " + ditDurationMilliseconds + " milliseconds."); return ditDurationMilliseconds; } private void setDurations(int _speed) { ditDuration = getDit(_speed); dahDuration = ditDuration * 3; ditPause = ditDuration; dahPause = dahDuration; } /** * * @return */ public byte[] getBytes() { return tone; } }
package org.voovan.http.server; import org.voovan.http.message.packet.Cookie; import org.voovan.http.server.exception.ResourceNotFound; import org.voovan.http.server.exception.RouterNotFound; import org.voovan.http.server.router.MimeFileRouter; import org.voovan.tools.*; import org.voovan.tools.log.Logger; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.*; public class HttpDispatcher { /** * [MainKey] = HTTP method ,[Value] = { [Value Key] = Route path, [Value value] = RouteBuiz } */ private Map<String, Map<String, HttpRouter>> methodRouters; private WebServerConfig webConfig; private SessionManager sessionManager; /** * * * @param webConfig Web * @param sessionManager Session */ public HttpDispatcher(WebServerConfig webConfig,SessionManager sessionManager) { methodRouters = new LinkedHashMap<String, Map<String, HttpRouter>>(); this.webConfig = webConfig; this.sessionManager = sessionManager; // HTTP this.addRouteMethod("GET"); this.addRouteMethod("POST"); this.addRouteMethod("HEAD"); this.addRouteMethod("PUT"); this.addRouteMethod("DELETE"); this.addRouteMethod("TRACE"); this.addRouteMethod("CONNECT"); this.addRouteMethod("OPTIONS"); // Mime addRouteHandler("GET", MimeTools.getMimeTypeRegex(), new MimeFileRouter(webConfig.getContextPath())); } /** * ,:HTTP GETPOST * * @param method HTTP */ protected void addRouteMethod(String method) { if (!methodRouters.containsKey(method)) { Map<String,HttpRouter> routers = new TreeMap<String, HttpRouter>(new Comparator<String>() { @Override public int compare(String o1, String o2) { if(o1.length() > o2.length()){ return -1; } else if(o1.length() < o2.length()){ return 1; } else { return 0; } } }); methodRouters.put(method, routers); } } /** * * * @param method Http * @param routeRegexPath * @param router */ public void addRouteHandler(String method, String routeRegexPath, HttpRouter router) { if (methodRouters.keySet().contains(method)) { methodRouters.get(method).put(routeRegexPath, router); } } /** * Http , * * @param request HTTP * @param response HTTP */ public void process(HttpRequest request, HttpResponse response){ Chain<HttpFilterConfig> filterConfigs = webConfig.getFilterConfigs().clone(); //Session diposeSession(request,response); //, Redirect diposeFilter(filterConfigs,request,response); disposeRoute(request,response); diposeInvertedFilter(filterConfigs,request,response); WebContext.writeAccessLog(request,response); } /** * Http * @param request Http * @param response Http */ public void disposeRoute(HttpRequest request, HttpResponse response){ String requestPath = request.protocol().getPath(); String requestMethod = request.protocol().getMethod(); boolean isMatched = false; Map<String, HttpRouter> routers = methodRouters.get(requestMethod); for (Map.Entry<String,HttpRouter> routeEntry : routers.entrySet()) { String routePath = routeEntry.getKey(); isMatched = matchPath(requestPath,routePath,webConfig.isMatchRouteIgnoreCase()); if (isMatched) { HttpRouter router = routeEntry.getValue(); try { Map<String, String> pathVariables = fetchPathVariables(requestPath,routePath); request.getParameters().putAll(pathVariables); router.process(request, response); } catch (Exception e) { exceptionMessage(request, response, e); } break; } } if(!isMatched) { exceptionMessage(request, response, new RouterNotFound("Not avaliable router!")); } } /** * * @param routePath * @return */ public static String routePath2RegexPath(String routePath){ String routeRegexPath = routePath.replaceAll(":[^/?]+", "[^/?]+"); routeRegexPath = routeRegexPath.replaceAll("/\\*","/.*"); return routeRegexPath; } /** * * @param requestPath * @param routePath * @param matchRouteIgnoreCase * @return */ public static boolean matchPath(String requestPath, String routePath,boolean matchRouteIgnoreCase){ ///home/:name/home/[^/?]+ String routeRegexPath = routePath2RegexPath(routePath); if(matchRouteIgnoreCase){ requestPath = requestPath.toLowerCase(); routeRegexPath = routeRegexPath.toLowerCase(); } if(TString.regexMatch(requestPath, routeRegexPath+"$" ) > 0 ){ return true; }else if(TString.regexMatch(requestPath, routeRegexPath+"/$" ) > 0){ return true; } return false ; } /** * ,/:test/:name /test/var1{name:var1} * @param requestPath * @param routePath * @return Map */ public static Map<String, String> fetchPathVariables(String requestPath,String routePath) { Map<String, String> resultMap = new HashMap<String, String>(); String[] requestPathPieces = requestPath.substring(1,requestPath.length()).split("/"); String[] routePathPieces = routePath.substring(1, routePath.length()).split("/"); if(requestPathPieces.length == routePathPieces.length){ try { for (int i = 1; i <= routePathPieces.length; i++) { int routePathPiecesLength = routePathPieces.length; int pathPiecesLength = requestPathPieces.length; String routePathPiece = routePathPieces[routePathPiecesLength - i]; if (routePathPiece.startsWith(":")) { String name = TString.removePrefix(routePathPiece); String value = URLDecoder.decode(requestPathPieces[pathPiecesLength - i], "UTF-8"); resultMap.put(name, value); } } } catch (UnsupportedEncodingException e) { Logger.error("RoutePath URLDecoder.decode failed by charset: UTF-8", e); } } return resultMap; } /** * Session * @param request HTTP * @param response HTTP */ public void diposeSession(HttpRequest request, HttpResponse response){ // Cookiesession Cookie sessionCookie = request.getCookie(WebContext.getSessionName()); // session , session if (!sessionManager.containsSession(sessionCookie)) { // session HttpSession session = sessionManager.newHttpSession(request, response); // Session request.setSession(session); } else { // Cookie session Session HttpSession session = sessionManager.getSession(sessionCookie.getValue()); // Session request.setSession(session); } } /** * // * @param filterConfigs HTTP * @param request * @param response */ public void diposeFilter(Chain<HttpFilterConfig> filterConfigs, HttpRequest request, HttpResponse response) { filterConfigs.rewind(); Object filterResult = null; while(filterConfigs.hasNext()){ HttpFilterConfig filterConfig = filterConfigs.next(); HttpFilter httpFilter = filterConfig.getHttpFilterInstance(); if(httpFilter!=null) { filterResult = httpFilter.onRequest(filterConfig, request, response, filterResult); } } } /** * * @param filterConfigs HTTP * @param request * @param response */ public void diposeInvertedFilter(Chain<HttpFilterConfig> filterConfigs, HttpRequest request, HttpResponse response) { filterConfigs.rewind(); Object filterResult = null; while(filterConfigs.hasPrevious()){ HttpFilterConfig filterConfig = filterConfigs.previous(); HttpFilter httpFilter = filterConfig.getHttpFilterInstance(); if(httpFilter!=null) { filterResult = httpFilter.onResponse(filterConfig, request, response, filterResult); } } } /** * * * @param request * @param response * @param e */ public void exceptionMessage(HttpRequest request, HttpResponse response, Exception e) { Map<String, Object> errorDefine = WebContext.getErrorDefine(); String requestMethod = request.protocol().getMethod(); String requestPath = request.protocol().getPath(); String className = e.getClass().getName(); String errorMessage = e.toString(); String stackInfo = TEnv.getStackMessage(); // HTML stackInfo = TString.indent(stackInfo,1).replace("\n", "<br>"); response.header().put("Content-Type", "text/html"); // error , Map<String, Object> error = new HashMap<String, Object>(); if( !(e instanceof ResourceNotFound || e instanceof RouterNotFound) ){ error.put("StatusCode", 500); Logger.error(e); }else{ error.put("StatusCode", 404); } error.put("Page", "Error.html"); error.put("Description", stackInfo); // error , if (errorDefine.containsKey(className)) { error.putAll(TObject.cast(errorDefine.get(className))); response.protocol().setStatus(TObject.cast(error.get("StatusCode"))); } else if (errorDefine.get("Other") != null) { error.putAll(TObject.cast(errorDefine.get("Other"))); response.protocol().setStatus(TObject.cast(error.get("StatusCode"))); } String errorPageContent = WebContext.getDefaultErrorPage(); if(TFile.fileExists(TEnv.getSystemPath("/conf/error-page/" + error.get("Page")))) { try { errorPageContent = new String(TFile.loadFileFromContextPath("/conf/error-page/" + error.get("Page")),"UTF-8"); } catch (UnsupportedEncodingException e1) { Logger.error("This charset is unsupported.",e); } } if(errorPageContent!=null){ errorPageContent = TString.tokenReplace(errorPageContent, "StatusCode", error.get("StatusCode").toString()); errorPageContent = TString.tokenReplace(errorPageContent, "RequestMethod", requestMethod); errorPageContent = TString.tokenReplace(errorPageContent, "RequestPath", requestPath); errorPageContent = TString.tokenReplace(errorPageContent, "ErrorMessage", errorMessage); errorPageContent = TString.tokenReplace(errorPageContent, "Description", error.get("Description").toString()); errorPageContent = TString.tokenReplace(errorPageContent, "Version", WebContext.getVERSION()); errorPageContent = TString.tokenReplace(errorPageContent, "DateTime", TDateTime.now()); response.clear(); response.write(errorPageContent); } } }
package prosecutor.barrister.languages; //Licence: AGPL v3 //This file is part of Barrister, which is part of Prosecutor. import com.sun.org.apache.bcel.internal.generic.RET; import com.sun.org.apache.bcel.internal.generic.RETURN; import java.lang.reflect.Field; public class Tokens { public static void generateIndex(){ int i=1; try { i=generateIndexFor(Class.class,i); i=generateIndexFor(Conditions.class,i); i=generateIndexFor(Expressions.class,i); i=generateIndexFor(Statements.class,i); i=generateIndexFor(RETURN.class,i); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } private static int generateIndexFor(java.lang.Class clazz,int startIndex) throws NoSuchFieldException, IllegalAccessException { Field[] fields=clazz.getDeclaredFields(); for(int i=0;i<fields.length;i++) { if(fields[i].isAnnotationPresent(Duplicate.class)) { Duplicate duplicate=(Duplicate)fields[i].getAnnotation(Duplicate.class); fields[i].setInt(null,duplicate.from().getDeclaredField(duplicate.name().equals("")?fields[i].getName():duplicate.name()).getInt(null)); } else { fields[i].setInt(null,startIndex++); } } return startIndex; } public static class Class { public static int CLASS_CONSTRUCTOR_START , CLASS_CONSTRUCTOR_END; public static int CLASS_METHOD_START , CLASS_METHOD_END; } public static class Conditions { public static int IF_START,IF_STOP; public static int WHILE_START,WHILE_STOP; public static int FOR_START,FOR_STOP; public static int SWITCH_START,SWITCH_STOP; public static int CONDITIONAL_EXPRESSION_START; } public static class Expressions { @Duplicate(from = Conditions.class) public static int CONDITIONAL_EXPRESSION_START; public static int ASSIGNMENT_EXPRESSION_START; } public static class Statements { public static int ASSERT; public static int CONTINUE; public static int RETURN; public static int THROW; public static int SYNCHRONIZED_START,SYNCHRONIZED_STOP; } public static class ReturnTypes { public static int RETURN_VOID; } public @interface Duplicate { java.lang.Class from(); String name() default ""; } }
package seedu.taskitty.storage; import seedu.taskitty.commons.exceptions.IllegalValueException; import seedu.taskitty.model.tag.Tag; import seedu.taskitty.model.tag.UniqueTagList; import seedu.taskitty.model.task.*; import javax.xml.bind.annotation.XmlElement; import java.util.ArrayList; import java.util.List; /** * JAXB-friendly version of the Person. */ public class XmlAdaptedTask { @XmlElement(required = true) private String name; @XmlElement private String startDate; @XmlElement private String endDate; @XmlElement private String startTime; @XmlElement private String endTime; @XmlElement private boolean isDone; @XmlElement private List<XmlAdaptedTag> tagged = new ArrayList<>(); /** * No-arg constructor for JAXB use. */ public XmlAdaptedTask() {} /** * Converts a given Person into this class for JAXB use. * * @param source future changes to this will not affect the created XmlAdaptedPerson */ public XmlAdaptedTask(ReadOnlyTask source) { name = source.getName().fullName; TaskDate sourceStartDate = source.getStartDate(); TaskDate sourceEndDate = source.getEndDate(); TaskTime sourceStartTime = source.getStartTime(); TaskTime sourceEndTime = source.getEndTime(); boolean sourceIsDone = source.getIsDone(); if (sourceStartDate != null) { startDate = sourceStartDate.toString(); } if (sourceEndDate != null) { endDate = sourceEndDate.toString(); } if (sourceStartTime != null) { startTime = sourceStartTime.toString(); } if (sourceEndTime != null) { endTime = sourceEndTime.toString(); } isDone = source.getIsDone(); tagged = new ArrayList<>(); for (Tag tag : source.getTags()) { tagged.add(new XmlAdaptedTag(tag)); } } public void markAsDone() { if (!isDone) { isDone = true; } } public Task toModelType() throws IllegalValueException { final List<Tag> taskTags = new ArrayList<>(); for (XmlAdaptedTag tag : tagged) { taskTags.add(tag.toModelType()); } final Name name = new Name(this.name); TaskDate startDate = null; if (this.startDate != null) { startDate = new TaskDate(this.startDate); } TaskDate endDate = null; if (this.endDate != null) { endDate = new TaskDate(this.endDate); } TaskTime startTime = null; if (this.startTime != null) { startTime = new TaskTime(this.startTime); } TaskTime endTime = null; if (this.endTime != null) { endTime = new TaskTime(this.endTime); } final UniqueTagList tags = new UniqueTagList(taskTags); Task task = new Task(name, startDate, startTime, endDate, endTime, tags); if (isDone) { task.markAsDone(); } return task; } }
package seedu.todo.controllers; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import seedu.todo.commons.exceptions.InvalidNaturalDateException; import seedu.todo.commons.exceptions.ParseException; import seedu.todo.commons.util.DateUtil; import seedu.todo.commons.util.FilterUtil; import seedu.todo.commons.util.ParseUtil; import seedu.todo.commons.util.StringUtil; import seedu.todo.controllers.concerns.Tokenizer; import seedu.todo.controllers.concerns.DateParser; import seedu.todo.controllers.concerns.Renderer; import seedu.todo.models.CalendarItem; import seedu.todo.models.Event; import seedu.todo.models.Task; import seedu.todo.models.TodoListDB; /** * @@author A0139922Y * Controller to find task/event by keyword * */ public class FindController implements Controller { private static final String NAME = "Find"; private static final String DESCRIPTION = "Find all tasks and events based on the provided keywords.\n" + "This command will be searching with non-case sensitive keywords."; private static final String COMMAND_WORD = "find"; // Syntax correction to console input private static final String COMMAND_SYNTAX = "find \"name\" tagName \"tag\" on \"date\" \"task/event\""; private static final String FIND_TASK_SYNTAX = "find \"name\" task \"complete/incomplete\""; private static final String FIND_EVENT_SYNTAX = "find \"name\" event \"over/ongoing\""; // Message output to console text area private static final String MESSAGE_RESULT_FOUND = "A total of %s found!"; private static final String MESSAGE_NO_RESULT_FOUND = "No task or event found!"; private static final String MESSAGE_NO_KEYWORD_FOUND = "No keyword found!"; private static final String MESSAGE_DATE_CONFLICT = "Unable to find!\nMore than 1 date criteria is provided!"; private static final String MESSAGE_NO_DATE_DETECTED = "Unable to find!\nThe natural date entered is not supported."; private static final String MESSAGE_INVALID_TASK_STATUS = "Unable to find!\nTry searching with complete or incomplete"; private static final String MESSAGE_INVALID_EVENT_STATUS = "Unable to find!\nTry searching with over or current"; private static final String MESSAGE_ITEM_TYPE_CONFLICT = "Unable to list!\nMore than 1 item type is provided!"; private static final int COMMAND_INPUT_INDEX = 0; //use to access parsing of dates private static final int NUM_OF_DATES_FOUND_INDEX = 0; private static final int DATE_ON_INDEX = 1; private static final int DATE_FROM_INDEX = 2; private static final int DATE_TO_INDEX = 3; private static CommandDefinition commandDefinition = new CommandDefinition(NAME, DESCRIPTION, COMMAND_SYNTAX); public static CommandDefinition getCommandDefinition() { return commandDefinition; } @Override public float inputConfidence(String input) { String command = StringUtil.splitStringBySpace(input.toLowerCase())[COMMAND_INPUT_INDEX]; return (command).equals(COMMAND_WORD) ? 1 : 0; } private static Map<String, String[]> getTokenDefinitions() { Map<String, String[]> tokenDefinitions = new HashMap<String, String[]>(); tokenDefinitions.put(Tokenizer.DEFAULT_TOKEN, new String[] { COMMAND_WORD }); tokenDefinitions.put(Tokenizer.EVENT_TYPE_TOKEN, Tokenizer.EVENT_TYPE_DEFINITION); tokenDefinitions.put(Tokenizer.TIME_TOKEN, Tokenizer.TIME_DEFINITION); tokenDefinitions.put(Tokenizer.TASK_STATUS_TOKEN, Tokenizer.TASK_STATUS_DEFINITION); tokenDefinitions.put(Tokenizer.EVENT_STATUS_TOKEN, Tokenizer.EVENT_STATUS_DEFINITION); tokenDefinitions.put(Tokenizer.TIME_FROM_TOKEN, Tokenizer.TIME_FROM_DEFINITION); tokenDefinitions.put(Tokenizer.TIME_TO_TOKEN, Tokenizer.TIME_TO_DEFINITION); tokenDefinitions.put(Tokenizer.ITEM_NAME_TOKEN, Tokenizer.ITEM_NAME_DEFINITION); tokenDefinitions.put(Tokenizer.TAG_NAME_TOKEN, Tokenizer.TAG_NAME_DEFINITION); return tokenDefinitions; } @Override public void process(String input) throws ParseException { Map<String, String[]> parsedResult; parsedResult = Tokenizer.tokenize(getTokenDefinitions(), input); HashSet<String> itemNameList = new HashSet<String>(); HashSet<String> tagNameList = new HashSet<String>(); HashSet<String> keywordList = new HashSet<String>(); // To be use to be filter out name and tag names updateHashList(parsedResult, keywordList, Tokenizer.DEFAULT_TOKEN); updateHashList(parsedResult, itemNameList, Tokenizer.ITEM_NAME_TOKEN); updateHashList(parsedResult, tagNameList, Tokenizer.TAG_NAME_TOKEN); itemNameList.addAll(keywordList); tagNameList.addAll(keywordList); // Show console output message, since no keyword found if (keywordList.size() == 0 && itemNameList.size() == 0 && tagNameList.size() == 0) { //No keyword provided, display error Renderer.renderDisambiguation(COMMAND_SYNTAX, MESSAGE_NO_KEYWORD_FOUND); return; } // Check if input includes itemType and itemStatus boolean isItemTypeProvided = !ParseUtil.isTokenNull(parsedResult, Tokenizer.EVENT_TYPE_TOKEN); boolean isTaskStatusProvided = !ParseUtil.isTokenNull(parsedResult, Tokenizer.TASK_STATUS_TOKEN); boolean isEventStatusProvided = !ParseUtil.isTokenNull(parsedResult, Tokenizer.EVENT_STATUS_TOKEN); // Set item type boolean isTask = true; //default if (isItemTypeProvided) { isTask = ParseUtil.doesTokenContainKeyword(parsedResult, Tokenizer.EVENT_TYPE_TOKEN, "task"); } if (isErrorCommand(isTaskStatusProvided, isEventStatusProvided, isTask, isItemTypeProvided, input)) { return; // Break out if found error } // Setting up view TodoListDB db = TodoListDB.getInstance(); List<Task> tasks; //default List<Event> events; //default List<CalendarItem> calendarItems; // Filter out the tasks and events based on type and names if (!isItemTypeProvided) { tasks = filterByTaskNameAndTagName(itemNameList, tagNameList, db.getAllTasks()); events = filterByEventNameAndTagName(itemNameList, tagNameList, db.getAllEvents()); } else { if (isTask) { events = new ArrayList<Event>(); tasks = filterByTaskNameAndTagName(itemNameList, tagNameList, db.getAllTasks()); } else { tasks = new ArrayList<Task>(); events = filterByEventNameAndTagName(itemNameList, tagNameList, db.getAllEvents()); } } // Filter Task and Event by Status calendarItems = filterTasksAndEventsByStatus(parsedResult, isTaskStatusProvided, isEventStatusProvided, tasks, events); tasks = FilterUtil.filterOutTask(calendarItems); events = FilterUtil.filterOutEvent(calendarItems); // Filter Task and Event by date calendarItems = filterTasksAndEventsByDate(tasks, events, parsedResult); if (calendarItems == null) { return; // Date conflict detected } tasks = FilterUtil.filterOutTask(calendarItems); events = FilterUtil.filterOutEvent(calendarItems); // Show message if no items had been found if (tasks.size() == 0 && events.size() == 0) { Renderer.renderIndex(db, MESSAGE_NO_RESULT_FOUND); return; } String consoleMessage = String.format(MESSAGE_RESULT_FOUND, StringUtil.displayNumberOfTaskAndEventFoundWithPuralizer(tasks.size(), events.size())); Renderer.renderSelectedIndex(db, consoleMessage, tasks, events); } /* * Filter out the selected tasks and events based on the status and update tasks and events accordingly * * @param parsedResult * parsedResult by Tokenizer * @param isTaskStatusProvided * true if complete or incomplete is found, else false * @param isEventStatusProvided * true if over or current is found, else false * @param tasks * List of Task items * @param events * List of Event items * @return * tasks and events in a list form by status */ private List<CalendarItem> filterTasksAndEventsByStatus(Map<String, String[]> parsedResult, boolean isTaskStatusProvided, boolean isEventStatusProvided, List<Task> tasks, List<Event> events) { List<CalendarItem> calendarItems = new ArrayList<CalendarItem>(); // Set item status boolean isCompleted = false; //default boolean isOver = false; //default List<Task> filteredTasks = tasks; List<Event> filteredEvents = events; // Filter out by Task Status if provided if (isTaskStatusProvided) { isCompleted = !ParseUtil.doesTokenContainKeyword(parsedResult, Tokenizer.TASK_STATUS_TOKEN, "incomplete"); filteredTasks = FilterUtil.filterTasksByStatus(tasks, isCompleted); filteredEvents = new ArrayList<Event>(); } // Filter out by Event Status if provided if (isEventStatusProvided) { isOver = ParseUtil.doesTokenContainKeyword(parsedResult, Tokenizer.EVENT_STATUS_TOKEN, "over"); filteredEvents = FilterUtil.filterEventsByStatus(events, isOver); filteredTasks = new ArrayList<Task>(); } calendarItems.addAll(filteredTasks); calendarItems.addAll(filteredEvents); return calendarItems; } /* * Filter out the selected tasks and events based on the dates * and update tasks and events accordingly * * @param tasks * List of Task items * @param events * List of Event items * @param parsedResult * parsedResult by Tokenizer * @return * tasks and events in a list form by date or null when date conflict found */ private List<CalendarItem> filterTasksAndEventsByDate(List<Task> tasks, List<Event> events, Map<String, String[]> parsedResult) { // Get dates from input List<CalendarItem> calendarItems = new ArrayList<CalendarItem>(); String[] parsedDates = ParseUtil.parseDates(parsedResult); LocalDateTime [] validDates = parsingDates(parsedResult, parsedDates); List<Task> filteredTasks; List<Event> filteredEvents; if (validDates == null) { return null; // Break out when date conflict found } // Set dates that are found, if not found value will be null LocalDateTime dateOn = validDates[DATE_ON_INDEX]; LocalDateTime dateFrom = validDates[DATE_FROM_INDEX]; LocalDateTime dateTo = validDates[DATE_TO_INDEX]; if (dateOn != null) { // Filter by single date filteredTasks = FilterUtil.filterTaskBySingleDate(tasks, dateOn); filteredEvents = FilterUtil.filterEventBySingleDate(events, dateOn); } else { // Filter by range filteredTasks = FilterUtil.filterTaskWithDateRange(tasks, dateFrom, dateTo); filteredEvents = FilterUtil.filterEventWithDateRange(events, dateFrom, dateTo); } calendarItems.addAll(filteredTasks); calendarItems.addAll(filteredEvents); return calendarItems; } /* * Filter out all the events based on the name list that has been parsed. * This method also ensure that no duplicate event will be return. * * @param itemNameList * a list of item name that has been parsed from input * @param tagNameList * a List of tag name that has been parsed from input * @param events * all the events in the DB * @return a list of Event which names or tag names is filtered with the list */ private List<Event> filterByEventNameAndTagName(HashSet<String> itemNameList, HashSet<String> tagNameList, List<Event> events) { HashSet<Event> mergedEvents = new HashSet<Event>(); List<Event> eventsByNames = FilterUtil.filterEventByNames(events, itemNameList); List<Event> eventsByTags = FilterUtil.filterEventByTags(events, tagNameList); mergedEvents.addAll(eventsByNames); mergedEvents.addAll(eventsByTags); events = new ArrayList<Event>(mergedEvents); return events; } /* * Filter out all the tasks based on the name list that has been parsed. * This method also ensure that no duplicate task will be return. * * @param itemNameList * a list of item name that has been parsed from input * @param tagNameList * a List of tag name that has been parsed from input * @param tasks * all the tasks in the DB * @return a list of Task which names or tag names is filtered with the list */ private List<Task> filterByTaskNameAndTagName(HashSet<String> itemNameList, HashSet<String> tagNameList, List<Task> tasks) { HashSet<Task> mergedTasks = new HashSet<Task>(); List<Task> tasksByNames = FilterUtil.filterTaskByNames(tasks, itemNameList); List<Task> tasksByTags = FilterUtil.filterTaskByTags(tasks, tagNameList); mergedTasks.addAll(tasksByNames); mergedTasks.addAll(tasksByTags); tasks = new ArrayList<Task>(mergedTasks); return tasks; } /** * Extract the parsed result and update into the hashlist * @param parsedResult */ private void updateHashList(Map<String, String[]> parsedResult, HashSet<String> hashList, String token) { String result = ParseUtil.getTokenResult(parsedResult, token); // If found any matching , update list if (result != null) { hashList.add(result); String[] resultArray = StringUtil.splitStringBySpace(result); for (int i = 0; i < resultArray.length; i ++) { hashList.add(resultArray[i]); } } } /* * To be use to check if there are any command syntax error * * @return true, if there is an error in the command syntax, false if syntax is allowed */ private boolean isErrorCommand(boolean isTaskStatusProvided, boolean isEventStatusProvided, boolean isTask, boolean isItemTypeProvided, String input) { // Check if more than 1 item type is provided if (FilterUtil.isItemTypeConflict(input)) { Renderer.renderDisambiguation(COMMAND_SYNTAX, MESSAGE_ITEM_TYPE_CONFLICT); return true; } if (isItemTypeProvided) { // Task and Event Command Syntax detected if (isTask && isEventStatusProvided) { Renderer.renderDisambiguation(FIND_TASK_SYNTAX, MESSAGE_INVALID_TASK_STATUS); return true; } if (!isTask && isTaskStatusProvided) { Renderer.renderDisambiguation(FIND_EVENT_SYNTAX, MESSAGE_INVALID_EVENT_STATUS); return true; } } return false; } /* * To be used to parsed dates and check for any dates conflict * * @return null if dates conflict detected, else return { null, dateOn, dateFrom, dateTo } */ private LocalDateTime[] parsingDates(Map<String, String[]> parsedResult, String[] parsedDates) { LocalDateTime dateOn = null; LocalDateTime dateFrom = null; LocalDateTime dateTo = null; if (parsedDates != null) { String naturalOn = parsedDates[DATE_ON_INDEX]; String naturalFrom = parsedDates[DATE_FROM_INDEX]; String naturalTo = parsedDates[DATE_TO_INDEX]; if (naturalOn != null && Integer.parseInt(parsedDates[NUM_OF_DATES_FOUND_INDEX]) > 1) { // Date conflict detected Renderer.renderDisambiguation(COMMAND_SYNTAX, MESSAGE_DATE_CONFLICT); return null; } // Parse natural date using Natty. try { dateOn = naturalOn == null ? null : DateUtil.floorDate(DateParser.parseNatural(naturalOn)); dateFrom = naturalFrom == null ? null : DateUtil.floorDate(DateParser.parseNatural(naturalFrom)); dateTo = naturalTo == null ? null : DateUtil.floorDate(DateParser.parseNatural(naturalTo)); } catch (InvalidNaturalDateException e) { Renderer.renderDisambiguation(COMMAND_SYNTAX, MESSAGE_NO_DATE_DETECTED); return null; } } return new LocalDateTime[] { null, dateOn, dateFrom, dateTo }; } }
package seedu.todo.controllers; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import seedu.todo.commons.exceptions.ParseException; import seedu.todo.commons.util.DateUtil; import seedu.todo.commons.util.FilterUtil; import seedu.todo.commons.util.ParseUtil; import seedu.todo.commons.util.StringUtil; import seedu.todo.controllers.concerns.Tokenizer; import seedu.todo.controllers.concerns.Renderer; import seedu.todo.models.Event; import seedu.todo.models.Task; import seedu.todo.models.TodoListDB; /** * Controller to list CalendarItems. * * @@author Tiong Yaocong A0139922Y * */ public class ListController implements Controller { private static final String NAME = "List"; private static final String DESCRIPTION = "List all tasks and events by type or status."; private static final String COMMAND_SYNTAX = "list [task complete/incomplete or event] [event over/ongoing] " + "[on date] or [from date to date]"; private static final String COMMAND_WORD = "list"; private static final String TASK_SYNTAX = "list task [complete/incomplete]"; private static final String EVENT_SYNTAX = "list event [over/ongoing]"; private static final String DATE_SYNTAX = "list [date] or [from <date> to <date>]"; private static final String MESSAGE_RESULT_FOUND = "A total of %s found!"; private static final String MESSAGE_NO_RESULT_FOUND = "No task or event found!"; private static final String MESSAGE_LIST_SUCCESS = "Listing Today's, incompleted tasks and ongoing events"; private static final String MESSAGE_INVALID_TASK_STATUS = "Unable to list!\nTry listing with [complete] or [incomplete]"; private static final String MESSAGE_INVALID_EVENT_STATUS = "Unable to list!\nTry listing with [over] or [current]"; private static final String MESSAGE_DATE_CONFLICT = "Unable to find!\nMore than 1 date criteria is provided!"; private static final String MESSAGE_NO_DATE_DETECTED = "Unable to find!\nThe natural date entered is not supported."; //use to access parsing of dates private static final int NUM_OF_DATES_FOUND_INDEX = 0; private static final int DATE_ON_INDEX = 1; private static final int DATE_FROM_INDEX = 2; private static final int DATE_TO_INDEX = 3; private static CommandDefinition commandDefinition = new CommandDefinition(NAME, DESCRIPTION, COMMAND_SYNTAX); public static CommandDefinition getCommandDefinition() { return commandDefinition; } @Override public float inputConfidence(String input) { return (input.toLowerCase().startsWith("list")) ? 1 : 0; } private static Map<String, String[]> getTokenDefinitions() { Map<String, String[]> tokenDefinitions = new HashMap<String, String[]>(); tokenDefinitions.put("default", new String[] {"list"}); tokenDefinitions.put("eventType", new String[] { "event", "events", "task", "tasks"}); tokenDefinitions.put("taskStatus", new String[] { "complete" , "completed", "incomplete", "incompleted"}); tokenDefinitions.put("eventStatus", new String[] { "over" , "ongoing", "current", "schedule" , "scheduled"}); tokenDefinitions.put("time", new String[] { "at", "by", "on", "time" }); tokenDefinitions.put("timeFrom", new String[] { "from" }); tokenDefinitions.put("timeTo", new String[] { "to", "before", "until" }); return tokenDefinitions; } @Override public void process(String input) throws ParseException { Map<String, String[]> parsedResult; parsedResult = Tokenizer.tokenize(getTokenDefinitions(), input); TodoListDB db = TodoListDB.getInstance(); if (input.trim().equals(COMMAND_WORD)) { Renderer.renderIndex(db, MESSAGE_LIST_SUCCESS); return; } boolean isItemTypeProvided = !ParseUtil.isTokenNull(parsedResult, "eventType"); boolean isTaskStatusProvided = !ParseUtil.isTokenNull(parsedResult, "taskStatus"); boolean isEventStatusProvided = !ParseUtil.isTokenNull(parsedResult, "eventStatus"); boolean isTask = true; //default if (isItemTypeProvided) { isTask = ParseUtil.doesTokenContainKeyword(parsedResult, "eventType", "task"); if (isTask && isEventStatusProvided) { Renderer.renderDisambiguation(TASK_SYNTAX, MESSAGE_INVALID_TASK_STATUS); return; } if (!isTask && isTaskStatusProvided) { Renderer.renderDisambiguation(EVENT_SYNTAX, MESSAGE_INVALID_EVENT_STATUS); return; } } boolean isCompleted = false; //default boolean isOver = false; //default if (isTaskStatusProvided) { isCompleted = !ParseUtil.doesTokenContainKeyword(parsedResult, "taskStatus", "incomplete"); } if (isEventStatusProvided) { isOver = ParseUtil.doesTokenContainKeyword(parsedResult, "eventStatus", "over"); } String[] parsedDates = ParseUtil.parseDates(parsedResult); //date enter with COMMAND_WORD e.g list today String date = ParseUtil.getTokenResult(parsedResult, "default"); if (date != null && parsedDates != null) { Renderer.renderDisambiguation(DATE_SYNTAX, MESSAGE_DATE_CONFLICT); return; } LocalDateTime dateCriteria = null; LocalDateTime dateOn = null; LocalDateTime dateFrom = null; LocalDateTime dateTo = null; if (date != null) { dateCriteria = DateUtil.parseNatural(date); if (dateCriteria == null) { Renderer.renderDisambiguation(DATE_SYNTAX, MESSAGE_NO_DATE_DETECTED); return ; } } if (parsedDates != null) { String naturalOn = parsedDates[DATE_ON_INDEX]; String naturalFrom = parsedDates[DATE_FROM_INDEX]; String naturalTo = parsedDates[DATE_TO_INDEX]; if (naturalOn != null && Integer.parseInt(parsedDates[NUM_OF_DATES_FOUND_INDEX]) > 1) { //date conflict detected Renderer.renderDisambiguation(DATE_SYNTAX, MESSAGE_DATE_CONFLICT); return; } // Parse natural date using Natty. dateOn = naturalOn == null ? null : DateUtil.parseNatural(naturalOn); dateFrom = naturalFrom == null ? null : DateUtil.parseNatural(naturalFrom); dateTo = naturalTo == null ? null : DateUtil.parseNatural(naturalTo); } if (parsedDates != null && dateOn == null && dateFrom == null && dateTo == null) { //Natty failed to parse date Renderer.renderDisambiguation(DATE_SYNTAX, MESSAGE_NO_DATE_DETECTED); return ; } if (parsedDates != null && isEventStatusProvided) { //detect date conflict Renderer.renderDisambiguation(DATE_SYNTAX, MESSAGE_DATE_CONFLICT); return; } //Setting up views List<Task> tasks = db.getAllTasks(); List<Event> events = db.getAllEvents();; if (isItemTypeProvided) { if (isTask) { events = new ArrayList<Event>(); } else if (!isTask) { tasks = new ArrayList<Task>(); } } if (isTaskStatusProvided) { tasks = FilterUtil.filterTasksByStatus(tasks, isCompleted); events = new ArrayList<Event>(); } if (isEventStatusProvided) { events = FilterUtil.filterEventsByStatus(events, isOver); tasks = new ArrayList<Task>(); } if (dateCriteria != null) { tasks = FilterUtil.filterTaskBySingleDate(tasks, dateCriteria); events = FilterUtil.filterEventBySingleDate(events, dateCriteria); } if (dateOn != null) { //filter by single date tasks = FilterUtil.filterTaskBySingleDate(tasks, dateOn); events = FilterUtil.filterEventBySingleDate(events, dateOn); } else { //filter by range tasks = FilterUtil.filterTaskWithDateRange(tasks, dateFrom, dateTo); events = FilterUtil.filterEventWithDateRange(events, dateFrom, dateTo); } if (tasks.size() == 0 && events.size() == 0) { Renderer.renderIndex(db, MESSAGE_NO_RESULT_FOUND); return; } String consoleMessage = String.format(MESSAGE_RESULT_FOUND, StringUtil.displayNumberOfTaskAndEventFoundWithPuralizer(tasks.size(), events.size())); Renderer.renderSelectedIndex(db, consoleMessage, tasks, events); } }
package seedu.todo.controllers; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.joestelmach.natty.DateGroup; import com.joestelmach.natty.Parser; import seedu.todo.commons.exceptions.UnmatchedQuotesException; import seedu.todo.commons.util.DateUtil; import seedu.todo.commons.util.StringUtil; import seedu.todo.models.TodoListDB; import seedu.todo.ui.UiManager; import seedu.todo.ui.views.IndexView; public class ListController implements Controller { private static String NAME = "List"; private static String DESCRIPTION = "Lists all tasks and events."; private static String COMMAND_SYNTAX = "list"; private static final String MESSAGE_LISTING_SUCCESS = "Listing a total of %d %s and %d %s."; private static CommandDefinition commandDefinition = new CommandDefinition(NAME, DESCRIPTION, COMMAND_SYNTAX); public static CommandDefinition getCommandDefinition() { return commandDefinition; } @Override public float inputConfidence(String input) { return (input.startsWith("list")) ? 1 : 0; } private static Map<String, String[]> getTokenDefinitions() { Map<String, String[]> tokenDefinitions = new HashMap<String, String[]>(); tokenDefinitions.put("default", new String[] {"list"}); tokenDefinitions.put("eventType", new String[] { "event", "task"}); tokenDefinitions.put("status", new String[] { "complete" , "completed", "uncomplete", "uncompleted"}); tokenDefinitions.put("time", new String[] { "at", "by", "on", "time" }); tokenDefinitions.put("timeFrom", new String[] { "from" }); tokenDefinitions.put("timeTo", new String[] { "to", "before" }); return tokenDefinitions; } @Override public void process(String input) { Map<String, String[]> parsedResult; try { parsedResult = Tokenizer.tokenize(getTokenDefinitions(), input); } catch (UnmatchedQuotesException e) { System.out.println("Unmatched quote!"); return ; } // Task or event? boolean isTask = true; boolean isEvent = true; boolean listAll = true; boolean isCompleted = true; boolean listAllStatus = true; String naturalFrom = null; String naturalTo = null; String naturalOn = null; //check if required to list all or just task or event if (parsedResult.get("eventType") != null) { listAll = false; if (parsedResult.get("eventType")[0].equals("event")) { isTask = false; } else { isEvent = false; } } //check if required to list only completed or uncomplete if (parsedResult.get("status") != null) { listAllStatus = false; if (parsedResult.get("status")[0].equals("uncomplete")) { isCompleted = false; } } if (parsedResult.get("time") == null) { if (parsedResult.get("timeFrom") != null) { naturalFrom = parsedResult.get("timeFrom")[1]; } if (parsedResult.get("timeTo") != null) { naturalTo = parsedResult.get("timeTo")[1]; } } else { naturalOn = parsedResult.get("time")[1]; } // Parse natural date using Natty. LocalDateTime dateOn = naturalOn == null ? null : parseNatural(naturalOn); LocalDateTime dateFrom = naturalFrom == null ? null : parseNatural(naturalFrom); LocalDateTime dateTo = naturalTo == null ? null : parseNatural(naturalTo); TodoListDB db = TodoListDB.getInstance(); IndexView view = UiManager.loadView(IndexView.class); // isTask and isEvent = true, list all type if (listAll) { //no event or task keyword found isTask = false; isEvent = false; setupTaskView(isCompleted, listAllStatus, dateOn, dateFrom, dateTo, db, view); setupEventView(isCompleted, listAllStatus, dateOn, dateFrom, dateTo, db, view); } if (isTask) { setupTaskView(isCompleted, listAllStatus, dateOn, dateFrom, dateTo, db, view); } if (isEvent) { setupEventView(isCompleted, listAllStatus, dateOn, dateFrom, dateTo, db, view); } UiManager.renderView(view); // Update console message int numTasks = view.tasks.size(); int numEvents = view.events.size(); String consoleMessage = String.format(MESSAGE_LISTING_SUCCESS, numTasks, StringUtil.pluralizer(numTasks, "task", "tasks"), numEvents, StringUtil.pluralizer(numEvents, "event", "events")); UiManager.updateConsoleMessage(consoleMessage); } private void setupEventView(boolean isCompleted, boolean listAllStatus, LocalDateTime dateOn, LocalDateTime dateFrom, LocalDateTime dateTo, TodoListDB db, IndexView view) { if (dateFrom == null && dateTo == null && dateOn == null) { if (listAllStatus) { view.events = db.getAllEvents(); } else if (isCompleted) { System.out.println(LocalDateTime.now()); view.events = db.getEventByRange(null, LocalDateTime.now()); } else { view.events = db.getEventByRange(LocalDateTime.now(), null); } } else if (dateOn != null) { //by keyword found view.events = db.getEventbyDate(dateOn); } else { view.events = db.getEventByRange(dateFrom, dateTo); } } private void setupTaskView(boolean isCompleted, boolean listAllStatus, LocalDateTime dateOn, LocalDateTime dateFrom, LocalDateTime dateTo, TodoListDB db, IndexView view) { if (dateFrom == null && dateTo == null && dateOn == null) { if (listAllStatus) { view.tasks = db.getAllTasks(); } else { view.tasks = db.getTaskByRange(dateFrom, dateTo, isCompleted, listAllStatus); } } else if (dateOn != null) { //by keyword found view.tasks = db.getTaskByDate(dateOn, isCompleted, listAllStatus); } else { view.tasks = db.getTaskByRange(dateFrom, dateTo, isCompleted, listAllStatus); } } private LocalDateTime parseNatural(String natural) { Parser parser = new Parser(); List<DateGroup> groups = parser.parse(natural); Date date = null; try { date = groups.get(0).getDates().get(0); } catch (IndexOutOfBoundsException e) { System.out.println("Error!"); // TODO return null; } LocalDateTime ldt = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); return DateUtil.floorDate(ldt); } }
package tk.allele.duckshop.items; import info.somethingodd.OddItem.OddItem; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import tk.allele.duckshop.errors.InvalidSyntaxException; import tk.allele.duckshop.trading.TradeAdapter; import javax.annotation.Nullable; import java.util.Collection; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Represents a tangible item, rather than money. */ public class TangibleItem extends Item { /** * The format for a tangible item: the amount as an integer, then a * space, then the item name, then an optional durability value. */ private static final Pattern tangibleItemPattern = Pattern.compile("(\\d+)\\s+([A-Za-z0-9_-]+)\\s*(\\d*)"); private static final int NAME_LENGTH = 10; private final int itemId; private final int amount; private final short damage; /** * Create a new TangibleItem instance. * <p> * The item string is not parsed; it is simply kept so it can be * later retrieved by {@link #getOriginalString()}. */ public TangibleItem(final int itemId, final int amount, final short damage, @Nullable final String itemString) { super(itemString); this.itemId = itemId; this.amount = amount; this.damage = damage; } public TangibleItem(final int itemId, final int amount, final short damage) { this(itemId, amount, damage, null); } /** * Parse a TangibleItem from a String. * * @throws InvalidSyntaxException if the item cannot be parsed. */ public static TangibleItem fromString(final String itemString) throws InvalidSyntaxException { Matcher matcher = tangibleItemPattern.matcher(itemString); if (matcher.matches()) { // Group 1 is definitely an integer, since it was matched with "\d+" int amount = Integer.parseInt(matcher.group(1)); String itemName = matcher.group(2); int itemId; short damage = 0; // Try parsing it as an item ID first try { itemId = Integer.parseInt(itemName); } catch (NumberFormatException ex) { // If it isn't an integer, treat it as an item name ItemStack itemDfn; try { itemDfn = OddItem.getItemStack(itemName); } catch (IllegalArgumentException ex2) { throw new InvalidSyntaxException(); } itemId = itemDfn.getTypeId(); damage = itemDfn.getDurability(); } // If there's another number after that, it's a damage value try { damage = Short.parseShort(matcher.group(3)); } catch (NumberFormatException ex) { // Do nothing -- keep the damage value from the code above } // Check if it's actually a real item if (Material.getMaterial(itemId) == null) { throw new InvalidSyntaxException(); } // Create the object! return new TangibleItem(itemId, amount, damage, itemString); } else { throw new InvalidSyntaxException(); } } @Override public int countAddTo(TradeAdapter adapter) { return adapter.countAddTangibleItem(this); } @Override public int countTakeFrom(TradeAdapter adapter) { return adapter.countSubtractTangibleItem(this); } @Override public void addTo(TradeAdapter adapter) { adapter.addTangibleItem(this); } @Override public void takeFrom(TradeAdapter adapter) { adapter.subtractTangibleItem(this); } /** * Get the item ID, or the data value. */ public int getItemId() { return itemId; } /** * Get the number of items. */ public int getAmount() { return amount; } /** * Get the damage value of this object. */ public short getDamage() { return damage; } /** * Create a single ItemStack corresponding to this object. */ public ItemStack toItemStack() { return new ItemStack(itemId, amount, damage); } /** * Create an array of ItemStacks with the same data as this object, * but grouped into stacks. */ public ItemStack[] toItemStackArray() { int maxStackSize = Material.getMaterial(itemId).getMaxStackSize(); ItemStack[] stacks; int quotient = amount / maxStackSize; if (amount % maxStackSize == 0) { stacks = new ItemStack[quotient]; } else { // If it cannot be divided evenly, the last cell will // contain the part left over stacks = new ItemStack[quotient + 1]; stacks[quotient] = new ItemStack(itemId, amount % maxStackSize, damage); } for (int i = 0; i < quotient; ++i) { stacks[i] = new ItemStack(itemId, maxStackSize, damage); } return stacks; } @Override public boolean equals(Object thatObj) { if (thatObj instanceof TangibleItem) { TangibleItem that = (TangibleItem) thatObj; return (this.itemId == that.itemId && this.damage == that.damage); } else if (thatObj instanceof ItemStack) { ItemStack that = (ItemStack) thatObj; return (this.itemId == that.getTypeId() && this.damage == that.getDurability()); } else { return false; } } @Override public int hashCode() { int hash = itemId - 199; hash = hash * 887 + damage; hash = hash * 887 + amount; return hash; } private static String getBestName(Collection<String> aliases) { for (String name : aliases) { // Skip names which are too long if (name.length() <= NAME_LENGTH) { return name; } } return null; } private static String getBestNameForId(int itemId, short damage) { String name; try { name = getBestName(OddItem.getAliases(new ItemStack(itemId, 1, damage))); } catch (IllegalArgumentException ex) { // Fall through name = null; } return name; } @Override public String toString() { StringBuilder buffer = new StringBuilder(15); buffer.append(Integer.toString(amount)); buffer.append(" "); String name = getBestNameForId(itemId, damage); if (name != null) { // If there is a specific name for this, use it buffer.append(name); } else { // Otherwise, use the generic name + damage value name = getBestNameForId(itemId, (short) 0); if (name != null) { buffer.append(name); buffer.append(Short.toString(damage)); } else { // If there isn't even a generic name, just use the ID buffer.append(Integer.toString(itemId)); if (damage != 0) { buffer.append(" "); buffer.append(Short.toString(damage)); } } } return buffer.toString(); } }
package treehouse.tool.cordova; import static javax.util.List.list; import static javax.util.Map.entry; import static javax.util.Map.map; import javax.io.File; import javax.io.Streams; import javax.util.List; import javax.util.Map; import treehouse.Builder; import treehouse.Engine; import treehouse.app.App; import treehouse.job.Job; import treehouse.job.ProcessJob; public abstract class CordovaBuilder implements Builder { protected Engine engine; protected File directory; protected File artifact; protected String state = "unknown"; public CordovaBuilder(Engine engine, File directory) { this.engine = engine; this.directory = directory; } public static class CordovaAndroidBuilder extends CordovaBuilder { public CordovaAndroidBuilder(Engine engine, File directory) { super(engine, directory); } public Job<File> build(App app, Map<String, String> options) throws Exception { File certificate = certificate(app); List<String> extra = list("--", "--keystore=" + certificate, "--storePassword=" + app.getName().toLowerCase(), "--password=" + app.getName().toLowerCase(), "--alias=" + app.getName().toLowerCase()); return new ProcessJob<File>(this.engine.cordova().build(app, directory, "android", options, map( entry("ANDROID_HOME", this.engine.android().home().toString()) ), extra)).onTerminate(this::finish).onOutput((line, job) -> this.handle(line, job, Boolean.parseBoolean(options.get("verbose", "false")))); } public void handle(String line, ProcessJob<File> job, Boolean verbose) { if (verbose) System.out.println(" [cordova] " + line); if (line.contains("BUILD SUCCESSFUL")) this.state = "success"; if (line.contains(".apk")) this.artifact = new File(line.trim()); } public void finish(Integer code, ProcessJob<File> job) { if ("success".equalsIgnoreCase(this.state) && this.artifact != null && this.artifact.exists()) job.complete(this.artifact); else job.completeExceptionally(new Exception("Error building")); } protected File certificate(App app) throws Exception { File keystore = new File(new File(this.directory, "build/work/ssl"), app.getName().toLowerCase() + ".keystore"); return keystore.exists() ? keystore : generate(app, keystore); } protected File generate(App app, File keystore) throws Exception { System.out.println("Generating key to sign the app..."); String output = Streams.read(javax.lang.Runtime.process("keytool", "-genkey", "-alias", app.getName().toLowerCase(), "-keystore", keystore.mkdirs().toString(), "-keypass", app.getName().toLowerCase(), "-keypass", app.getName().toLowerCase(), "-keyalg", "RSA", "-keysize", "2048", "-validity", "20000", "-storepass", app.getName().toLowerCase(), "-dname", "CN=" + app.getName().toLowerCase() + ", OU=, O=, L=, S=, C=US" ).redirectErrorStream(true).start().getInputStream()); if (keystore.exists() == false) throw new Exception("Unable to generate keystore: " + output); return keystore; } } public static List<String> platforms() { return list("android"); } public static CordovaBuilder builder(String platform, Engine engine, File directory) { if (platform.equals("android")) return new CordovaAndroidBuilder(engine, directory); return null; } }
package dt.call.aclient.screens; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.drawable.ColorDrawable; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioRecord; import android.media.AudioTrack; import android.media.MediaRecorder; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import org.xiph.vorbis.decoder.DecodeFeed; import org.xiph.vorbis.decoder.DecodeStreamInfo; import org.xiph.vorbis.encoder.EncodeFeed; import org.xiph.vorbis.player.VorbisPlayer; import org.xiph.vorbis.recorder.VorbisRecorder; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutionException; import dt.call.aclient.CallState; import dt.call.aclient.Const; import dt.call.aclient.R; import dt.call.aclient.Utils; import dt.call.aclient.Vars; import dt.call.aclient.background.async.CallEndAsync; import dt.call.aclient.background.async.CallTimeoutAsync; public class CallMain extends AppCompatActivity implements View.OnClickListener, SensorEventListener { private static final String tag = "CallMain"; private static final boolean ENABLE_VORBISLOG = false; //this level of logcat shouldn't normally be needed when logcat is enabled private static final int CHANNELS = 1; private static final int BITRATE = 32*1000; private static final int FREQ441 = 44100; //standard sampling frequency //wave audio presets: uses its own variables for stereo, format etc private static final int WAVFORMAT = AudioFormat.ENCODING_PCM_16BIT; private static final int STREAMCALL = AudioManager.STREAM_VOICE_CALL; private static final int WAVBUFFER = 1024; //ui stuff private FloatingActionButton end, mic, speaker; private boolean micMute = false, onSpeaker = false; private boolean screenShowing; private TextView status, callerid, time; private int min=0, sec=0; private Timer counter = new Timer(); private BroadcastReceiver myReceiver; //proximity sensor stuff private SensorManager sensorManager; private Sensor proximity; //related to audio playback and recording private AudioManager audioManager; private VorbisRecorder vorbisRecorder; private EncodeFeed encodeFeed; private AudioRecord wavRecorder; private VorbisPlayer vorbisPlayer; private DecodeFeed decodeFeed; private AudioTrack wavPlayer; /* * Vorbis recorder refuses to die. The only reason callEndAsync exists. * Need to pull the socket out from under its feet so it stops... and crashes the whole app. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_call_main); //allow this screen to show even when there is a password/pattern lock screen Window window = this.getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); end = (FloatingActionButton)findViewById(R.id.call_main_end_call); end.setOnClickListener(this); mic = (FloatingActionButton)findViewById(R.id.call_main_mic); mic.setOnClickListener(this); mic.setEnabled(false); speaker = (FloatingActionButton)findViewById(R.id.call_main_spk); speaker.setOnClickListener(this); speaker.setEnabled(false); status = (TextView)findViewById(R.id.call_main_status); //by default ringing. change it when in a call callerid = (TextView)findViewById(R.id.call_main_callerid); time = (TextView)findViewById(R.id.call_main_time); callerid.setText(Vars.callWith.toString()); /** * The stuff under here might look like a lot which has the potential to seriously slow down onCreate() * but it's really just long because defining some of the setup is long (like encode feed, decode feed * broadcast receiver etc...) * * It's not as bad as it looks */ //proximity sensor sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); proximity = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); //Start showing the counter for how long it's taking to answer the call or how long // the call has been going for TimerTask counterTask = new TimerTask() { @Override public void run() { if(sec == 60) { min++; sec = 0; if(Vars.state == CallState.INIT) { //if the person hasn't answered after 60 seconds give up. it's probably not going to happen. new CallTimeoutAsync().execute(); Vars.state = CallState.NONE; //guarantee state == NONE. don't leave it to chance onStop(); } } else { sec++; } if(screenShowing) { runOnUiThread(new Runnable() { @Override public void run() { updateTime(); } }); } } }; counter.schedule(counterTask, 0, 1000); //listen for call accepted or rejected myReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Utils.logcat(Const.LOGD, tag, "received a broadcast intent"); String response = intent.getStringExtra(Const.BROADCAST_CALL_RESP); if(response.equals(Const.BROADCAST_CALL_START)) { min = 0; sec = 0; callMode(); } else if(response.equals(Const.BROADCAST_CALL_END)) { //whether the call was rejected or time to end, it's the same result //so share the same variable to avoid 2 sendBroadcast chunks of code that are almost the same //media read/write are stopped in command listener when it got the call end //Vars.state would've already been set by the server command that's broadcasting a call end onStop(); } } }; registerReceiver(myReceiver, new IntentFilter(Const.BROADCAST_CALL)); /** * Audio setup from here */ //make it possible to use the earpiece and to switch back and forth audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); audioManager.setSpeakerphoneOn(false); //setup stuff needed for vorbis playback wavPlayer = new AudioTrack(STREAMCALL, FREQ441, AudioFormat.CHANNEL_OUT_MONO, WAVFORMAT, WAVBUFFER, AudioTrack.MODE_STREAM); decodeFeed = new DecodeFeed() { @Override public int readVorbisData(byte[] buffer, int amountToWrite) { int totalRead=0, dataRead; try { //guarantee you have amountToWrite bytes to send to the native library while(totalRead < amountToWrite) { dataRead = Vars.mediaSocket.getInputStream().read(buffer, totalRead, amountToWrite-totalRead); totalRead = totalRead + dataRead; vorbisLogcat(Const.LOGD, tag, "got " + dataRead + "bytes from the MEDIA SOCKET, total: " + totalRead); } vorbisLogcat(Const.LOGD, tag, "buffer: " + new String(buffer)); } catch (IOException i) { Utils.logcat(Const.LOGE, tag, "ioexception reading media: "); Utils.dumpException(tag, i); } //as stated in the javadoc, you MUST fill the buffer with amountToWrite bytes of vorbis data. //you must confirm to the native library (using return) that you're sending amountToWrite bytes. //if you don't send back that much bytes, the library will fail if(totalRead != amountToWrite) { int missing = amountToWrite - totalRead; Utils.logcat(Const.LOGE, tag, "vorbis data missing " + missing + "bytes. VORBIS LIBRARY WILL FAIL IN 3 2 1..."); onStop(); } return totalRead; } @Override public void writePCMData(short[] pcmData, int amountToRead) { try { wavPlayer.write(pcmData, 0, amountToRead); vorbisLogcat(Const.LOGD, tag, "converted vorbis to wav"); } catch (IllegalStateException i) {//in the case where you hang up but there was still a bit of stuff left in the buffer Utils.logcat(Const.LOGD, tag, "still had stuff to play, oh well"); } } @Override public void stop() { Utils.logcat(Const.LOGD, tag, "Vorbis player stop called"); if(wavPlayer != null) { try { wavPlayer.stop(); wavPlayer.release(); } catch (IllegalStateException i) { Utils.logcat(Const.LOGD, tag, "tried to re-stop: "); Utils.dumpException(tag, i); } } } @Override public void startReadingHeader() { } @Override public void start(DecodeStreamInfo decodeStreamInfo) { wavPlayer.play(); } }; vorbisPlayer = new VorbisPlayer(decodeFeed); //setup the audio recording stuff encodeFeed = new EncodeFeed() { @Override //amountToWrite is the amount of wav data that ??must?? be read to satisfy the native library public long readPCMData(byte[] pcmDataBuffer, int amountToWrite) { if (micMute) {//can't stop the thread without causing a crash. just return all zeros buffer for mic mute return amountToWrite; } //although unlikely to be necessary, buffer the mic input int totalRead = 0, dataRead; while(totalRead < amountToWrite) { dataRead = wavRecorder.read(pcmDataBuffer, totalRead, amountToWrite - totalRead); totalRead = totalRead + dataRead; vorbisLogcat(Const.LOGD, tag, "got " + dataRead + "bytes from the mic, total: " + totalRead); } vorbisLogcat(Const.LOGD, tag, "buffer: " + new String(pcmDataBuffer)); return totalRead; } @Override public int writeVorbisData(byte[] vorbisData, int amountToRead) { try { //BE CAREFUL!!! the vorbisData buffer isn't always filled to the max with vorbis // data. make sure you don't send the extra space in the buffer (bunch of zeros). // specify to socket write the amount of data in vorbisData that is ACTUALLY vorbis // data and not extra space Vars.mediaSocket.getOutputStream().write(vorbisData, 0, amountToRead); vorbisLogcat(Const.LOGD, tag, "sent " + amountToRead + " voice data out"); } catch (IOException i) { Utils.logcat(Const.LOGE, tag, "ioexception writing vorbis to server: "); Utils.dumpException(tag, i); onStop(); } return amountToRead; } @Override public void stop() { //doesn't do anything. it's stopEncoding that gets called stopEncoding(); } @Override public void stopEncoding() { Utils.logcat(Const.LOGD, tag, "vorbis RECORDER stop called"); try { wavRecorder.stop(); wavRecorder.release(); } catch (IllegalStateException | NullPointerException ex) { Utils.logcat(Const.LOGE, tag, "probably tried called stop on an already stopped encoder "); Utils.dumpException(tag, ex); } } @Override public void start() { wavRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, FREQ441, AudioFormat.CHANNEL_IN_MONO, WAVFORMAT, WAVBUFFER); wavRecorder.startRecording(); } }; vorbisRecorder = new VorbisRecorder(encodeFeed); //now that the setup has been complete: //set the ui to call mode: if you got to this screen after accepting an incoming call if(Vars.state == CallState.INCALL) { callMode(); } } @Override protected void onResume() { super.onResume(); screenShowing = true; sensorManager.registerListener(this, proximity, SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onPause() { super.onPause(); screenShowing = false; sensorManager.unregisterListener(this); } @Override protected void onStop() { super.onStop(); screenShowing = false; /** * onStop() is called when the CallMain screen isn't visible anymore. Either from ending a call * or from going to another app during a call. To make sure the call doesn't stop, only do the * cleanup if you're leaving the screen because the call ended. * * Vars.state = NONE will be set before calling onStop() manually to guarantee that onStop() sees * the call state as none. The 2 async calls: end, timeout will set state = NONE, BUT BECAUSE they're * async there is a chance that onStop() is called before the async is. Don't leave it to dumb luck. */ if(Vars.state == CallState.NONE) { vorbisRecorder.stop(); vorbisPlayer.stop(); new CallEndAsync().execute(); //a must to stop the recorder thread //no longer in a call audioManager.setMode(AudioManager.MODE_NORMAL); counter.cancel(); try { unregisterReceiver(myReceiver); } catch (IllegalArgumentException i) { Utils.logcat(Const.LOGW, tag, "don't unregister you get a leak, do unregister you get an exception... "); } //go back to the home screen and clear the back history so there is no way to come back to //call main Intent goHome = new Intent(this, UserHome.class); goHome.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(goHome); } } @Override public void onClick(View v) { if(v == end) { Vars.state = CallState.NONE; //guarantee onStop sees state == NONE onStop(); } else if (v == mic) { micMute = !micMute; if(micMute) { mic.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_mic_off_white_48dp)); } else { mic.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_mic_white_48dp)); } } else if (v == speaker) { onSpeaker = !onSpeaker; if(onSpeaker) { speaker.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_volume_up_white_48dp)); audioManager.setSpeakerphoneOn(true); } else { speaker.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_phone_in_talk_white_48dp)); audioManager.setSpeakerphoneOn(false); } } } private void updateTime() { if(sec < 10) { time.setText(min + ":0" + sec); } else { time.setText(min + ":" + sec); } } private void callMode() { //setup the ui to call mode try {//apparently this line has the possibility of a null pointer exception as warned by android studio...??? getSupportActionBar().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(CallMain.this, R.color.material_green))); } catch (NullPointerException n) { Utils.logcat(Const.LOGE, tag, "null pointer changing action bar to green: "); Utils.dumpException(tag, n); } status.setText(getString(R.string.call_main_status_incall)); mic.setEnabled(true); speaker.setEnabled(true); Thread recordThread = new Thread(new Runnable() { @Override public void run() { vorbisRecorder.start(FREQ441, CHANNELS, BITRATE); } }); recordThread.setName("Vorbis Recorder"); recordThread.start(); Thread playbackThread = new Thread(new Runnable() { @Override public void run() { vorbisPlayer.start(); } }); playbackThread.setName("Vorbis Playback"); playbackThread.start(); } @Override public void onBackPressed() { /* * Do nothing. If you're in a call then there's no reason to go back to the User Home */ } @Override public void onSensorChanged(SensorEvent event) { float distance = event.values[0]; if(distance <= 5) { //with there being no good information on turning the screen on and off //go with the next best thing of disabling all the buttons Utils.logcat(Const.LOGD, tag, "proximity sensor NEAR: " + distance); screenShowing = false; end.setEnabled(false); mic.setEnabled(false); speaker.setEnabled(false); } else { Utils.logcat(Const.LOGD, tag, "proximity sensor FAR: " + distance); screenShowing = true; end.setEnabled(true); mic.setEnabled(true); speaker.setEnabled(true); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { //not relevant for proximity sensor so do nothing } //for debugging vorbis encoder/decoder internals. produces excessive logcat spam //only turn this on when necessary private void vorbisLogcat(int level, String tag, String message) { if(ENABLE_VORBISLOG) { Utils.logcat(level, tag, message); } } }
package net.sf.cglib; import net.sf.cglib.beans.*; import net.sf.cglib.algorithm.*; import junit.framework.*; /** *@author Gerhard Froehlich <a href="mailto:g-froehlich@gmx.de"> * g-froehlich@gmx.de</a> *@version $Id: TestAll.java,v 1.30 2003-09-10 02:23:04 herbyderby Exp $ */ public class TestAll extends TestCase { public TestAll(String testName) { super(testName); } public static Test suite() { // System.setSecurityManager( new java.rmi.RMISecurityManager()); System.getProperties().list(System.out); TestSuite suite = new TestSuite(); suite.addTest(TestEnhancer.suite()); suite.addTest(TestBulkBean.suite()); suite.addTest(TestMixin.suite()); suite.addTest(TestKeyFactory.suite()); suite.addTest(TestProxy.suite()); suite.addTest(TestMethodProxy.suite()); suite.addTest(TestParallelSorter.suite()); suite.addTest(TestSwitch.suite()); suite.addTest(TestStringSwitch.suite()); suite.addTest(TestBeanMap.suite()); suite.addTest(TestDispatcher.suite()); suite.addTest(TestLazyLoader.suite()); suite.addTest(TestNoOp.suite()); suite.addTest(TestMemberSwitch.suite()); suite.addTest(TestFastClass.suite()); return suite; } public static void main(String args[]) { String[] testCaseName = {TestAll.class.getName()}; junit.textui.TestRunner.main(testCaseName); } }
package jsse; import com.cisco.fnr.FNRUtils; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.bouncycastle.jce.provider.BouncyCastleProvider; import java.lang.reflect.Field; import java.security.Security; import java.util.Arrays; public class SWPTest extends TestCase { private String password; /** * Create the test case * * @param testName name of the test case */ public SWPTest (String testName) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( SWPTest.class ); } public void setUp() throws Exception { super.setUp(); password = "test"; // NOT FOR PRODUCTION Security.addProvider(new BouncyCastleProvider()); } public void tearDown() throws Exception { super.tearDown(); } /** * Rigourous Test :-) * Searchable without False Positives * Notice that the load factor is 1 */ public void testSWP_NO_FP_AES() { System.out.println("Test AES Searchable "); double loadFactor = 1; // No false positives but additional storage try { SWP swp = new SWP(SSEUtil.getSecretKeySpec(password, SSEUtil.getRandomBytes(20)), "AES",loadFactor, 128); byte[] plainBytes = ("Hello").getBytes(); byte[] cipherText = swp.encrypt(plainBytes, 1); if(cipherText.length == 2 * SWP.BLOCK_BYTES) assertTrue("Additional Storage", true); else assertTrue("Strange",false); byte[] plainText = swp.decrypt(cipherText, 1); if (Arrays.equals(plainBytes, plainText)) assertTrue("Encryption and Decryption works !",true); else assertTrue("Failed", false); // Get Trapdoor byte[] trapDoor = swp.getTrapDoor(plainBytes); // Check Match if (swp.isMatch(trapDoor, cipherText)) assertTrue("Matching works Blind-foldedly !",true); else assertTrue("Matching Does not work !", false); } catch (Exception e){ e.printStackTrace(); assertTrue("Something went wrong .. some where !!! .." + e.getMessage(),false); } } public void testSWP_NO_FP_FNR() { System.out.println("Test FNR Searchable String "); double loadFactor = 1; // No false positives but additional storage try { String givenText = "192.168.1.1" ; byte[] plainBytes = FNRUtils.rankIPAddress(givenText); SWP swp = new SWP(SSEUtil.getSecretKeySpec(password, SSEUtil.getRandomBytes(20)), "FNR",loadFactor, plainBytes.length*Byte.SIZE); byte[] cipherBytes = swp.encrypt(plainBytes, 1); if(cipherBytes.length == 2 * SWP.BLOCK_BYTES) assertTrue("Additional Storage", true); else assertTrue("Strange",false); byte[] decryptBytes = swp.decrypt(cipherBytes, 1); if (Arrays.equals(plainBytes, decryptBytes)) assertTrue("Encryption and Decryption works !",true); else assertTrue("Failed", false); // Get Trapdoor byte[] trapDoor = swp.getTrapDoor(plainBytes); // Check Match if (swp.isMatch(trapDoor, cipherBytes)) assertTrue("Matching works Blind-foldedly !",true); else assertTrue("Matching Does not work !", false); } catch (Exception e){ e.printStackTrace(); assertTrue("Something went wrong .. some where !!! .." + e.getMessage(),false); } } public void testSWP_NO_FP_FNR_IP() { System.out.println("Test FNR Searchable IP Address "); double loadFactor = 1; // No false positives but additional storage try { String givenIp = "192.168.1.1" ; System.out.println("IPAddress " + givenIp); byte[] plainBytes = FNRUtils.rankIPAddress(givenIp); SWP swp = new SWP(SSEUtil.getSecretKeySpec(password, SSEUtil.getRandomBytes(20)), "FNR",loadFactor, plainBytes.length*Byte.SIZE); byte[] cipherBytes = swp.encrypt(plainBytes, 1); if(cipherBytes.length == 2 * SWP.BLOCK_BYTES) assertTrue("Additional Storage", true); else assertTrue("Strange",false); byte[] decryptBytes = swp.decrypt(cipherBytes, 1); if (Arrays.equals(plainBytes, decryptBytes)) assertTrue("Encryption and Decryption works !",true); else assertTrue("Failed", false); // Get Trapdoor byte[] trapDoor = swp.getTrapDoor(plainBytes); // Check Match if (swp.isMatch(trapDoor, cipherBytes)) assertTrue("Matching works Blind-foldedly !",true); else assertTrue("Matching Does not work !", false); } catch (Exception e){ e.printStackTrace(); assertTrue("Something went wrong .. some where !!! .." + e.getMessage(),false); } } /** * Rigourous Test :-) * SWP With no additional storage * Search could have False Positives * Notice that the load factor is < 1 */ public void testSWP_NO_ADD_STORAGE_AES() { System.out.println("Test AES Searchable "); double loadFactor = 0.7; // No false positives but additional storage try { SWP swp = new SWP(SSEUtil.getSecretKeySpec(password, SSEUtil.getRandomBytes(20)), "AES",loadFactor, 128); byte[] plainBytes = ("Hello").getBytes(); byte[] cipherText = swp.encrypt(plainBytes, 1); if(cipherText.length != SWP.BLOCK_BYTES) assertTrue("Strange",false); else assertTrue("NO additional Storage", true); byte[] plainText = swp.decrypt(cipherText, 1); if (Arrays.equals(plainBytes, plainText)) assertTrue("Encryption and Decryption works !",true); else assertTrue("Failed", false); // Get Trapdoor byte[] trapDoor = swp.getTrapDoor(plainBytes); // Check Match if (swp.isMatch(trapDoor, cipherText)) assertTrue("Matching works Blind-foldedly !",true); else assertTrue("Matching Does not work !", false); } catch (Exception e){ e.printStackTrace(); assertTrue("Something went wrong .. some where !!! .." + e.getMessage(),false); } } public void testSWP_NO_ADD_STORAGE_FNR() { System.out.println("Test FNR Searchable String"); double loadFactor = 0.7; // No false positives but additional storage try { String givenText = "Hello" ; byte[] plainBytes = givenText.getBytes(); SWP swp = new SWP(SSEUtil.getSecretKeySpec(password, SSEUtil.getRandomBytes(20)), "FNR",loadFactor, plainBytes.length*Byte.SIZE); byte[] cipherText = swp.encrypt(plainBytes, 1); if(cipherText.length != SWP.BLOCK_BYTES) assertTrue("Strange",false); else assertTrue("No additional Storage", true); byte[] decryptBytes = swp.decrypt(cipherText, 1); if (Arrays.equals(plainBytes, decryptBytes)) assertTrue("Encryption and Decryption works !",true); else assertTrue("Failed", false); // Get Trapdoor byte[] trapDoor = swp.getTrapDoor(plainBytes); // Check Match if (swp.isMatch(trapDoor, cipherText)) assertTrue("Matching works Blind-foldedly !",true); else assertTrue("Matching Does not work !", false); } catch (Exception e){ e.printStackTrace(); assertTrue("Something went wrong .. some where !!! .." + e.getMessage(),false); } } public void testSWP_NO_ADD_STORAGE_FNR_IP() { System.out.println("Test FNR Searchable IPAddress"); double loadFactor = 0.7; // No false positives but additional storage try { String givenIp = "192.168.1.1" ; System.out.println("IPAddress " + givenIp); byte[] plainBytes = FNRUtils.rankIPAddress(givenIp); SWP swp = new SWP(SSEUtil.getSecretKeySpec(password, SSEUtil.getRandomBytes(20)), "FNR",loadFactor, plainBytes.length*Byte.SIZE); byte[] cipheBytes = swp.encrypt(plainBytes, 1); String cipherIp = FNRUtils.deRankIPAddress(cipheBytes); System.out.println("Cipher IPAddress " + cipherIp); if(cipheBytes.length != SWP.BLOCK_BYTES) assertTrue("Strange",false); else assertTrue("No additional Storage", true); byte[] decryptBytes = swp.decrypt(cipheBytes, 1); String decryptedIP = FNRUtils.deRankIPAddress(decryptBytes); System.out.println("Decrypted IPAddress " + decryptedIP); if (Arrays.equals(plainBytes, decryptBytes)) assertTrue("Encryption and Decryption works on bytes !",true); else assertTrue("Failed Encryption and Decryption works on bytes ", false); if(givenIp.equals(decryptedIP)) assertTrue("Encryption and Decryption works on IP Address !",true); else assertTrue("Failed Encryption and Decryption works on IP Address ", false); // Get Trapdoor byte[] trapDoor = swp.getTrapDoor(plainBytes); System.out.println("Trapdoor IPAddress " + FNRUtils.deRankIPAddress(trapDoor)); // Check Match if (swp.isMatch(trapDoor, cipheBytes)) assertTrue("Matching works Blind-foldedly !",true); else assertTrue("Matching Does not work !", false); } catch (Exception e){ e.printStackTrace(); assertTrue("Something went wrong .. some where !!! .." + e.getMessage(),false); } } public void testLoadFactor(){ System.out.println("Test Load factor "); double loadFactor= 0 ; try { new SWP(SSEUtil.getSecretKeySpec(password, SSEUtil.getRandomBytes(20)), "AES",loadFactor, 128); } catch (Exception e){ assertTrue(true); } loadFactor = 2; try { new SWP(SSEUtil.getSecretKeySpec(password, SSEUtil.getRandomBytes(20)), "AES",loadFactor, 128); } catch (Exception e){ assertTrue(true); } loadFactor = 1; try { new SWP(SSEUtil.getSecretKeySpec(password, SSEUtil.getRandomBytes(20)), "AES",loadFactor, 128); } catch (Exception e){ assertTrue(false); } loadFactor = 0.5; try { new SWP(SSEUtil.getSecretKeySpec(password, SSEUtil.getRandomBytes(20)), "AES",loadFactor, 128); } catch (Exception e){ assertTrue(false); } } }
package org.rstudio.studio.client.workbench.views.environment.model; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArrayString; public class RObject extends JavaScriptObject { protected RObject() { } public final native String getName() /*-{ return this.name; }-*/; public final native String getType() /*-{ return this.type; }-*/; public final native boolean isData() /*-{ return this.is_data; }-*/; public final native String getValue() /*-{ return this.value ? this.value : "NO_VALUE"; }-*/; public final native String getDescription() /*-{ return this.description ? this.description : ""; }-*/; public final native JsArrayString getContents() /*-{ return this.contents; }-*/; public final native int getLength() /*-{ return this.length; }-*/; public final native int getSize() /*-{ return this.size; }-*/; public final native boolean getContentsDeferred() /*-{ return this.contents_deferred; }-*/; public final native void setDeferredContents(JsArrayString contents) /*-{ this.contents_deferred = false; this.contents = contents; }-*/; }
package nl.esciencecenter.ncradar; import java.io.File; import java.io.IOException; import ucar.ma2.Array; import ucar.ma2.Index; import ucar.nc2.NetcdfFile; import ucar.nc2.Variable; public class RadarScanJava extends NetcdfAttributeReader { private final PolarData polarData; private final ScanMeta scanMeta; private final RadarMeta radarMeta; public RadarScanJava(String directory, String filename, int datasetIndex) throws IOException { String datasetName = "dataset" + (datasetIndex + 1); String fullFilename = directory + File.separator + filename; this.radarMeta = new RadarMeta(fullFilename); double dataOffset = readDataOffset(fullFilename, datasetName); byte[] scanDataRaw = readScanDataRaw(fullFilename, datasetName); double dataScale = readDataScale(fullFilename, datasetName); int missingValueValue = readMissingValueValue(fullFilename, datasetName); int numberOfAzimuthBins = readNumberOfAzimuthBins(fullFilename, datasetName); int numberOfRangeBins = readNumberOfRangeBins(fullFilename, datasetName); double rangeOffset = readRangeOffset(fullFilename, datasetName); double rangeScale = readRangeScale(fullFilename, datasetName); int iAzimFirstRay = readiAzimFirstRay(fullFilename, datasetName); this.polarData = new PolarData(numberOfAzimuthBins, numberOfRangeBins, scanDataRaw, dataOffset, dataScale, rangeOffset, rangeScale, missingValueValue, iAzimFirstRay); double elevationAngle = readElevationAngle(fullFilename, datasetName); String endDate = readEndDate(fullFilename, datasetName); String endTime = readEndTime(fullFilename, datasetName); String scanType = readScanType(fullFilename, datasetName); String startDate = readStartDate(fullFilename, datasetName); String startTime = readStartTime(fullFilename, datasetName); this.scanMeta = new ScanMeta(datasetIndex, datasetName, directory, elevationAngle, endDate, endTime, filename, scanType, startDate, startTime); } public void calcVerticesAndFaces() { polarData.calcVerticesAndFaces(); } public double getDataOffset() { return polarData.getDataOffset(); } public double getDataScale() { return polarData.getDataScale(); } public int getDatasetIndex() { return scanMeta.getDatasetIndex(); } public String getDatasetName() { return scanMeta.getDatasetName(); } public String getDirectory() { return scanMeta.getDirectory(); } public double getElevationAngle() { return scanMeta.getElevationAngle(); } public String getEndDate() { return scanMeta.getEndDate(); } public String getEndTime() { return scanMeta.getEndTime(); } public int[][] getFaces() { return polarData.getFaces(); } public double[] getFacesValues() { double[][] scanData = this.getScanData2D(); int nAzim = this.getNumberOfAzimuthBins(); int nRang = this.getNumberOfRangeBins(); double[] facesValues = new double[2 * nAzim * nRang]; int iFace = 0; for (int iRang = 0; iRang < nRang; iRang++) { for (int iAzim = 0; iAzim < nAzim; iAzim++) { double v = scanData[iAzim][iRang]; facesValues[iFace] = v; facesValues[iFace + 1] = v; iFace = iFace + 2; } } return facesValues; } public String getFilename() { return scanMeta.getFilename(); } public int getiAzimFirstRay() { return polarData.getiAzimFirstRay(); } public int getMissingValueValue() { return polarData.getMissingValueValue(); } public float getNominalMaxTransmissionPower() { return radarMeta.getNominalMaxTransmissionPower(); } public int getNumberOfAzimuthBins() { return polarData.getNumberOfAzimuthBins(); } public int getNumberOfRangeBins() { return polarData.getNumberOfRangeBins(); } public PolarData getPolarData() { return polarData.clone(); } public float getPulseLength() { return radarMeta.getPulseLength(); } public float getPulseRepeatFrequencyHigh() { return radarMeta.getPulseRepeatFrequencyHigh(); } public float getPulseRepeatFrequencyLow() { return radarMeta.getPulseRepeatFrequencyLow(); } public float getRadarConstant() { return radarMeta.getRadarConstant(); } public double getRadarPositionHeight() { return radarMeta.getRadarPositionHeight(); } public double getRadarPositionLatitude() { return radarMeta.getRadarPositionLatitude(); } public double getRadarPositionLongitude() { return radarMeta.getRadarPositionLongitude(); } public float getRadialVelocityAntenna() { return radarMeta.getRadialVelocityAntenna(); } public double getRangeOffset() { return polarData.getRangeOffset(); } public double getRangeScale() { return polarData.getRangeScale(); } public double[] getScanData() { return polarData.getData(); } public double[][] getScanData2D() { return polarData.getData2D(); } public byte[] getScanDataRaw() { return polarData.getDataRaw(); } public byte[][] getScanDataRaw2D() { return polarData.getDataRaw2D(); } public String getScanType() { return scanMeta.getScanType(); } public String getStartDate() { return scanMeta.getStartDate(); } public String getStartTime() { return scanMeta.getStartTime(); } public double[][] getVertices() { return polarData.getVertices(); } private double readDataOffset(String fullFilename, String datasetName) throws IOException { String fullAttributename = datasetName + "_data1_what_offset"; return readDoubleAttribute(fullFilename, fullAttributename); } private double readDataScale(String fullFilename, String datasetName) throws IOException { String fullAttributename = datasetName + "_data1_what_gain"; return readDoubleAttribute(fullFilename, fullAttributename); } private double readElevationAngle(String fullFilename, String datasetName) throws IOException { String fullAttributename = datasetName + "_where_elangle"; return readDoubleAttribute(fullFilename, fullAttributename); } private String readEndDate(String fullFilename, String datasetName) throws IOException { String fullAttributename = datasetName + "_what_enddate"; return readStringAttribute(fullFilename, fullAttributename); } private String readEndTime(String fullFilename, String datasetName) throws IOException { String fullAttributename = datasetName + "_what_endtime"; return readStringAttribute(fullFilename, fullAttributename); } private int readiAzimFirstRay(String fullFilename, String datasetName) throws IOException { String fullAttributename = datasetName + "_where_a1gate"; return (int) readLongAttribute(fullFilename, fullAttributename); } private int readMissingValueValue(String fullFilename, String datasetName) throws IOException { String fullAttributename = datasetName + "_data1_what_nodata"; return readIntegerAttribute(fullFilename, fullAttributename); } private int readNumberOfAzimuthBins(String fullFilename, String datasetName) throws IOException { String fullAttributename = datasetName + "_where_nrays"; return (int) readLongAttribute(fullFilename, fullAttributename); } private int readNumberOfRangeBins(String fullFilename, String datasetName) throws IOException { String fullAttributename = datasetName + "_where_nbins"; return (int) readLongAttribute(fullFilename, fullAttributename); } private double readRangeOffset(String fullFilename, String datasetName) throws IOException { String fullAttributename = datasetName + "_where_rstart"; return readDoubleAttribute(fullFilename, fullAttributename); } private double readRangeScale(String fullFilename, String datasetName) throws IOException { String fullAttributename = datasetName + "_where_rscale"; return readDoubleAttribute(fullFilename, fullAttributename); } private byte[] readScanDataRaw(String fullFilename, String datasetName) throws IOException { NetcdfFile ncfile = null; try { ncfile = NetcdfFile.open(fullFilename); Variable var = ncfile.findVariable(datasetName + "/data1/data"); Array data = var.read(); int[] dims = data.getShape(); Index index = data.getIndex(); int nRows = dims[0]; int nCols = dims[1]; int iGlobal = 0; byte[] scanDataRaw = new byte[nRows * nCols]; for (int iRow = 0; iRow < nRows; iRow++) { for (int iCol = 0; iCol < nCols; iCol++) { scanDataRaw[iGlobal] = data.getByte(index .set(iRow, iCol)); } } return scanDataRaw; } finally { ncfile.close(); } } private String readScanType(String fullFilename, String datasetName) throws IOException { String fullAttributename = datasetName + "_data1_what_quantity"; return readStringAttribute(fullFilename, fullAttributename); } private String readStartDate(String fullFilename, String datasetName) throws IOException { String fullAttributename = datasetName + "_what_startdate"; return readStringAttribute(fullFilename, fullAttributename); } private String readStartTime(String fullFilename, String datasetName) throws IOException { String fullAttributename = datasetName + "_what_starttime"; return readStringAttribute(fullFilename, fullAttributename); } }
//#if ${CarrinhoCheckout} == "T" package br.com.webstore.features; import java.awt.Color; import java.awt.Desktop.Action; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.beans.PropertyChangeListener; import java.math.BigDecimal; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextArea; import javax.swing.SwingConstants; import javax.swing.border.BevelBorder; import javax.swing.table.DefaultTableModel; import org.jdesktop.swingx.plaf.basic.CalendarRenderingHandler; import br.com.webstore.dao.CarrinhoDao; import br.com.webstore.dao.ProdutoDao; import br.com.webstore.facade.GenericFacade; import br.com.webstore.model.Carrinho; import br.com.webstore.model.Produto; import br.com.webstore.model.StatusVenda; import br.com.webstore.model.Usuario; import br.com.webstore.model.Venda; import br.com.webstore.views.WebStoreEventMainScreenP; import java.sql.*; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.List; import java.util.Vector; import javax.swing.JTable; import javax.swing.ListSelectionModel; public class CarrinhoCheckout extends JPanel { /** * Serial version */ private static final long serialVersionUID = 8737213081913021625L; public static final String NAME = "Carrinho"; /** * Create the panel. */ Connection connection = null; private JTable table; private JLabel lblValor; private JScrollPane scrollPane; private Usuario user; private GenericFacade facade; private static CarrinhoCheckout instance; public static CarrinhoCheckout getInstance(final GenericFacade gfacade, final Usuario usuario){ if(instance == null) instance = new CarrinhoCheckout(gfacade, usuario); return instance; } public CarrinhoCheckout(final GenericFacade gfacade, final Usuario usuario) { this.user = usuario; this.facade = gfacade; criarLayout(null); } public void criarLayout(final Produto produto){ this.removeAll(); setLayout(null); //List<Venda> venda = gfacade.findVendaByUser(usuario, gfacade.findStatusVendabyName("Carrinho")); final Carrinho carrinho = Carrinho.getInstance(); boolean flag = false; if(produto != null){ for (Map.Entry<Produto, Integer> hashProduto : carrinho.getMapCarrinho().entrySet()) { if(hashProduto.getKey().getId() == produto.getId()){ carrinho.getMapCarrinho().put(hashProduto.getKey(), hashProduto.getValue() + 1); flag = true; } } if(!flag){ carrinho.putMapCarrinho(produto, 1); } } //Cabealho final Vector<String> headers = new Vector<String>(3); headers.addElement(new String("Codigo")); headers.addElement(new String("Descrio")); headers.addElement(new String("Quantidade")); headers.addElement(new String("Valor")); table = new JTable(); JLabel lblTituloValor = new JLabel("Valor Total"); lblValor = new JLabel("0"); this.scrollPane = new JScrollPane(); this.scrollPane.setBounds(0, 0, 480, 99); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); final DefaultTableModel modelCarrinho = new DefaultTableModel(headers, carrinho.getMapCarrinho().size()); CarrinhoCheckout.this.table.setModel(modelCarrinho); int row = 0; BigDecimal valorTotal = BigDecimal.ZERO; BigDecimal valorPorProduto = BigDecimal.ZERO; for (Map.Entry<Produto, Integer> hashProduto : carrinho.getMapCarrinho().entrySet()) { CarrinhoCheckout.this.table.getModel().setValueAt(hashProduto.getKey().getId().toString(), row, 0); CarrinhoCheckout.this.table.getModel().setValueAt(hashProduto.getKey().getDescricao(), row, 1); CarrinhoCheckout.this.table.getModel().setValueAt(hashProduto.getValue(), row, 2); valorPorProduto = calculoDoValorQuantidade(hashProduto); CarrinhoCheckout.this.table.getModel().setValueAt(valorPorProduto, row, 3); valorTotal = valorTotal.add(valorPorProduto); row++; } lblValor.setText(valorTotal.toString()); //table.setModel(new CarrinhoDao(null).getCarrinho(venda.get(0))); javax.swing.Action action = new AbstractAction() { public void actionPerformed(ActionEvent e) { TableCellListener tcl = (TableCellListener)e.getSource(); int id = Integer.parseInt(tcl.getTable().getValueAt(tcl.getRow(), 0).toString()); for (Map.Entry<Produto, Integer> hashProduto : carrinho.getMapCarrinho().entrySet()) { if(hashProduto.getKey().getId() == id){ carrinho.getMapCarrinho().put(hashProduto.getKey(), Integer.parseInt(tcl.getNewValue().toString())); } } /* System.out.println("Row : " + tcl.getRow()); System.out.println("Column: " + tcl.getColumn()); System.out.println("Old : " + tcl.getOldValue()); System.out.println("New : " + tcl.getNewValue());*/ } }; TableCellListener tcl = new TableCellListener(table, action); table.setBounds(22, 24, 361, 76); table.setModel(modelCarrinho); add(table); JButton btnDetalhes = new JButton("Excluir"); btnDetalhes .addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { //ListSelectionModel lsm = CarrinhoCheckout.this.table.getSelectionModel(); int index = CarrinhoCheckout.this.table.getSelectedRow(); index = CarrinhoCheckout.this.table.convertRowIndexToModel(index); if (index == -1) { JOptionPane.showMessageDialog(null, " necessrio selecionar um item."); } else { //remover da tabela //CarrinhoCheckout.this.table.getRowCount(); //CarrinhoCheckout.this.table.remove(index); Integer id = Integer.parseInt(CarrinhoCheckout.this.table.getValueAt(index, 0).toString()); modelCarrinho.removeRow(index); CarrinhoCheckout.this.table.updateUI(); //remover do HashMap Set<Entry<Produto, Integer>> aux = carrinho.getMapCarrinho().entrySet(); for (Map.Entry<Produto, Integer> hashProduto : aux) { if(hashProduto.getKey().getId() == id){ carrinho.getMapCarrinho().remove(hashProduto.getKey()); } } //tenho que atualizar a tabela } } }); this.scrollPane.setViewportView(this.table); this.add(this.scrollPane); btnDetalhes .setBounds(440, 273, 90, 23); lblTituloValor.setBounds(270, 200, 100, 30); lblValor.setBounds(400, 200, 50, 30); this.add(btnDetalhes ); this.add(lblTituloValor); this.add(lblValor); } /** * @param hashProduto * @return */ private BigDecimal calculoDoValorQuantidade(Entry<Produto, Integer> hashProduto) { BigDecimal valorProduto = hashProduto.getKey().getValor(); BigDecimal quantidade = new BigDecimal(hashProduto.getValue()); BigDecimal valorTotal = valorProduto.multiply(quantidade); return valorTotal; } } //#endif
package wraith.library.WindowUtil; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.ArrayList; import javax.swing.JPanel; public class SpreadSheet extends JPanel{ private String[] columnNames; private double[] columnSizes; private byte[] alignments; private int rowHeight; private final ArrayList<Object[]> data = new ArrayList<>(); private final ArrayList<Boolean> isBold = new ArrayList<>(); private static final Color ALT_COLOR = new Color(230, 255, 230); public SpreadSheet(String[] columnNames, double[] columnSizes, byte[] alignments, int rowHeight){ this.columnNames=columnNames; this.columnSizes=columnSizes; this.alignments=alignments; this.rowHeight=rowHeight; } public void addRow(Object[] row, boolean bold){ data.add(row); isBold.add(bold); setPreferredSize(new Dimension(10, (data.size()+1)*rowHeight)); repaint(); } public void removeRow(Object[] row){ int index = data.indexOf(row); if(index>=0){ data.remove(index); isBold.remove(index); setPreferredSize(new Dimension(10, (data.size()+1)*rowHeight)); repaint(); } } @Override public void paint(Graphics g1){ Graphics2D g = (Graphics2D)g1; int width = getWidth(); int height = getHeight(); int rowsShown = height/rowHeight; FontMetrics fm = g.getFontMetrics(); int textY = (int)(fm.getAscent()+(rowHeight-(fm.getAscent()+fm.getDescent()))*0.5); for(int i = 0; i<=rowsShown; i++){ g.setColor(i==0?Color.lightGray:i%2==1?Color.white:ALT_COLOR); g.fillRect(0, rowHeight*i, width, rowHeight); g.setColor(Color.black); g.drawLine(0, rowHeight*i, width, rowHeight*i); if(i==0){ Font oldFont = getFont(); g.setFont(new Font(oldFont.getName(), Font.BOLD, oldFont.getSize())); for(int j = 0; j<columnNames.length; j++)g.drawString(columnNames[j], (int)(((((j==columnSizes.length-1?1:columnSizes[j+1])-columnSizes[j])*width)-fm.stringWidth(columnNames[j].toString()))*0.5+width*columnSizes[j]), rowHeight*i+textY); g.setFont(oldFont); }else{ if(i-1<data.size()){ for(int j = 0; j<columnSizes.length; j++){ Font oldFont = null; if(isBold.get(i-1)){ oldFont=getFont(); g.setFont(new Font(oldFont.getName(), Font.BOLD, oldFont.getSize())); } if(alignments[j]==-1)g.drawString(data.get(i-1)[j].toString(), (int)(width*columnSizes[j])+3, rowHeight*i+textY); else if(alignments[j]==0)g.drawString(data.get(i-1)[j].toString(), (int)(((((j==columnSizes.length-1?1:columnSizes[j+1])-columnSizes[j])*width)-fm.stringWidth(data.get(i-1)[j].toString()))*0.5+width*columnSizes[j]), rowHeight*i+textY); else g.drawString(data.get(i-1)[j].toString(), (int)(width*columnSizes[j])+3, rowHeight*i+textY); if(isBold.get(i-1))g.setFont(oldFont); } } } } g.setColor(Color.black); for(int i = 0; i<columnSizes.length-1; i++)g.drawLine((int)(width*columnSizes[i+1]), 0, (int)(width*columnSizes[i+1]), height); g.dispose(); } public void setRows(ArrayList<Object[]> rows, boolean[] bolded){ data.clear(); isBold.clear(); data.addAll(rows); for(int i = 0; i<bolded.length; i++)isBold.add(bolded[i]); repaint(); } public void setNames(String[] columnNames){ this.columnNames=columnNames; repaint(); } public void updateColumnData(String[] columnNames, double[] columnSizes, byte[] alignments, int rowHeight){ this.columnNames=columnNames; this.columnSizes=columnSizes; this.rowHeight=rowHeight; this.alignments=alignments; data.clear(); isBold.clear(); } }
package agave; import agave.annotations.ContentType; import agave.annotations.Converters; import agave.annotations.Path; import agave.annotations.PositionalParameters; import agave.annotations.Required; import agave.converters.ConverterChain; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author <a href="mailto:damiancarrillo@gmail.com">Damian Carrillo</a> */ public class HandlerManager implements Filter { private Logger LOGGER = LoggerFactory.getLogger(HandlerManager.class); private static final String CLASS_SUFFIX = ".class"; private static final String CLASSDIR = "/WEB-INF/classes/"; private static final String DEBUG = "debug"; private static final String GET = "get"; public static final String DEFAULT_CONTENT_TYPE = ContentType.APPLICATION_XHTML_XML; private FilterConfig filterConfig = null; private Map<String, String> configuration; protected Map<String, Class<? extends ResourceHandler>> resourceHandlers; protected Map<String, Class<? extends FormHandler>> formHandlers; private boolean debugMode = false; /** * Init method for this filter * @param filterConfig */ public void init(FilterConfig filterConfig) { Date start = new Date(); LOGGER.info("Initializing Framework Execution Environment"); String debugModeValue = filterConfig.getInitParameter(DEBUG); if ("true".equalsIgnoreCase(debugModeValue)) { debugMode = true; } this.filterConfig = filterConfig; configuration = new HashMap<String, String>(); Enumeration<String> initParameters = filterConfig.getInitParameterNames(); while (initParameters.hasMoreElements()) { String configKey = initParameters.nextElement(); String configValue = filterConfig.getInitParameter(configKey); configuration.put(configKey, configValue); } resourceHandlers = new LinkedHashMap<String, Class<? extends ResourceHandler>>(); formHandlers = new LinkedHashMap<String, Class<? extends FormHandler>>(); String classDirPath = filterConfig.getServletContext().getRealPath(CLASSDIR); File root = new File(filterConfig.getServletContext().getRealPath(CLASSDIR)); // Discover and map the resource handlers Set<Class<? extends ResourceHandler>> resourceHandlerClasses = new HashSet<Class<? extends ResourceHandler>>(); discoverClasses(classDirPath, root, ResourceHandler.class, resourceHandlerClasses); mapResourceHandlers(resourceHandlerClasses); // Discover and map the form handlers Set<Class<? extends FormHandler>> formHandlerClasses = new HashSet<Class<? extends FormHandler>>(); discoverClasses(classDirPath, root, FormHandler.class, formHandlerClasses); mapFormHandlers(formHandlerClasses); Date end = new Date(); LOGGER.info("Initialization took " + (end.getTime() - start.getTime()) + "ms"); } /** * * @param req * @param resp * @param chain The filter chain we are processing * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */ public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if (req instanceof HttpServletRequest && resp instanceof HttpServletResponse) { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)resp; if (LOGGER.isDebugEnabled()) { String msg = "Displaying request headers (disable this by " + "removing the debug parameter to HandlerManager in the web.xml)"; LOGGER.debug(msg); } Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(headerName + ": " + request.getHeader(headerName)); } } String requestedPath = request.getRequestURI(); String contextPath = request.getContextPath(); String method = request.getMethod(); if (!contextPath.equals("/") && requestedPath.startsWith(contextPath)) { requestedPath = requestedPath.substring(contextPath.length()); } if (method.equals("POST")) { String matchedPath = matchPath(requestedPath, formHandlers.keySet()); if (matchedPath != null) { handlePost(new HandlerContext( configuration, filterConfig.getServletContext(), request, response, requestedPath, matchedPath, resourceHandlers, formHandlers)); // do not continue processing filter chain return; } } else if (method.equals("GET")) { String matchedPath = matchPath(requestedPath, resourceHandlers.keySet()); if (matchedPath != null) { handleGet(new HandlerContext( configuration, filterConfig.getServletContext(), request, response, requestedPath, matchedPath, resourceHandlers, formHandlers)); // do not continue processing filter chain return; } } } chain.doFilter(req, resp); } /** * Destroy method for this filter. */ public void destroy() { filterConfig = null; } /** * * @param context * @throws agave.HandlerException * @throws java.io.IOException */ protected void handlePost(HandlerContext context) throws HandlerException, IOException { Class<? extends FormHandler> handlerClass = formHandlers.get(context.getMatchedPath()); LOGGER.info("Handling POST for path " + context.getRequestedPath() + " with " + handlerClass.getName()); try { Constructor<? extends FormHandler> constructor = handlerClass.getConstructor(); FormHandler handler = constructor.newInstance(); // Assign the query string parameters to their matching properties Map<String, String> params = new HashMap<String, String>(); // Interpret any posted files (header name is case insensitive) String ctHeader = context.getRequest().getHeader("Content-Type"); if (ctHeader != null && ctHeader.trim().startsWith("multipart")) { InputStream in = context.getRequest().getInputStream(); Pattern bp = Pattern.compile("^.*boundary=(.*)$"); Matcher bm = bp.matcher(ctHeader); String boundary = null; if (bm.matches() && bm.groupCount() >= 1) { boundary = bm.group(1); MultipartInterpreter mi = new MultipartInterpreter(in, boundary, true); params.putAll(mi.getProperties()); bindParameters(context, handlerClass, handler, mi.getFiles()); } else { throw new IOException("Unable to process multipart form post: " + " part boundary was malformed (in the Content-Type header)"); } } else { Enumeration requestParamNames = context.getRequest().getParameterNames(); while (requestParamNames.hasMoreElements()) { String requestParamName = (String)requestParamNames.nextElement(); String requestParamValue = context.getRequest().getParameter(requestParamName); LOGGER.debug("Request parameter: " + requestParamName + " = " + requestParamValue); if (requestParamValue != null) { params.put(requestParamName, requestParamValue); } } } bindParameters(context, handlerClass, handler, params); String path = handler.process(context); context.getResponse().sendRedirect(path); } catch (Exception ex) { throw new HandlerException(ex); } } /** * * @param context * @throws java.io.IOException * @throws agave.HandlerException */ protected void handleGet(HandlerContext context) throws HandlerException, IOException { Class<? extends ResourceHandler> handlerClass = resourceHandlers.get(context.getMatchedPath()); LOGGER.info("Handling GET for path " + context.getRequestedPath() + " with " + handlerClass.getName()); try { Constructor<? extends ResourceHandler> constructor = handlerClass.getConstructor(); ResourceHandler handler = constructor.newInstance(); // Assign the query string parameters to their matching properties Map<String, String> params = new HashMap<String, String>(); Enumeration requestParamNames = context.getRequest().getParameterNames(); while (requestParamNames.hasMoreElements()) { String requestParamName = (String)requestParamNames.nextElement(); String requestParamValue = context.getRequest().getParameter(requestParamName); if (requestParamValue != null) { params.put(requestParamName, requestParamValue); } } // Assign any positional parameters PositionalParameters positionalParams = handlerClass.getAnnotation(PositionalParameters.class); String paramStr = context.getRequestedPath().replaceFirst(context.getMatchedPath(), ""); if (paramStr.startsWith("/")) { paramStr = paramStr.substring(1); } if (positionalParams != null && paramStr != null && !paramStr.equals("") && !paramStr.equals("/")) { String[] paramValues = paramStr.split("\\s*/\\s*"); String[] paramNames = positionalParams.value(); if (paramValues.length < paramNames.length) { throw new HandlerException("Missing one or more positional parameters."); } for (int i = 0; i < paramNames.length; i++) { params.put(paramNames[i], paramValues[i]); } } bindParameters(context, handlerClass, handler, params); ContentType contentTypeAnn = handlerClass.getAnnotation(ContentType.class); String contentType = (contentTypeAnn == null) ? DEFAULT_CONTENT_TYPE : contentTypeAnn.value(); context.getResponse().setContentType(contentType); // have the handler render itself handler.render(context); } catch (Exception ex) { throw new HandlerException(ex); } } /** * Rewrites a path so that it is turned into a fully qualified class name. * @param file the file whose name will be rewritten * @param root the root path string * @return the rewritten class name */ protected String rewriteClassName(String root, File file) { if (!root.endsWith("/")) { root = root + "/"; } String fileName = file.getAbsolutePath(); fileName = fileName.replace(root, ""); fileName = fileName.replace(".class", ""); fileName = fileName.replace("/", "."); return fileName; } /** * Find the longest path that matches the supplied path amongst the set of * mapped handlers. * @param path The requested path * @param keys The set of handlers mapped to paths * @return The longest matched path */ protected String matchPath(final String path, final Set<String> keys) { int matchLength = 0; String longestMatch = null; for (String key : keys) { if (path.startsWith(key)) { if (key.length() > matchLength) { matchLength = key.length(); longestMatch = key; } } } return longestMatch; } /** * Bind a possibly converted value of some sort to a property in a class. * @param context The context in which the handler operates in * @param handlerClass The handler class * @param handler The instance of the handlerClass that has been created * for each request. * @param params The parameters to set on the handler instance * @throws agave.HandlerException if any exception occurs */ protected <T> void bindParameters(HandlerContext context, Class<? extends Handler> handlerClass, Handler handler, Map<String, T> params) throws HandlerException { for (String paramName : params.keySet()) { T paramValue = params.get(paramName); if (paramValue != null && !paramValue.equals("")) { try { String setterName = "set" + paramName.substring(0, 1).toUpperCase() + paramName.substring(1); Method[] methods = handlerClass.getMethods(); Method setter = null; // Find the method named by the setterName above for (Method m : methods) { if (m.getName().equals(setterName)) { setter = m; break; } } if (setter != null) { // If there is a converter on the setter, use it Converters converters = setter.getAnnotation(Converters.class); if (converters != null) { ConverterChain chain = new ConverterChain(converters.value()); setter.invoke(handler, chain.convertAll(context, paramValue)); } else { setter.invoke(handler, paramValue); LOGGER.debug("Calling setter '" + setter.getName() + "' with paramater " + paramValue.toString()); } } else { throw new NoSuchMethodException("Could not find setter " + setterName + " on class " + handlerClass.getName()); } } catch (Exception ex) { throw new HandlerException("Could not bind positional parameter '" + paramName + "'", ex); } } } try { for (Method method : handlerClass.getMethods()) { if (method.getName().startsWith(GET) && method.isAnnotationPresent(Required.class) && method.invoke(handler) == null) { throw new HandlerException("Missing required value returned from: " + method.getName()); } } } catch (InvocationTargetException ex) { throw new HandlerException(ex); } catch (IllegalArgumentException ex) { throw new HandlerException(ex); } catch (IllegalAccessException ex) { throw new HandlerException(ex); } } /** * Discovers classes the are children of the supplied target class. This * method is recursive. * @param classDir The base directory to scan for classes. This is laid out * in the Servlet specification. * @param root The file whose children to inspect * @param target The target class * @param matches A set of classes that are children of the target class */ protected <T> void discoverClasses(String classDir, File root, Class<T> target, Set<Class<? extends T>> matches) { if (root.isDirectory()) { for (File file : root.listFiles()) { discoverClasses(classDir, file, target, matches); } } else { if (root.exists() && root.canRead() && root.getPath().endsWith(CLASS_SUFFIX)) { String className = rewriteClassName(classDir, root); try { Class<?> candidate = Class.forName(className); if (target.isAssignableFrom(candidate)) { // Class heirarchy is tested for so the following should not be // a problem Class<T> match = (Class<T>)candidate; matches.add(match); } } catch (ClassNotFoundException ex) { LOGGER.error("Could not call Class.forName()", ex); } } } } /** * Map the discovered resource handles by inspecting their {@code Path} * annotation. * @param handlers a {@code Set} of discovered resource handler classes */ protected void mapResourceHandlers(Set<Class<? extends ResourceHandler>> handlers) { LOGGER.info("[Resource Handlers]"); if (debugMode) { resourceHandlers.put("/info", InfoPage.class); String msg = "Mapping /info -> " + InfoPage.class.getName() + "(Disable this particular handler by removing the debug " + " parameter to the HandlerManager in web.xml)"; LOGGER.info(msg); } for (Class<? extends ResourceHandler> handler : handlers) { if (handler.isAnnotationPresent(Path.class)) { Path pathAnnotation = handler.getAnnotation(Path.class); String mappedPath = pathAnnotation.value(); resourceHandlers.put(mappedPath, handler); LOGGER.info("Mapping " + mappedPath + " -> " + handler.getName()); } } } /** * Map the discovered form handlers by inspecting their {@code Path} * annotation. * @param handlers a {@code Set} of discovered form handler classes */ protected void mapFormHandlers(Set<Class<? extends FormHandler>> handlers) { LOGGER.info("[Form Handlers]"); for (Class<? extends FormHandler> handler : handlers) { if (handler.isAnnotationPresent(Path.class)) { Path pathAnnotation = handler.getAnnotation(Path.class); String mappedPath = pathAnnotation.value(); formHandlers.put(mappedPath, handler); LOGGER.info("Mapping " + mappedPath + " -> " + handler.getName()); } } } }
package biomodel.gui.sbmlcore; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import main.Gui; import main.util.Utility; import org.sbml.jsbml.*; import org.sbml.jsbml.ext.arrays.ArraysSBasePlugin; import org.sbml.jsbml.ext.arrays.Index; import org.sbml.jsbml.ext.comp.Port; import org.sbml.jsbml.ext.layout.Layout; import biomodel.annotation.AnnotationUtility; import biomodel.annotation.SBOLAnnotation; import biomodel.gui.sbol.SBOLField; import biomodel.gui.schematic.ModelEditor; import biomodel.parser.BioModel; import biomodel.util.GlobalConstants; import biomodel.util.SBMLutilities; /** * This is a class for creating SBML events. * * @author Chris Myers * */ public class Events extends JPanel implements ActionListener, MouseListener { private static final long serialVersionUID = 1L; private JButton addEvent, addTrans, removeEvent, editEvent, addAssignment, editAssignment, removeAssignment; private JList events; // JList of events private JList eventAssign; // JList of event assignments private JTextField iIndex, EAdimensions; private JComboBox eaID; private BioModel bioModel; private ModelEditor modelEditor; private SBOLField sbolField; private boolean isTextual; private JTextField eventID; private boolean isTransition; /* Create event panel */ public Events(Gui biosim, BioModel bioModel, ModelEditor modelEditor, boolean isTextual) { super(new BorderLayout()); this.bioModel = bioModel; this.isTextual = isTextual; this.modelEditor = modelEditor; Model model = bioModel.getSBMLDocument().getModel(); addEvent = new JButton("Add Event"); addTrans = new JButton("Add Transition"); if (biosim.lema) { removeEvent = new JButton("Remove Transition"); editEvent = new JButton("Edit Transition"); } else { removeEvent = new JButton("Remove Event"); editEvent = new JButton("Edit Event"); } events = new JList(); eventAssign = new JList(); ListOf<Event> listOfEvents = model.getListOfEvents(); String[] ev = new String[model.getEventCount()]; for (int i = 0; i < model.getEventCount(); i++) { org.sbml.jsbml.Event event = listOfEvents.get(i); if (!event.isSetId()) { String eventId = "event0"; int en = 0; while (bioModel.isSIdInUse(eventId)) { en++; eventId = "event" + en; } event.setId(eventId); } ev[i] = event.getId(); ev[i] += SBMLutilities.getDimensionString(event); } JPanel addRem = new JPanel(); if (!biosim.lema) { addRem.add(addEvent); } if (isTextual) { addRem.add(addTrans); addTrans.addActionListener(this); } addRem.add(removeEvent); addRem.add(editEvent); addEvent.addActionListener(this); removeEvent.addActionListener(this); editEvent.addActionListener(this); JLabel panelLabel; if (biosim.lema) { panelLabel = new JLabel("List of Transitions:"); } else { panelLabel = new JLabel("List of Events:"); } JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(260, 220)); scroll.setPreferredSize(new Dimension(276, 152)); scroll.setViewportView(events); Utility.sort(ev); events.setListData(ev); events.setSelectedIndex(0); events.addMouseListener(this); this.add(panelLabel, "North"); this.add(scroll, "Center"); this.add(addRem, "South"); } /** * Creates a frame used to edit events or create new ones. */ public String eventEditor(String option,String selected,boolean isTransition) { this.isTransition = isTransition; String[] origAssign = new String[0]; String[] assign = new String[0]; String[] placeAssign = new String[0]; ArrayList<String> presetPlaces = new ArrayList<String>(); JPanel eventPanel = new JPanel(new BorderLayout()); // JPanel evPanel = new JPanel(new GridLayout(2, 2)); JPanel evPanel = new JPanel(new GridLayout(9, 2)); if (isTransition) { evPanel.setLayout(new GridLayout(7, 2)); } JLabel IDLabel = new JLabel("ID:"); JLabel NameLabel = new JLabel("Name:"); JLabel triggerLabel; if (isTransition) { triggerLabel = new JLabel("Enabling condition:"); } else { triggerLabel = new JLabel("Trigger:"); } JLabel delayLabel = new JLabel("Delay:"); JLabel priorityLabel = new JLabel("Priority:"); JLabel assignTimeLabel = new JLabel("Use values at trigger time:"); JLabel persistentTriggerLabel; if (isTransition) { persistentTriggerLabel = new JLabel("Enabling is persistent:"); } else { persistentTriggerLabel = new JLabel("Trigger is persistent:"); } JLabel initialTriggerLabel = new JLabel("Trigger initially true:"); JLabel dynamicProcessLabel = new JLabel("Dynamic Process:"); JLabel onPortLabel = new JLabel("Is Mapped to a Port:"); JLabel failTransitionLabel = new JLabel("Fail transition:"); eventID = new JTextField(12); JTextField eventName = new JTextField(12); JTextField eventTrigger = new JTextField(12); JTextField eventDelay = new JTextField(12); JTextField eventPriority = new JTextField(12); JCheckBox assignTime = new JCheckBox(""); JCheckBox persistentTrigger = new JCheckBox(""); JCheckBox initialTrigger = new JCheckBox(""); JCheckBox failTransition = new JCheckBox(""); JComboBox dynamicProcess = new JComboBox(new String[] {"none", "Symmetric Division","Asymmetric Division","Death", "Move Random", "Move Left", "Move Right", "Move Above", "Move Below"}); JCheckBox onPort = new JCheckBox(); iIndex = new JTextField(20); EAdimensions = new JTextField(20); if (bioModel != null && bioModel.IsWithinCompartment() == false) { dynamicProcess.setEnabled(false); dynamicProcess.setSelectedItem("none"); } JPanel eventAssignPanel = new JPanel(new BorderLayout()); JPanel addEventAssign = new JPanel(); addAssignment = new JButton("Add Assignment"); removeAssignment = new JButton("Remove Assignment"); editAssignment = new JButton("Edit Assignment"); addEventAssign.add(addAssignment); addEventAssign.add(removeAssignment); addEventAssign.add(editAssignment); addAssignment.addActionListener(this); removeAssignment.addActionListener(this); editAssignment.addActionListener(this); JLabel eventAssignLabel = new JLabel("List of Assignments:"); eventAssign.removeAll(); eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(260, 220)); scroll.setPreferredSize(new Dimension(276, 152)); scroll.setViewportView(eventAssign); int Eindex = -1; String selectedID = ""; if (option.equals("OK")) { ListOf<Event> e = bioModel.getSBMLDocument().getModel().getListOfEvents(); for (int i = 0; i < bioModel.getSBMLDocument().getModel().getEventCount(); i++) { org.sbml.jsbml.Event event = e.get(i); if (event.getId().equals(selected)) { isTransition = SBMLutilities.isTransition(event); if (isTransition) { evPanel.setLayout(new GridLayout(8, 2)); } Eindex = i; eventID.setText(event.getId()); selectedID = event.getId(); eventName.setText(event.getName()); String trigger = SBMLutilities.myFormulaToString(event.getTrigger().getMath()); ASTNode triggerMath = event.getTrigger().getMath(); for (int j = 0; j < bioModel.getSBMLDocument().getModel().getParameterCount(); j++) { Parameter parameter = bioModel.getSBMLDocument().getModel().getParameter(j); if (parameter!=null && SBMLutilities.isPlace(parameter)) { if (!isTextual && (trigger.contains("eq("+parameter.getId()+", 1)")|| trigger.contains("("+parameter.getId()+" == 1)"))) { triggerMath = SBMLutilities.removePreset(triggerMath, parameter.getId()); presetPlaces.add(parameter.getId()); } } } eventTrigger.setText(bioModel.removeBooleans(triggerMath)); String dynamic = AnnotationUtility.parseDynamicAnnotation(event); if (dynamic!=null) { dynamicProcess.setSelectedItem(dynamic); } if (event.isSetDelay() && event.getDelay().isSetMath()) { ASTNode delay = event.getDelay().getMath(); if ((delay.getType() == ASTNode.Type.FUNCTION) && (delay.getName().equals("priority"))) { eventDelay.setText(SBMLutilities.myFormulaToString(delay.getLeftChild())); eventPriority.setText(SBMLutilities.myFormulaToString(delay.getRightChild())); } else { eventDelay.setText(bioModel.removeBooleans(delay)); } } if (event.getUseValuesFromTriggerTime()) { assignTime.setSelected(true); } if (AnnotationUtility.checkObsoleteAnnotation(event.getTrigger(),"<TriggerCanBeDisabled/>")) { persistentTrigger.setSelected(false); } else { persistentTrigger.setSelected(true); } if (AnnotationUtility.checkObsoleteAnnotation(event.getTrigger(),"<TriggerInitiallyFalse/>")) { initialTrigger.setSelected(false); } else { initialTrigger.setSelected(true); } if (event.isSetPriority()) { eventPriority.setText(bioModel.removeBooleans(event.getPriority().getMath())); } if (event.getTrigger().isSetPersistent()) { persistentTrigger.setSelected(event.getTrigger().getPersistent()); if (isTransition) { Rule r = bioModel.getSBMLDocument().getModel().getRule(GlobalConstants.TRIGGER + "_" + event.getId()); if (r != null) { persistentTrigger.setSelected(true); triggerMath = r.getMath(); if (triggerMath.getType()==ASTNode.Type.FUNCTION_PIECEWISE && triggerMath.getChildCount() > 2) { triggerMath = triggerMath.getChild(1); if (triggerMath.getType()==ASTNode.Type.LOGICAL_OR) { triggerMath = triggerMath.getLeftChild(); trigger = SBMLutilities.myFormulaToString(triggerMath); for (int j = 0; j < bioModel.getSBMLDocument().getModel().getParameterCount(); j++) { Parameter parameter = bioModel.getSBMLDocument().getModel().getParameter(j); if (parameter!=null && SBMLutilities.isPlace(parameter)) { if (!isTextual && (trigger.contains("eq("+parameter.getId()+", 1)")|| trigger.contains("("+parameter.getId()+" == 1)"))) { triggerMath = SBMLutilities.removePreset(triggerMath, parameter.getId()); //presetPlaces.add(parameter.getId()); } } } eventTrigger.setText(bioModel.removeBooleans(triggerMath)); } } } } else { persistentTrigger.setSelected(false); } } if (event.getTrigger().isSetInitialValue()) { initialTrigger.setSelected(event.getTrigger().getInitialValue()); } if (bioModel.getPortByIdRef(event.getId())!=null) { onPort.setSelected(true); } else { onPort.setSelected(false); } int numPlaces=0; int numFail=0; for (int j = 0; j < event.getEventAssignmentCount(); j++) { EventAssignment ea = event.getListOfEventAssignments().get(j); Parameter parameter = bioModel.getSBMLDocument().getModel().getParameter(ea.getVariable()); if (parameter!=null && SBMLutilities.isPlace(parameter)) { numPlaces++; } else if (ea.getVariable().equals(GlobalConstants.FAIL)) { numFail++; } } if (isTextual) { assign = new String[event.getEventAssignmentCount()-(numFail)]; } else { assign = new String[event.getEventAssignmentCount()-(numPlaces+numFail)]; } if (isTextual) { placeAssign = new String[0]; } else { placeAssign = new String[numPlaces]; } origAssign = new String[event.getEventAssignmentCount()]; int k=0; int l=0; for (int j = 0; j < event.getEventAssignmentCount(); j++) { Parameter parameter = bioModel.getSBMLDocument().getModel().getParameter(event.getListOfEventAssignments().get(j).getVariable()); EventAssignment ea = event.getListOfEventAssignments().get(j); ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(ea); String freshIndex = "; "; for(int i1 = sBasePlugin.getIndexCount()-1; i1>=0; i1 Index indie = sBasePlugin.getIndex(i1,"variable"); if (indie!=null) { freshIndex += "[" + SBMLutilities.myFormulaToString(indie.getMath()) + "]"; } } String dimens = " "; for(int i1 = sBasePlugin.getDimensionCount()-1; i1>=0; i1 org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.getDimensionByArrayDimension(i1); dimens += "[" + dimX.getSize() + "]"; } if (parameter!=null && SBMLutilities.isPlace(parameter)) { if (isTextual) { assign[l] = ea.getVariable() + dimens + " := " + SBMLutilities.myFormulaToString(ea.getMath()) + freshIndex; l++; } else { placeAssign[k] = ea.getVariable() + dimens + " := " + SBMLutilities.myFormulaToString(ea.getMath()) + freshIndex; k++; } } else if (ea.getVariable().equals(GlobalConstants.FAIL)){ failTransition.setSelected(true); } else { String assignMath = SBMLutilities.myFormulaToString(ea.getMath()); if (parameter!=null && SBMLutilities.isBoolean(parameter)) { assignMath = bioModel.removeBooleanAssign(event.getListOfEventAssignments().get(j).getMath()); } assign[l] = ea.getVariable() + dimens + " := " + assignMath + freshIndex; l++; } origAssign[j] = ea.getVariable() + dimens + " := " + SBMLutilities.myFormulaToString(ea.getMath()) + freshIndex; } if (!modelEditor.isParamsOnly()) { //Parse out SBOL annotations and add to SBOL field List<URI> sbolURIs = new LinkedList<URI>(); String sbolStrand = AnnotationUtility.parseSBOLAnnotation(event, sbolURIs); // Field for annotating event with SBOL DNA components sbolField = new SBOLField(sbolURIs, sbolStrand, GlobalConstants.SBOL_DNA_COMPONENT, modelEditor, 2, false); } String dimInID = SBMLutilities.getDimensionString(event); eventID.setText(eventID.getText()+dimInID); } } } else { // Field for annotating event with SBOL DNA components sbolField = new SBOLField(new LinkedList<URI>(), GlobalConstants.SBOL_ASSEMBLY_PLUS_STRAND, GlobalConstants.SBOL_DNA_COMPONENT, modelEditor, 2, false); String eventId = "event0"; if (isTransition) eventId = "t0"; int en = 0; while (bioModel.isSIdInUse(eventId)) { en++; if (isTransition) eventId = "t" + en; else eventId = "event" + en; } eventID.setText(eventId); } Utility.sort(assign); eventAssign.setListData(assign); eventAssign.setSelectedIndex(0); eventAssign.addMouseListener(this); eventAssignPanel.add(eventAssignLabel, "North"); eventAssignPanel.add(scroll, "Center"); eventAssignPanel.add(addEventAssign, "South"); evPanel.add(IDLabel); evPanel.add(eventID); evPanel.add(NameLabel); evPanel.add(eventName); evPanel.add(onPortLabel); evPanel.add(onPort); evPanel.add(triggerLabel); evPanel.add(eventTrigger); JPanel persistPanel = new JPanel(); persistPanel.add(persistentTriggerLabel); persistPanel.add(persistentTrigger); evPanel.add(persistPanel); if (!isTransition) { JPanel initTrigPanel = new JPanel(); initTrigPanel.add(initialTriggerLabel); initTrigPanel.add(initialTrigger); evPanel.add(initTrigPanel); JPanel assignTimePanel = new JPanel(); assignTimePanel.add(assignTimeLabel); assignTimePanel.add(assignTime); evPanel.add(new JLabel("")); evPanel.add(assignTimePanel); } else { JPanel failTransPanel = new JPanel(); failTransPanel.add(failTransitionLabel); failTransPanel.add(failTransition); evPanel.add(failTransPanel); } evPanel.add(delayLabel); evPanel.add(eventDelay); evPanel.add(priorityLabel); evPanel.add(eventPriority); if (!isTransition) { evPanel.add(dynamicProcessLabel); evPanel.add(dynamicProcess); } eventPanel.add(evPanel, "North"); if (!modelEditor.isParamsOnly()) eventPanel.add(sbolField, "Center"); eventPanel.add(eventAssignPanel, "South"); Object[] options = { option, "Cancel" }; String title = "Event Editor"; if (isTransition) { title = "Transition Editor"; } int value = JOptionPane.showOptionDialog(Gui.frame, eventPanel, title, JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); String[] dimID = new String[]{""}; String[] dimensionIds = new String[]{""}; boolean error = true; while (error && value == JOptionPane.YES_OPTION) { assign = new String[eventAssign.getModel().getSize()]; for (int i = 0; i < eventAssign.getModel().getSize(); i++) { assign[i] = eventAssign.getModel().getElementAt(i).toString(); } dimID = SBMLutilities.checkSizeParameters(bioModel.getSBMLDocument(), eventID.getText(), false); if(dimID!=null){ dimensionIds = SBMLutilities.getDimensionIds("",dimID.length-1); error = SBMLutilities.checkID(bioModel.getSBMLDocument(), dimID[0].trim(), selected, false); } else{ error = true; } if(!error){ if (eventTrigger.getText().trim().equals("")) { JOptionPane.showMessageDialog(Gui.frame, "Event must have a trigger formula.", "Enter Trigger Formula", JOptionPane.ERROR_MESSAGE); error = true; } else if (SBMLutilities.myParseFormula(eventTrigger.getText().trim()) == null) { JOptionPane.showMessageDialog(Gui.frame, "Trigger formula is not valid.", "Enter Valid Formula", JOptionPane.ERROR_MESSAGE); error = true; } else if (!SBMLutilities.returnsBoolean(bioModel.addBooleans(eventTrigger.getText().trim()), bioModel.getSBMLDocument().getModel())) { JOptionPane.showMessageDialog(Gui.frame, "Trigger formula must be of type Boolean.", "Enter Valid Formula", JOptionPane.ERROR_MESSAGE); error = true; } else if (!eventDelay.getText().trim().equals("") && SBMLutilities.myParseFormula(eventDelay.getText().trim()) == null) { JOptionPane.showMessageDialog(Gui.frame, "Delay formula is not valid.", "Enter Valid Formula", JOptionPane.ERROR_MESSAGE); error = true; } else if (!eventPriority.getText().trim().equals("") && SBMLutilities.myParseFormula(eventPriority.getText().trim()) == null) { JOptionPane.showMessageDialog(Gui.frame, "Priority formula is not valid.", "Enter Valid Formula", JOptionPane.ERROR_MESSAGE); error = true; } else if (bioModel.getSBMLDocument().getLevel() < 3 && assign.length == 0) { JOptionPane.showMessageDialog(Gui.frame, "Event must have at least one event assignment.", "Event Assignment Needed", JOptionPane.ERROR_MESSAGE); error = true; } else { error = SBMLutilities.displayinvalidVariables("Event trigger", bioModel.getSBMLDocument(), dimensionIds, eventTrigger.getText().trim(), "", false); if (!error) { error = SBMLutilities.displayinvalidVariables("Event delay", bioModel.getSBMLDocument(), dimensionIds, eventDelay.getText().trim(), "", false); } if (!error) { error = SBMLutilities.displayinvalidVariables("Event priority", bioModel.getSBMLDocument(), dimensionIds, eventPriority.getText().trim(), "", false); } if (!error) { error = SBMLutilities.checkNumFunctionArguments(bioModel.getSBMLDocument(), SBMLutilities.myParseFormula(eventTrigger.getText().trim())); } if (!error) { error = SBMLutilities.checkFunctionArgumentTypes(bioModel.getSBMLDocument(), bioModel.addBooleans(eventTrigger.getText().trim())); } if ((!error) && (!eventDelay.getText().trim().equals(""))) { error = SBMLutilities.checkNumFunctionArguments(bioModel.getSBMLDocument(), bioModel.addBooleans(eventDelay.getText().trim())); if (!error) { if (SBMLutilities.returnsBoolean(bioModel.addBooleans(eventDelay.getText().trim()), bioModel.getSBMLDocument().getModel())) { JOptionPane.showMessageDialog(Gui.frame, "Event delay must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); error = true; } } } if ((!error) && (!eventPriority.getText().trim().equals(""))) { error = SBMLutilities.checkNumFunctionArguments(bioModel.getSBMLDocument(), bioModel.addBooleans(eventPriority.getText().trim())); if (!error) { if (SBMLutilities.returnsBoolean(bioModel.addBooleans(eventPriority.getText().trim()), bioModel.getSBMLDocument().getModel())) { JOptionPane.showMessageDialog(Gui.frame, "Event priority must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); error = true; } } } } } if (!error) { String[] EAdimID = new String[]{""}; String[] EAdex = new String[]{""}; String[] EAdimensionIds = new String[]{""}; for (int i = 0; i < assign.length; i++) { String left = assign[i].split(":=")[0].trim(); String rightSide = assign[i].split(":=")[1].split(";")[1].trim(); EAdimID = SBMLutilities.checkSizeParameters(bioModel.getSBMLDocument(), left, false); if(EAdimID!=null){ EAdimensionIds = SBMLutilities.getDimensionIds("e",EAdimID.length-1); String variableId = EAdimID[0].trim(); if (variableId.endsWith("_"+GlobalConstants.RATE)) { variableId = variableId.replace("_"+GlobalConstants.RATE, ""); } SBase variable = SBMLutilities.getElementBySId(bioModel.getSBMLDocument(), variableId); EAdex = SBMLutilities.checkIndices(rightSide, variable, bioModel.getSBMLDocument(), EAdimensionIds, "variable", EAdimID, dimensionIds, dimID); error = (EAdex==null); } else{ error = true; } } } if (!error) { //edit event org.sbml.jsbml.Event e = (bioModel.getSBMLDocument().getModel().getListOfEvents()).get(Eindex); if (option.equals("OK")) { events.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); String[] ev = new String[events.getModel().getSize()]; for (int i = 0; i < events.getModel().getSize(); i++) { ev[i] = events.getModel().getElementAt(i).toString(); } events.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); e.setUseValuesFromTriggerTime(assignTime.isSelected()); while (e.getEventAssignmentCount() > 0) { e.getListOfEventAssignments().remove(0); } String[] EAdimID = new String[]{""}; String[] EAdex = new String[]{""}; String[] EAdimensionIds = new String[]{""}; for (int i = 0; i < assign.length; i++) { EventAssignment ea = e.createEventAssignment(); String var = assign[i].split(" ")[0]; ea.setVariable(var); String left = assign[i].split(":=")[0].trim(); String rightSide = assign[i].split(":=")[1].split(";")[1].trim(); EAdimID = SBMLutilities.checkSizeParameters(bioModel.getSBMLDocument(), left, false); if(EAdimID!=null){ EAdimensionIds = SBMLutilities.getDimensionIds("e",EAdimID.length-1); String variableId = EAdimID[0].trim(); if (variableId.endsWith("_"+GlobalConstants.RATE)) { variableId = variableId.replace("_"+GlobalConstants.RATE, ""); } SBase variable = SBMLutilities.getElementBySId(bioModel.getSBMLDocument(), variableId); EAdex = SBMLutilities.checkIndices(rightSide, variable, bioModel.getSBMLDocument(), EAdimensionIds, "variable", EAdimID, dimensionIds, dimID); } ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(ea); sBasePlugin.unsetListOfDimensions(); for(int i1 = 0; EAdimID!=null && i1<EAdimID.length-1; i1++){ org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.createDimension(EAdimensionIds[i1]); dimX.setSize(EAdimID[i1+1]); dimX.setArrayDimension(i1); } sBasePlugin.unsetListOfIndices(); for(int i1 = 0; EAdex!=null && i1<EAdex.length-1; i1++){ Index indexRule = new Index(); indexRule.setArrayDimension(i1); indexRule.setReferencedAttribute("variable"); ASTNode indexMath = SBMLutilities.myParseFormula(EAdex[i1+1]); indexRule.setMath(indexMath); sBasePlugin.addIndex(indexRule); } Parameter p = bioModel.getSBMLDocument().getModel().getParameter(var); if (p != null && SBMLutilities.isBoolean(p)) { ea.setMath(bioModel.addBooleanAssign(assign[i].split(":=")[1].split(";")[0].trim())); } else { ea.setMath(SBMLutilities.myParseFormula(assign[i].split(":=")[1].split(";")[0].trim())); } if (p == null && var.endsWith("_"+GlobalConstants.RATE)) { p = bioModel.getSBMLDocument().getModel().createParameter(); p.setId(var); p.setConstant(false); p.setValue(0); RateRule r = bioModel.getSBMLDocument().getModel().createRateRule(); SBMLutilities.setMetaId(r, GlobalConstants.RULE+"_" + var); r.setVariable(var.replace("_" + GlobalConstants.RATE,"")); r.setMath(SBMLutilities.myParseFormula(var)); } error = checkEventAssignmentUnits(ea); if (error) break; } EAdimID = new String[]{""}; EAdex = new String[]{""}; EAdimensionIds = new String[]{""}; for (int i = 0; i < placeAssign.length; i++) { EventAssignment ea = e.createEventAssignment(); ea.setVariable(placeAssign[i].split(" ")[0]); String left = placeAssign[i].split(":=")[0].trim(); String rightSide = placeAssign[i].split(":=")[1].split(";")[1]; ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(ea); EAdimID = SBMLutilities.checkSizeParameters(bioModel.getSBMLDocument(), left, false); if(EAdimID!=null){ EAdimensionIds = SBMLutilities.getDimensionIds("e",EAdimID.length-1); String variableId = EAdimID[0].trim(); if (variableId.endsWith("_"+GlobalConstants.RATE)) { variableId = variableId.replace("_"+GlobalConstants.RATE, ""); } SBase variable = SBMLutilities.getElementBySId(bioModel.getSBMLDocument(), variableId); EAdex = SBMLutilities.checkIndices(rightSide, variable, bioModel.getSBMLDocument(), dimensionIds, "variable", EAdimID, dimensionIds, dimID); error = (EAdex==null); } else{ error = true; } if (error) break; sBasePlugin.unsetListOfDimensions(); for(int i1 = 0; EAdimID!=null && i1<EAdimID.length-1; i1++){ org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.createDimension(EAdimensionIds[i1]); dimX.setSize(EAdimID[i1+1]); dimX.setArrayDimension(i1); } sBasePlugin.unsetListOfIndices(); for(int i1 = 0; EAdex!=null && i1<EAdex.length-1; i1++){ Index indexRule = new Index(); indexRule.setArrayDimension(i1); indexRule.setReferencedAttribute("variable"); ASTNode indexMath = SBMLutilities.myParseFormula(EAdex[i1+1]); indexRule.setMath(indexMath); sBasePlugin.addIndex(indexRule); } ea.setMath(SBMLutilities.myParseFormula(placeAssign[i].split(":=")[1].split(";")[0].trim())); error = checkEventAssignmentUnits(ea); if (error) break; } if (!error) { if (eventDelay.getText().trim().equals("")) { e.unsetDelay(); } else { String oldDelayStr = ""; if (e.isSetDelay()) { oldDelayStr = SBMLutilities.myFormulaToString(e.getDelay().getMath()); } e.createDelay(); e.getDelay().setMath(bioModel.addBooleans(eventDelay.getText().trim())); error = checkEventDelayUnits(e.getDelay()); if (error) { if (oldDelayStr.equals("")) { e.unsetDelay(); } else { e.createDelay(); e.getDelay().setMath(SBMLutilities.myParseFormula(oldDelayStr)); } } } } if (!error) { if (eventPriority.getText().trim().equals("")) { e.unsetPriority(); } else { e.createPriority(); e.getPriority().setMath(bioModel.addBooleans(eventPriority.getText().trim())); } } if (!error) { e.createTrigger(); if (!persistentTrigger.isSelected()) { e.getTrigger().setPersistent(false); ASTNode triggerMath = bioModel.addBooleans(eventTrigger.getText().trim()); if (!isTextual) { for (int j = 0; j < presetPlaces.size(); j++) { triggerMath = SBMLutilities.addPreset(triggerMath, presetPlaces.get(j)); } } e.getTrigger().setMath(triggerMath); if (isTransition) { Rule r = bioModel.getSBMLDocument().getModel().getRule(GlobalConstants.TRIGGER + "_" + e.getId()); if (r != null) { r.removeFromParent(); } Parameter p = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.TRIGGER + "_" + e.getId()); if (p != null) { p.removeFromParent(); } } } else { if (isTransition) { e.getTrigger().setPersistent(false); ASTNode leftChild = bioModel.addBooleans(eventTrigger.getText().trim()); if (!isTextual) { for (int j = 0; j < presetPlaces.size(); j++) { leftChild = SBMLutilities.addPreset(leftChild, presetPlaces.get(j)); } } ASTNode rightChild = SBMLutilities.myParseFormula("eq(" + GlobalConstants.TRIGGER + "_" + e.getId() + ",1)"); if (!isTextual) { for (int j = 0; j < presetPlaces.size(); j++) { rightChild = SBMLutilities.addPreset(rightChild, presetPlaces.get(j)); } } ASTNode ruleMath = SBMLutilities.myParseFormula("piecewise(1,or(" + SBMLutilities.myFormulaToString(leftChild) + "," + SBMLutilities.myFormulaToString(rightChild) + "),0)"); Parameter p = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.TRIGGER + "_" + e.getId()); if (p == null) { p = bioModel.getSBMLDocument().getModel().createParameter(); p.setId(GlobalConstants.TRIGGER + "_" + e.getId()); p.setConstant(false); p.setValue(0); } Rule r = bioModel.getSBMLDocument().getModel().getRule(GlobalConstants.TRIGGER + "_" + e.getId()); if (r == null) { r = bioModel.getSBMLDocument().getModel().createAssignmentRule(); SBMLutilities.setVariable(r, GlobalConstants.TRIGGER + "_" + e.getId()); } SBMLutilities.setMetaId(r, GlobalConstants.TRIGGER + "_" + GlobalConstants.RULE+"_"+e.getId()); r.setMath(ruleMath); ASTNode triggerMath = SBMLutilities.myParseFormula(GlobalConstants.TRIGGER + "_" + e.getId()); if (!isTextual) { for (int j = 0; j < presetPlaces.size(); j++) { triggerMath = SBMLutilities.addPreset(triggerMath, presetPlaces.get(j)); } } e.getTrigger().setMath(triggerMath); } else { e.getTrigger().setPersistent(true); ASTNode triggerMath = bioModel.addBooleans(eventTrigger.getText().trim()); if (!isTextual) { for (int j = 0; j < presetPlaces.size(); j++) { triggerMath = SBMLutilities.addPreset(triggerMath, presetPlaces.get(j)); } } e.getTrigger().setMath(triggerMath); } } if (!initialTrigger.isSelected()) { e.getTrigger().setInitialValue(false); } else { e.getTrigger().setInitialValue(true); } if (dimID==null || dimID[0].trim().equals("")) { e.unsetId(); } else { e.setId(dimID[0].trim()); } if (eventName.getText().trim().equals("")) { e.unsetName(); } else { e.setName(eventName.getText().trim()); } if (failTransition.isSelected()) { Parameter p = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.FAIL); if (p==null) { p = bioModel.getSBMLDocument().getModel().createParameter(); p.setId(GlobalConstants.FAIL); p.setSBOTerm(GlobalConstants.SBO_BOOLEAN); p.setConstant(false); p.setValue(0); Constraint c = bioModel.getSBMLDocument().getModel().createConstraint(); SBMLutilities.setMetaId(c, GlobalConstants.FAIL_TRANSITION); /* SBMLutilities.createFunction(bioModel.getSBMLDocument().getModel(), "G", "Globally Property", "lambda(t,x,or(not(t),x))"); */ c.setMath(SBMLutilities.myParseFormula("eq("+GlobalConstants.FAIL+",0)")); } EventAssignment ea = e.getListOfEventAssignments().get(GlobalConstants.FAIL); if (ea==null) { ea = e.createEventAssignment(); ea.setVariable(GlobalConstants.FAIL); ea.setMath(SBMLutilities.myParseFormula("piecewise(1,true,0)")); } } else { EventAssignment ea = e.getListOfEventAssignments().get(GlobalConstants.FAIL); if (ea != null) { ea.removeFromParent(); } } ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(e); sBasePlugin.unsetListOfDimensions(); for(int i1 = 0; dimID!=null && i1<dimID.length-1; i1++){ org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.createDimension(dimensionIds[i1]); dimX.setSize(dimID[i1+1]); dimX.setArrayDimension(i1); } Port port = bioModel.getPortByIdRef(selectedID); if (port!=null) { if (onPort.isSelected()) { port.setId(GlobalConstants.EVENT+"__"+e.getId()); port.setIdRef(e.getId()); ArraysSBasePlugin sBasePluginPort = SBMLutilities.getArraysSBasePlugin(port); sBasePluginPort.setListOfDimensions(sBasePlugin.getListOfDimensions().clone()); sBasePluginPort.unsetListOfIndices(); for (int i = 0; i < sBasePlugin.getListOfDimensions().size(); i++) { org.sbml.jsbml.ext.arrays.Dimension dimen = sBasePlugin.getDimensionByArrayDimension(i); Index portIndex = sBasePluginPort.createIndex(); portIndex.setReferencedAttribute("comp:idRef"); portIndex.setArrayDimension(i); portIndex.setMath(SBMLutilities.myParseFormula(dimen.getId())); } } else { bioModel.getSBMLCompModel().removePort(port); } } else { if (onPort.isSelected()) { port = bioModel.getSBMLCompModel().createPort(); port.setId(GlobalConstants.EVENT+"__"+e.getId()); port.setIdRef(e.getId()); ArraysSBasePlugin sBasePluginPort = SBMLutilities.getArraysSBasePlugin(port); sBasePluginPort.setListOfDimensions(sBasePlugin.getListOfDimensions().clone()); sBasePluginPort.unsetListOfIndices(); for (int i = 0; i < sBasePlugin.getListOfDimensions().size(); i++) { org.sbml.jsbml.ext.arrays.Dimension dimen = sBasePlugin.getDimensionByArrayDimension(i); Index portIndex = sBasePluginPort.createIndex(); portIndex.setReferencedAttribute("comp:idRef"); portIndex.setArrayDimension(i); portIndex.setMath(SBMLutilities.myParseFormula(dimen.getId())); } } } int index = events.getSelectedIndex(); ev[index] = e.getId(); for (int i = 1; dimID!=null && i < dimID.length; i++) { ev[index] += "[" + dimID[i] + "]"; } Utility.sort(ev); events.setListData(ev); events.setSelectedIndex(index); bioModel.makeUndoPoint(); } //edit dynamic process if (!error) { if (!((String)dynamicProcess.getSelectedItem()).equals("none")) { AnnotationUtility.setDynamicAnnotation(e, (String)dynamicProcess.getSelectedItem()); } else { AnnotationUtility.removeDynamicAnnotation(e); } } else { while (e.getEventAssignmentCount() > 0) { e.getListOfEventAssignments().remove(0); } for (int i = 0; i < origAssign.length; i++) { EventAssignment ea = e.createEventAssignment(); ea.setVariable(origAssign[i].split(" ")[0]); String[] rightSide = origAssign[i].split(":=")[1].split(","); ea.setMath(SBMLutilities.myParseFormula(rightSide[0].trim())); } } } //end if option is "ok" //add event else { JList add = new JList(); e = bioModel.getSBMLDocument().getModel().createEvent(); if (isTransition) { e.setSBOTerm(GlobalConstants.SBO_PETRI_NET_TRANSITION); } e.setUseValuesFromTriggerTime(assignTime.isSelected()); e.createTrigger(); if (dimID!=null && !dimID[0].trim().equals("")) { e.setId(dimID[0].trim()); } bioModel.setMetaIDIndex( SBMLutilities.setDefaultMetaID(bioModel.getSBMLDocument(), e, bioModel.getMetaIDIndex())); if (!eventName.getText().trim().equals("")) { e.setName(eventName.getText().trim()); } if (!persistentTrigger.isSelected()) { e.getTrigger().setPersistent(false); e.getTrigger().setMath(bioModel.addBooleans(eventTrigger.getText().trim())); } else { if (isTransition) { e.getTrigger().setPersistent(false); ASTNode leftChild = bioModel.addBooleans(eventTrigger.getText().trim()); if (!isTextual) { for (int j = 0; j < presetPlaces.size(); j++) { leftChild = SBMLutilities.addPreset(leftChild, presetPlaces.get(j)); } } ASTNode rightChild = SBMLutilities.myParseFormula("eq(" + GlobalConstants.TRIGGER + "_" + e.getId() + ",1)"); if (!isTextual) { for (int j = 0; j < presetPlaces.size(); j++) { rightChild = SBMLutilities.addPreset(rightChild, presetPlaces.get(j)); } } ASTNode ruleMath = SBMLutilities.myParseFormula("piecewise(1,or(" + SBMLutilities.myFormulaToString(leftChild) + "," + SBMLutilities.myFormulaToString(rightChild) + "),0)"); Parameter p = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.TRIGGER + "_" + e.getId()); if (p == null) { p = bioModel.getSBMLDocument().getModel().createParameter(); p.setId(GlobalConstants.TRIGGER + "_" + e.getId()); p.setConstant(false); p.setValue(0); } Rule r = bioModel.getSBMLDocument().getModel().getRule(GlobalConstants.TRIGGER + "_" + e.getId()); if (r == null) { r = bioModel.getSBMLDocument().getModel().createAssignmentRule(); SBMLutilities.setVariable(r, GlobalConstants.TRIGGER + "_" + e.getId()); } SBMLutilities.setMetaId(r, GlobalConstants.TRIGGER + "_" + GlobalConstants.RULE+"_"+e.getId()); r.setMath(ruleMath); ASTNode triggerMath = SBMLutilities.myParseFormula(GlobalConstants.TRIGGER + "_" + e.getId()); if (!isTextual) { for (int j = 0; j < presetPlaces.size(); j++) { triggerMath = SBMLutilities.addPreset(triggerMath, presetPlaces.get(j)); } } e.getTrigger().setMath(triggerMath); } else { e.getTrigger().setPersistent(true); e.getTrigger().setMath(bioModel.addBooleans(eventTrigger.getText().trim())); } } if (!initialTrigger.isSelected()) { e.getTrigger().setInitialValue(false); } else { e.getTrigger().setInitialValue(true); } if (!eventPriority.getText().trim().equals("")) { e.createPriority(); e.getPriority().setMath(bioModel.addBooleans(eventPriority.getText().trim())); } if (!eventDelay.getText().trim().equals("")) { e.createDelay(); e.getDelay().setMath(bioModel.addBooleans(eventDelay.getText().trim())); error = checkEventDelayUnits(e.getDelay()); } if (!error) { String[] EAdimID = new String[]{""}; String[] EAdex = new String[]{""}; String[] EAdimensionIds = new String[]{""}; for (int i = 0; i < assign.length; i++) { EventAssignment ea = e.createEventAssignment(); String var = assign[i].split(" ")[0]; ea.setVariable(var); String left = assign[i].split(":=")[0].trim(); String rightSide = assign[i].split(":=")[1].split(";")[1].trim(); EAdimID = SBMLutilities.checkSizeParameters(bioModel.getSBMLDocument(), left, false); if(EAdimID!=null){ EAdimensionIds = SBMLutilities.getDimensionIds("e",EAdimID.length-1); String variableId = EAdimID[0].trim(); if (variableId.endsWith("_"+GlobalConstants.RATE)) { variableId = variableId.replace("_"+GlobalConstants.RATE, ""); } SBase variable = SBMLutilities.getElementBySId(bioModel.getSBMLDocument(), variableId); EAdex = SBMLutilities.checkIndices(rightSide, variable, bioModel.getSBMLDocument(), EAdimensionIds, "variable", EAdimID, dimensionIds, dimID); } ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(ea); if(!error){ sBasePlugin.unsetListOfDimensions(); for(int i1 = 0; EAdimID!=null && i1<EAdimID.length-1; i1++){ org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.createDimension(EAdimensionIds[i1]); dimX.setSize(EAdimID[i1+1]); dimX.setArrayDimension(i1); } sBasePlugin.unsetListOfIndices(); for(int i1 = 0; EAdex!=null && i1<EAdex.length-1; i1++){ Index indexRule = new Index(); indexRule.setArrayDimension(i1); indexRule.setReferencedAttribute("variable"); ASTNode indexMath = SBMLutilities.myParseFormula(EAdex[i1+1]); indexRule.setMath(indexMath); sBasePlugin.addIndex(indexRule); } if (var.endsWith("\'")) { var = "rate_" + var.replace("\'",""); } ea.setVariable(var); Parameter p = bioModel.getSBMLDocument().getModel().getParameter(var); if (p != null && SBMLutilities.isBoolean(p)) { ea.setMath(bioModel.addBooleanAssign(assign[i].split(":=")[1].split(";")[0].trim())); } else { ea.setMath(SBMLutilities.myParseFormula(assign[i].split(":=")[1].split(";")[0].trim())); } if (p == null && var.endsWith("_" + GlobalConstants.RATE)) { p = bioModel.getSBMLDocument().getModel().createParameter(); p.setId(var); p.setConstant(false); p.setValue(0); RateRule r = bioModel.getSBMLDocument().getModel().createRateRule(); SBMLutilities.setMetaId(r, GlobalConstants.RULE+"_" + var); r.setVariable(var.replace("_"+GlobalConstants.RATE,"")); r.setMath(SBMLutilities.myParseFormula(var)); } error = checkEventAssignmentUnits(ea); if (error) break; } } } //add dynamic process if (!error) { if (!((String)dynamicProcess.getSelectedItem()).equals("none")) { AnnotationUtility.setDynamicAnnotation(e, (String)dynamicProcess.getSelectedItem()); } if (failTransition.isSelected()) { Parameter p = bioModel.getSBMLDocument().getModel().getParameter(GlobalConstants.FAIL); if (p==null) { p = bioModel.getSBMLDocument().getModel().createParameter(); p.setId(GlobalConstants.FAIL); p.setSBOTerm(GlobalConstants.SBO_BOOLEAN); p.setConstant(false); p.setValue(0); Constraint c = bioModel.getSBMLDocument().getModel().createConstraint(); SBMLutilities.setMetaId(c, GlobalConstants.FAIL_TRANSITION); /* SBMLutilities.createFunction(bioModel.getSBMLDocument().getModel(), "G", "Globally Property", "lambda(t,x,or(not(t),x))"); */ c.setMath(SBMLutilities.myParseFormula("eq("+GlobalConstants.FAIL+",0)")); } EventAssignment ea = e.getListOfEventAssignments().get(GlobalConstants.FAIL); if (ea==null) { ea = e.createEventAssignment(); ea.setVariable(GlobalConstants.FAIL); ea.setMath(SBMLutilities.myParseFormula("piecewise(1,true,0)")); } } else { EventAssignment ea = e.getListOfEventAssignments().get(GlobalConstants.FAIL); if (ea != null) { ea.removeFromParent(); } } ArraysSBasePlugin sBasePlugin = SBMLutilities.getArraysSBasePlugin(e); for(int i1 = 0; dimID!=null && i1<dimID.length-1; i1++){ org.sbml.jsbml.ext.arrays.Dimension dimX = sBasePlugin.createDimension(dimensionIds[i1]); dimX.setSize(dimID[i1+1]); dimX.setArrayDimension(i1); } if (onPort.isSelected()) { Port port = bioModel.getSBMLCompModel().createPort(); port.setId(GlobalConstants.EVENT+"__"+e.getId()); port.setIdRef(e.getId()); ArraysSBasePlugin sBasePluginPort = SBMLutilities.getArraysSBasePlugin(port); sBasePluginPort.setListOfDimensions(sBasePlugin.getListOfDimensions().clone()); sBasePluginPort.unsetListOfIndices(); for (int i = 0; i < sBasePlugin.getListOfDimensions().size(); i++) { org.sbml.jsbml.ext.arrays.Dimension dimen = sBasePlugin.getDimensionByArrayDimension(i); Index portIndex = sBasePluginPort.createIndex(); portIndex.setReferencedAttribute("comp:idRef"); portIndex.setArrayDimension(i); portIndex.setMath(SBMLutilities.myParseFormula(dimen.getId())); } } } String eventEntry = e.getId(); for (int i = 1; dimID!=null && i < dimID.length; i++) { eventEntry += "[" + dimID[i] + "]"; } Object[] adding = { eventEntry }; // Object[] adding = { // myFormulaToString(e.getTrigger().getMath()) }; add.setListData(adding); add.setSelectedIndex(0); events.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); String[] ev = new String[events.getModel().getSize()]; for (int i = 0; i < events.getModel().getSize(); i++) { ev[i] = events.getModel().getElementAt(i).toString(); } adding = Utility.add(ev, events, add); ev = new String[adding.length]; for (int i = 0; i < adding.length; i++) { ev[i] = (String) adding[i]; } Utility.sort(ev); int index = events.getSelectedIndex(); events.setListData(ev); events.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); if (bioModel.getSBMLDocument().getModel().getEventCount() == 1) { events.setSelectedIndex(0); } else { events.setSelectedIndex(index); } if (error) { removeTheEvent(bioModel, SBMLutilities.myFormulaToString(e.getTrigger().getMath())); } } if (!error && !modelEditor.isParamsOnly()) { // Add SBOL annotation to event if (sbolField.getSBOLURIs().size() > 0) { if (!e.isSetMetaId() || e.getMetaId().equals("")) SBMLutilities.setDefaultMetaID(bioModel.getSBMLDocument(), e, bioModel.getMetaIDIndex()); SBOLAnnotation sbolAnnot = new SBOLAnnotation(e.getMetaId(), sbolField.getSBOLURIs(), sbolField.getSBOLStrand()); AnnotationUtility.setSBOLAnnotation(e, sbolAnnot); } else AnnotationUtility.removeSBOLAnnotation(e); } } if (error) { value = JOptionPane.showOptionDialog(Gui.frame, eventPanel, title, JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } } if (value == JOptionPane.NO_OPTION) { return selected; } modelEditor.setDirty(true); if (dimID!=null && !dimID[0].equals("")) return dimID[0].trim(); return selected; } /** * Check the units of an event delay */ private static boolean checkEventDelayUnits(Delay delay) { if (delay.containsUndeclaredUnits()) { if (Gui.getCheckUndeclared()) { JOptionPane.showMessageDialog(Gui.frame, "Event assignment delay contains literals numbers or parameters with undeclared units.\n" + "Therefore, it is not possible to completely verify the consistency of the units.", "Contains Undeclared Units", JOptionPane.WARNING_MESSAGE); } return false; } else if (Gui.getCheckUnits()) { if (SBMLutilities.checkUnitsInEventDelay(delay)) { JOptionPane.showMessageDialog(Gui.frame, "Event delay should be units of time.", "Event Delay Not Time Units", JOptionPane.ERROR_MESSAGE); return true; } } return false; } /** * Check the units of an event assignment */ private boolean checkEventAssignmentUnits(EventAssignment assign) { if (assign.containsUndeclaredUnits()) { if (Gui.getCheckUndeclared()) { JOptionPane.showMessageDialog(Gui.frame, "Event assignment to " + assign.getVariable() + " contains literals numbers or parameters with undeclared units.\n" + "Therefore, it is not possible to completely verify the consistency of the units.", "Contains Undeclared Units", JOptionPane.WARNING_MESSAGE); } return false; } else if (Gui.getCheckUnits()) { if (SBMLutilities.checkUnitsInEventAssignment(bioModel.getSBMLDocument(), assign)) { JOptionPane.showMessageDialog(Gui.frame, "Units on the left and right-hand side for the event assignment " + assign.getVariable() + " do not agree.", "Units Do Not Match", JOptionPane.ERROR_MESSAGE); return true; } } return false; } /** * Refresh events panel */ public void refreshEventsPanel() { Model model = bioModel.getSBMLDocument().getModel(); ListOf<Event> listOfEvents = model.getListOfEvents(); String[] ev = new String[model.getEventCount()]; for (int i = 0; i < model.getEventCount(); i++) { org.sbml.jsbml.Event event = listOfEvents.get(i); if (!event.isSetId()) { String eventId = "event0"; int en = 0; while (bioModel.isSIdInUse(eventId)) { en++; eventId = "event" + en; } event.setId(eventId); } ev[i] = event.getId() + SBMLutilities.getDimensionString(event); } Utility.sort(ev); events.setListData(ev); events.setSelectedIndex(0); } /** * Remove an event from a list and SBML gcm.getSBMLDocument() * * @param events * a list of events * @param gcm.getSBMLDocument() * an SBML gcm.getSBMLDocument() from which to remove the event * @param usedIDs * a list of all IDs current in use * @param ev * an array of all events */ private void removeEvent(JList events, BioModel gcm) { int index = events.getSelectedIndex(); if (index != -1) { String selected = ((String) events.getSelectedValue()).split("\\[")[0]; removeTheEvent(gcm, selected); events.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); Utility.remove(events); events.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); if (index < events.getModel().getSize()) { events.setSelectedIndex(index); } else { events.setSelectedIndex(index - 1); } modelEditor.setDirty(true); gcm.makeUndoPoint(); } } /** * Remove an event from an SBML gcm.getSBMLDocument() * * @param gcm.getSBMLDocument() * the SBML gcm.getSBMLDocument() from which to remove the event * @param selected * the event Id to remove */ public static void removeTheEvent(BioModel bioModel, String selected) { ListOf<Event> EL = bioModel.getSBMLDocument().getModel().getListOfEvents(); for (int i = 0; i < bioModel.getSBMLDocument().getModel().getEventCount(); i++) { org.sbml.jsbml.Event E = EL.get(i); if (E.getId().equals(selected)) { EL.remove(i); } } for (int i = 0; i < bioModel.getSBMLCompModel().getListOfPorts().size(); i++) { Port port = bioModel.getSBMLCompModel().getListOfPorts().get(i); if (port.isSetIdRef() && port.getIdRef().equals(selected)) { bioModel.getSBMLCompModel().getListOfPorts().remove(i); break; } } Layout layout = bioModel.getLayout(); if (layout.getListOfAdditionalGraphicalObjects().get(GlobalConstants.GLYPH+"__"+selected)!=null) { layout.getListOfAdditionalGraphicalObjects().remove(GlobalConstants.GLYPH+"__"+selected); } if (layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+selected) != null) { layout.getListOfTextGlyphs().remove(GlobalConstants.TEXT_GLYPH+"__"+selected); } } /** * Creates a frame used to edit event assignments or create new ones. * */ private void eventAssignEditor(BioModel bioModel, JList eventAssign, String option) { if (option.equals("OK") && eventAssign.getSelectedIndex() == -1) { JOptionPane.showMessageDialog(Gui.frame, "No event assignment selected.", "Must Select an Event Assignment", JOptionPane.ERROR_MESSAGE); return; } JPanel eventAssignPanel = new JPanel(new GridLayout(3,1)); JPanel topEAPanel = new JPanel(); JPanel northEAPanel = new JPanel(); JPanel southEAPanel = new JPanel(); JLabel idLabel = new JLabel("Variable:"); JLabel indexLabel = new JLabel("Indices:"); JLabel eqnLabel = new JLabel("Assignment:"); eaID = new JComboBox(); eaID.addActionListener(this); iIndex = new JTextField(20); String selected; String[] assign = new String[eventAssign.getModel().getSize()]; for (int i = 0; i < eventAssign.getModel().getSize(); i++) { assign[i] = eventAssign.getModel().getElementAt(i).toString(); } if (option.equals("OK")) { selected = ((String) eventAssign.getSelectedValue()).split(" ")[0]; } else { selected = ""; } Model model = bioModel.getSBMLDocument().getModel(); for (int i = 0; i < model.getCompartmentCount(); i++) { String id = model.getCompartment(i).getId(); if (!(model.getCompartment(i).getConstant())) { if (keepVarEvent(bioModel, assign, selected, id)) { eaID.addItem(id); } } } for (int i = 0; i < model.getParameterCount(); i++) { Parameter p = model.getParameter(i); if ((!isTextual && SBMLutilities.isPlace(p))||p.getId().endsWith("_"+GlobalConstants.RATE)) continue; if (p.getId().equals(GlobalConstants.FAIL)) continue; String id = p.getId(); if (!p.getConstant()) { if (keepVarEvent(bioModel, assign, selected, id)) { eaID.addItem(id); } if (isTransition && !SBMLutilities.isBoolean(p) && !SBMLutilities.isPlace(p)) { if (keepVarEvent(bioModel, assign, selected, id+"_"+GlobalConstants.RATE)) { eaID.addItem(id+"_"+GlobalConstants.RATE); } } } } for (int i = 0; i < model.getSpeciesCount(); i++) { String id = model.getSpecies(i).getId(); if (!(model.getSpecies(i).getConstant())) { if (keepVarEvent(bioModel, assign, selected, id)) { eaID.addItem(id); } } } for (int i = 0; i < model.getReactionCount(); i++) { Reaction reaction = model.getReaction(i); for (int j = 0; j < reaction.getReactantCount(); j++) { SpeciesReference reactant = reaction.getReactant(j); if ((reactant.isSetId()) && (!reactant.getId().equals("")) && !(reactant.getConstant())) { String id = reactant.getId(); if (keepVarEvent(bioModel, assign, selected, id)) { eaID.addItem(id); } } } for (int j = 0; j < reaction.getProductCount(); j++) { SpeciesReference product = reaction.getProduct(j); if ((product.isSetId()) && (!product.getId().equals("")) && !(product.getConstant())) { String id = product.getId(); if (keepVarEvent(bioModel, assign, selected, id)) { eaID.addItem(id); } } } } JTextField eqn = new JTextField(30); // From the event assignments list to the event assignment window // The listed string is: X[<first index>][<second index>] := <math>, Dim0 = <first dimension>, Dim1 = // <second dimension> if (option.equals("OK")) { String selectAssign = ((String) eventAssign.getSelectedValue()); eaID.setSelectedItem(selectAssign.split(" ")[0]); String left = selectAssign.split(":=")[0].trim(); EAdimensions.setText(left.substring(selectAssign.split(" ")[0].length()).trim()); String rightSide = selectAssign.split(":=")[1].split(";")[1]; eqn.setText(selectAssign.split(":=")[1].split(";")[0].trim()); iIndex.setText(rightSide.trim()); } topEAPanel.add(new JLabel("Dimension Size Ids:")); topEAPanel.add(EAdimensions); northEAPanel.add(idLabel); northEAPanel.add(eaID); northEAPanel.add(indexLabel); northEAPanel.add(iIndex); southEAPanel.add(eqnLabel); southEAPanel.add(eqn); eventAssignPanel.add(topEAPanel); eventAssignPanel.add(northEAPanel); eventAssignPanel.add(southEAPanel); Object[] options = { option, "Cancel" }; int value = JOptionPane.showOptionDialog(Gui.frame, eventAssignPanel, "Event Asssignment Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); String[] EAdimID = new String[]{""}; String[] EAdimensionIds = new String[]{""}; String[] EAdex = new String[]{""}; boolean error = true; while (error && value == JOptionPane.YES_OPTION) { error = false; if (eqn.getText().trim().equals("")) { JOptionPane.showMessageDialog(Gui.frame, "Event assignment is missing.", "Enter Assignment", JOptionPane.ERROR_MESSAGE); error = true; } else if (SBMLutilities.myParseFormula(eqn.getText().trim()) == null) { JOptionPane.showMessageDialog(Gui.frame, "Event assignment is not valid.", "Enter Valid Assignment", JOptionPane.ERROR_MESSAGE); error = true; } else { String[] dimID = SBMLutilities.checkSizeParameters(bioModel.getSBMLDocument(), eventID.getText(), false); String[] dimensionIds = null; if(dimID!=null){ dimensionIds = SBMLutilities.getDimensionIds("",dimID.length-1); } EAdimID = SBMLutilities.checkSizeParameters(bioModel.getSBMLDocument(), EAdimensions.getText(), true); if(EAdimID!=null){ EAdimensionIds = SBMLutilities.getDimensionIds("e",EAdimID.length-1); String variableId = (String)eaID.getSelectedItem(); if (variableId.endsWith("_"+GlobalConstants.RATE)) { variableId = variableId.replace("_"+GlobalConstants.RATE, ""); } SBase variable = SBMLutilities.getElementBySId(bioModel.getSBMLDocument(), variableId); EAdex = SBMLutilities.checkIndices(iIndex.getText(), variable, bioModel.getSBMLDocument(), EAdimensionIds, "variable", EAdimID, dimensionIds, dimID); error = (EAdex==null); if (!error) { ArrayList<String> meshDimensionIds = new ArrayList<String>(); if (dimensionIds!=null) { meshDimensionIds.addAll(Arrays.asList(dimensionIds)); } if (EAdimensionIds!=null) { meshDimensionIds.addAll(Arrays.asList(EAdimensionIds)); } error = SBMLutilities.displayinvalidVariables("Event assignment", bioModel.getSBMLDocument(), meshDimensionIds.toArray(new String[meshDimensionIds.size()]), eqn.getText().trim(), "", false); } } else{ error = true; } if (!error) { Parameter p = bioModel.getSBMLDocument().getModel().getParameter((String)eaID.getSelectedItem()); ASTNode assignMath = SBMLutilities.myParseFormula(eqn.getText().trim()); if (p != null && SBMLutilities.isBoolean(p)) { assignMath = bioModel.addBooleanAssign(eqn.getText().trim()); } error = SBMLutilities.checkNumFunctionArguments(bioModel.getSBMLDocument(), SBMLutilities.myParseFormula(eqn.getText().trim())); if (!error) { error = SBMLutilities.checkFunctionArgumentTypes(bioModel.getSBMLDocument(), assignMath); } if (!error) { if (p != null && SBMLutilities.isBoolean(p)) { if (!SBMLutilities.returnsBoolean(SBMLutilities.myParseFormula(eqn.getText().trim()), bioModel.getSBMLDocument().getModel())) { JOptionPane.showMessageDialog(Gui.frame, "Event assignment must evaluate to a Boolean.", "Boolean Expected", JOptionPane.ERROR_MESSAGE); error = true; } } else { if (SBMLutilities.returnsBoolean(SBMLutilities.myParseFormula(eqn.getText().trim()), bioModel.getSBMLDocument().getModel())) { JOptionPane.showMessageDialog(Gui.frame, "Event assignment must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE); error = true; } } } } } if (!error) { if (option.equals("OK")) { int index = eventAssign.getSelectedIndex(); eventAssign.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); assign = Utility.getList(assign, eventAssign); eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // String for the indices String assignIndex = "; " + iIndex.getText(); // String for the dimensions String dimens = " " + EAdimensions.getText(); assign[index] = eaID.getSelectedItem() + dimens + " := " + eqn.getText().trim() + assignIndex; Utility.sort(assign); eventAssign.setListData(assign); eventAssign.setSelectedIndex(index); } else { JList add = new JList(); int index = eventAssign.getSelectedIndex(); // String for the indices String assignIndex = "; " + iIndex.getText(); // String for the dimensions String dimens = " " + EAdimensions.getText(); Object[] adding = { eaID.getSelectedItem() + dimens + " := " + eqn.getText().trim() + assignIndex }; add.setListData(adding); add.setSelectedIndex(0); eventAssign.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); adding = Utility.add(assign, eventAssign, add); assign = new String[adding.length]; for (int i = 0; i < adding.length; i++) { assign[i] = (String) adding[i]; } Utility.sort(assign); eventAssign.setListData(assign); eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); if (adding.length == 1) { eventAssign.setSelectedIndex(0); } else { eventAssign.setSelectedIndex(index); } } } if (error) { value = JOptionPane.showOptionDialog(Gui.frame, eventAssignPanel, "Event Assignment Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } } if (value == JOptionPane.NO_OPTION) { return; } } /** * Determines if a variable is already used in assignment rule or another * event assignment */ private static boolean keepVarEvent(BioModel gcm, String[] assign, String selected, String id) { if (!selected.equals(id)) { for (int j = 0; j < assign.length; j++) { if (id.equals(assign[j].split(" ")[0])) { return false; } } ListOf<Rule> r = gcm.getSBMLDocument().getModel().getListOfRules(); for (int i = 0; i < gcm.getSBMLDocument().getModel().getRuleCount(); i++) { Rule rule = r.get(i); if (rule.isAssignment() && SBMLutilities.getVariable(rule).equals(id)) return false; } } return true; } /** * Remove an event assignment * * @param eventAssign * Jlist of event assignments for selected event * @param assign * String array of event assignments for selected event */ private static void removeAssignment(JList eventAssign) { int index = eventAssign.getSelectedIndex(); if (index != -1) { eventAssign.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); Utility.remove(eventAssign); eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); if (index < eventAssign.getModel().getSize()) { eventAssign.setSelectedIndex(index); } else { eventAssign.setSelectedIndex(index - 1); } } } @Override public void actionPerformed(ActionEvent e) { // if the add event button is clicked if (e.getSource() == addEvent) { eventEditor("Add","",false); bioModel.makeUndoPoint(); }else if (e.getSource() == addTrans) { eventEditor("Add","",true); bioModel.makeUndoPoint(); } // if the edit event button is clicked else if (e.getSource() == editEvent) { if (events.getSelectedIndex() == -1) { JOptionPane.showMessageDialog(Gui.frame, "No event selected.", "Must Select an Event", JOptionPane.ERROR_MESSAGE); return; } String selected = ((String) events.getSelectedValue()).split("\\[")[0]; eventEditor("OK",selected,false); } // if the remove event button is clicked else if (e.getSource() == removeEvent) { removeEvent(events, bioModel); } // if the add event assignment button is clicked else if (e.getSource() == addAssignment) { //else if (((JButton) e.getSource()).getText().equals("Add Assignment")) { eventAssignEditor(bioModel, eventAssign, "Add"); } // if the edit event assignment button is clicked else if (e.getSource() == editAssignment) { eventAssignEditor(bioModel, eventAssign, "OK"); } // if the remove event assignment button is clicked else if (e.getSource() == removeAssignment) { removeAssignment(eventAssign); } else if (e.getSource() == eaID){ if (bioModel.isArray((String)eaID.getSelectedItem())) { iIndex.setEnabled(true); } else { iIndex.setText(""); iIndex.setEnabled(false); } } } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { if (e.getSource() == events) { if (events.getSelectedIndex() == -1) { JOptionPane.showMessageDialog(Gui.frame, "No event selected.", "Must Select an Event", JOptionPane.ERROR_MESSAGE); return; } String selected = ((String) events.getSelectedValue()).split("\\[")[0]; eventEditor("OK",selected,false); } else if (e.getSource() == eventAssign) { eventAssignEditor(bioModel, eventAssign, "OK"); } } } /** * This method currently does nothing. */ @Override public void mouseEntered(MouseEvent e) { } /** * This method currently does nothing. */ @Override public void mouseExited(MouseEvent e) { } /** * This method currently does nothing. */ @Override public void mousePressed(MouseEvent e) { } /** * This method currently does nothing. */ @Override public void mouseReleased(MouseEvent e) { } }
package com.intellij.application.options; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathMacros; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.*; import com.intellij.util.containers.HashMap; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import java.util.*; /** * @author dsl */ public class PathMacrosImpl extends PathMacros implements ApplicationComponent, NamedJDOMExternalizable { private static final Logger LOG = Logger.getInstance("#com.intellij.application.options.PathMacrosImpl"); private final Map<String,String> myMacros = new HashMap<String, String>(); @NonNls public static final String MACRO_ELEMENT = "macro"; @NonNls public static final String NAME_ATTR = "name"; @NonNls public static final String VALUE_ATTR = "value"; // predefined macros @NonNls public static final String APPLICATION_HOME_MACRO_NAME = "APPLICATION_HOME_DIR"; @NonNls public static final String PROJECT_DIR_MACRO_NAME = "PROJECT_DIR"; @NonNls public static final String MODULE_DIR_MACRO_NAME = "MODULE_DIR"; private static final Set<String> ourSystemMacroNames = new HashSet<String>(); { ourSystemMacroNames.add(APPLICATION_HOME_MACRO_NAME); ourSystemMacroNames.add(PROJECT_DIR_MACRO_NAME); ourSystemMacroNames.add(MODULE_DIR_MACRO_NAME); } public static PathMacrosImpl getInstanceEx() { return (PathMacrosImpl)ApplicationManager.getApplication().getComponent(PathMacros.class); } public String getComponentName() { return "PathMacrosImpl"; } public void initComponent() { } public void disposeComponent() { } public String getExternalFileName() { return "path.macros"; } public Set<String> getUserMacroNames() { ApplicationManager.getApplication().assertReadAccessAllowed(); return myMacros.keySet(); } public Set<String> getSystemMacroNames() { ApplicationManager.getApplication().assertReadAccessAllowed(); return ourSystemMacroNames; } public Set<String> getAllMacroNames() { final Set<String> userMacroNames = getUserMacroNames(); final Set<String> systemMacroNames = getSystemMacroNames(); final Set<String> allNames = new HashSet<String>(userMacroNames.size() + systemMacroNames.size()); allNames.addAll(systemMacroNames); allNames.addAll(userMacroNames); return allNames; } public String getValue(String name) { ApplicationManager.getApplication().assertReadAccessAllowed(); return myMacros.get(name); } public void removeAllMacros() { ApplicationManager.getApplication().assertWriteAccessAllowed(); myMacros.clear(); } public void setMacro(String name, String value) { ApplicationManager.getApplication().assertWriteAccessAllowed(); LOG.assertTrue(name != null); LOG.assertTrue(value != null); myMacros.put(name, value); } public void removeMacro(String name) { ApplicationManager.getApplication().assertWriteAccessAllowed(); final String value = myMacros.remove(name); LOG.assertTrue(value != null); } public void readExternal(Element element) throws InvalidDataException { final List children = element.getChildren(MACRO_ELEMENT); for (int i = 0; i < children.size(); i++) { Element macro = (Element)children.get(i); final String name = macro.getAttributeValue(NAME_ATTR); final String value = macro.getAttributeValue(VALUE_ATTR); if (name == null || value == null) { throw new InvalidDataException(); } myMacros.put(name, value); } } public void writeExternal(Element element) throws WriteExternalException { final Set<Map.Entry<String,String>> entries = myMacros.entrySet(); for (Map.Entry<String, String> entry : entries) { final Element macro = new Element(MACRO_ELEMENT); macro.setAttribute(NAME_ATTR, entry.getKey()); macro.setAttribute(VALUE_ATTR, entry.getValue()); element.addContent(macro); } } public void addMacroReplacements(ReplacePathToMacroMap result) { final Set<String> macroNames = getUserMacroNames(); for (final String name : macroNames) { result.addMacroReplacement(getValue(name), name); } } public void addMacroExpands(ExpandMacroToPathMap result) { final Set<String> macroNames = getUserMacroNames(); for (final String name : macroNames) { result.addMacroExpand(name, getValue(name)); } } }
package org.jasig.portal.layout; import java.util.Enumeration; import java.util.Hashtable; import java.util.Collection; import java.util.Vector; import java.util.Iterator; import java.util.Set; import java.util.HashSet; import org.jasig.portal.groups.IGroupMember; import org.jasig.portal.IUserLayoutStore; import org.jasig.portal.PortalException; import org.jasig.portal.UserProfile; import org.jasig.portal.layout.restrictions.IUserLayoutRestriction; import org.jasig.portal.layout.restrictions.PriorityRestriction; import org.jasig.portal.layout.restrictions.RestrictionTypes; import org.jasig.portal.layout.restrictions.UserLayoutRestriction; import org.jasig.portal.layout.restrictions.UserLayoutRestrictionFactory; import org.jasig.portal.security.IPerson; import org.jasig.portal.services.LogService; import org.jasig.portal.utils.CommonUtils; import org.jasig.portal.utils.DocumentFactory; import org.jasig.portal.utils.GuidGenerator; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ContentHandler; /** * An implementation of Aggregated User Layout Manager Interface defining common operations on user layout nodes, * that is channels and folders * * @author <a href="mailto:mvi@immagic.com">Michael Ivanov</a> * @version $Revision$ */ public class AggregatedLayoutManager implements IAggregatedUserLayoutManager { private AggregatedUserLayoutStore layoutStore; private AggregatedLayout layout; private UserProfile userProfile; private IPerson person; private Set listeners = new HashSet(); // Boolean flags for marking nodes //private boolean addTargetsAllowed = false; //private boolean moveTargetsAllowed = false; private IALNodeDescription addTargetsNodeDesc; private String moveTargetsNodeId; private int restrictionMask = 0; private boolean autoCommit = false; // The ID of the current loaded fragment private String fragmentId; // The IDs and names of the fragments which a user is owner of //private Hashtable fragments; // GUID generator private static GuidGenerator guid = null; private String cacheKey = null; public AggregatedLayoutManager( IPerson person, UserProfile userProfile ) throws Exception { this.person = person; this.userProfile = userProfile; layout = new AggregatedLayout ( String.valueOf(getLayoutId()), this ); autoCommit = false; if ( guid == null ) guid = new GuidGenerator(); updateCacheKey(); } public AggregatedLayoutManager( IPerson person, UserProfile userProfile, IUserLayoutStore layoutStore ) throws Exception { this ( person, userProfile ); this.layoutStore = (AggregatedUserLayoutStore) layoutStore; this.loadUserLayout(); } private void updateCacheKey() { cacheKey = guid.getNewGuid(); } public IUserLayout getUserLayout() throws PortalException { return layout; } public void setUserLayout(IUserLayout userLayout) throws PortalException { if ( !(layout instanceof AggregatedLayout) ) throw new PortalException ( "The user layout instance must have AggregatedLayout type!" ); this.layout = (AggregatedLayout) layout; updateCacheKey(); } /** * A factory method to create an empty <code>IUserLayoutNodeDescription</code> instance * * @param nodeType a node type value * @return an <code>IUserLayoutNodeDescription</code> instance * @exception PortalException if the error occurs. */ public IUserLayoutNodeDescription createNodeDescription( int nodeType ) throws PortalException { IALNodeDescription nodeDesc = null; switch ( nodeType ) { case IUserLayoutNodeDescription.FOLDER: nodeDesc = new ALFolderDescription(); break; case IUserLayoutNodeDescription.CHANNEL: nodeDesc = new ALChannelDescription(); break; } // Adding the user priority restriction if ( nodeDesc != null ) { int[] priorityRange = UserPriorityManager.getPriorityRange(person); PriorityRestriction restriction = new PriorityRestriction(); restriction.setRestriction(priorityRange[0],priorityRange[1]); nodeDesc.addRestriction(restriction); } return nodeDesc; } /** * Sets a layout manager to auto-commit mode that allows to update the database immediately * @param autoCommit a boolean value */ public void setAutoCommit (boolean autoCommit) { this.autoCommit = autoCommit; } /** * Returns an Id of the current user layout. * * @return a <code>int</code> value */ public int getLayoutId() { return userProfile.getLayoutId(); } /** * Returns an Id of a parent user layout node. * The user layout root node always has ID="root" * * @param nodeId a <code>String</code> value * @return a <code>String</code> value * @exception PortalException if an error occurs */ public String getParentId(String nodeId) throws PortalException { return layout.getParentId(nodeId); } /** * Returns a list of child node Ids for a given node. * * @param nodeId a <code>String</code> value * @return a <code>Enumeration</code> of <code>String</code> child node Ids. * @exception PortalException if an error occurs */ public Enumeration getChildIds(String nodeId) throws PortalException { return layout.getChildIds(nodeId); } /** * Determine an Id of a previous sibling node. * * @param nodeId a <code>String</code> node ID * @return a <code>String</code> Id value of a previous sibling node, or <code>null</code> if this is the first sibling. * @exception PortalException if an error occurs */ public String getPreviousSiblingId(String nodeId) throws PortalException { return layout.getPreviousSiblingId(nodeId); } /** * Determine an Id of a next sibling node. * * @param nodeId a <code>String</code> node ID * @return a <code>String</code> Id value of a next sibling node, or <code>null</code> if this is the last sibling. * @exception PortalException if an error occurs */ public String getNextSiblingId(String nodeId) throws PortalException { return layout.getNextSiblingId(nodeId); } /** * Checks the restriction specified by the parameters below * @param nodeId a <code>String</code> node ID * @param restrictionType a restriction type * @param restrictionPath a <code>String</code> restriction path * @param propertyValue a <code>String</code> property value to be checked * @return a boolean value * @exception PortalException if an error occurs */ protected boolean checkRestriction(String nodeId, int restrictionType, String restrictionPath, String propertyValue) throws PortalException { ALNode node = getLayoutNode(nodeId); return (node!=null)?checkRestriction(node,restrictionType,restrictionPath,propertyValue):true; } /** * Checks the local restriction specified by the parameters below * @param nodeId a <code>String</code> node ID * @param restrictionType a restriction type * @param propertyValue a <code>String</code> property value to be checked * @return a boolean value * @exception PortalException if an error occurs */ protected boolean checkRestriction(String nodeId, int restrictionType, String propertyValue ) throws PortalException { return (nodeId!=null)?checkRestriction(nodeId, restrictionType, UserLayoutRestriction.LOCAL_RESTRICTION, propertyValue):true; } /** * Checks the restriction specified by the parameters below * @param node a <code>ALNode</code> node to be checked * @param restrictionType a restriction type * @param restrictionPath a <code>String</code> restriction path * @param propertyValue a <code>String</code> property value to be checked * @return a boolean value * @exception PortalException if an error occurs */ protected boolean checkRestriction(ALNode node, int restrictionType, String restrictionPath, String propertyValue) throws PortalException { IUserLayoutRestriction restriction = node.getRestriction(UserLayoutRestriction.getRestrictionName(restrictionType,restrictionPath)); if ( restriction != null ) return restriction.checkRestriction(propertyValue); return true; } private void moveWrongFragmentsToLostFolder() throws PortalException { Collection nodes = layoutStore.getIncorrectPushedFragmentNodes(person,userProfile); for ( Iterator i = nodes.iterator(); i.hasNext(); ) { String nodeId = (String) i.next(); ALNode node = getLayoutNode(nodeId); if ( node != null && nodeId != null ) { if ( !moveNodeToLostFolder(nodeId) ) LogService.log(LogService.INFO, "Unable to move the pushed fragment with ID="+node.getFragmentId()+" to the lost folder"); } } } /** * Moves the nodes to the lost folder if they don't satisfy their restrictions * @exception PortalException if an error occurs */ protected void moveWrongNodesToLostFolder() throws PortalException { moveWrongNodesToLostFolder(getRootFolderId(),0); } /** * Moves the nodes to the lost folder if they don't satisfy their restrictions * @param nodeId a <code>String</code> node ID * @param depth a depth of the given node * @exception PortalException if an error occurs */ private void moveWrongNodesToLostFolder(String nodeId, int depth) throws PortalException { ALNode node = getLayoutNode(nodeId); // Checking restrictions on the node Vector restrictions = node.getRestrictionsByPath(UserLayoutRestriction.LOCAL_RESTRICTION); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); // check other restrictions except priority and depth if ( ( restriction.getRestrictionType() & (RestrictionTypes.DEPTH_RESTRICTION | RestrictionTypes.PRIORITY_RESTRICTION )) == 0 && !restriction.checkRestriction(node) ) { moveNodeToLostFolder(nodeId); break; } } // Checking the depth restriction if ( !checkRestriction(nodeId,RestrictionTypes.DEPTH_RESTRICTION,depth+"") ) { moveNodeToLostFolder(nodeId); } // Checking children related restrictions on the children if they exist restrictions = node.getRestrictionsByPath("children"); boolean isFolder = (node.getNodeType() == IUserLayoutNodeDescription.FOLDER ); if ( isFolder ) { for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); for ( String nextId = ((ALFolder)node).getFirstChildNodeId(); nextId != null; ) { ALNode nextNode = getLayoutNode(nextId); String tmpNodeId = nextNode.getNextNodeId(); if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 && !restriction.checkRestriction(nextNode) ) { moveNodeToLostFolder(nextId); } nextId = tmpNodeId; } } } // Checking parent related restrictions on the parent if it exists String parentNodeId = node.getParentNodeId(); if ( parentNodeId != null ) { restrictions = node.getRestrictionsByPath("parent"); ALNode parentNode = getLayoutNode(parentNodeId); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 && !restriction.checkRestriction(parentNode) ) { moveNodeToLostFolder(nodeId); break; } } } if ( isFolder ) { ++depth; ALFolder folder = (ALFolder) node; String firstChildId = folder.getFirstChildNodeId(); if ( firstChildId != null ) { String id = getLastSiblingNode(firstChildId).getId(); while ( id != null && !changeSiblingNodesOrder(folder.getFirstChildNodeId()) ) { String lastNodeId = getLastSiblingNode(id).getId(); id = getLayoutNode(lastNodeId).getPreviousNodeId(); moveNodeToLostFolder(lastNodeId); } for ( String nextId = folder.getFirstChildNodeId(); nextId != null; nextId = getLayoutNode(nextId).getNextNodeId() ) moveWrongNodesToLostFolder(nextId,depth); } } } // Gets the content of the lost folder public String getLostFolderXML() throws PortalException { Document document = DocumentFactory.getNewDocument(); layout.writeTo(ALFolderDescription.LOST_FOLDER_ID,document); return org.jasig.portal.utils.XML.serializeNode(document); } /** * Checks the local restriction specified by the parameters below * @param node a <code>ALNode</code> node to be checked * @param restrictionType a restriction type * @param propertyValue a <code>String</code> property value to be checked * @return a boolean value * @exception PortalException if an error occurs */ protected boolean checkRestriction(ALNode node, int restrictionType, String propertyValue ) throws PortalException { return checkRestriction(node, restrictionType, UserLayoutRestriction.LOCAL_RESTRICTION, propertyValue); } /** * Checks the necessary restrictions while adding a new node * @param nodeDesc a <code>IALNodeDescription</code> node description of a new node to be added * @param parentId a <code>String</code> parent node ID * @param nextSiblingId a <code>String</code> next sibling node ID * @return a boolean value * @exception PortalException if an error occurs */ private boolean checkAddRestrictions( IALNodeDescription nodeDesc, String parentId, String nextSiblingId ) throws PortalException { String newNodeId = nodeDesc.getId(); ALNode newNode = null; if ( newNodeId == null ) { if ( nodeDesc instanceof IALChannelDescription ) newNode = new ALChannel((IALChannelDescription)nodeDesc); else newNode = new ALFolder((IALFolderDescription)nodeDesc); } else newNode = getLayoutNode(newNodeId); ALNode parentNode = getLayoutNode(parentId); if ( !(parentNode.getNodeType()==IUserLayoutNodeDescription.FOLDER ) ) throw new PortalException ("The target parent node should be a folder!"); //if ( checkRestriction(parentNode,RestrictionTypes.IMMUTABLE_RESTRICTION,"false") ) { if ( !parentNode.getNodeDescription().isImmutable() ) { // Checking children related restrictions Vector restrictions = parentNode.getRestrictionsByPath("children"); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 && !restriction.checkRestriction(newNode) ) return false; } // Checking parent related restrictions restrictions = newNode.getRestrictionsByPath("parent"); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 && !restriction.checkRestriction(parentNode) ) return false; } // Considering two cases if the node is new or it is already in the user layout if ( newNodeId != null ) { // Checking depth restrictions for the node and all its descendants (if there are any) if ( !checkDepthRestrictions(newNodeId,parentId) ) return false; } else return checkRestriction(newNode,RestrictionTypes.DEPTH_RESTRICTION,(getDepth(parentId)+1)+""); // Checking sibling nodes order return changeSiblingNodesPriorities(newNode,parentId,nextSiblingId); } else return false; } /** * Checks the necessary restrictions while moving a node * @param nodeId a <code>String</code> node ID of a node to be moved * @param newParentId a <code>String</code> new parent node ID * @param nextSiblingId a <code>String</code> next sibling node ID * @return a boolean value * @exception PortalException if an error occurs */ private boolean checkMoveRestrictions( String nodeId, String newParentId, String nextSiblingId ) throws PortalException { ALNode node = getLayoutNode(nodeId); ALNode oldParentNode = getLayoutNode(node.getParentNodeId()); ALFolder newParentNode = getLayoutFolder(newParentId); /*if ( checkRestriction(oldParentNode,RestrictionTypes.IMMUTABLE_RESTRICTION,"false") && checkRestriction(newParentNode,RestrictionTypes.IMMUTABLE_RESTRICTION,"false") ) {*/ if ( !oldParentNode.getNodeDescription().isImmutable() && !newParentNode.getNodeDescription().isImmutable() ) { if ( !oldParentNode.equals(newParentNode) ) { // Checking children related restrictions Vector restrictions = newParentNode.getRestrictionsByPath("children"); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 && !restriction.checkRestriction(node) ) return false; } // Checking parent related restrictions restrictions = node.getRestrictionsByPath("parent"); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 && !restriction.checkRestriction(newParentNode) ) return false; } // Checking depth restrictions for the node and all its descendants if ( !checkDepthRestrictions(nodeId,newParentId) ) return false; } // Checking sibling nodes order in the line where the node is being moved to //String firstChildId = newParentNode.getFirstChildNodeId(); //return (firstChildId!=null)?changeSiblingNodesPriorities(firstChildId):true; return changeSiblingNodesPriorities(node,newParentId,nextSiblingId); } else return false; } /** * Checks the necessary restrictions while deleting a node * @param nodeId a <code>String</code> node ID of a node to be deleted * @return a boolean value * @exception PortalException if an error occurs */ private boolean checkDeleteRestrictions( String nodeId ) throws PortalException { ALNode node = getLayoutNode(nodeId); if ( nodeId == null || node == null ) return true; //if ( checkRestriction(node.getParentNodeId(),RestrictionTypes.IMMUTABLE_RESTRICTION,"false") ) { if ( !getLayoutNode(node.getParentNodeId()).getNodeDescription().isImmutable() ) { // Checking the unremovable restriction on the node to be deleted //return checkRestriction(nodeId,RestrictionTypes.UNREMOVABLE_RESTRICTION,"false"); return !node.getNodeDescription().isUnremovable(); } else return false; } /** * Recursively checks the depth restrictions beginning with a given node * @param nodeId a <code>String</code> node ID * @param newParentId a <code>String</code> new parent node ID * @return a boolean value * @exception PortalException if an error occurs */ private boolean checkDepthRestrictions(String nodeId,String newParentId) throws PortalException { if ( nodeId == null ) return true; int nodeDepth = getDepth(nodeId); int parentDepth = getDepth(newParentId); if ( nodeDepth == parentDepth+1 ) return true; return checkDepthRestrictions(nodeId,newParentId,nodeDepth); } /** * Recursively checks the depth restrictions beginning with a given node * @param nodeId a <code>String</code> node ID * @param newParentId a <code>String</code> new parent node ID * @param parentDepth a parent depth * @return a boolean value * @exception PortalException if an error occurs */ private boolean checkDepthRestrictions(String nodeId,String newParentId,int parentDepth) throws PortalException { ALNode node = getLayoutNode(nodeId); // Checking restrictions for the node if ( !checkRestriction(nodeId,RestrictionTypes.DEPTH_RESTRICTION,(parentDepth+1)+"") ) return false; if ( node.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { for ( String nextId = ((ALFolder)node).getFirstChildNodeId(); nextId != null; nextId = node.getNextNodeId() ) { node = getLayoutNode(nextId); if ( !checkDepthRestrictions(nextId,node.getParentNodeId(),parentDepth+1) ) return false; } } return true; } /** * Gets the tree depth for a given node * @param nodeId a <code>String</code> node ID * @return a depth value * @exception PortalException if an error occurs */ public int getDepth(String nodeId) throws PortalException { int depth = 0; for ( String parentId = getParentId(nodeId); parentId != null; parentId = getParentId(parentId), depth++ ); return depth; } /** * Moves the node to the lost folder * @param nodeId a <code>String</code> node ID * @return a boolean value * @exception PortalException if an error occurs */ private boolean moveNodeToLostFolder(String nodeId) throws PortalException { ALFolder lostFolder = getLayoutFolder(IALFolderDescription.LOST_FOLDER_ID); if ( lostFolder == null ) { lostFolder = ALFolder.createLostFolder(); } // Moving the node to the lost folder return moveNode(nodeId,IALFolderDescription.LOST_FOLDER_ID,null); } /** * Gets the restriction specified by the parameters below * @param node a <code>ALNode</code> node * @param restrictionType a restriction type * @param restrictionPath a <code>String</code> restriction path * @return a <code>IUserLayoutRestriction</code> instance * @exception PortalException if an error occurs */ private static IUserLayoutRestriction getRestriction( ALNode node, int restrictionType, String restrictionPath ) throws PortalException { return node.getRestriction(UserLayoutRestriction.getRestrictionName(restrictionType,restrictionPath)); } /** * Return a priority restriction for the given node. * @return a <code>PriorityRestriction</code> object * @exception PortalException if an error occurs */ public static PriorityRestriction getPriorityRestriction( ALNode node ) throws PortalException { PriorityRestriction priorRestriction = getPriorityRestriction(node,UserLayoutRestriction.LOCAL_RESTRICTION); if ( priorRestriction == null ) { priorRestriction = (PriorityRestriction) UserLayoutRestrictionFactory.createRestriction(RestrictionTypes.PRIORITY_RESTRICTION,"0-"+java.lang.Integer.MAX_VALUE,UserLayoutRestriction.LOCAL_RESTRICTION); } return priorRestriction; } /** * Return a priority restriction for the given node. * @return a <code>PriorityRestriction</code> object * @exception PortalException if an error occurs */ private static PriorityRestriction getPriorityRestriction( ALNode node, String restrictionPath ) throws PortalException { return (PriorityRestriction) getRestriction(node,RestrictionTypes.PRIORITY_RESTRICTION,restrictionPath); } /** * Change if it's possible priority values for all the sibling nodes * @param nodeId a <code>String</code> any node ID from the sibling line to be checked * @return a boolean value * @exception PortalException if an error occurs */ protected boolean changeSiblingNodesPriorities( String nodeId ) throws PortalException { int tmpPriority = Integer.MAX_VALUE; String firstNodeId = getFirstSiblingNode(nodeId).getId(); // Fill out the vector by priority values for ( String nextId = firstNodeId; nextId != null; ) { ALNode nextNode = getLayoutNode(nextId); int[] nextRange = getPriorityRestriction(nextNode).getRange(); int value = Math.min(nextRange[1],tmpPriority-1); if ( value < tmpPriority && value >= nextRange[0] ) { nextNode.setPriority(value); tmpPriority = value; } else return false; nextId = nextNode.getNextNodeId(); } return true; } /** * Change if it's possible priority values for all the sibling nodes defined by the collection * @param nodes a <code>Vector</code> instance with ALNode objects * @return a boolean value * @exception PortalException if an error occurs */ protected boolean changeSiblingNodesPriorities( Vector nodes ) throws PortalException { int tmpPriority = Integer.MAX_VALUE; // Fill out the vector by priority values int size = nodes.size(); for ( int i = 0; i < size; i++ ) { ALNode nextNode = (ALNode) nodes.get(i); if ( nextNode == null ) return false; int[] nextRange = getPriorityRestriction(nextNode).getRange(); int value = Math.min(nextRange[1],tmpPriority-1); if ( value < tmpPriority && value >= nextRange[0] ) { nextNode.setPriority(value); tmpPriority = value; } else return false; } return true; } /** * Change priority values for all the sibling nodes when trying to add a new node * @param node a <code>ALNode</code> a node to be added * @param parentNodeId a <code>String</code> parent node ID * @param nextNodeId a <code>String</code> next sibling node ID * @return a boolean value * @exception PortalException if an error occurs */ protected synchronized boolean changeSiblingNodesPriorities(ALNode node, String parentNodeId, String nextNodeId ) throws PortalException { ALNode firstNode = null, nextNode = null; String firstNodeId = null; int priority = 0, nextPriority = 0, prevPriority = 0, range[] = null, prevRange[] = null, nextRange[] = null; PriorityRestriction priorityRestriction = null; String nodeId = node.getId(); ALFolder parent = getLayoutFolder(parentNodeId); if ( parentNodeId != null ) { firstNodeId = parent.getFirstChildNodeId(); // if the node is equal the first node in the sibling line we get the next node if ( nodeId.equals(firstNodeId) ) firstNodeId = node.getNextNodeId(); if ( firstNodeId == null ) return true; } else return false; firstNode = getLayoutNode(firstNodeId); if ( nextNodeId != null ) { nextNode = getLayoutNode(nextNodeId); nextPriority = nextNode.getPriority(); priorityRestriction = getPriorityRestriction(nextNode); nextRange = priorityRestriction.getRange(); } priority = node.getPriority(); priorityRestriction = getPriorityRestriction(node); range = priorityRestriction.getRange(); // If we add a new node to the beginning of the sibling line if ( firstNodeId.equals(nextNodeId) ) { if ( range[1] <= nextRange[0] ) return false; if ( priority > nextPriority ) return true; if ( range[1] > nextPriority ) { node.setPriority(range[1]); return true; } if ( (nextPriority+1) <= range[1] && (nextPriority+1) >= range[0] ) { node.setPriority(nextPriority+1); return true; } } // If we add a new node to the end of the sibling line if ( nextNode == null ) { // Getting the last node ALNode lastNode = getLastSiblingNode(firstNodeId); int lastPriority = lastNode.getPriority(); PriorityRestriction lastPriorityRestriction = getPriorityRestriction(lastNode); int[] lastRange = lastPriorityRestriction.getRange(); if ( range[0] >= lastRange[1] ) return false; if ( priority < lastPriority ) return true; if ( range[0] < lastPriority ) { node.setPriority(range[0]); return true; } if ( (lastPriority-1) <= range[1] && (lastPriority-1) >= range[0] ) { node.setPriority(range[0]); return true; } } // If we add a new node in a general case if ( nextNode != null && !nextNode.equals(firstNode) && !nodeId.equals(nextNodeId) ) { // Getting the last node ALNode prevNode = getLayoutNode(nextNode.getPreviousNodeId()); prevPriority = prevNode.getPriority(); PriorityRestriction lastPriorityRestriction = getPriorityRestriction(prevNode); prevRange = lastPriorityRestriction.getRange(); if ( range[1] <= nextRange[0] || range[0] >= prevRange[1] ) return false; if ( priority < prevPriority && priority > nextPriority ) return true; int maxPossibleLowValue = Math.max(range[0],nextPriority+1); int minPossibleHighValue = Math.min(range[1],prevPriority-1); if ( minPossibleHighValue >= maxPossibleLowValue ) { node.setPriority(minPossibleHighValue); return true; } } Vector nodes = new Vector(); for ( String nextId = firstNodeId; nextId != null; ) { if ( !nextId.equals(nodeId) ) { if ( nextId.equals(nextNodeId) ) nodes.add(node); nodes.add(getLayoutNode(nextId)); } nextId = getLayoutNode(nextId).getNextNodeId(); } if ( nextNodeId == null ) nodes.add(node); return changeSiblingNodesPriorities(nodes); } /** * Change the sibling nodes order depending on their priority values * @param firstNodeId a <code>String</code> first node ID in the sibling line * @return a boolean value * @exception PortalException if an error occurs */ protected boolean changeSiblingNodesOrder(String firstNodeId) throws PortalException { if ( firstNodeId == null ) throw new PortalException ( "The first node ID in the sibling line cannot be NULL!" ); ALNode firstNode = getLayoutNode(firstNodeId); String parentNodeId = firstNode.getParentNodeId(); boolean rightOrder = true; ALNode node = null; for ( String nextNodeId = firstNodeId; nextNodeId != null; ) { node = getLayoutNode(nextNodeId); nextNodeId = node.getNextNodeId(); if ( nextNodeId != null ) { ALNode nextNode = getLayoutNode(nextNodeId); if ( node.getPriority() <= nextNode.getPriority() ) { rightOrder = false; break; } } } if ( rightOrder ) return true; // Check if the current order is right if ( changeSiblingNodesPriorities(firstNodeId) ) return true; Set movedNodes = new HashSet(); // Choosing more suitable order of the nodes in the sibling line for ( String lastNodeId = getLastSiblingNode(firstNodeId).getId(); lastNodeId != null; ) { for ( String curNodeId = lastNodeId; curNodeId != null; ) { if ( !lastNodeId.equals(curNodeId) && !movedNodes.contains(lastNodeId) ) { if ( moveNode(lastNodeId,parentNodeId,curNodeId) ) { if ( changeSiblingNodesPriorities(getLayoutFolder(parentNodeId).getFirstChildNodeId()) ) return true; movedNodes.add(lastNodeId); lastNodeId = getLastSiblingNode(curNodeId).getId(); curNodeId = lastNodeId; } } curNodeId = getLayoutNode(curNodeId).getPreviousNodeId(); } if ( !movedNodes.contains(lastNodeId) ) { if ( moveNode(lastNodeId,parentNodeId,null) ) { if ( changeSiblingNodesPriorities(getLayoutFolder(parentNodeId).getFirstChildNodeId()) ) return true; movedNodes.add(lastNodeId); } } lastNodeId = getLayoutNode(lastNodeId).getPreviousNodeId(); } return false; } /** * Return a cache key, uniqly corresponding to the composition and the structure of the user layout. * * @return a <code>String</code> value * @exception PortalException if an error occurs */ public String getCacheKey() throws PortalException { return cacheKey; } /** * Output a tree of a user layout (with appropriate markings) defined by a particular node into * a <code>ContentHandler</code> * @param contentHandler a <code>ContentHandler</code> value * @exception PortalException if an error occurs */ public void getUserLayout(ContentHandler contentHandler) throws PortalException { layout.writeTo(contentHandler); } /** * Output subtree of a user layout (with appropriate markings) defined by a particular node into * a <code>ContentHandler</code> * * @param nodeId a <code>String</code> a node determining a user layout subtree. * @param contentHandler a <code>ContentHandler</code> value * @exception PortalException if an error occurs */ public void getUserLayout(String nodeId, ContentHandler contentHandler) throws PortalException { layout.writeTo(nodeId,contentHandler); } private ALNode getLayoutNode(String nodeId) { return layout.getLayoutNode(nodeId); } private ALFolder getLayoutFolder(String folderId) { return layout.getLayoutFolder(folderId); } private ALNode getLastSiblingNode ( String nodeId ) { return layout.getLastSiblingNode(nodeId); } private ALNode getFirstSiblingNode ( String nodeId ) { return layout.getFirstSiblingNode(nodeId); } public Document getUserLayoutDOM() throws PortalException { Document document = DocumentFactory.getNewDocument(); layout.writeTo(document); return document; } private void setUserLayoutDOM( Node n, String parentNodeId, Hashtable layoutData ) throws PortalException { Element node = (Element) n; NodeList childNodes = node.getChildNodes(); IALNodeDescription nodeDesc = ALNode.createUserLayoutNodeDescription(node); String nodeId = node.getAttribute("ID"); nodeDesc.setId(nodeId); nodeDesc.setName(node.getAttribute("name")); nodeDesc.setFragmentId(node.getAttribute("fragmentID")); nodeDesc.setHidden(CommonUtils.strToBool(node.getAttribute("hidden"))); nodeDesc.setImmutable(CommonUtils.strToBool(node.getAttribute("immutable"))); nodeDesc.setUnremovable(CommonUtils.strToBool(node.getAttribute("unremovable"))); nodeDesc.setHidden(CommonUtils.strToBool(node.getAttribute("hidden"))); ALNode layoutNode = null; IALChannelDescription channelDesc = null; if (nodeDesc instanceof IALChannelDescription) channelDesc = (IALChannelDescription) nodeDesc; // Getting parameters and restrictions for ( int i = 0; i < childNodes.getLength(); i++ ) { Node childNode = childNodes.item(i); String nodeName = childNode.getNodeName(); NamedNodeMap attributes = childNode.getAttributes(); if ( IAggregatedLayout.PARAMETER.equals(nodeName) && channelDesc != null ) { Node paramNameNode = attributes.getNamedItem("name"); String paramName = (paramNameNode!=null)?paramNameNode.getFirstChild().getNodeValue():null; Node paramValueNode = attributes.getNamedItem("value"); String paramValue = (paramValueNode!=null)?paramValueNode.getFirstChild().getNodeValue():null; Node overParamNode = attributes.getNamedItem("override"); String overParam = (overParamNode!=null)?overParamNode.getFirstChild().getNodeValue():"yes"; if ( paramName != null && paramValue != null ) { channelDesc.setParameterValue(paramName, paramValue); channelDesc.setParameterOverride(paramName, "yes".equalsIgnoreCase(overParam)?true:false); } } else if ( IAggregatedLayout.RESTRICTION.equals(nodeName) ) { Node restrPathNode = attributes.getNamedItem("path"); String restrPath = (restrPathNode!=null)?restrPathNode.getFirstChild().getNodeValue():null; Node restrValueNode = attributes.getNamedItem("value"); String restrValue = (restrValueNode!=null)?restrValueNode.getFirstChild().getNodeValue():null; Node restrTypeNode = attributes.getNamedItem("type"); String restrType = (restrTypeNode!=null)?restrTypeNode.getFirstChild().getNodeValue():"0"; if ( restrValue != null ) { IUserLayoutRestriction restriction = UserLayoutRestrictionFactory.createRestriction(CommonUtils.parseInt(restrType),restrValue,restrPath); nodeDesc.addRestriction(restriction); } } } if ( channelDesc != null ) { channelDesc.setChannelPublishId(node.getAttribute("chanID")); channelDesc.setChannelTypeId(node.getAttribute("typeID")); channelDesc.setClassName(node.getAttribute("class")); channelDesc.setDescription(node.getAttribute("description")); channelDesc.setEditable(CommonUtils.strToBool(node.getAttribute("editable"))); channelDesc.setHasAbout(CommonUtils.strToBool(node.getAttribute("hasAbout"))); channelDesc.setHasHelp(CommonUtils.strToBool(node.getAttribute("hasHelp"))); channelDesc.setIsSecure(CommonUtils.strToBool(node.getAttribute("secure"))); channelDesc.setFunctionalName(node.getAttribute("fname")); channelDesc.setTimeout(Long.parseLong(node.getAttribute("timeout"))); channelDesc.setTitle(node.getAttribute("title")); // Adding to the layout layoutNode = new ALChannel(channelDesc); } else { layoutNode = new ALFolder((IALFolderDescription)nodeDesc); } // Setting priority value layoutNode.setPriority(CommonUtils.parseInt(node.getAttribute("priority"),0)); ALFolder parentFolder = getLayoutFolder(parentNodeId); // Binding the current node to the parent child list and parentNodeId to the current node if ( parentFolder != null ) { //parentFolder.addChildNode(nodeDesc.getId()); layoutNode.setParentNodeId(parentNodeId); } Element nextNode = (Element) node.getNextSibling(); Element prevNode = (Element) node.getPreviousSibling(); if ( nextNode != null && isNodeFolderOrChannel(nextNode) ) layoutNode.setNextNodeId(nextNode.getAttribute("ID")); if ( prevNode != null && isNodeFolderOrChannel(prevNode) ) layoutNode.setPreviousNodeId(prevNode.getAttribute("ID") ); // Setting the first child node ID if ( layoutNode.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { String id = ((Element)node.getFirstChild()).getAttribute("ID"); if ( id != null && id.length() > 0 ) ((ALFolder)layoutNode).setFirstChildNodeId(id); } // Putting the LayoutNode object into the layout layoutData.put(nodeDesc.getId(), layoutNode); // Recurrence for all children for ( int i = 0; i < childNodes.getLength() && (layoutNode.getNodeType()==IUserLayoutNodeDescription.FOLDER); i++ ) { Element childNode = (Element) childNodes.item(i); if ( isNodeFolderOrChannel ( childNode ) ) setUserLayoutDOM ( childNode, nodeDesc.getId(), layoutData ); } } public void setUserLayoutDOM( Document domLayout ) throws PortalException { Hashtable layoutData = new Hashtable(); String rootId = getRootFolderId(); Element rootNode = (Element) domLayout.getDocumentElement().getFirstChild(); ALFolder rootFolder = new ALFolder((IALFolderDescription)ALNode.createUserLayoutNodeDescription(rootNode)); rootFolder.setFirstChildNodeId(((Element)rootNode.getFirstChild()).getAttribute("ID")); layoutData.put(rootId,rootFolder); NodeList childNodes = rootNode.getChildNodes(); for ( int i = 0; i < childNodes.getLength(); i++ ) setUserLayoutDOM ( childNodes.item(i), rootId, layoutData ); layout.setLayoutData(layoutData); updateCacheKey(); } private boolean isNodeFolderOrChannel ( Element node ) { String nodeName = node.getNodeName(); return ( IAggregatedLayout.FOLDER.equals(nodeName) || IAggregatedLayout.CHANNEL.equals(nodeName) ); } public void setLayoutStore(IUserLayoutStore layoutStore ) { this.layoutStore = (AggregatedUserLayoutStore) layoutStore; } public void loadUserLayout() throws PortalException { try { if ( layoutStore != null ) { fragmentId = null; layout = (AggregatedLayout) layoutStore.getAggregatedLayout(person,userProfile); layout.setLayoutManager(this); // Setting the first child node id for the root node to NULL if it does not exist in the layout ALFolder rootFolder = getLayoutFolder(getRootFolderId()); String firstChildId = rootFolder.getFirstChildNodeId(); if ( firstChildId != null && getLayoutNode(firstChildId) == null ) rootFolder.setFirstChildNodeId(null); // Moving the wrong pushed fragments to the lost folder moveWrongFragmentsToLostFolder(); // Checking restrictions and move "wrong" nodes to the lost folder moveWrongNodesToLostFolder(); // Inform layout listeners for(Iterator i = listeners.iterator(); i.hasNext();) { LayoutEventListener lel = (LayoutEventListener)i.next(); lel.layoutLoaded(); } updateCacheKey(); } } catch ( Exception e ) { LogService.log(LogService.ERROR, e); throw new PortalException(e.getMessage()); } } /** * Returns true if any fragment is currently loaded into the layout manager, * false - otherwise * @return a boolean value * @exception PortalException if an error occurs */ public boolean isFragmentLoaded() throws PortalException { return isLayoutFragment(); } public void saveUserLayout() throws PortalException { try { if ( !isLayoutFragment() ) { layoutStore.setAggregatedLayout(person,userProfile,layout); // Inform layout listeners for(Iterator i = listeners.iterator(); i.hasNext();) { LayoutEventListener lel = (LayoutEventListener)i.next(); lel.layoutSaved(); } } else { saveFragment(); } updateCacheKey(); } catch ( Exception e ) { throw new PortalException(e.getMessage()); } } public void saveFragment ( ILayoutFragment fragment ) throws PortalException { layoutStore.setFragment(person,fragment); } public void deleteFragment ( String fragmentId ) throws PortalException { layoutStore.deleteFragment(person,fragmentId); } /** * Returns the list of Ids of the fragments that the user can subscribe to * @return <code>Collection</code> a set of the fragment IDs * @exception PortalException if an error occurs */ public Collection getSubscribableFragments() throws PortalException { return layoutStore.getSubscribableFragments(person); } public Collection getFragments () throws PortalException { return layoutStore.getFragments(person).keySet(); } /** * Returns the user group keys which the fragment is published to * @param fragmentId a <code>String</code> value * @return a <code>Collection</code> object containing the group keys * @exception PortalException if an error occurs */ public Collection getPublishGroups (String fragmentId ) throws PortalException { return layoutStore.getPublishGroups(person,fragmentId); } /** * Persists the user groups which the fragment is published to * @param groups an array of <code>IGroupMember</code> objects * @param fragmentId a <code>String</code> value * @exception PortalException if an error occurs */ public void setPublishGroups ( IGroupMember[] groups, String fragmentId ) throws PortalException { layoutStore.setPublishGroups(groups,person,fragmentId); } public ILayoutFragment getFragment ( String fragmentId ) throws PortalException { return layoutStore.getFragment(person,fragmentId); } public String createFragment( String fragmentName, String fragmentDesc, String fragmentRootName ) throws PortalException { try { // Creating an empty layout with a root folder String newFragmentId = layoutStore.getNextFragmentId(); ALFragment fragment = new ALFragment (newFragmentId,this); // Creating the layout root node ALFolder rootFolder = ALFolder.createRootFolder(); // Creating the fragment root node ALFolderDescription nodeDesc = (ALFolderDescription) createNodeDescription(IUserLayoutNodeDescription.FOLDER); // Setting the root fragment ID = 1 nodeDesc.setId("1"); nodeDesc.setName(fragmentRootName); nodeDesc.setFolderType(IUserLayoutFolderDescription.REGULAR_TYPE); // Setting the fragment ID nodeDesc.setFragmentId(newFragmentId); //Creating a new folder with the folder description ALFolder fragmentRoot = new ALFolder(nodeDesc); //Updating the DB and getting the node ID for the new node //fragmentRoot = layoutStore.addUserLayoutNode(person,userProfile,fragmentRoot); // Setting the link between the layout root and the fragment root fragmentRoot.setParentNodeId(rootFolder.getId()); rootFolder.setFirstChildNodeId(fragmentRoot.getId()); // Fill the hashtable with the new nodes Hashtable layoutData = new Hashtable(); layoutData.put(rootFolder.getId(),rootFolder); layoutData.put(fragmentRoot.getId(),fragmentRoot); // Setting the layout data fragment.setLayoutData(layoutData); fragment.setName(fragmentName); fragment.setDescription(fragmentDesc); // Setting the fragment in the database layoutStore.setFragment(person,fragment); // Getting the list of the fragments /*fragments = (Hashtable) layoutStore.getFragments(person); if ( fragments != null && fragments.size() > 0 ) fragment.setFragments(fragments); */ updateCacheKey(); // Return a new fragment ID return newFragmentId; } catch ( Exception e ) { e.printStackTrace(); throw new PortalException(e.getMessage()); } } public void loadFragment( String fragmentId ) throws PortalException { try { layout = (ALFragment) layoutStore.getFragment(person,fragmentId); layout.setLayoutManager(this); /*fragments = (Hashtable) layoutStore.getFragments(person); if ( fragments != null && fragments.size() > 0 ) layout.setFragments(fragments);*/ this.fragmentId = fragmentId; // Checking restrictions and move "wrong" nodes to the lost folder //moveWrongNodesToLostFolder(); updateCacheKey(); } catch ( Exception e ) { throw new PortalException(e.getMessage()); } } public void saveFragment() throws PortalException { try { if ( isLayoutFragment() ) { layoutStore.setFragment(person,(ILayoutFragment)layout); /*fragments = (Hashtable) layoutStore.getFragments(person); if ( fragments != null && fragments.size() > 0 ) layout.setFragments(fragments);*/ } updateCacheKey(); } catch ( Exception e ) { throw new PortalException(e.getMessage()); } } /** * Deletes the current fragment if the layout is a fragment * @exception PortalException if an error occurs */ public void deleteFragment() throws PortalException { try { if ( isLayoutFragment() ) { layoutStore.deleteFragment(person,fragmentId); } loadUserLayout(); updateCacheKey(); } catch ( Exception e ) { throw new PortalException(e.getMessage()); } } private boolean isLayoutFragment() { return ( fragmentId != null && layout != null ); } public IUserLayoutNodeDescription getNode(String nodeId) throws PortalException { return layout.getNodeDescription(nodeId); } public synchronized boolean moveNode(String nodeId, String parentId, String nextSiblingId) throws PortalException { // if the node is being moved to itself that operation must be prevented if ( nodeId.equals(nextSiblingId) ) return false; ALNode node = getLayoutNode(nodeId); // If the node is being moved to the same position if ( parentId.equals(node.getParentNodeId()) ) if ( CommonUtils.nvl(nextSiblingId).equals(CommonUtils.nvl(node.getNextNodeId()))) return true; // Checking restrictions if the parent is not the lost folder if ( !parentId.equals(IALFolderDescription.LOST_FOLDER_ID) ) if ( !canMoveNode(nodeId,parentId,nextSiblingId) ) return false; ALFolder targetFolder = getLayoutFolder(parentId); ALFolder sourceFolder = getLayoutFolder(node.getParentNodeId()); String sourcePrevNodeId = node.getPreviousNodeId(); String sourceNextNodeId = node.getNextNodeId(); ALNode targetNextNode = getLayoutNode(nextSiblingId); ALNode targetPrevNode = null, sourcePrevNode = null, sourceNextNode = null; String prevSiblingId = null; // If the nextNode != null we calculate the prev node from it otherwise we have to run to the last node in the sibling line if ( targetNextNode != null ) targetPrevNode = getLayoutNode(targetNextNode.getPreviousNodeId()); else targetPrevNode = getLastSiblingNode(targetFolder.getFirstChildNodeId()); if ( targetPrevNode != null ) { targetPrevNode.setNextNodeId(nodeId); prevSiblingId = targetPrevNode.getId(); } // Changing the previous node id for the new next sibling node if ( targetNextNode != null ) targetNextNode.setPreviousNodeId(nodeId); if ( nodeId.equals(sourceFolder.getFirstChildNodeId()) ) { // Set the new first child node ID to the source folder sourceFolder.setFirstChildNodeId(node.getNextNodeId()); } String firstChildId = targetFolder.getFirstChildNodeId(); if ( firstChildId == null || firstChildId.equals(nextSiblingId) ) { // Set the new first child node ID to the target folder targetFolder.setFirstChildNodeId(nodeId); } // Set the new next node ID for the source previous node if ( sourcePrevNodeId != null ) { sourcePrevNode = getLayoutNode(sourcePrevNodeId); sourcePrevNode.setNextNodeId(sourceNextNodeId); } // Set the new previous node ID for the source next node if ( sourceNextNodeId != null ) { sourceNextNode = getLayoutNode(sourceNextNodeId); sourceNextNode.setPreviousNodeId(sourcePrevNodeId); } node.setParentNodeId(parentId); node.setNextNodeId(nextSiblingId); node.setPreviousNodeId(prevSiblingId); // TO UPDATE THE APPROPRIATE INFO IN THE DB // TO BE DONE !!!!!!!!!!! boolean result = true; if ( autoCommit ) { if ( sourcePrevNode != null ) result &= layoutStore.updateUserLayoutNode(person,userProfile,sourcePrevNode); if ( sourceNextNode != null ) result &= layoutStore.updateUserLayoutNode(person,userProfile,sourceNextNode); if ( targetPrevNode != null ) result &= layoutStore.updateUserLayoutNode(person,userProfile,targetPrevNode); if ( targetNextNode != null ) result &= layoutStore.updateUserLayoutNode(person,userProfile,targetNextNode); result &= layoutStore.updateUserLayoutNode(person,userProfile,targetFolder); result &= layoutStore.updateUserLayoutNode(person,userProfile,sourceFolder); // Changing the node being moved result &= layoutStore.updateUserLayoutNode(person,userProfile,node); } if (result) { // Inform the layout listeners LayoutMoveEvent ev = new LayoutMoveEvent(this, getNode(nodeId), getParentId(nodeId)); for (Iterator i = listeners.iterator(); i.hasNext();) { LayoutEventListener lel=(LayoutEventListener)i.next(); if (node.getNodeDescription().getType() == IUserLayoutNodeDescription.CHANNEL) { lel.channelMoved(ev); } else { lel.folderMoved(ev); } } } updateCacheKey(); return result; } public synchronized boolean deleteNode(String nodeId) throws PortalException { if ( nodeId == null ) return false; ALNode node = getLayoutNode(nodeId); if ( node == null ) return false; // Checking restrictions if ( !canDeleteNode(nodeId) ) { LogService.log(LogService.DEBUG, "The node with ID = '" + nodeId + "' cannot be deleted"); return false; } // Inform the layout listeners LayoutMoveEvent ev = new LayoutMoveEvent(this, node.getNodeDescription(), node.getParentNodeId()); for(Iterator i = listeners.iterator(); i.hasNext();) { LayoutEventListener lel = (LayoutEventListener)i.next(); if(getNode(nodeId).getType() == IUserLayoutNodeDescription.CHANNEL) { lel.channelDeleted(ev); } else { lel.folderDeleted(ev); } } // Deleting the node from the parent ALFolder parentFolder = getLayoutFolder(node.getParentNodeId()); boolean result = false; if ( nodeId.equals(parentFolder.getFirstChildNodeId()) ) { // Set the new first child node ID to the source folder parentFolder.setFirstChildNodeId(node.getNextNodeId()); // Update it in the database if ( autoCommit ) result = layoutStore.updateUserLayoutNode(person,userProfile,parentFolder); } // Changing the next node id for the previous sibling node // and the previous node for the next sibling node String prevSiblingId = node.getPreviousNodeId(); String nextSiblingId = node.getNextNodeId(); if ( prevSiblingId != null ) { ALNode prevNode = getLayoutNode(prevSiblingId); prevNode.setNextNodeId(nextSiblingId); if ( autoCommit ) result = layoutStore.updateUserLayoutNode(person,userProfile,prevNode); } if ( nextSiblingId != null ) { ALNode nextNode = getLayoutNode(nextSiblingId); nextNode.setPreviousNodeId(prevSiblingId); if ( autoCommit ) result = layoutStore.updateUserLayoutNode(person,userProfile,nextNode); } // DELETE THE NODE FROM THE DB if ( autoCommit ) result = layoutStore.deleteUserLayoutNode(person,userProfile,node); // Deleting the nodefrom the hashtable and returning the result value result = (layout.getLayoutData().remove(nodeId)!=null) && ((autoCommit)?result:true); updateCacheKey(); return result; } public synchronized IUserLayoutNodeDescription addNode(IUserLayoutNodeDescription nodeDesc, String parentId,String nextSiblingId) throws PortalException { // Checking restrictions if ( !canAddNode(nodeDesc,parentId,nextSiblingId) ) return null; ALFolder parentFolder = getLayoutFolder(parentId); ALNode nextNode = getLayoutNode(nextSiblingId); ALNode prevNode = null; // If the nextNode != null we calculate the prev node from it otherwise we have to run to the last node in the sibling line if ( nextNode != null ) prevNode = getLayoutNode(nextNode.getPreviousNodeId()); else prevNode = getLastSiblingNode( parentFolder.getFirstChildNodeId()); // If currently a fragment is loaded the node desc should have a fragment ID if ( isFragmentLoaded() ) ((IALNodeDescription)nodeDesc).setFragmentId(fragmentId); ALNode layoutNode=ALNode.createALNode(nodeDesc); // Setting the parent node ID layoutNode.setParentNodeId(parentId); if ( prevNode != null ) layoutNode.setPreviousNodeId(prevNode.getId()); if ( nextNode != null ) layoutNode.setNextNodeId(nextSiblingId); // Add the new node to the database and get the node with a new node ID if ( autoCommit ) layoutNode = layoutStore.addUserLayoutNode(person,userProfile,layoutNode); else { IALNodeDescription desc = layoutNode.getNodeDescription(); desc.setId(layoutStore.getNextNodeId(person)); if ( desc.getType() == IUserLayoutNodeDescription.CHANNEL ) layoutStore.fillChannelDescription((IALChannelDescription)desc); } String nodeId = layoutNode.getId(); // Putting the new node into the hashtable layout.getLayoutData().put(nodeId,layoutNode); if ( prevNode != null ) prevNode.setNextNodeId(nodeId); if ( nextNode != null ) nextNode.setPreviousNodeId(nodeId); // Setting new child node ID to the parent node if ( prevNode == null ) parentFolder.setFirstChildNodeId(nodeId); if ( autoCommit ) { // TO UPDATE ALL THE NEIGHBOR NODES IN THE DATABASE if ( nextNode != null ) layoutStore.updateUserLayoutNode(person,userProfile,nextNode); if ( prevNode != null ) layoutStore.updateUserLayoutNode(person,userProfile,prevNode); // Update the parent node layoutStore.updateUserLayoutNode(person,userProfile,parentFolder); } // Inform the layout listeners LayoutEvent ev = new LayoutEvent(this, layoutNode.getNodeDescription()); for (Iterator i = listeners.iterator(); i.hasNext();) { LayoutEventListener lel = (LayoutEventListener)i.next(); if (layoutNode.getNodeDescription().getType() == IUserLayoutNodeDescription.CHANNEL) { lel.channelAdded(ev); } else { lel.folderAdded(ev); } } updateCacheKey(); return layoutNode.getNodeDescription(); } private void changeDescendantsBooleanProperties (IALNodeDescription nodeDesc,IALNodeDescription oldNodeDesc, String nodeId) throws PortalException { changeDescendantsBooleanProperties(nodeDesc.isHidden()==oldNodeDesc.isHidden(),nodeDesc.isImmutable()==oldNodeDesc.isImmutable(), nodeDesc.isUnremovable()==oldNodeDesc.isUnremovable(),nodeDesc,nodeId); updateCacheKey(); } private void changeDescendantsBooleanProperties (boolean hiddenValuesMatch, boolean immutableValuesMatch, boolean unremovableValuesMatch, IALNodeDescription nodeDesc, String nodeId) throws PortalException { ALNode node = getLayoutNode(nodeId); if ( node.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { // Loop for all children String firstChildId = ((ALFolder)node).getFirstChildNodeId(); for ( String nextNodeId = firstChildId; nextNodeId != null; ) { ALNode currentNode = getLayoutNode(nextNodeId); // Checking the hidden property if it's changed if ( !hiddenValuesMatch ) { // Checking the hidden node restriction boolean canChange = checkRestriction(currentNode,RestrictionTypes.HIDDEN_RESTRICTION,CommonUtils.boolToStr(nodeDesc.isHidden())); // Checking the hidden parent node related restriction canChange &= checkRestriction(currentNode.getParentNodeId(),RestrictionTypes.HIDDEN_RESTRICTION,"children",CommonUtils.boolToStr(nodeDesc.isHidden())); // Checking the hidden children node related restrictions if ( currentNode.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { ALFolder folder = (ALFolder) node; //Loop for all children for ( String nextId = folder.getFirstChildNodeId(); nextId != null; nextId = getLayoutNode(nextId).getNextNodeId() ) canChange &= checkRestriction(nextId,RestrictionTypes.HIDDEN_RESTRICTION,"parent",CommonUtils.boolToStr(nodeDesc.isHidden())); } // Changing the hidden value if canChange is true if ( canChange ) currentNode.getNodeDescription().setHidden(nodeDesc.isHidden()); } // Checking the immutable property if it's changed if ( !immutableValuesMatch ) { // Checking the immutable node restriction boolean canChange = checkRestriction(currentNode,RestrictionTypes.IMMUTABLE_RESTRICTION,CommonUtils.boolToStr(nodeDesc.isImmutable())); // Checking the immutable parent node related restriction canChange &= checkRestriction(currentNode.getParentNodeId(),RestrictionTypes.IMMUTABLE_RESTRICTION,"children",CommonUtils.boolToStr(nodeDesc.isImmutable())); // Checking the immutable children node related restrictions if ( currentNode.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { ALFolder folder = (ALFolder) node; //Loop for all children for ( String nextId = folder.getFirstChildNodeId(); nextId != null; nextId = getLayoutNode(nextId).getNextNodeId() ) canChange &= checkRestriction(nextId,RestrictionTypes.IMMUTABLE_RESTRICTION,"parent",CommonUtils.boolToStr(nodeDesc.isImmutable())); } // Changing the immutable value if canChange is true if ( canChange ) currentNode.getNodeDescription().setImmutable(nodeDesc.isImmutable()); } // Checking the unremovable property if it's changed if ( !unremovableValuesMatch ) { // Checking the unremovable node restriction boolean canChange = checkRestriction(currentNode,RestrictionTypes.UNREMOVABLE_RESTRICTION,CommonUtils.boolToStr(nodeDesc.isUnremovable())); // Checking the unremovable parent node related restriction canChange &= checkRestriction(currentNode.getParentNodeId(),RestrictionTypes.UNREMOVABLE_RESTRICTION,"children",CommonUtils.boolToStr(nodeDesc.isUnremovable())); // Checking the unremovable children node related restrictions if ( currentNode.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { ALFolder folder = (ALFolder) node; //Loop for all children for ( String nextId = folder.getFirstChildNodeId(); nextId != null; nextId = getLayoutNode(nextId).getNextNodeId() ) canChange &= checkRestriction(nextId,RestrictionTypes.UNREMOVABLE_RESTRICTION,"parent",CommonUtils.boolToStr(nodeDesc.isImmutable())); } // Changing the unremovable value if canChange is true if ( canChange ) currentNode.getNodeDescription().setUnremovable(nodeDesc.isUnremovable()); } /// Recurrence changeDescendantsBooleanProperties(hiddenValuesMatch,immutableValuesMatch,unremovableValuesMatch,nodeDesc,nextNodeId); nextNodeId = currentNode.getNextNodeId(); } } } public synchronized boolean updateNode(IUserLayoutNodeDescription nodeDesc) throws PortalException { // Checking restrictions if ( !canUpdateNode(nodeDesc) ) return false; ALNode node = getLayoutNode(nodeDesc.getId()); IALNodeDescription oldNodeDesc = node.getNodeDescription(); // We have to change all the boolean properties on descendants changeDescendantsBooleanProperties((IALNodeDescription)nodeDesc,oldNodeDesc,nodeDesc.getId()); node.setNodeDescription((IALNodeDescription)nodeDesc); // Inform the layout listeners LayoutEvent ev = new LayoutEvent(this, nodeDesc); for (Iterator i = listeners.iterator(); i.hasNext();) { LayoutEventListener lel = (LayoutEventListener)i.next(); if (nodeDesc.getType() == IUserLayoutNodeDescription.CHANNEL) { lel.channelUpdated(ev); } else { lel.folderUpdated(ev); } } updateCacheKey(); // Update the node into the database if ( autoCommit ) return layoutStore.updateUserLayoutNode(person,userProfile,node); else return true; } public boolean canAddNode(IUserLayoutNodeDescription nodeDesc, String parentId, String nextSiblingId) throws PortalException { return checkAddRestrictions((IALNodeDescription)nodeDesc,parentId,nextSiblingId); } public boolean canMoveNode(String nodeId, String parentId, String nextSiblingId) throws PortalException { return checkMoveRestrictions(nodeId,parentId,nextSiblingId); } public boolean canDeleteNode(String nodeId) throws PortalException { return checkDeleteRestrictions(nodeId); } public boolean canUpdateNode(IUserLayoutNodeDescription nodeDescription) throws PortalException { IALNodeDescription nodeDesc=(IALNodeDescription)nodeDescription; String nodeId = nodeDesc.getId(); if ( nodeId == null ) return false; ALNode node = getLayoutNode(nodeId); IALNodeDescription currentNodeDesc = node.getNodeDescription(); // If the node Ids do no match to each other then return false if ( !nodeId.equals(currentNodeDesc.getId()) ) return false; // Checking the immutable node restriction //if ( checkRestriction(node,RestrictionTypes.IMMUTABLE_RESTRICTION,"true") ) if ( currentNodeDesc.isImmutable() ) return false; // Checking the immutable parent node related restriction if ( getRestriction(getLayoutNode(node.getParentNodeId()),RestrictionTypes.IMMUTABLE_RESTRICTION,"children") != null && checkRestriction(node.getParentNodeId(),RestrictionTypes.IMMUTABLE_RESTRICTION,"children","true") ) return false; // Checking the immutable children node related restrictions if ( node.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { ALFolder folder = (ALFolder) node; //Loop for all children for ( String nextId = folder.getFirstChildNodeId(); nextId != null; nextId = getLayoutNode(nextId).getNextNodeId() ) if ( getRestriction(getLayoutNode(nextId),RestrictionTypes.IMMUTABLE_RESTRICTION,"parent") != null && checkRestriction(nextId,RestrictionTypes.IMMUTABLE_RESTRICTION,"parent","true") ) return false; } // if a new node description doesn't contain any restrictions the old restrictions will be used if ( nodeDesc.getRestrictions() == null ) nodeDesc.setRestrictions(currentNodeDesc.getRestrictions()); Hashtable rhash = nodeDesc.getRestrictions(); // Setting the new node description to the node node.setNodeDescription(nodeDesc); // Checking restrictions for the node if ( rhash != null ) { for ( Enumeration enum = rhash.elements(); enum.hasMoreElements(); ) if ( !((IUserLayoutRestriction)enum.nextElement()).checkRestriction(node) ) { node.setNodeDescription(currentNodeDesc); return false; } } // Checking parent related restrictions for the children Vector restrictions = getLayoutNode(node.getParentNodeId()).getRestrictionsByPath("children"); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); if ( !restriction.checkRestriction(node) ) { node.setNodeDescription(currentNodeDesc); return false; } } // Checking child related restrictions for the parent if ( node.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { for ( String nextId = ((ALFolder)node).getFirstChildNodeId(); nextId != null; ) { ALNode child = getLayoutNode(nextId); restrictions = child.getRestrictionsByPath("parent"); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); if ( !restriction.checkRestriction(node) ) { node.setNodeDescription(currentNodeDesc); return false; } } nextId = child.getNextNodeId(); } } return true; } public void markAddTargets(IUserLayoutNodeDescription nodeDesc) throws PortalException { if ( nodeDesc != null && !( nodeDesc instanceof IALNodeDescription ) ) throw new PortalException ( "The given argument is not a node description!" ); addTargetsNodeDesc = (IALNodeDescription)nodeDesc; updateCacheKey(); } public void markMoveTargets(String nodeId) throws PortalException { if ( nodeId != null && getLayoutNode(nodeId) == null ) throw new PortalException ( "The node with nodeID="+nodeId+" does not exist in the layout!" ); moveTargetsNodeId = nodeId; updateCacheKey(); } /** * Returns the description of the node currently being added to the layout * * @return node an <code>IALNodeDescription</code> object * @exception PortalException if an error occurs */ public IALNodeDescription getNodeBeingAdded() throws PortalException { return addTargetsNodeDesc; } /** * Returns the description of the node currently being moved in the layout * * @return node an <code>IALNodeDescription</code> object * @exception PortalException if an error occurs */ public IALNodeDescription getNodeBeingMoved() throws PortalException { if ( moveTargetsNodeId != null ) { ALNode node = getLayoutNode(moveTargetsNodeId); return (node != null ) ? node.getNodeDescription() : null; } return null; } /** * Sets a restriction mask that logically multiplies one of the types from <code>RestrictionTypes</code> and * is responsible for filtering restrictions for the layout output to ContentHandler or DOM * @param restrictionMask a restriction mask */ public void setRestrictionMask (int restrictionMask) { this.restrictionMask = restrictionMask; } /** * Gets a restriction mask that logically multiplies one of the types from <code>RestrictionTypes</code> and * is responsible for filtering restrictions for the layout output to ContentHandler or DOM * @return a restriction mask */ public int getRestrictionMask () { return restrictionMask; } public boolean addLayoutEventListener(LayoutEventListener l){ return listeners.add(l); } public boolean removeLayoutEventListener(LayoutEventListener l){ return listeners.remove(l); } /** * Returns an id of the root folder. * * @return a <code>String</code> value */ public String getRootFolderId() { return layout.getRootId(); } /** * Returns a subscription id given a functional name. * @param fname the functional name to lookup. * @return a <code>String</code> subscription id. */ public String getSubscribeId (String fname) throws PortalException { return layout.getNodeId(fname); } }
package org.basex.io.random; import java.util.*; import org.basex.io.*; import org.basex.util.*; import org.basex.util.list.*; final class TableMemBlock { /** Table data, with two values for one XML node. */ private long[] data; /** First pre value. */ int firstPre; /** * Constructor with initial capacity. * @param compact compact block size */ private TableMemBlock(final boolean compact) { data = new long[(compact ? 1 : IO.BLOCKSIZE) << 1]; } /** * Creates new blocks. * @param count number of entries to add * @param compact compact block size * @return new blocks */ private static ArrayList<TableMemBlock> get(final int count, final boolean compact) { final int bs = IO.BLOCKSIZE + count - 1 >>> IO.BLOCKPOWER; final ArrayList<TableMemBlock> list = new ArrayList<>(bs); for(int b = 0; b < bs; b++) list.add(new TableMemBlock(compact)); return list; } /** * Creates new blocks with computed pre values. * @param count number of entries to add * @param pre pre value of first block (will be incremented for subsequent blocks) * @return new blocks */ static ArrayList<TableMemBlock> get(final int count, final int pre) { final ArrayList<TableMemBlock> blocks = get(count, true); int fp = pre; for(final TableMemBlock block : blocks) { block.firstPre = fp; fp += IO.BLOCKSIZE; } return blocks; } /** * Returns the number of remaining entries in this block. * @param nextPre pre value of next block * @return remaining entries */ int remaining(final int nextPre) { return IO.BLOCKSIZE - nextPre + firstPre; } /** * Returns the value at the specified position. * @param pre pre value * @param offset offset * @return value */ long value(final int pre, final int offset) { return data[index(pre, offset)]; } /** * Assigns a value at the specified position. * @param pre pre value * @param offset offset * @param value value */ void value(final int pre, final int offset, final long value) { final int i = index(pre, offset); resize(i + 1); data[i] = value; } /** * Deletes the specified number of entries. * @param pre pre value of first entry to delete * @param count number of entries to delete * @param nextPre pre value of next block * @return number of deleted entries */ int delete(final int pre, final int count, final int nextPre) { final int first = pre - firstPre, last = first + count, filled = nextPre - firstPre; if(last >= filled) return filled - first; System.arraycopy(data, last << 1, data, first << 1, filled - last << 1); return count; } /** * Inserts the specified number of entries. * @param pre pre value of first entry to insert (may point to the end of the block) * @param count number of entries to insert * @param nextPre pre value of next block * @return new blocks or {@code null} */ ArrayList<TableMemBlock> insert(final int pre, final int count, final int nextPre) { final int first = pre - firstPre, last = first + count, filled = nextPre - firstPre; final int remaining = IO.BLOCKSIZE - filled, copy = nextPre - pre; // check if entries can be inserted into existing block if(count <= remaining) { resize((last + copy) << 1); System.arraycopy(data, first << 1, data, last << 1, copy << 1); return null; } // otherwise, create new blocks resize(IO.BLOCKSIZE << 1); final ArrayList<TableMemBlock> blocks = get(count - remaining, false); // create temporary array with final entries final int total = filled + count; final long[] longs = new long[total << 1]; System.arraycopy(data, 0, longs, 0, first << 1); System.arraycopy(data, first << 1, longs, last << 1, copy << 1); /* redistribute entries evenly: * 300 entries: 2 blocks with 150 entries each * 301 entries: 2 blocks with 151 and 150 entries * 514 entries: 3 blocks with 172, 172 and 170 entries */ final int bs = blocks.size(), fill = (total + bs) / (bs + 1); final int total2 = total << 1, fill2 = fill << 1; // populate original block System.arraycopy(longs, 0, data, 0, fill2); // populate new blocks int copied = fill, copied2 = fill2; for(final TableMemBlock block : blocks) { block.firstPre = firstPre + copied; System.arraycopy(longs, copied2, block.data, 0, Math.min(fill2, total2 - copied2)); copied += fill; copied2 += fill2; } return blocks; } /** * Resizes the table block. * @param size minimum size */ private void resize(final int size) { final long[] dt = data; final int dl = dt.length; if(dl < size) data = Arrays.copyOf(dt, Math.min(Math.max(size, dl << 1), IO.BLOCKSIZE << 1)); } @Override public String toString() { final StringBuilder sb = new StringBuilder(Util.className(this) + '[' + firstPre + ": "); final IntList ints = new IntList(); int first = -1, last = 0; final int dl = data.length; for(int d = 0; d < dl; d++) { if(data[d] != 0) { if(first == -1) first = d; last = d; } else if(first != -1) { ints.add(first).add(last); first = -1; } } if(first != -1) ints.add(first).add(last); for(int i = 0; i < ints.size(); i += 2) { if(i != 0) sb.append(','); sb.append(ints.get(i)).append('-').append(ints.get(i + 1)); } return sb.append(']').toString(); } /** * Returns the index to the current table segment. * @param pre pre value * @param offset byte offset (0-16) * @return table index */ private int index(final int pre, final int offset) { final int p = pre - firstPre << 1; return offset < 8 ? p : p + 1; } }
package dk.itst.oiosaml.sp; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.security.cert.X509Certificate; import org.joda.time.DateTime; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.opensaml.DefaultBootstrap; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.core.Assertion; import org.opensaml.saml2.core.Attribute; import org.opensaml.saml2.core.AttributeStatement; import org.opensaml.saml2.core.AttributeValue; import org.opensaml.saml2.core.AuthnStatement; import org.opensaml.xml.ConfigurationException; import org.opensaml.xml.Namespace; import org.opensaml.xml.schema.XSAny; import org.opensaml.xml.schema.impl.XSAnyBuilder; import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.util.Base64; import org.opensaml.xml.util.XMLConstants; import org.opensaml.xml.util.XMLHelper; import dk.itst.oiosaml.common.OIOSAMLConstants; import dk.itst.oiosaml.common.SAMLUtil; import dk.itst.oiosaml.sp.model.OIOAssertion; import dk.itst.oiosaml.sp.service.TestHelper; import dk.itst.oiosaml.sp.util.AttributeUtil; public class UserAssertionImplTest { private OIOAssertion assertion; private AttributeStatement attributeStatement; private Assertion as; @BeforeClass public static void init() throws ConfigurationException { DefaultBootstrap.bootstrap(); } @Before public void setUp() { assertion = new OIOAssertion(createAssertion()); attributeStatement = SAMLUtil.buildXMLObject(AttributeStatement.class); assertion.getAssertion().getAttributeStatements().add(attributeStatement); as = assertion.getAssertion(); } @Test public void testGetAllAttributes() { UserAssertionImpl ua = new UserAssertionImpl(assertion); assertEquals(0, ua.getAllAttributes().size()); assertNull(ua.getAttribute("test")); attributeStatement.getAttributes().add(createAttribute("test", "test")); ua = new UserAssertionImpl(assertion); assertEquals(1, ua.getAllAttributes().size()); assertNotNull(ua.getAttribute("test")); assertEquals("test", ua.getAttribute("test").getValue()); } @Test public void testGetAssuranceLevel() { assertEquals(0, new UserAssertionImpl(assertion).getAssuranceLevel()); attributeStatement.getAttributes().add(AttributeUtil.createAssuranceLevel(2)); assertEquals(2, new UserAssertionImpl(assertion).getAssuranceLevel()); } @Test public void testGetCVRNumberIdentifier() { assertNull(new UserAssertionImpl(assertion).getCVRNumberIdentifier()); attributeStatement.getAttributes().add(AttributeUtil.createCVRNumberIdentifier("cvr")); assertEquals("cvr", new UserAssertionImpl(assertion).getCVRNumberIdentifier()); } @Test public void testGetCertificateSerialNumber() { assertNull(new UserAssertionImpl(assertion).getCertificateSerialNumber()); attributeStatement.getAttributes().add(createAttribute(OIOSAMLConstants.ATTRIBUTE_SERIAL_NUMBER_NAME, "cert")); assertEquals("cert", new UserAssertionImpl(assertion).getCertificateSerialNumber()); } @Test public void testGetCommonName() { assertNull(new UserAssertionImpl(assertion).getCommonName()); attributeStatement.getAttributes().add(AttributeUtil.createCommonName("name")); assertEquals("name", new UserAssertionImpl(assertion).getCommonName()); } @Test public void testGetIssueTime() { assertNull(new UserAssertionImpl(assertion).getIssueTime()); DateTime dt = new DateTime(); as.setIssueInstant(dt); assertEquals(dt.toDate(), new UserAssertionImpl(assertion).getIssueTime()); } @Test public void testGetIssuer() { assertNull(new UserAssertionImpl(assertion).getIssuer()); as.setIssuer(SAMLUtil.createIssuer("issuer")); assertEquals("issuer", new UserAssertionImpl(assertion).getIssuer()); } @Test public void testGetMail() { assertNull(new UserAssertionImpl(assertion).getMail()); attributeStatement.getAttributes().add(AttributeUtil.createMail("mail")); assertEquals("mail", new UserAssertionImpl(assertion).getMail()); } @Test public void testGetSubject() { assertNull(new UserAssertionImpl(assertion).getNameIDFormat()); assertNull(new UserAssertionImpl(assertion).getSubject()); as.setSubject(SAMLUtil.createSubject("subject", "url", new DateTime())); assertEquals(NameIDFormat.PERSISTENT, new UserAssertionImpl(assertion).getNameIDFormat()); assertEquals("subject", new UserAssertionImpl(assertion).getSubject()); } @Test public void testGetOrganizationName() { assertNull(new UserAssertionImpl(assertion).getOrganizationName()); attributeStatement.getAttributes().add(createAttribute(OIOSAMLConstants.ATTRIBUTE_ORGANISATION_NAME_NAME, "org")); assertEquals("org", new UserAssertionImpl(assertion).getOrganizationName()); } @Test public void testGetOrganizationUnit() { assertNull(new UserAssertionImpl(assertion).getOrganizationUnit()); attributeStatement.getAttributes().add(createAttribute(OIOSAMLConstants.ATTRIBUTE_ORGANISATION_UNIT_NAME, "org")); assertEquals("org", new UserAssertionImpl(assertion).getOrganizationUnit()); } @Test public void testGetPostalAddress() { assertNull(new UserAssertionImpl(assertion).getPostalAddress()); attributeStatement.getAttributes().add(createAttribute(OIOSAMLConstants.ATTRIBUTE_POSTAL_ADDRESS_NAME, "postal")); assertEquals("postal", new UserAssertionImpl(assertion).getPostalAddress()); } @Test public void testGetSessionExpireTime() { assertNull(new UserAssertionImpl(assertion).getSessionExpireTime()); AuthnStatement st = SAMLUtil.buildXMLObject(AuthnStatement.class); as.getAuthnStatements().add(st); DateTime dt = new DateTime(); st.setSessionNotOnOrAfter(dt); assertEquals(dt.toDate(), new UserAssertionImpl(assertion).getSessionExpireTime()); } @Test public void testGetSpecificationVersion() { assertNull(new UserAssertionImpl(assertion).getSpecificationVersion()); attributeStatement.getAttributes().add(createAttribute(OIOSAMLConstants.ATTRIBUTE_SPECVER_NAME, "version")); assertEquals("version", new UserAssertionImpl(assertion).getSpecificationVersion()); } @Test public void testGetSurname() { assertNull(new UserAssertionImpl(assertion).getSurname()); attributeStatement.getAttributes().add(AttributeUtil.createSurname("name")); assertEquals("name", new UserAssertionImpl(assertion).getSurname()); } @Test public void testGetTitle() { assertNull(new UserAssertionImpl(assertion).getTitle()); attributeStatement.getAttributes().add(createAttribute(OIOSAMLConstants.ATTRIBUTE_TITLE_NAME, "title")); assertEquals("title", new UserAssertionImpl(assertion).getTitle()); } @Test public void testGetUniqueAccountKey() { assertNull(new UserAssertionImpl(assertion).getUniqueAccountKey()); attributeStatement.getAttributes().add(createAttribute(OIOSAMLConstants.ATTRIBUTE_UNIQUE_ACCOUNT_KEY_NAME, "key")); assertEquals("key", new UserAssertionImpl(assertion).getUniqueAccountKey()); } @Test public void testGetUserId() { assertNull(new UserAssertionImpl(assertion).getUserId()); attributeStatement.getAttributes().add(AttributeUtil.createUid("uid")); assertEquals("uid", new UserAssertionImpl(assertion).getUserId()); } @Test public void testGetXML() { assertNotNull(new UserAssertionImpl(assertion).getXML()); } @Test public void testIsSigned() { assertFalse(new UserAssertionImpl(assertion).isSigned()); as.setSignature(SAMLUtil.createSignature("key")); assertTrue(new UserAssertionImpl(assertion).isSigned()); } @Test public void testGetCPRNumber() { assertNull(new UserAssertionImpl(assertion).getCPRNumber()); attributeStatement.getAttributes().add(createAttribute(OIOSAMLConstants.ATTRIBUTE_CPR_NUMBER_NAME, "cpr")); assertEquals("cpr", new UserAssertionImpl(assertion).getCPRNumber()); } @Test public void testGetEmployeeNumber() { assertNull(new UserAssertionImpl(assertion).getRIDNumber()); attributeStatement.getAttributes().add(AttributeUtil.createRidNumberIdentifier("rid")); assertEquals("rid", new UserAssertionImpl(assertion).getRIDNumber()); } @Test public void testPIDNumber() { assertNull(new UserAssertionImpl(assertion).getPIDNumber()); attributeStatement.getAttributes().add(AttributeUtil.createPidNumberIdentifier("pid")); assertEquals("pid", new UserAssertionImpl(assertion).getPIDNumber()); } @Test public void testGetPseudonym() { assertNull(new UserAssertionImpl(assertion).getPseudonym()); attributeStatement.getAttributes().add(createAttribute(OIOSAMLConstants.ATTRIBUTE_PSEUDONYM_NAME, "ps")); assertEquals("ps", new UserAssertionImpl(assertion).getPseudonym()); } @Test public void testGetUserCertificate() throws Exception { assertNull(new UserAssertionImpl(assertion).getUserCertificate()); Credential cred = TestHelper.getCredential(); X509Certificate cert = TestHelper.getCertificate(cred); attributeStatement.getAttributes().add(AttributeUtil.createUserCertificate(Base64.encodeBytes(cert.getEncoded()))); assertEquals(cert, new UserAssertionImpl(assertion).getUserCertificate()); attributeStatement.getAttributes().clear(); attributeStatement.getAttributes().add(AttributeUtil.createUserCertificate("test" + Base64.encodeBytes(cert.getEncoded()))); try { new UserAssertionImpl(assertion).getUserCertificate(); fail("certificate is invalid"); } catch (RuntimeException e) { } } @Test public void testIsYouthCertificate() { assertNull(new UserAssertionImpl(assertion).isYouthCertificate()); attributeStatement.getAttributes().add(createAttribute(OIOSAMLConstants.ATTRIBUTE_YOUTH_CERTIFICATE_NAME, "true")); assertEquals(true, new UserAssertionImpl(assertion).isYouthCertificate()); attributeStatement.getAttributes().clear(); attributeStatement.getAttributes().add(createAttribute(OIOSAMLConstants.ATTRIBUTE_YOUTH_CERTIFICATE_NAME, "false")); assertEquals(false, new UserAssertionImpl(assertion).isYouthCertificate()); } @Test public void testProfileCompliance() { assertFalse(new UserAssertionImpl(assertion).isOCESProfileCompliant()); assertFalse(new UserAssertionImpl(assertion).isOIOSAMLCompliant()); as.setSignature(SAMLUtil.createSignature("key")); as.setIssuer(SAMLUtil.createIssuer("issuer")); as.setSubject(SAMLUtil.createSubject("id", "url", new DateTime())); AuthnStatement st = SAMLUtil.buildXMLObject(AuthnStatement.class); st.setSessionIndex("idx"); as.getAuthnStatements().add(st); attributeStatement.getAttributes().add(AttributeUtil.createCommonName("name")); attributeStatement.getAttributes().add(AttributeUtil.createSurname("surname")); attributeStatement.getAttributes().add(AttributeUtil.createUid("uid")); attributeStatement.getAttributes().add(AttributeUtil.createMail("mail")); attributeStatement.getAttributes().add(AttributeUtil.createAssuranceLevel(2)); attributeStatement.getAttributes().add(createAttribute(OIOSAMLConstants.ATTRIBUTE_SPECVER_NAME, "DK-SAML-2.0")); assertTrue(new UserAssertionImpl(assertion).isOIOSAMLCompliant()); assertFalse(new UserAssertionImpl(assertion).isOCESProfileCompliant()); as.getSubject().getNameID().setFormat(NameIDFormat.X509SUBJECT.getFormat()); attributeStatement.getAttributes().add(AttributeUtil.createSerialNumber("number")); attributeStatement.getAttributes().add(createAttribute(OIOSAMLConstants.ATTRIBUTE_YOUTH_CERTIFICATE_NAME, "true")); attributeStatement.getAttributes().add(AttributeUtil.createPidNumberIdentifier("pid")); attributeStatement.getAttributes().remove(2); attributeStatement.getAttributes().add(AttributeUtil.createUid("PID:pid")); assertTrue(new UserAssertionImpl(assertion).isOIOSAMLCompliant()); assertTrue(new UserAssertionImpl(assertion).isOCESProfileCompliant()); attributeStatement.getAttributes().add(AttributeUtil.createRidNumberIdentifier("rid")); assertTrue(new UserAssertionImpl(assertion).isOIOSAMLCompliant()); assertFalse(new UserAssertionImpl(assertion).isOCESProfileCompliant()); } @Test public void testIsPersistentCompliant() { as.setSubject(SAMLUtil.createSubject("id", "url", new DateTime())); as.getSubject().getNameID().setFormat(NameIDFormat.PERSISTENT.getFormat()); attributeStatement.getAttributes().add(AttributeUtil.createAssuranceLevel(2)); attributeStatement.getAttributes().add(createAttribute(OIOSAMLConstants.ATTRIBUTE_SPECVER_NAME, "DK-SAML-2.0")); assertTrue(new UserAssertionImpl(assertion).isPersistentPseudonymProfileCompliant()); attributeStatement.getAttributes().add(AttributeUtil.createUid("PID:pid")); assertFalse(new UserAssertionImpl(assertion).isPersistentPseudonymProfileCompliant()); } @Test public void testGetAssertionId() throws Exception { assertEquals(as.getID(), new UserAssertionImpl(assertion).getAssertionId()); } @Test public void testAttributeWithXMLValue() { String xml = "<saml:Attribute xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\" NameFormat=\"urn:oasis:names:tc:SAML:2.0:attrname-format:basic\" Name=\"test\"><saml:AttributeValue>"; String value = XMLHelper.nodeToString(SAMLUtil.marshallObject(as)); if (value.indexOf("<?xml") == 0) { xml += value.substring(39); } else { xml += value; } xml += "</saml:AttributeValue></saml:Attribute>"; System.out.println(xml); Attribute attr = (Attribute) SAMLUtil.unmarshallElementFromString(xml); as.getAttributeStatements().get(0).getAttributes().add(attr); UserAttribute a = new UserAssertionImpl(assertion).getAttribute("test"); assertNotNull(a); assertEquals(value, a.getValue()); } private Assertion createAssertion() { return SAMLUtil.buildXMLObject(Assertion.class); } private Attribute createAttribute(String name, String value) { Attribute attr = SAMLUtil.buildXMLObject(Attribute.class); attr.setName(name); XSAnyBuilder builder = new XSAnyBuilder(); XSAny ep = builder.buildObject(SAMLConstants.SAML20_NS, AttributeValue.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX); ep.setTextContent(value); ep.getUnknownAttributes().put(AttributeUtil.XSI_TYPE_ATTRIBUTE_NAME, AttributeUtil.XS_STRING); ep.addNamespace(new Namespace(XMLConstants.XSI_NS, XMLConstants.XSI_PREFIX)); attr.getAttributeValues().add(ep); return attr; } }
package com.consol.citrus; import java.io.*; import java.util.*; import org.apache.commons.cli.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.TestNG; import org.testng.xml.*; import com.consol.citrus.exceptions.CitrusRuntimeException; import com.consol.citrus.exceptions.TestEngineFailedException; /** * Runs the test suite using applicationContext.xml and test.properties. * * @author deppisch Christoph Deppisch Consol* Software GmbH * @since 04.11.2008 */ public class Citrus { /** * Logger */ private static final Logger log = LoggerFactory.getLogger(Citrus.class); public static void main(String[] args) { log.info("CITRUS TESTFRAMEWORK "); log.info(""); Options options = new CitrusCliOptions(); CommandLineParser cliParser = new GnuParser(); CommandLine cmd = null; try { cmd = cliParser.parse(options, args); if(cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("CITRUS TestFramework", options); return; } String testDirectory = cmd.getOptionValue("testdir", CitrusConstants.DEFAULT_TEST_DIRECTORY); if(testDirectory.endsWith("/") == false) { testDirectory = testDirectory + "/"; } TestNG testNG = new TestNG(false); XmlSuite suite = new XmlSuite(); suite.setName(cmd.getOptionValue("suitename", CitrusConstants.DEFAULT_SUITE_NAME)); if(cmd.hasOption("test")) { for (String testName : cmd.getOptionValues("test")) { XmlTest test = new XmlTest(suite); test.setName(testName); test.setXmlClasses(Collections.singletonList(new XmlClass(getClassNameForTest(testDirectory, testName.trim())))); } } if(cmd.hasOption("package")) { for (String packageName : cmd.getOptionValues("package")) { XmlTest test = new XmlTest(suite); test.setName(packageName); XmlPackage xmlPackage = new XmlPackage(); xmlPackage.setName(packageName); test.setXmlPackages(Collections.singletonList(xmlPackage)); } } if(cmd.getArgList().size() > 0) { List<String> testNgXml = new ArrayList<String>(); for (String testNgXmlFile : cmd.getArgs()) { if(testNgXmlFile.endsWith(".xml")) { testNgXml.add(testNgXmlFile); } else { log.warn("Unrecognized argument '" + testNgXmlFile + "'"); } } testNG.setTestSuites(testNgXml); } List<XmlSuite> suites = new ArrayList<XmlSuite>(); suites.add(suite); testNG.setXmlSuites(suites); testNG.run(); System.exit(testNG.getStatus()); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("CITRUS TestFramework", options); } catch (FileNotFoundException e) { log.error("Failed to load test files", e); throw new TestEngineFailedException("TestSuite failed with error", e); } catch (IOException e) { log.error("Error while accessing test file", e); throw new TestEngineFailedException("TestSuite failed with error", e); } } /** * Method to retrieve the full class name for the test name searched for. * Subfolders are supported. * * @param startDir directory where to start the search * @param testName test name to search for * @throws CitrusRuntimeException * @return the class name of the test */ public static String getClassNameForTest(final String startDir, final String testName) throws IOException, FileNotFoundException { /* Stack to hold potential sub directories */ final Stack dirs = new Stack(); /* start directory */ final File startdir = new File(startDir); if (startdir.isDirectory()) dirs.push(startdir); /* walk through the directories */ while (dirs.size() > 0) { File file = (File) dirs.pop(); File[] found = file.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { File tmp = new File(dir.getPath() + "/" + name); /* Only allowing XML files as spring configuration files */ if ((name.endsWith(".xml") || tmp.isDirectory()) && !name.startsWith("CVS") && !name.startsWith(".svn")) { return true; } else { return false; } } }); for (int i = 0; i < found.length; i++) { /* Subfolder support */ if (found[i].isDirectory()) dirs.push(found[i]); else { if ((testName + ".xml").equalsIgnoreCase(found[i].getName())) { String fileName = found[i].getPath(); fileName = fileName.substring(0, (fileName.length()-".xml".length())); fileName = fileName.substring(startDir.length()).replace('\\', '.'); if (log.isDebugEnabled()) { log.debug("Found test '" + fileName + "'"); } return fileName; } } } } throw new CitrusRuntimeException("Could not find test with name '" + testName + "'. Test directory is: " + startDir); } }
package com.henrikrydgard.libnative; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.Field; import java.util.List; import java.util.Locale; import java.util.UUID; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.ActivityManager; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.ConfigurationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.graphics.PixelFormat; import android.graphics.Point; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Vibrator; import android.text.InputType; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.InputDevice; import android.view.InputEvent; import android.view.KeyEvent; import android.view.HapticFeedbackConstants; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.Toast; class Installation { private static String sID = null; private static final String INSTALLATION = "INSTALLATION"; public synchronized static String id(Context context) { if (sID == null) { File installation = new File(context.getFilesDir(), INSTALLATION); try { if (!installation.exists()) writeInstallationFile(installation); sID = readInstallationFile(installation); } catch (Exception e) { // We can't even open a file for writing? Then we can't get a unique-ish installation id. return "BROKENAPPUSERFILESYSTEM"; } } return sID; } private static String readInstallationFile(File installation) throws IOException { RandomAccessFile f = new RandomAccessFile(installation, "r"); byte[] bytes = new byte[(int) f.length()]; f.readFully(bytes); f.close(); return new String(bytes); } private static void writeInstallationFile(File installation) throws IOException { FileOutputStream out = new FileOutputStream(installation); String id = UUID.randomUUID().toString(); out.write(id.getBytes()); out.close(); } } public class NativeActivity extends Activity { // Remember to loadLibrary your JNI .so in a static {} block // Adjust these as necessary private static String TAG = "NativeActivity"; // Easy way to flip it on and off from code. private static final boolean useKitkatImmersiveMode = false; // Allows us to skip a lot of initialization on secondary calls to onCreate. private static boolean initialized = false; // Graphics and audio interfaces private NativeGLView mGLSurfaceView; private NativeAudioPlayer audioPlayer; protected NativeRenderer nativeRenderer; boolean useOpenSL = false; private String shortcutParam = ""; public static String runCommand; public static String commandParameter; public static String installID; // Remember settings for best audio latency private int optimalFramesPerBuffer; private int optimalSampleRate; // audioFocusChangeListener to listen to changes in audio state private AudioFocusChangeListener audioFocusChangeListener; private AudioManager audioManager; private Vibrator vibrator; // Allow for two connected gamepads but just consider them the same for now. // Actually this is not entirely true, see the code. InputDeviceState inputPlayerA; InputDeviceState inputPlayerB; String inputPlayerADesc; // Functions for the app activity to override to change behaviour. public boolean useLowProfileButtons() { return true; } @TargetApi(17) private void detectOptimalAudioSettings() { try { optimalFramesPerBuffer = Integer.parseInt(this.audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER)); optimalSampleRate = Integer.parseInt(this.audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE)); } catch (NumberFormatException e) { // Ignore, if we can't parse it it's bogus and zero is a fine value (means we couldn't detect it). } } String getApplicationLibraryDir(ApplicationInfo application) { String libdir = null; try { // Starting from Android 2.3, nativeLibraryDir is available: Field field = ApplicationInfo.class.getField("nativeLibraryDir"); libdir = (String) field.get(application); } catch (SecurityException e1) { } catch (NoSuchFieldException e1) { } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } if (libdir == null) { // Fallback for Android < 2.3: libdir = application.dataDir + "/lib"; } return libdir; } @TargetApi(13) void GetScreenSizeHC(Point size) { WindowManager w = getWindowManager(); w.getDefaultDisplay().getSize(size); } @SuppressWarnings("deprecation") void GetScreenSize(Point size) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { GetScreenSizeHC(size); } else { WindowManager w = getWindowManager(); Display d = w.getDefaultDisplay(); size.x = d.getWidth(); size.y = d.getHeight(); } } public void setShortcutParam(String shortcutParam) { this.shortcutParam = ((shortcutParam == null) ? "" : shortcutParam); } public void Initialize() { // Initialize audio classes. Do this here since detectOptimalAudioSettings() // needs audioManager this.audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); this.audioFocusChangeListener = new AudioFocusChangeListener(); if (Build.VERSION.SDK_INT >= 9) { // Native OpenSL is available. Let's use it! useOpenSL = true; } if (Build.VERSION.SDK_INT >= 17) { // Get the optimal buffer sz detectOptimalAudioSettings(); } Log.i(TAG, "onCreate"); // Get system information ApplicationInfo appInfo = null; PackageManager packMgmr = getPackageManager(); String packageName = getPackageName(); try { appInfo = packMgmr.getApplicationInfo(packageName, 0); } catch (NameNotFoundException e) { e.printStackTrace(); throw new RuntimeException("Unable to locate assets, aborting..."); } String libraryDir = getApplicationLibraryDir(appInfo); File sdcard = Environment.getExternalStorageDirectory(); Display display = ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); @SuppressWarnings("deprecation") int scrPixelFormat = display.getPixelFormat(); Point size = new Point(); GetScreenSize(size); int scrWidth = size.x; int scrHeight = size.y; float scrRefreshRate = display.getRefreshRate(); String externalStorageDir = sdcard.getAbsolutePath(); String dataDir = this.getFilesDir().getAbsolutePath(); String apkFilePath = appInfo.sourceDir; DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int dpi = metrics.densityDpi; // We only use dpi to calculate the width. Smaller aspect ratios have giant text despite high DPI. // Uh, I mean, this makes no sense. What was I thinking when I wrote this? Let's just use the DPI as it is. // dpi = (int)((float)dpi * ((float)scrWidth/(float)scrHeight) / (16.0/9.0)); // Adjust to 16:9 String deviceType = Build.MANUFACTURER + ":" + Build.MODEL; String languageRegion = Locale.getDefault().getLanguage() + "_" + Locale.getDefault().getCountry(); NativeApp.audioConfig(optimalFramesPerBuffer, optimalSampleRate); NativeApp.init(dpi, deviceType, languageRegion, apkFilePath, dataDir, externalStorageDir, libraryDir, shortcutParam, installID, useOpenSL); // OK, config should be initialized, we can query for screen rotation. if (Build.VERSION.SDK_INT >= 9) { updateScreenRotation(); } /* if (NativeApp.isLandscape()) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); }*/ Log.i(TAG, "Device: " + deviceType); Log.i(TAG, "W : " + scrWidth + " H: " + scrHeight + " rate: " + scrRefreshRate + " fmt: " + scrPixelFormat + " dpi: " + dpi); // Detect OpenGL support. // We don't currently use this detection for anything but good to have in the log. if (!detectOpenGLES20()) { Log.i(TAG, "OpenGL ES 2.0 NOT detected. Things will likely go badly."); } else { if (detectOpenGLES30()) { Log.i(TAG, "OpenGL ES 3.0 detected."); } else { Log.i(TAG, "OpenGL ES 2.0 detected."); } } vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE); if (Build.VERSION.SDK_INT >= 11) { checkForVibrator(); } /* editText = new EditText(this); editText.setText("Hello world"); addContentView(editText, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); */ // inputBox("Please ener a s", "", "Save"); } @TargetApi(9) private void updateScreenRotation() { // Query the native application on the desired rotation. int rot = 0; String rotString = NativeApp.queryConfig("screenRotation"); try { rot = Integer.parseInt(rotString); } catch (NumberFormatException e) { Log.e(TAG, "Invalid rotation: " + rotString); return; } Log.i(TAG, "Rotation requested: " + rot); switch (rot) { case 0: setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); break; case 1: setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); break; case 2: setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); break; case 3: setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); break; case 4: setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); break; } } // Need API 11 to check for existence of a vibrator? Zany. @TargetApi(11) public void checkForVibrator() { if (Build.VERSION.SDK_INT >= 11) { if (!vibrator.hasVibrator()) { vibrator = null; } } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); installID = Installation.id(this); if (!initialized) { Initialize(); initialized = true; } // Keep the screen bright - very annoying if it goes dark when tilting away Window window = this.getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setVolumeControlStream(AudioManager.STREAM_MUSIC); // Initialize audio and tell PPSSPP to gain audio focus if (!useOpenSL) { audioPlayer = new NativeAudioPlayer(); } NativeAudioPlayer.gainAudioFocus(this.audioManager, this.audioFocusChangeListener); NativeApp.audioInit(); mGLSurfaceView = new NativeGLView(this); mGLSurfaceView.setEGLContextClientVersion(2); // Setup the GLSurface and ask android for the correct // Number of bits for r, g, b, a, depth and stencil components // The PSP only has 16-bit Z so that should be enough. // Might want to change this for other apps (24-bit might be useful). // Actually, we might be able to do without both stencil and depth in // the back buffer, but that would kill non-buffered rendering. // It appears some gingerbread devices blow up if you use a config chooser at all ???? (Xperia Play) //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // On some (especially older devices), things blow up later (EGL_BAD_MATCH) if we don't set the format here, // if we specify that we want destination alpha in the config chooser, which we do. // Needed to avoid banding on Ouya? if (Build.MANUFACTURER == "OUYA") { mGLSurfaceView.getHolder().setFormat(PixelFormat.RGBX_8888); mGLSurfaceView.setEGLConfigChooser(new NativeEGLConfigChooser()); } nativeRenderer = new NativeRenderer(this); mGLSurfaceView.setRenderer(nativeRenderer); setContentView(mGLSurfaceView); if (Build.VERSION.SDK_INT >= 14) { darkenOnScreenButtons(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setImmersiveMode(); } } @Override protected void onStop() { super.onStop(); Log.i(TAG, "onStop - do nothing, just let Android switch away"); } @Override protected void onDestroy() { super.onDestroy(); Log.i(TAG, "onDestroy"); mGLSurfaceView.onDestroy(); nativeRenderer.onDestroyed(); NativeApp.audioShutdown(); // Probably vain attempt to help the garbage collector... audioPlayer = null; mGLSurfaceView = null; audioFocusChangeListener = null; audioManager = null; } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public void darkenOnScreenButtons() { if (useLowProfileButtons()) { mGLSurfaceView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); } } @TargetApi(Build.VERSION_CODES.KITKAT) public void setImmersiveMode() { // this.setImmersive(true); // This is an entirely different kind of immersive mode - hides some notification if (useKitkatImmersiveMode) { int flags = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; if (useLowProfileButtons()) { flags |= View.SYSTEM_UI_FLAG_LOW_PROFILE; } mGLSurfaceView.setSystemUiVisibility(flags); } } private boolean detectOpenGLES20() { ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); ConfigurationInfo info = am.getDeviceConfigurationInfo(); return info.reqGlEsVersion >= 0x20000; } private boolean detectOpenGLES30() { ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); ConfigurationInfo info = am.getDeviceConfigurationInfo(); return info.reqGlEsVersion >= 0x30000; } @Override protected void onPause() { super.onPause(); Log.i(TAG, "onPause"); NativeAudioPlayer.loseAudioFocus(this.audioManager, this.audioFocusChangeListener); if (audioPlayer != null) { audioPlayer.stop(); } Log.i(TAG, "nativeapp pause"); NativeApp.pause(); Log.i(TAG, "gl pause"); mGLSurfaceView.onPause(); Log.i(TAG, "onPause returning"); } @Override protected void onResume() { super.onResume(); Log.i(TAG, "onResume"); if (mGLSurfaceView != null) { mGLSurfaceView.onResume(); } else { Log.e(TAG, "mGLSurfaceView really shouldn't be null in onResume"); } NativeAudioPlayer.gainAudioFocus(this.audioManager, this.audioFocusChangeListener); if (audioPlayer != null) { audioPlayer.play(); } NativeApp.resume(); if (Build.VERSION.SDK_INT >= 14) { darkenOnScreenButtons(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setImmersiveMode(); } } // Prevent destroying and recreating the main activity when the device rotates etc, // since this would stop the sound. @Override public void onConfigurationChanged(Configuration newConfig) { // Ignore orientation change super.onConfigurationChanged(newConfig); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setImmersiveMode(); } } // We simply grab the first input device to produce an event and ignore all others that are connected. @TargetApi(Build.VERSION_CODES.GINGERBREAD) private InputDeviceState getInputDeviceState(InputEvent event) { InputDevice device = event.getDevice(); if (device == null) { return null; } if (inputPlayerA == null) { Log.i(TAG, "Input player A registered"); inputPlayerA = new InputDeviceState(device); inputPlayerADesc = getInputDesc(device); } if (inputPlayerA.getDevice() == device) { return inputPlayerA; } if (inputPlayerB == null) { Log.i(TAG, "Input player B registered"); inputPlayerB = new InputDeviceState(device); } if (inputPlayerB.getDevice() == device) { return inputPlayerB; } return inputPlayerA; } // We grab the keys before onKeyDown/... even see them. This is also better because it lets us // distinguish devices. @Override public boolean dispatchKeyEvent(KeyEvent event) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { InputDeviceState state = getInputDeviceState(event); if (state == null) { return super.dispatchKeyEvent(event); } // Let's let volume and back through to dispatchKeyEvent. boolean passThrough = false; switch (event.getKeyCode()) { case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_VOLUME_DOWN: case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_VOLUME_MUTE: case KeyEvent.KEYCODE_MENU: passThrough = true; break; default: break; } switch (event.getAction()) { case KeyEvent.ACTION_DOWN: if (state.onKeyDown(event) && !passThrough) { return true; } break; case KeyEvent.ACTION_UP: if (state.onKeyUp(event) && !passThrough) { return true; } break; } } // Let's go through the old path (onKeyUp, onKeyDown). return super.dispatchKeyEvent(event); } @TargetApi(16) static public String getInputDesc(InputDevice input) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { return input.getDescriptor(); } else { List<InputDevice.MotionRange> motions = input.getMotionRanges(); String fakeid = ""; for (InputDevice.MotionRange range : motions) fakeid += range.getAxis(); return fakeid; } } @Override @TargetApi(12) public boolean onGenericMotionEvent(MotionEvent event) { // Log.d(TAG, "onGenericMotionEvent: " + event); if ((event.getSource() & InputDevice.SOURCE_JOYSTICK) != 0) { if (Build.VERSION.SDK_INT >= 12) { InputDeviceState state = getInputDeviceState(event); if (state == null) { Log.w(TAG, "Joystick event but failed to get input device state."); return super.onGenericMotionEvent(event); } state.onJoystickMotion(event); return true; } } if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { switch (event.getAction()) { case MotionEvent.ACTION_HOVER_MOVE: // process the mouse hover movement... return true; case MotionEvent.ACTION_SCROLL: NativeApp.mouseWheelEvent(event.getX(), event.getY()); return true; } } return super.onGenericMotionEvent(event); } @SuppressLint("NewApi") @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Eat these keys, to avoid accidental exits / other screwups. // Maybe there's even more we need to eat on tablets? switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (event.isAltPressed()) { NativeApp.keyDown(0, 1004); // special custom keycode } else if (NativeApp.isAtTopLevel()) { Log.i(TAG, "IsAtTopLevel returned true."); return super.onKeyDown(keyCode, event); } else { NativeApp.keyDown(0, keyCode); } return true; case KeyEvent.KEYCODE_MENU: case KeyEvent.KEYCODE_SEARCH: NativeApp.keyDown(0, keyCode); return true; case KeyEvent.KEYCODE_VOLUME_DOWN: case KeyEvent.KEYCODE_VOLUME_UP: // NativeApp should ignore these. return super.onKeyDown(keyCode, event); case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: // Joysticks are supported in Honeycomb MR1 and later via the onGenericMotionEvent method. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1 && event.getSource() == InputDevice.SOURCE_JOYSTICK) { return super.onKeyDown(keyCode, event); } // Fall through default: // send the rest of the keys through. // TODO: get rid of the three special cases above by adjusting the native side of the code. // Log.d(TAG, "Key down: " + keyCode + ", KeyEvent: " + event); NativeApp.keyDown(0, keyCode); return true; } } @SuppressLint("NewApi") @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (event.isAltPressed()) { NativeApp.keyUp(0, 1004); // special custom keycode } else if (NativeApp.isAtTopLevel()) { Log.i(TAG, "IsAtTopLevel returned true."); return super.onKeyUp(keyCode, event); } else { NativeApp.keyUp(0, keyCode); } return true; case KeyEvent.KEYCODE_MENU: case KeyEvent.KEYCODE_SEARCH: // Search probably should also be ignored. We send it to the app. NativeApp.keyUp(0, keyCode); return true; case KeyEvent.KEYCODE_VOLUME_DOWN: case KeyEvent.KEYCODE_VOLUME_UP: return super.onKeyUp(keyCode, event); case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: // Joysticks are supported in Honeycomb MR1 and later via the onGenericMotionEvent method. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1 && event.getSource() == InputDevice.SOURCE_JOYSTICK) { return super.onKeyUp(keyCode, event); } // Fall through default: // send the rest of the keys through. // TODO: get rid of the three special cases above by adjusting the native side of the code. // Log.d(TAG, "Key down: " + keyCode + ", KeyEvent: " + event); NativeApp.keyUp(0, keyCode); return true; } } @TargetApi(11) private AlertDialog.Builder createDialogBuilderWithTheme() { return new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_DARK); } // The return value is sent elsewhere. TODO in java, in SendMessage in C++. public void inputBox(String title, String defaultText, String defaultAction) { final FrameLayout fl = new FrameLayout(this); final EditText input = new EditText(this); input.setGravity(Gravity.CENTER); FrameLayout.LayoutParams editBoxLayout = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT); editBoxLayout.setMargins(2, 20, 2, 20); fl.addView(input, editBoxLayout); input.setInputType(InputType.TYPE_CLASS_TEXT); input.setText(defaultText); input.selectAll(); AlertDialog.Builder bld = null; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) bld = new AlertDialog.Builder(this); else bld = createDialogBuilderWithTheme(); AlertDialog dlg = bld .setView(fl) .setTitle(title) .setPositiveButton(defaultAction, new DialogInterface.OnClickListener(){ public void onClick(DialogInterface d, int which) { NativeApp.sendMessage("inputbox_completed", input.getText().toString()); d.dismiss(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface d, int which) { NativeApp.sendMessage("inputbox_failed", ""); d.cancel(); } }).create(); dlg.setCancelable(true); dlg.show(); } public boolean processCommand(String command, String params) { if (command.equals("launchBrowser")) { Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(params)); startActivity(i); return true; } else if (command.equals("launchEmail")) { Intent send = new Intent(Intent.ACTION_SENDTO); String uriText; uriText = "mailto:email@gmail.com" + "?subject=Your app is..." + "&body=great! Or?"; uriText = uriText.replace(" ", "%20"); Uri uri = Uri.parse(uriText); send.setData(uri); startActivity(Intent.createChooser(send, "E-mail the app author!")); return true; } else if (command.equals("sharejpeg")) { Intent share = new Intent(Intent.ACTION_SEND); share.setType("image/jpeg"); share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + params)); startActivity(Intent.createChooser(share, "Share Picture")); } else if (command.equals("sharetext")) { Intent sendIntent = new Intent(); sendIntent.setType("text/plain"); sendIntent.putExtra(Intent.EXTRA_TEXT, params); sendIntent.setAction(Intent.ACTION_SEND); startActivity(sendIntent); } else if (command.equals("showTwitter")) { String twitter_user_name = params; try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("twitter://user?screen_name=" + twitter_user_name))); } catch (Exception e) { startActivity(new Intent( Intent.ACTION_VIEW, Uri.parse("https://twitter.com/#!/" + twitter_user_name))); } } else if (command.equals("launchMarket")) { // Don't need this, can just use launchBrowser with a market: // http://developer.android.com/guide/publishing/publishing.html#marketintent return false; } else if (command.equals("toast")) { Toast toast = Toast.makeText(this, params, Toast.LENGTH_SHORT); toast.show(); return true; } else if (command.equals("showKeyboard")) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); // No idea what the point of the ApplicationWindowToken is or if it // matters where we get it from... inputMethodManager.toggleSoftInputFromWindow( mGLSurfaceView.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0); return true; } else if (command.equals("hideKeyboard")) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.toggleSoftInputFromWindow( mGLSurfaceView.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0); return true; } else if (command.equals("inputbox")) { String title = "Input"; String defString = ""; String[] param = params.split(":"); if (param[0].length() > 0) title = param[0]; if (param.length > 1) defString = param[1]; Log.i(TAG, "Launching inputbox: " + title + " " + defString); inputBox(title, defString, "OK"); return true; } else if (command.equals("vibrate")) { if (vibrator != null) { int milliseconds = -1; if (params != "") { try { milliseconds = Integer.parseInt(params); } catch (NumberFormatException e) { } } // Special parameters to perform standard haptic feedback // operations // -1 = Standard keyboard press feedback // -2 = Virtual key press // -3 = Long press feedback // Note that these three do not require the VIBRATE Android switch (milliseconds) { case -1: mGLSurfaceView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP); break; case -2: mGLSurfaceView.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); break; case -3: mGLSurfaceView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); break; default: vibrator.vibrate(milliseconds); break; } } return true; } else if (command.equals("finish")) { finish(); } else if (command.equals("rotate")) { if (Build.VERSION.SDK_INT >= 9) { updateScreenRotation(); } } return false; } }
package at.ac.univie.isc.asio.jaxrs; import javax.ws.rs.core.MediaType; /** * Common request and response types supported in asio. */ public enum Mime { // request types QUERY_SQL(MediaType.valueOf("application/sql-query")) , QUERY_SPARQL(MediaType.valueOf("application/sparql-query")) , UPDATE_SQL(MediaType.valueOf("application/sql-update")) , UPDATE_SPARQL(MediaType.valueOf("application/sparql-update")) // response types , CSV(MediaType.valueOf("text/csv")) , XML(MediaType.APPLICATION_XML_TYPE) , JSON(MediaType.APPLICATION_JSON_TYPE) ; private final MediaType type; private Mime(final MediaType type) { this.type = type; } public MediaType type() { return type; } @Override public String toString() { return type.toString(); } }
package com.dragonheart.test; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import com.dragonheart.dijkstra.Point; import com.dragonheart.dijkstra.Edge; import com.dragonheart.dijkstra.DijkstraGraph; public class testDijkstraGraph { private Point a, b, c, d, e, f; private Edge A, B, C, D, E, F, G, H; private DijkstraGraph graph; @Before public void setUp() throws Exception { a = new Point(2, 0); b = new Point(0, 2); c = new Point(2, 2); d = new Point(5, 2); e = new Point(2, 5); f = new Point(0, 5); A = new Edge(a, b, 1.0); B = new Edge(a, c, 3.0); C = new Edge(a, d, 5.0); D = new Edge(b, c, 1.0); E = new Edge(b, e, 3.0); F = new Edge(c, e, 1.0); G = new Edge(d, e, 1.0); H = new Edge(b, f, 1.0); graph = new DijkstraGraph(); graph.addPoint(a); graph.addPoint(b); graph.addPoint(c); graph.addPoint(d); graph.addPoint(e); graph.addPoint(f); graph.addEdge(A); graph.addEdge(B); graph.addEdge(C); graph.addEdge(D); graph.addEdge(E); graph.addEdge(F); graph.addEdge(G); graph.addEdge(H); } /** * Test method for {@link com.dragonheart.dijkstra.DijkstraGraph#processGraph()} */ @Test public final void testProcessGraph_WhenNoSourcesNodes_ReturnFalse() { assertFalse(graph.processGraph()); } /** * Test method for {@link com.dragonheart.dijkstra.DijkstraGraph#processGraph()} */ @Test public final void testProcessGraph_WithSourceNodes_ReturnTrue() { graph.setSource(a, 0.0); assertTrue(graph.processGraph()); } /** * Test method for {@link com.dragonheart.dijkstra.DijkstraGraph#processGraph()} */ @Test public final void testProcessGraph_BasicResults() { graph.setSource(e, 0.0); graph.processGraph(); List<Point> path = graph.getPathFrom(a); assertTrue(path.get(0).aggregateCost == 3); } /** * Test method for {@link com.dragonheart.dijkstra.DijkstraGraph#processGraph()} */ @Test public final void testProcessGraph_StackingResults() { graph.setSource(e, 0.0); graph.processGraph(); graph.processGraph(1.0); List<Point> path = graph.getPathFrom(a); assertTrue(path.get(0).aggregateCost == 6); } /** * Test method for {@link com.dragonheart.dijkstra.DijkstraGraph#getPathFrom(Point)} */ @Test public final void testGetPathFrom_WithSingleSourceNode() { graph.setSource(e, 0.0); graph.processGraph(); List<Point> path = graph.getPathFrom(a); assertTrue(path.get(0) == a); assertTrue(path.get(1) == b); assertTrue(path.get(2) == c); assertTrue(path.get(3) == e); } /** * Test method for {@link com.dragonheart.dijkstra.DijkstraGraph#getPathFrom(Point)} */ @Test public final void testGetPathFrom_WithMultipleSourceNodes() { ArrayList<Point> nodes = new ArrayList<Point>(); nodes.add(e); nodes.add(f); graph.setSources(nodes, 0.0); graph.processGraph(); List<Point> path = graph.getPathFrom(a); assertTrue(path.get(0) == a); assertTrue(path.get(1) == b); assertTrue(path.get(2) == f); } }
package org.eigenbase.sql.type; import org.eigenbase.resource.*; import org.eigenbase.sql.*; import org.eigenbase.sql.validate.*; import org.eigenbase.reltype.*; import org.eigenbase.util.*; import java.util.*; /** * Parameter type-checking strategy where all operand types must be * either the same or null. * * @author Wael Chatila * @version $Id$ */ public class SameOperandTypeChecker extends ExplicitOperandTypeChecker { private final int nOperands; public SameOperandTypeChecker( SqlTypeName [][] explicitTypes) { super(explicitTypes); nOperands = explicitTypes.length; } public boolean check( SqlValidator validator, SqlValidatorScope scope, SqlCall call, boolean throwOnFailure) { RelDataType [] types = new RelDataType[nOperands]; for (int i = 0; i < nOperands; ++i) { types[i] = validator.deriveType(scope, call.operands[i]); } RelDataType nullType = validator.getTypeFactory().createSqlType(SqlTypeName.Null); int prev = -1; for (int i = 0; i < nOperands; ++i) { if (types[i] == nullType) { continue; } if (prev == -1) { prev = i; } else { RelDataTypeFamily family1 = types[i].getFamily(); RelDataTypeFamily family2 = types[prev].getFamily(); // REVIEW jvs 2-June-2005: This is needed to keep // the Saffron type system happy. if (types[i].getSqlTypeName() != null) { family1 = types[i].getSqlTypeName().getFamily(); } if (types[prev].getSqlTypeName() != null) { family2 = types[prev].getSqlTypeName().getFamily(); } if (family1 == family2) { continue; } if (!throwOnFailure) { return false; } throw validator.newValidationError( call, EigenbaseResource.instance().newNeedSameTypeParameter()); } } return true; } } // End SameOperandTypeChecker.java
package urllistcompare; import urllistcompare.util.*; import java.util.ArrayList; import urllistcompare.exceptions.*; /** * @author Rocco Barbini * @email roccobarbi@gmail.com * * A single normalised URL, which includes 2 linked lists of URLElements (for the formats that are being * compared). * This class must manage at least: * - the addition of new URLElement instances, which must be processed to increase the relevant page impressions count; * - the decision if one of the formats is missing (0 page impressions); * - the computation of relative and absolute differences between the two formats; * - the extraction of the list of URLElements for each URL format. * * If the url field is null, it's a signal that the element is broken and MUST NOT be used. * */ public class URLNorm { private LinkedList<URLElement> element[]; private int impressions[]; private URLFormat format[]; public URLNorm() { element = new LinkedList[2]; impressions = new int[2]; format = new URLFormat[2]; } public URLNorm(URLFormat format0, URLFormat format1) { element = new LinkedList[2]; impressions = new int[2]; format = new URLFormat[2]; format[0] = format0; format[1] = format1; } /** * Adds a URLElement instance to the relevant LinkeList and adds its page impressions count to the relevant array. * Checks that both the URLElement and the current URLNorm are properly set. * * @param u the URLElement that needs to be added * @throws InvalidURLNormException if at least one of the formats has not been set correctly or if the URL has the wrong format */ public void add(URLElement u) throws InvalidURLNormException { if(format[0] == null || format[1] == null) throw new InvalidURLNormException("Tried to add an element" + "without defining both formats."); try{ if(u.getFormat() == format[0]){ element[0].add(u); impressions[0] += u.getImpressions(); } else if (u.getFormat() == format[1]){ element[1].add(u); impressions[1] += u.getImpressions(); } else { System.err.println("Invalid format: tried to add to a URLNorm instance a URLElement instance with the wrong URLFormat."); } } catch (InvalidUrlException e) { System.err.println("InvalidUrlException: tried to add an empty URLElement instance to a URLNorm instance."); } } /** * Checks if the URL is completely missing (zero page impressions) in at least one of the formats. * * @param f the URLFormat that is been checked * @return true if the format passed as an argument recorded zero impressions, false otherwise * @throws InvalidURLNormException if at least one of the formats has not been set correctly or the wrong URLFormat is passed as an argument */ public boolean isMissing(URLFormat f) throws InvalidURLNormException { boolean output = false; if(format[0] == null || format[1] == null) throw new InvalidURLNormException("Tried to check if a format is missing" + "without defining both formats."); if(format[0] != f && format[1] != f) throw new InvalidURLNormException("Tried to check if a format is missing" + "with a format that is not included in this URLNorm instance."); if((f == format[0] && impressions[0] == 0) || (f == format[1] && impressions[1] == 0)){ output = true; } return output; } /** * Checks the absolute difference between the page impressions of the specified format and those of the other format. * If there are formats A and B, andad format A is passed as argument, the result is A - B. * * @param f the format to check * @return the difference of f relative to the other format * @throws InvalidURLNormException if at least one of the formats has not been set correctly or the wrong URLFormat is passed as an argument */ public int getDifference(URLFormat f) throws InvalidURLNormException { int output = 0; if(format[0] == null || format[1] == null) throw new InvalidURLNormException("Tried to check if a format is missing" + "without defining both formats."); if(format[0] != f && format[1] != f) throw new InvalidURLNormException("Tried to check if a format is missing" + "with a format that is not included in this URLNorm instance."); if(f == format[0]){ output = impressions[0] - impressions[1]; } else { output = impressions[1] - impressions[0]; } return output; } /** * Checks the list of URLElements of a specific format. * * @param f the format for which the list of elements needs to be extracted * @return the list of URLElements of a specific format * @throws InvalidURLNormException if at least one of the formats has not been set correctly or the wrong URLFormat is passed as an argument */ public ArrayList<URLElement> getElements(URLFormat f) throws InvalidURLNormException{ int index = 0; if(format[0] == null || format[1] == null) throw new InvalidURLNormException("Tried to check if a format is missing" + "without defining both formats."); if(format[0] == f){ index = 0; } else if(format[1] == f){ index = 1; } else { throw new InvalidURLNormException("Tried to check if a format is missing" + "with a format that is not included in this URLNorm instance."); } ArrayList<URLElement> output = element[index].toArrayList(); return output; } // TODO: add functionality }
package invtweaks.forge; import invtweaks.*; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.oredict.OreDictionary; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Field; import java.util.*; public class ForgeItemTreeListener implements InvTweaksItemTreeListener { @SuppressWarnings("unchecked") @Override public void onTreeLoaded(InvTweaksItemTree tree) { try { Field toolClassesField = ForgeHooks.class.getDeclaredField("toolClasses"); toolClassesField.setAccessible(true); Map<Item, List> toolClasses = (Map<Item, List>)toolClassesField.get(null); Map<String, Map> toolClassesByName = new HashMap<String, Map>(); for(Item i : toolClasses.keySet()) { List entry = toolClasses.get(i); String className = (String)entry.get(0); int level = (Integer)entry.get(1); if(!toolClassesByName.containsKey(className)) { Map<Item, Integer> map = new HashMap<Item, Integer>(); map.put(i, level); toolClassesByName.put(className, map); } else { toolClassesByName.get(className).put(i, level); } } for(String name : toolClassesByName.keySet()) { tree.addCategory(tree.getRootCategory().getName(), new InvTweaksItemTreeCategory("forge_toolClasses_" + name)); Map itemsByPriority = toolClassesByName.get(name); List<Item> itemList = new ArrayList<Item>(itemsByPriority.keySet()); Collections.sort(itemList, new ItemPriorityComparator(itemsByPriority)); for(Item i : itemList) { tree.addItem("forge_toolClasses_" + name, new InvTweaksItemTreeItem(i.getItemName(), i.itemID, -1, (Integer)itemsByPriority.get(i))); } } for(String name : OreDictionary.getOreNames()) { tree.addCategory(tree.getRootCategory().getName(), new InvTweaksItemTreeCategory("forge_oreDict_" + name)); for(ItemStack i : OreDictionary.getOres(name)) { tree.addItem("forge_oreDict_" + name, new InvTweaksItemTreeItem(i.getItemName(), i.itemID, i.getItemDamage(), 0)); } } } catch(Exception e) { StringWriter stringWriter = new StringWriter(); e.printStackTrace(new PrintWriter(stringWriter)); stringWriter.flush(); InvTweaks.log.warning(stringWriter.toString()); } } private class ItemPriorityComparator implements Comparator<Item> { Map<Item, Integer> priorities; ItemPriorityComparator(Map<Item, Integer> prios) { priorities = prios; } @Override public int compare(Item o1, Item o2) { return priorities.get(o1) - priorities.get(o2); } } }
package weardrip.weardrip; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Point; import android.graphics.Rect; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.wearable.watchface.CanvasWatchFaceService; import android.support.wearable.watchface.WatchFaceService; import android.support.wearable.watchface.WatchFaceStyle; import android.text.format.DateFormat; import android.text.format.Time; import android.util.Log; import android.view.Display; import android.view.LayoutInflater; import android.view.SurfaceHolder; import android.view.View; import android.view.WindowInsets; import android.view.WindowManager; import android.widget.TextView; import com.eveningoutpost.dexdrip.Models.BgReading; import com.eveningoutpost.dexdrip.UtilityModels.CollectionServiceStarter; import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.interfaces.datasets.ILineDataSet; import com.github.mikephil.charting.listener.OnChartValueSelectedListener; import com.github.mikephil.charting.utils.ColorTemplate; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.TimeUnit; public class wearDripWatchFace extends CanvasWatchFaceService { private static final Typeface NORMAL_TYPEFACE = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL); public static final int FUZZER = (1000 * 30 * 5); public double end_time = (new Date().getTime() + (60000 * 10)) / FUZZER; private final int numValues =(60/5)*24; public double start_time = end_time - ((60000 * 60 * 24)) / FUZZER; private final List<BgReading> bgReadings = BgReading.latestForGraph(numValues, (long) (start_time * FUZZER)); /** * Update rate in milliseconds for interactive mode. We update once a second since seconds are * displayed in interactive mode. */ private static final long INTERACTIVE_UPDATE_RATE_MS = TimeUnit.SECONDS.toMillis(1); @Override public Engine onCreateEngine() { CollectionServiceStarter.newStart(this); return new Engine(); } boolean mLowBitAmbient; private LineChart lineChart; private int year = 2015; private LineDataSet createSet() { LineDataSet set = new LineDataSet(null, "Dynamic Data"); set.setAxisDependency(YAxis.AxisDependency.LEFT); set.setColor(ColorTemplate.getHoloBlue()); set.setCircleColor(Color.WHITE); set.setLineWidth(2f); set.setCircleRadius(4f); set.setFillAlpha(65); set.setFillColor(ColorTemplate.getHoloBlue()); set.setHighLightColor(Color.rgb(244, 117, 117)); set.setValueTextColor(Color.WHITE); set.setValueTextSize(9f); set.setDrawValues(false); return set; } ArrayList<String> XAxisTimeValue = new ArrayList<String>(); public void addEntry() { LineData data = lineChart.getData(); if (data != null) { ILineDataSet set = data.getDataSetByIndex(0); // set.addEntry(...); // can be called as well if (set == null) { set = createSet(); data.addDataSet(set); } // add a new x-value first Date date = new Date(); // given date Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance calendar.setTime(date); // assigns calendar to given date int inthours = calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format String hourString = String.format("%02d", inthours); XAxisTimeValue.add(hourString); data.addXValue(XAxisTimeValue.get(data.getXValCount())); data.addEntry(new Entry((float) (Math.random() * 40) + 30f, set.getEntryCount()), 0); // let the chart know it's data has changed lineChart.notifyDataSetChanged(); // limit the number of visible entries lineChart.setVisibleXRangeMaximum(120); // mChart.setVisibleYRange(30, AxisDependency.LEFT); // move to the latest entry lineChart.moveViewToX(data.getXValCount() - 121); // this automatically refreshes the chart (calls invalidate()) // mChart.moveViewTo(data.getXValCount()-7, 55f, // AxisDependency.LEFT); } } private class Engine extends CanvasWatchFaceService.Engine implements OnChartValueSelectedListener { static final int MSG_UPDATE_TIME = 0; /** * Handler to update the time periodically in interactive mode. */ final Handler mUpdateTimeHandler = new Handler() { @Override public void handleMessage(Message message) { switch (message.what) { case MSG_UPDATE_TIME: invalidate(); if (shouldTimerBeRunning()) { long timeMs = System.currentTimeMillis(); long delayMs = INTERACTIVE_UPDATE_RATE_MS - (timeMs % INTERACTIVE_UPDATE_RATE_MS); mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs); } break; } } }; final BroadcastReceiver mTimeZoneReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { mTime.clear(intent.getStringExtra("time-zone")); mTime.setToNow(); } }; boolean mRegisteredTimeZoneReceiver = false; boolean mAmbient; Time mTime; float mXOffset = 0; float mYOffset = 0; private int specW, specH; private View myLayout; private TextView day, month, hour, minute, second, sgv, delta, watch_time, timestamp; private final Point displaySize = new Point(); /** * Whether the display supports fewer bits for each color in ambient mode. When true, we * disable anti-aliasing in ambient mode. */ @Override public void onCreate(SurfaceHolder holder) { super.onCreate(holder); setWatchFaceStyle(new WatchFaceStyle.Builder(wearDripWatchFace.this) .setCardPeekMode(WatchFaceStyle.PEEK_MODE_SHORT) .setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE) .setShowSystemUiTime(false) .setAcceptsTapEvents(true) .build()); Resources resources = wearDripWatchFace.this.getResources(); mTime = new Time(); // Inflate the layout that we're using for the watch face LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); myLayout = inflater.inflate(R.layout.wear_drip_watchface_layout, null); // Load the display spec - we'll need this later for measuring myLayout Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); display.getSize(displaySize); // Find some views for later use sgv = (TextView) myLayout.findViewById(R.id.sgv); delta = (TextView) myLayout.findViewById(R.id.delta); timestamp = (TextView) myLayout.findViewById(R.id.timestamp); watch_time = (TextView) myLayout.findViewById(R.id.watch_time); lineChart = (LineChart) myLayout.findViewById(R.id.chart); lineChart.setDescription(""); lineChart.setNoDataTextDescription("You need to provide data for the chart."); lineChart.setDrawGridBackground(false); //lineChart.setBackgroundColor(-1); lineChart.invalidate(); lineChart.setOnChartValueSelectedListener(this); // enable touch gestures lineChart.setTouchEnabled(false); // enable scaling and dragging lineChart.setDragEnabled(false); lineChart.setScaleEnabled(false); lineChart.setDrawGridBackground(false); // if disabled, scaling can be done on x- and y-axis separately lineChart.setPinchZoom(false); LineData data = new LineData(); data.setValueTextColor(Color.WHITE); // add empty data lineChart.setData(data); // get the legend (only possible after setting data) Legend l = lineChart.getLegend(); // modify the legend ... // l.setPosition(LegendPosition.LEFT_OF_CHART); l.setForm(Legend.LegendForm.LINE); l.setTextColor(Color.WHITE); XAxis xl = lineChart.getXAxis(); xl.setTextColor(Color.WHITE); xl.setDrawGridLines(false); xl.setAvoidFirstLastClipping(true); xl.setSpaceBetweenLabels(5); xl.setEnabled(true); YAxis leftAxis = lineChart.getAxisLeft(); leftAxis.setTextColor(Color.WHITE); leftAxis.setAxisMaxValue(100f); leftAxis.setAxisMinValue(0f); leftAxis.setDrawGridLines(true); YAxis rightAxis = lineChart.getAxisRight(); rightAxis.setEnabled(false); } @Override public void onDestroy() { mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME); super.onDestroy(); } @Override public void onVisibilityChanged(boolean visible) { super.onVisibilityChanged(visible); if (visible) { registerReceiver(); // Update time zone in case it changed while we weren't visible. mTime.clear(TimeZone.getDefault().getID()); mTime.setToNow(); } else { unregisterReceiver(); } // Whether the timer should be running depends on whether we're visible (as well as // whether we're in ambient mode), so we may need to start or stop the timer. updateTimer(); } private void registerReceiver() { if (mRegisteredTimeZoneReceiver) { return; } mRegisteredTimeZoneReceiver = true; IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED); wearDripWatchFace.this.registerReceiver(mTimeZoneReceiver, filter); } private void unregisterReceiver() { if (!mRegisteredTimeZoneReceiver) { return; } mRegisteredTimeZoneReceiver = false; wearDripWatchFace.this.unregisterReceiver(mTimeZoneReceiver); } @Override public void onApplyWindowInsets(WindowInsets insets) { super.onApplyWindowInsets(insets); if (insets.isRound()) { mXOffset = mYOffset = 0; } else { mXOffset = mYOffset = 0; } // Recompute the MeasureSpec fields - these determine the actual size of the layout specW = View.MeasureSpec.makeMeasureSpec(displaySize.x, View.MeasureSpec.EXACTLY); specH = View.MeasureSpec.makeMeasureSpec(displaySize.y, View.MeasureSpec.EXACTLY); } @Override public void onPropertiesChanged(Bundle properties) { super.onPropertiesChanged(properties); mLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false); } @Override public void onTimeTick() { super.onTimeTick(); invalidate(); } @Override public void onAmbientModeChanged(boolean inAmbientMode) { super.onAmbientModeChanged(inAmbientMode); if (mAmbient != inAmbientMode) { mAmbient = inAmbientMode; // Show/hide the seconds fields if (inAmbientMode) { //second.setVisibility(View.GONE); //myLayout.findViewById(R.id.chart).setVisibility(View.GONE); } else { //second.setVisibility(View.VISIBLE); //myLayout.findViewById(R.id.chart).setVisibility(View.VISIBLE); } invalidate(); } // Whether the timer should be running depends on whether we're visible (as well as // whether we're in ambient mode), so we may need to start or stop the timer. updateTimer(); } String bgvalue; public void showBG() { BgReading mBgReading; mBgReading = BgReading.last(); if (mBgReading != null) { double calculated_value = mBgReading.calculated_value; DecimalFormat df = new DecimalFormat("#", new DecimalFormatSymbols(Locale.ENGLISH)); bgvalue = String.valueOf(df.format(calculated_value)); } else { bgvalue = "n/a"; } } String timestamplastreading; public void getTimestampLastreading() { Long mTimeStampLastreading; mTimeStampLastreading = BgReading.getTimeSinceLastReading(); if (mTimeStampLastreading != null) { long minutesago=((mTimeStampLastreading)/1000)/60; timestamplastreading = String.valueOf(minutesago); } else { timestamplastreading = " } } String deltalastreading; public void unitizedDeltaString() { List<BgReading> last2 = BgReading.latest(2); if (BgReading.latest(2) != null) { if (last2.size() < 2 || last2.get(0).timestamp - last2.get(1).timestamp > 20 * 60 * 1000) { // don't show delta if there are not enough values or the values are more than 20 mintes apart deltalastreading = "???"; } double value = BgReading.currentSlope() * 5 * 60 * 1000; if (Math.abs(value) > 100) { // a delta > 100 will not happen with real BG values -> problematic sensor data deltalastreading = "ERR"; } DecimalFormat df = new DecimalFormat("#", new DecimalFormatSymbols(Locale.ENGLISH)); String delta_sign = ""; if (value > 0) { delta_sign = "+"; } deltalastreading = delta_sign + df.format(value); } else { deltalastreading = " } } @Override public void onDraw(Canvas canvas, Rect bounds) { // Get the current Time mTime.setToNow(); showBG(); getTimestampLastreading(); unitizedDeltaString(); delta.setText(deltalastreading); sgv.setText(bgvalue); watch_time.setText(String.format("%02d:%02d", mTime.hour, mTime.minute)); timestamp.setText(timestamplastreading + "′"); if (!mAmbient) { //second.setText(String.format("%02d", mTime.second)); } // Update the layout myLayout.measure(specW, specH); myLayout.layout(0, 0, myLayout.getMeasuredWidth(), myLayout.getMeasuredHeight()); // Draw it to the Canvas canvas.drawColor(Color.BLACK); canvas.translate(mXOffset, mYOffset); myLayout.draw(canvas); } /** * Starts the {@link #mUpdateTimeHandler} timer if it should be running and isn't currently * or stops it if it shouldn't be running but currently is. */ private void updateTimer() { mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME); if (shouldTimerBeRunning()) { mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME); } } /** * Returns whether the {@link #mUpdateTimeHandler} timer should be running. The timer should * only run when we're visible and in interactive mode. */ private boolean shouldTimerBeRunning() { return isVisible() && !isInAmbientMode(); } @Override public void onValueSelected(Entry e, int dataSetIndex, Highlight h) { } @Override public void onNothingSelected() { } @Override public void onTapCommand( @TapType int tapType, int x, int y, long eventTime) { switch (tapType) { case WatchFaceService.TAP_TYPE_TAP: break; case WatchFaceService.TAP_TYPE_TOUCH: addEntry(); break; case WatchFaceService.TAP_TYPE_TOUCH_CANCEL: break; default: super.onTapCommand(tapType, x, y, eventTime); break; } } } }
package com.psddev.dari.util; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Array; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Deque; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.UUID; /** Writer implementation that adds basic HTML formatting. */ public class HtmlWriter extends Writer { private static final String GRID_PADDING; static { StringBuilder gp = new StringBuilder(); for (int i = 0; i < 500; ++ i) { gp.append(" ."); } GRID_PADDING = gp.toString(); } private Writer delegate; private final Map<Class<?>, HtmlFormatter<Object>> defaultFormatters = new HashMap<Class<?>, HtmlFormatter<Object>>(); private final Map<Class<?>, HtmlFormatter<Object>> overrideFormatters = new HashMap<Class<?>, HtmlFormatter<Object>>(); private final Deque<String> tags = new ArrayDeque<String>(); /** Creates an instance. */ public HtmlWriter() { } /** * Creates an instance that writes to the given {@code delegate}. * * @param delegate May be {@code null}. */ public HtmlWriter(Writer delegate) { this.delegate = delegate; } /** * Returns the delegate. * * @return May be {@code null}. */ public Writer getDelegate() { return delegate; } /** * Sets the delegate. * * @param delegate May be {@code null}. */ public void setDelegate(Writer delegate) { this.delegate = delegate; } @SuppressWarnings("unchecked") public <T> void putDefault(Class<T> objectClass, HtmlFormatter<? super T> formatter) { defaultFormatters.put(objectClass, (HtmlFormatter<Object>) formatter); } @SuppressWarnings("unchecked") public <T> void putOverride(Class<T> objectClass, HtmlFormatter<? super T> formatter) { overrideFormatters.put(objectClass, (HtmlFormatter<Object>) formatter); } public void putAllStandardDefaults() { putDefault(null, HtmlFormatter.NULL); putDefault(Class.class, HtmlFormatter.CLASS); putDefault(Collection.class, HtmlFormatter.COLLECTION); putDefault(Date.class, HtmlFormatter.DATE); putDefault(Double.class, HtmlFormatter.FLOATING_POINT); putDefault(Enum.class, HtmlFormatter.ENUM); putDefault(Float.class, HtmlFormatter.FLOATING_POINT); putDefault(Map.class, HtmlFormatter.MAP); putDefault(Number.class, HtmlFormatter.NUMBER); putDefault(PaginatedResult.class, HtmlFormatter.PAGINATED_RESULT); putDefault(StackTraceElement.class, HtmlFormatter.STACK_TRACE_ELEMENT); putDefault(Throwable.class, HtmlFormatter.THROWABLE); // Optional. if (HtmlFormatter.JASPER_EXCEPTION_CLASS != null) { putDefault(HtmlFormatter.JASPER_EXCEPTION_CLASS, HtmlFormatter.JASPER_EXCEPTION); } } public void removeDefault(Class<?> objectClass) { defaultFormatters.remove(objectClass); } public void removeOverride(Class<?> objectClass) { overrideFormatters.remove(objectClass); } /** * Escapes the given {@code string} so that it's safe to use in * an HTML page. */ protected String escapeHtml(String string) { return StringUtils.escapeHtml(string); } /** * Writes the given {@code tag} with the given {@code attributes}. * * <p>This method doesn't keep state, so it should be used with doctype * declaration and self-closing tags like {@code img}.</p> */ public HtmlWriter writeTag(String tag, Object... attributes) throws IOException { if (tag == null) { throw new IllegalArgumentException("Tag can't be null!"); } Writer delegate = getDelegate(); delegate.write('<'); delegate.write(tag); if (attributes != null) { Map<String, Object> map = new LinkedHashMap<String, Object>(); addAttributes(map, attributes); for (Map.Entry<String, Object> entry : map.entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); if (!ObjectUtils.isBlank(name) && value != null) { delegate.write(' '); delegate.write(escapeHtml(name)); delegate.write("=\""); delegate.write(escapeHtml(value.toString())); delegate.write('"'); } } } delegate.write('>'); return this; } private void addAttributes(Map<String, Object> map, Object... attributes) { for (int i = 0, length = attributes.length; i < length; ++ i) { Object name = attributes[i]; if (name == null) { ++ i; } else if (name.getClass().isArray()) { addAttributes(map, ObjectUtils.to(Object[].class, name)); } else if (name instanceof Map) { for (Map.Entry<?, ?> entry : ((Map<?, ?>) name).entrySet()) { Object key = entry.getKey(); Object value = entry.getValue(); if (key != null && value != null) { map.put(key.toString(), value); } } } else { ++ i; if (i < length) { map.put(name.toString(), attributes[i]); } } } } /** * Writes the given start {@code tag} with the given {@code attributes}. * * <p>This method keeps state, so there should be a matching {@link #end} * call afterwards.</p> */ public HtmlWriter writeStart(String tag, Object... attributes) throws IOException { writeTag(tag, attributes); tags.addFirst(tag); return this; } /** Writes the end tag previously started with {@link #start}. */ public HtmlWriter writeEnd() throws IOException { String tag = tags.removeFirst(); if (tag == null) { throw new IllegalStateException("No more tags!"); } Writer delegate = getDelegate(); delegate.write("</"); delegate.write(tag); delegate.write('>'); return this; } /** * Escapes and writes the given {@code unescapedHtml}, or if it's * {@code null}, the given {@code defaultUnescapedHtml}. */ public HtmlWriter writeHtmlOrDefault(Object unescapedHtml, String defaultUnescapedHtml) throws IOException { getDelegate().write(escapeHtml(unescapedHtml == null ? defaultUnescapedHtml : unescapedHtml.toString())); return this; } /** * Escapes and writes the given {@code unescapedHtml}, or if it's * {@code null}, nothing. */ public HtmlWriter writeHtml(Object unescapedHtml) throws IOException { writeHtmlOrDefault(unescapedHtml, ""); return this; } /** Formats and writes the given {@code object}. */ public HtmlWriter writeObject(Object object) throws IOException { HtmlFormatter<Object> formatter; if (object == null) { formatter = overrideFormatters.get(null); if (formatter == null) { formatter = defaultFormatters.get(null); } if (formatter != null) { formatter.format(this, null); return this; } } else { if (formatWithMap(overrideFormatters, object)) { return this; } if (object instanceof HtmlObject) { ((HtmlObject) object).format(this); return this; } if (formatWithMap(defaultFormatters, object)) { return this; } } if (object != null && object.getClass().isArray()) { writeStart("ul"); for (int i = 0, length = Array.getLength(object); i < length; ++ i) { writeStart("li").writeObject(Array.get(object, i)).writeEnd(); } writeEnd(); return this; } return writeHtml(object); } private boolean formatWithMap( Map<Class<?>, HtmlFormatter<Object>> formatters, Object object) throws IOException { HtmlFormatter<Object> formatter; for (Class<?> objectClass = object.getClass(); objectClass != null; objectClass = objectClass.getSuperclass()) { formatter = formatters.get(objectClass); if (formatter != null) { formatter.format(this, object); return true; } for (Class<?> interfaceClass : objectClass.getInterfaces()) { formatter = formatters.get(interfaceClass); if (formatter != null) { formatter.format(this, object); return true; } } } return false; } /** Returns a CSS string based on the given {@code properties}. */ public String cssString(Object... properties) { return Static.cssString(properties); } /** Writes a CSS rule based on the given parameters. */ public HtmlWriter writeCss(String selector, Object... properties) throws IOException { write(selector); write('{'); write(cssString(properties)); write("}\n"); return this; } public HtmlWriter writeGrid(Object object, HtmlGrid grid) throws IOException { Map<String, Area> areas = createAreas(grid); boolean debug; try { debug = !Settings.isProduction() && ObjectUtils.to(boolean.class, PageContextFilter.Static.getRequest().getParameter("_grid")); } catch (Exception error) { debug = false; } writeStart("style", "type", "text/css"); writeCss(".dari-grid-area", "-moz-box-sizing", "content-box", "-webkit-box-sizing", "content-box", "box-sizing", "content-box", "float", "left", "margin", "0 -100% 0 -30000px"); writeCss(".dari-grid-adj", "float", "left"); for (Area area : areas.values()) { String selector = area.id != null ? "#" + area.id : ".dari-grid-area[data-grid-area=\"" + area.name + "\"]"; writeCss(selector, "clear", area.clear ? "left" : null, "padding-left", area.frPaddingLeft + "%", "width", area.frWidth + "%"); for (Map.Entry<String, Adjustment> entry : area.adjustments.entrySet()) { String unit = entry.getKey(); Adjustment adjustment = entry.getValue(); writeCss(selector + "-" + unit, "height", adjustment.height, "margin", adjustment.getMargin(unit), "width", adjustment.width); } } writeEnd(); if (object == null) { object = areas; } for (Map.Entry<String, Area> entry : areas.entrySet()) { String areaName = entry.getKey(); Area area = entry.getValue(); // The main wrapping DIV around the area. Initially shifted // left 30000px so that it's off-screen as not to overlap // other elements that come before. writeStart("div", "class", "dari-grid-area", "id", area.id, "data-grid-area", areaName); int adjustments = 0; for (Map.Entry<String, Adjustment> adjustmentEntry : area.adjustments.entrySet()) { ++ adjustments; String unit = adjustmentEntry.getKey(); writeStart("div", "class", "dari-grid-adj", "id", area.id + "-" + unit); } writeStart("div", "style", cssString( "height", 0, "overflow", "hidden", "visibility", "hidden")); write(GRID_PADDING); writeEnd(); if (debug) { writeStart("div", "style", cssString( "border", "3px dashed red", "padding", "3px")); } // Minimum width with multiple units. if (area.singleWidth == null) { int i = 0; for (CssUnit column : area.width.getAll()) { if (!"fr".equals(column.getUnit())) { ++ i; writeStart("div", "style", cssString( "padding-left", column, "height", 0)); } } for (; i > 0; writeEnd(); } } // Minimum height with multiple units. if (area.singleHeight == null) { writeStart("div", "style", cssString( "float", "left", "width", 0)); int i = 0; for (CssUnit row : area.height.getAll()) { ++ i; writeStart("div", "style", cssString( "padding-top", row, "width", 0)); } for (; i > 0; writeEnd(); } writeEnd(); } writeObject(CollectionUtils.getByPath(object, entry.getKey())); if (area.singleHeight == null) { writeStart("div", "style", cssString("clear", "left")); writeEnd(); } if (debug) { writeEnd(); } for (; adjustments > 0; -- adjustments) { writeEnd(); } writeEnd(); } writeStart("div", "style", cssString("clear", "left")); writeEnd(); return this; } private Map<String, Area> createAreas(HtmlGrid grid) { List<CssUnit> columns = grid.getColumns(); List<CssUnit> rows = grid.getRows(); List<List<String>> template = new ArrayList<List<String>>(grid.getTemplate()); // Clone the template so that the original isn't changed. for (ListIterator<List<String>> i = template.listIterator(); i.hasNext(); ) { i.set(new ArrayList<String>(i.next())); } Map<String, Area> areaInstances = new LinkedHashMap<String, Area>(); int clearAt = -1; for (int rowStart = 0, rowSize = rows.size(); rowStart < rowSize; ++ rowStart) { List<String> areas = template.get(rowStart); for (int columnStart = 0, columnSize = columns.size(); columnStart < columnSize; ++ columnStart) { String area = areas.get(columnStart); // Already processed or padding. if (area == null || ".".equals(area)) { continue; } int rowStop = rowStart + 1; int columnStop = columnStart + 1; // Figure out the "width" of the area. for (; columnStop < columnSize; ++ columnStop) { if (!ObjectUtils.equals(areas.get(columnStop), area)) { break; } else { areas.set(columnStop, null); } } // Figure out the "height" of the area. for (; rowStop < rowSize; ++ rowStop) { if (columnStart < template.get(rowStop).size() && !ObjectUtils.equals(template.get(rowStop).get(columnStart), area)) { break; } else { for (int i = columnStart; i < columnStop; ++ i) { if (i < template.get(rowStop).size()) { template.get(rowStop).set(i, null); } } } } // Figure out the rough initial position and size using // percentages. Area areaInstance = new Area(area); areaInstances.put(area, areaInstance); double frMax = 0; double frBefore = 0; double frAfter = 0; for (int i = 0; i < columnSize; ++ i) { CssUnit column = columns.get(i); if ("fr".equals(column.getUnit())) { double fr = column.getNumber(); frMax += fr; if (i < columnStart) { frBefore += fr; } else if (i >= columnStop) { frAfter += fr; } } } if (frMax == 0) { frMax = 1; frAfter = 1; } double frBeforeRatio = frBefore / frMax; double frAfterRatio = frAfter / frMax; areaInstance.frPaddingLeft = frBeforeRatio * 100.0; areaInstance.frWidth = (frMax - frBefore - frAfter) * 100.0 / frMax; // Adjust left and width. for (int i = 0; i < columnSize; ++ i) { CssUnit column = columns.get(i); String columnUnit = column.getUnit(); if (!"fr".equals(columnUnit)) { double columnNumber = column.getNumber(); double left = columnNumber * ((i < columnStart ? 1 : 0) - frBeforeRatio); double right = columnNumber * ((i >= columnStop ? 1 : 0) - frAfterRatio); if (left != 0.0 || right != 0.0) { Adjustment adjustment = areaInstance.getOrCreateAdjustment(columnUnit); adjustment.left += left; adjustment.right += right; } } } // Adjust top. for (int i = rowSize - 1; i >= 0; CssUnit row = rows.get(i); String rowUnit = row.getUnit(); if (i < rowStart && "auto".equals(rowUnit)) { break; } else if (!"fr".equals(rowUnit)) { double top = row.getNumber() * (i < rowStart ? 1 : 0); if (top != 0.0) { Adjustment adjustment = areaInstance.getOrCreateAdjustment(rowUnit); adjustment.top += top; } } } // Make sure there's always "px" adjustment layer so that // we can shift right 30000px to cancel out the positioning // from the main wrapping DIV. Adjustment pxAdjustment = areaInstance.adjustments.remove("px"); if (pxAdjustment == null) { pxAdjustment = new Adjustment(); } pxAdjustment.left += 30000; pxAdjustment.right -= 30000; areaInstance.adjustments.put("px", pxAdjustment); // Set width explicitly if there's only one unit. CombinedCssUnit width = areaInstance.width = new CombinedCssUnit(columns.subList(columnStart, columnStop)); CssUnit singleWidth = areaInstance.singleWidth = width.getSingle(); if (singleWidth != null) { pxAdjustment.width = singleWidth; } // Set height explicitly if there's only one unit. CombinedCssUnit height = areaInstance.height = new CombinedCssUnit(rows.subList(rowStart, rowStop)); CssUnit singleHeight = areaInstance.singleHeight = height.getSingle(); if (singleHeight != null) { pxAdjustment.height = singleHeight; } // Clear because of "auto" height? if (clearAt >= 0 && clearAt <= rowStart) { clearAt = -1; areaInstance.clear = true; } if (height.hasAuto() && rowStop > clearAt) { clearAt = rowStop; } } } return areaInstances; } /** * Writes the given {@code object} and positions it according to the * grid rules as specified by the given parameters. * * @see #grid(Object, HtmlGrid) */ public HtmlWriter writeGrid(Object object, String columns, String rows, String... template) throws IOException { return writeGrid(object, new HtmlGrid(columns, rows, template)); } private static class Area { public final String name; public final String id = "i" + UUID.randomUUID().toString().replaceAll("-", ""); public boolean clear; public double frPaddingLeft; public double frWidth; public CombinedCssUnit width; public CssUnit singleWidth; public CombinedCssUnit height; public CssUnit singleHeight; public final Map<String, Adjustment> adjustments = new LinkedHashMap<String, Adjustment>(); public Area(String name) { this.name = name; } public Adjustment getOrCreateAdjustment(String unit) { Adjustment adjustment = adjustments.get(unit); if (adjustment == null) { adjustment = new Adjustment(); adjustments.put(unit, adjustment); } return adjustment; } } private class CombinedCssUnit { private final Map<String, CssUnit> combined = new HashMap<String, CssUnit>(); public CombinedCssUnit(Iterable<CssUnit> values) { for (CssUnit value : values) { String unit = value.getUnit(); CssUnit old = combined.get(unit); if (old == null) { combined.put(unit, value); } else { combined.put(unit, new CssUnit(old.getNumber() + value.getNumber(), unit)); } } for (Iterator<Map.Entry<String, CssUnit>> i = combined.entrySet().iterator(); i.hasNext(); ) { CssUnit value = i.next().getValue(); if (!"auto".equals(value.getUnit()) && value.getNumber() == 0.0) { i.remove(); } } } public Collection<CssUnit> getAll() { return combined.values(); } public CssUnit getSingle() { if (combined.size() != 1) { return null; } else { CssUnit value = combined.values().iterator().next(); return "fr".equals(value.getUnit()) ? null : value; } } public boolean hasAuto() { return combined.keySet().contains("auto"); } } private static class Adjustment { public double left; public double right; public double top; public CssUnit width; public CssUnit height; public String getMargin(String unit) { return new CssUnit(top, unit) + " " + new CssUnit(right, unit) + " 0 " + new CssUnit(left, unit); } } @Override public Writer append(char letter) throws IOException { getDelegate().write(letter); return this; } @Override public Writer append(CharSequence text) throws IOException { getDelegate().append(text); return this; } @Override public Writer append(CharSequence text, int start, int end) throws IOException { getDelegate().append(text, start, end); return this; } @Override public void close() throws IOException { getDelegate().close(); } @Override public void flush() throws IOException { getDelegate().flush(); } @Override public void write(char[] buffer) throws IOException { getDelegate().write(buffer); } @Override public void write(char[] buffer, int offset, int length) throws IOException { getDelegate().write(buffer, offset, length); } @Override public void write(int letter) throws IOException { getDelegate().write(letter); } @Override public void write(String text) throws IOException { getDelegate().write(text); } @Override public void write(String text, int offset, int length) throws IOException { getDelegate().write(text, offset, length); } /** {@link HtmlWriter} utility methods. */ public static final class Static { /** Returns a CSS string based on the given {@code properties}. */ public static String cssString(Object... properties) { StringBuilder css = new StringBuilder(); if (properties != null) { for (int i = 1, length = properties.length; i < length; i += 2) { Object property = properties[i - 1]; if (property != null) { Object value = properties[i]; if (value != null) { css.append(property); css.append(':'); css.append(value); css.append(';'); } } } } return css.toString(); } } /** @deprecated Use {@link #writeHtmlOrDefault} instead. */ @Deprecated public HtmlWriter stringOrDefault(Object string, String defaultString) throws IOException { return htmlOrDefault(string, defaultString); } /** @deprecated Use {@link #writeHtml} instead. */ @Deprecated public HtmlWriter string(Object string) throws IOException { return html(string); } /** @deprecated Use {@link #writeTag} instead. */ @Deprecated public HtmlWriter tag(String tag, Object... attributes) throws IOException { return writeTag(tag, attributes); } /** @deprecated Use {@link #writeStart} instead. */ @Deprecated public HtmlWriter start(String tag, Object... attributes) throws IOException { return writeStart(tag, attributes); } /** @deprecated Use {@link #writeEnd} instead. */ @Deprecated public HtmlWriter end() throws IOException { return writeEnd(); } /** @deprecated Use {@link #writeHtmlOrDefault} instead. */ @Deprecated public HtmlWriter htmlOrDefault(Object unescapedHtml, String defaultUnescapedHtml) throws IOException { return writeHtmlOrDefault(unescapedHtml, defaultUnescapedHtml); } /** @deprecated Use {@link #writeHtml} instead. */ @Deprecated public HtmlWriter html(Object unescapedHtml) throws IOException { return writeHtml(unescapedHtml); } /** @deprecated Use {@link #writeObject} instead. */ @Deprecated public HtmlWriter object(Object object) throws IOException { return writeObject(object); } /** @deprecated Use {@link #writeCss} instead. */ @Deprecated public HtmlWriter css(String selector, Object... properties) throws IOException { return writeCss(selector, properties); } /** @deprecated Use {@link #writeGrid} instead. */ @Deprecated public HtmlWriter grid(Object object, HtmlGrid grid, boolean inlineCss) throws IOException { return writeGrid(object, grid, inlineCss); } /** @deprecated Use {@link #writeGrid} instead. */ @Deprecated public HtmlWriter grid(Object object, HtmlGrid grid) throws IOException { return writeGrid(object, grid); } /** @deprecated Use {@link #writeGrid} instead. */ @Deprecated public HtmlWriter grid(Object object, String columns, String rows, String... template) throws IOException { return writeGrid(object, columns, rows, template); } /** @deprecated Use {@link #writeGrid(Object, HtmlGrid)} instead. */ @Deprecated public HtmlWriter writeGrid(Object object, HtmlGrid grid, boolean inlineCss) throws IOException { return writeGrid(object, grid); } }
public class IrishDwarf extends Dwarf { public IrishDwarf(String name) { super(name); } public IrishDwarf(String name, DataTerceiraEra dataTerceiraEra) { super(name, dataTerceiraEra); } public void tentarSorte() { double sorte = getNumeroSorte(); if (sorte == -3333) this.inventario.adicionaItemProporcionalQuantidade(); } }
/* * $Id: TestRegistryArchivalUnit.java,v 1.2 2005-05-25 19:24:12 tlipkis Exp $ */ package org.lockss.plugin; import java.util.*; import junit.framework.*; import org.lockss.app.*; import org.lockss.config.*; import org.lockss.daemon.*; import org.lockss.test.*; import org.lockss.util.*; import org.lockss.state.*; /** * Test class for org.lockss.plugin.RegistryArchivalUnit */ public class TestRegistryArchivalUnit extends LockssTestCase { static Logger log = Logger.getLogger("TestRegistryArchivalUnit"); private RegistryPlugin regPlugin; private MockLockssDaemon daemon; private PluginManager pluginMgr; String baseUrl = "http://foo.com/bar"; public void setUp() throws Exception { super.setUp(); daemon = getMockLockssDaemon(); // make and init a real Pluginmgr pluginMgr = daemon.getPluginManager(); // Make and start a UrlManager to set up the URLStreamHandlerFactory. // This is all so the cuurl created below can be opened by the parser UrlManager uMgr = new UrlManager(); uMgr.initService(daemon); daemon.setDaemonInited(true); uMgr.startService(); regPlugin = new MyRegistryPlugin(); regPlugin.initPlugin(daemon); } public void tearDown() throws Exception { super.tearDown(); // more... } public void testLoadAuConfigDescrs() throws ArchivalUnit.ConfigurationException { Properties auProps = new Properties(); auProps.setProperty(ConfigParamDescr.BASE_URL.getKey(), baseUrl); Configuration auConfig = ConfigurationUtil.fromProps(auProps); Properties props = new Properties(); props.setProperty(RegistryArchivalUnit.PARAM_REGISTRY_TREEWALK_START, "93m"); props.setProperty(RegistryArchivalUnit.PARAM_REGISTRY_CRAWL_INTERVAL, "107m"); props.setProperty(RegistryArchivalUnit.PARAM_REGISTRY_FETCH_DELAY, "12s"); ConfigurationUtil.setCurrentConfigFromProps(props); MyRegistryArchivalUnit au = new MyRegistryArchivalUnit(regPlugin); au.setConfiguration(auConfig); TypedEntryMap paramMap = au.getProperties(); assertEquals(93 * Constants.MINUTE, paramMap.getLong(TreeWalkManager.PARAM_TREEWALK_START_DELAY)); assertEquals(107 * Constants.MINUTE, paramMap.getLong(ArchivalUnit.AU_NEW_CRAWL_INTERVAL)); assertEquals(12 * Constants.SECOND, paramMap.getLong(ArchivalUnit.AU_FETCH_DELAY)); } public void testShouldCallTopLevelPoll() throws Exception { RegistryArchivalUnit au = new RegistryArchivalUnit(regPlugin); // Expect that "shouldCallTopLevelPoll" will always return false. assertFalse(au.shouldCallTopLevelPoll(null)); } public void testRecomputeRegNameTitle() throws Exception { Properties auProps = new Properties(); auProps.setProperty(ConfigParamDescr.BASE_URL.getKey(), baseUrl); Configuration auConfig = ConfigurationUtil.fromProps(auProps); MyRegistryArchivalUnit au = new MyRegistryArchivalUnit(regPlugin); au.setConfiguration(auConfig); PluginTestUtil.registerArchivalUnit(regPlugin, au); TypedEntryMap map = au.getProperties(); au.addContent(map.getString(ArchivalUnit.AU_START_URL), "<html><head><h2>foobar</h2>\n" + "<title>This Title No Verb</title></head></html>"); assertEquals("This Title No Verb", au.recomputeRegName()); } public void testRecomputeRegNameTowTitles() throws Exception { Properties auProps = new Properties(); auProps.setProperty(ConfigParamDescr.BASE_URL.getKey(), baseUrl); Configuration auConfig = ConfigurationUtil.fromProps(auProps); MyRegistryArchivalUnit au = new MyRegistryArchivalUnit(regPlugin); au.setConfiguration(auConfig); PluginTestUtil.registerArchivalUnit(regPlugin, au); TypedEntryMap map = au.getProperties(); au.addContent(map.getString(ArchivalUnit.AU_START_URL), "<html><head><h2>foobar</h2>\n" + "<title>First Title No Verb</title>" + "<title>Second Title No Verb</title></head></html>"); assertEquals("First Title No Verb", au.recomputeRegName()); } public void testRecomputeRegNameNoTitle() throws Exception { Properties auProps = new Properties(); auProps.setProperty(ConfigParamDescr.BASE_URL.getKey(), baseUrl); Configuration auConfig = ConfigurationUtil.fromProps(auProps); MyRegistryArchivalUnit au = new MyRegistryArchivalUnit(regPlugin); au.setConfiguration(auConfig); PluginTestUtil.registerArchivalUnit(regPlugin, au); TypedEntryMap map = au.getProperties(); au.addContent(map.getString(ArchivalUnit.AU_START_URL), "<html><h3>This Page No Title</h3></html>"); assertEquals(null, au.recomputeRegName()); } // Both of these methods are currently empty implementations on // RegistryPlugin, but it's nice to exercise them anyway, since they // are part of Plugin's public interface. public void testSetTitleConfigFromConfig() throws Exception { regPlugin.setTitleConfigFromConfig(null); } public void testSetConfig() throws Exception { regPlugin.setConfig(null, null, null); } static class MyRegistryPlugin extends RegistryPlugin implements PluginTestable{ public void registerArchivalUnit(ArchivalUnit au) { aus.add(au); } public void unregisterArchivalUnit(ArchivalUnit au) { aus.remove(au); } } static class MyRegistryArchivalUnit extends RegistryArchivalUnit { Map cumap = new HashMap(); public MyRegistryArchivalUnit(RegistryPlugin plugin) { super(plugin); } public void addContent(String url, String content) { MockCachedUrl cu = new MockCachedUrl(url, this); cu.setContent(content); cu.setExists(true); cu.setProperties(new CIProperties()); cumap.put(url, cu); } public CachedUrl makeCachedUrl(String url) { return (CachedUrl)cumap.get(url); } } }
package com.github.kratorius.jefs; import org.junit.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class LFBitSetTest { private static final int ONE_MB = 1024 * 1024; @Test public void testNewBitSetIsZero() { LFBitSet bs = new LFBitSet(ONE_MB); for (int i = 0; i < ONE_MB; i++) { assertFalse(bs.get(i)); } } @Test(expected = IllegalArgumentException.class) public void testNegativeIndexingNotAllowed() { new LFBitSet(-1); } @Test(expected = IndexOutOfBoundsException.class) public void testOutOfBounds() { LFBitSet bs = new LFBitSet(ONE_MB); bs.get(ONE_MB + 1); } @Test public void testSetGet_singleThread() { LFBitSet bs = new LFBitSet(ONE_MB); for (int i = 0; i < ONE_MB; i++) { assertFalse(bs.get(i)); bs.set(i); assertTrue(bs.get(i)); } // make sure set(i) didn't change anything else for (int i = 0; i < ONE_MB; i++) { assertTrue(bs.get(i)); } } @Test public void testFlip_singleThread() { LFBitSet bs = new LFBitSet(ONE_MB); for (int i = 0; i < ONE_MB; i++) { assertFalse(bs.get(i)); bs.flip(i); assertTrue(bs.get(i)); } } @Test public void testClear_singleThread() { LFBitSet bs = new LFBitSet(ONE_MB); for (int i = 0; i < ONE_MB; i++) { bs.set(i); assertTrue(bs.get(i)); } for (int i = 0; i < ONE_MB; i++) { bs.clear(i); assertFalse(bs.get(i)); } } @Test public void testClearWholeArray() { LFBitSet bs = new LFBitSet(ONE_MB); for (int i = 0; i < ONE_MB; i++) { bs.set(i); assertTrue(bs.get(i)); } bs.clear(); for (int i = 0; i < ONE_MB; i++) { assertFalse(bs.get(i)); } } class FlipperRangeThread implements Runnable { public Exception exception; final LFBitSet bitSet; final int from; final int to; public FlipperRangeThread(LFBitSet bitSet, int from, int to) { this.bitSet = bitSet; this.from = from; this.to = to; } @Override public void run() { for (int i = from; i < to; i++) { try { bitSet.flip(i); } catch (Exception e) { exception = e; return; } } } } class FlipperThreadEven implements Runnable { public Exception exception; final LFBitSet bitSet; final int size; final boolean even; public FlipperThreadEven(LFBitSet bitSet, int size, boolean even) { this.bitSet = bitSet; this.size = size; this.even = even; } @Override public void run() { for (int i = 0; i < size; i++) { if ((even && ((i % 2) == 0)) || (!even && ((i % 2) != 0))) { try { bitSet.flip(i); } catch (Exception e) { exception = e; } } } } } @Test public void testFlip_twoThreads_noContention() throws InterruptedException { final int arraySize = ONE_MB * 256; final LFBitSet bs = new LFBitSet(arraySize); // first half of the array must be set to 1, the other to 0 for (int i = 0; i < (arraySize / 2); i++) { bs.set(i); } // each thread will flip his own half FlipperRangeThread f1 = new FlipperRangeThread(bs, 0, (arraySize / 2)); FlipperRangeThread f2 = new FlipperRangeThread(bs, (arraySize / 2), arraySize); Thread t1 = new Thread(f1); Thread t2 = new Thread(f2); t1.start(); t2.start(); t1.join(); t2.join(); assertNull(f1.exception); assertNull(f2.exception); for (int i = 0; i < (arraySize / 2); i++) { assertFalse(bs.get(i)); } for (int i = (arraySize / 2); i < arraySize; i++) { assertTrue(bs.get(i)); } } @Test public void testFlip_twoThreads_contention() throws InterruptedException { final int arraySize = ONE_MB * 256; final LFBitSet bs = new LFBitSet(arraySize); // every other item will be set to 1 for (int i = 0; i < arraySize; i++) { if ((i % 2) == 0) { bs.set(i); } } // each thread will flip either even or odd positions FlipperThreadEven f1 = new FlipperThreadEven(bs, arraySize, true); FlipperThreadEven f2 = new FlipperThreadEven(bs, arraySize, false); Thread t1 = new Thread(f1); Thread t2 = new Thread(f2); t1.start(); t2.start(); t1.join(); t2.join(); // in the end all the items must be flipped for (int i = 0; i < arraySize; i++) { if ((i % 2) == 0) { assertFalse(bs.get(i)); } else { assertTrue(bs.get(i)); } } } class SetThread implements Runnable { private LFBitSet bitSet; private List<Integer> positions; public SetThread(LFBitSet bitSet, List<Integer> positions) { this.bitSet = bitSet; this.positions = positions; } @Override public void run() { for (int pos : positions) { bitSet.set(pos); } } } class ClearThread implements Runnable { private LFBitSet bitSet; private List<Integer> positions; public ClearThread(LFBitSet bitSet, List<Integer> positions) { this.bitSet = bitSet; this.positions = positions; } @Override public void run() { for (int pos : positions) { bitSet.clear(pos); } } } class FlipThread implements Runnable { private LFBitSet bitSet; private List<Integer> positions; public FlipThread(LFBitSet bitSet, List<Integer> positions) { this.bitSet = bitSet; this.positions = positions; } @Override public void run() { for (int pos : positions) { bitSet.flip(pos); } } } @Test public void testSet_asManyThreadsAsCores() throws InterruptedException { final int arraySize = ONE_MB * 32; // or the shuffle list won't fit in memory (of my machine) final LFBitSet bs = new LFBitSet(arraySize); int logicalCores = Runtime.getRuntime().availableProcessors(); ArrayList<Thread> threads = new ArrayList<>(logicalCores); // change to something more memory-efficient so we can test larger bitsets List<Integer> items = new ArrayList<>(arraySize); for (int i = 0; i < arraySize; i++) { items.add(i); } Collections.shuffle(items); // each thread will have to set only a subset of this list int start = 0; int stop = arraySize / logicalCores; for (int i = 0; i < logicalCores; i++) { // add the remainder of items to the last thread if (i == (logicalCores - 1)) { stop += arraySize % logicalCores; } threads.add(new Thread(new SetThread(bs, items.subList(start, stop)))); start = stop; stop += arraySize / logicalCores; } for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); } // in the end all the items must be set for (int i = 0; i < arraySize; i++) { assertTrue(bs.get(i)); } } @Test public void testSet_moreThreadsThanCores() throws InterruptedException { final int arraySize = ONE_MB * 32; // or the shuffle list won't fit in memory (of my machine) final LFBitSet bs = new LFBitSet(arraySize); int logicalCores = Runtime.getRuntime().availableProcessors() + 1; ArrayList<Thread> threads = new ArrayList<>(logicalCores); // change to something more memory-efficient so we can test larger bitsets List<Integer> items = new ArrayList<>(arraySize); for (int i = 0; i < arraySize; i++) { items.add(i); } Collections.shuffle(items); // each thread will have to set only a subset of this list int start = 0; int stop = arraySize / logicalCores; for (int i = 0; i < logicalCores; i++) { // add the remainder of items to the last thread if (i == (logicalCores - 1)) { stop += arraySize % logicalCores; } threads.add(new Thread(new SetThread(bs, items.subList(start, stop)))); start = stop; stop += arraySize / logicalCores; } for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); } // in the end all the items must be set for (int i = 0; i < arraySize; i++) { assertTrue(bs.get(i)); } } @Test public void testClear_asManyThreadsAsCores() throws InterruptedException { final int arraySize = ONE_MB * 32; // or the shuffle list won't fit in memory (of my machine) final LFBitSet bs = new LFBitSet(arraySize); int logicalCores = Runtime.getRuntime().availableProcessors(); ArrayList<Thread> threads = new ArrayList<>(logicalCores); // change to something more memory-efficient so we can test larger bitsets List<Integer> items = new ArrayList<>(arraySize); for (int i = 0; i < arraySize; i++) { bs.set(i); items.add(i); } Collections.shuffle(items); // each thread will have to set only a subset of this list int start = 0; int stop = arraySize / logicalCores; for (int i = 0; i < logicalCores; i++) { // add the remainder of items to the last thread if (i == (logicalCores - 1)) { stop += arraySize % logicalCores; } threads.add(new Thread(new ClearThread(bs, items.subList(start, stop)))); start = stop; stop += arraySize / logicalCores; } for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); } // in the end all the items must be set for (int i = 0; i < arraySize; i++) { assertFalse(bs.get(i)); } } @Test public void testClear_moreThreadsThanCores() throws InterruptedException { final int arraySize = ONE_MB * 32; // or the shuffle list won't fit in memory (of my machine) final LFBitSet bs = new LFBitSet(arraySize); int logicalCores = Runtime.getRuntime().availableProcessors() + 1; ArrayList<Thread> threads = new ArrayList<>(logicalCores); // change to something more memory-efficient so we can test larger bitsets List<Integer> items = new ArrayList<>(arraySize); for (int i = 0; i < arraySize; i++) { bs.set(i); items.add(i); } Collections.shuffle(items); // each thread will have to set only a subset of this list int start = 0; int stop = arraySize / logicalCores; for (int i = 0; i < logicalCores; i++) { // add the remainder of items to the last thread if (i == (logicalCores - 1)) { stop += arraySize % logicalCores; } threads.add(new Thread(new ClearThread(bs, items.subList(start, stop)))); start = stop; stop += arraySize / logicalCores; } for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); } // in the end all the items must be set for (int i = 0; i < arraySize; i++) { assertFalse(bs.get(i)); } } @Test public void testFlip_asManyThreadsAsCores() throws InterruptedException { final int arraySize = ONE_MB * 32; // or the shuffle list won't fit in memory (of my machine) final LFBitSet bs = new LFBitSet(arraySize); int logicalCores = Runtime.getRuntime().availableProcessors(); ArrayList<Thread> threads = new ArrayList<>(logicalCores); // change to something more memory-efficient so we can test larger bitsets List<Integer> items = new ArrayList<>(arraySize); for (int i = 0; i < arraySize; i++) { items.add(i); } Collections.shuffle(items); // each thread will have to set only a subset of this list int start = 0; int stop = arraySize / logicalCores; for (int i = 0; i < logicalCores; i++) { // add the remainder of items to the last thread if (i == (logicalCores - 1)) { stop += arraySize % logicalCores; } threads.add(new Thread(new FlipThread(bs, items.subList(start, stop)))); start = stop; stop += arraySize / logicalCores; } for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); } // in the end all the items must be set for (int i = 0; i < arraySize; i++) { assertTrue(bs.get(i)); } } @Test public void testFlip_moreThreadsThanCores() throws InterruptedException { final int arraySize = ONE_MB * 32; // or the shuffle list won't fit in memory (of my machine) final LFBitSet bs = new LFBitSet(arraySize); int logicalCores = Runtime.getRuntime().availableProcessors() + 1; ArrayList<Thread> threads = new ArrayList<>(logicalCores); // change to something more memory-efficient so we can test larger bitsets List<Integer> items = new ArrayList<>(arraySize); for (int i = 0; i < arraySize; i++) { items.add(i); } Collections.shuffle(items); // each thread will have to set only a subset of this list int start = 0; int stop = arraySize / logicalCores; for (int i = 0; i < logicalCores; i++) { // add the remainder of items to the last thread if (i == (logicalCores - 1)) { stop += arraySize % logicalCores; } threads.add(new Thread(new FlipThread(bs, items.subList(start, stop)))); start = stop; stop += arraySize / logicalCores; } for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); } // in the end all the items must be set for (int i = 0; i < arraySize; i++) { assertTrue(bs.get(i)); } } }
package net.formula97.andorid.car_kei_bo; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import android.app.Activity; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.provider.Settings; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.InputFilter.LengthFilter; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; /** * @author kazutoshi * */ public class FuelMileageAdd extends Activity implements OnClickListener { Spinner spinner_carName; EditText editText_amountOfOil; EditText EditText_odometer; EditText editText_unitPrice; EditText editText_dateOfRefuel; EditText editText_timeOfRefuel; EditText editText_comments; Button button_addRefuelRecord; Button button_cancelAddRefuelRecord; Button button_editDate; Button button_editTime; TextView textView_oilUnit; TextView textView_distanceUnit; TextView textView_moneyUnit; DatePickerDialog dpDialog; TimePickerDialog tpDialog; DatePickerDialog.OnDateSetListener dpListener; TimePickerDialog.OnTimeSetListener tpListener; private int CAR_ID; private String CAR_NAME; private DbManager dbman = new DbManager(this); public static SQLiteDatabase db; Cursor cSpinnerCarList; private Calendar currentDateTime; private DateManager dmngr = new DateManager(); private static String TEXT_BLANK = ""; /* ( Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { // TODO super.onCreate(savedInstanceState); setContentView(R.layout.fuelmileageadd); spinner_carName = (Spinner)findViewById(R.id.spinner_carName); editText_amountOfOil = (EditText)findViewById(R.id.editText_amountOfOil); EditText_odometer = (EditText)findViewById(R.id.EditText_odometer); editText_unitPrice = (EditText)findViewById(R.id.editText_unitPrice); editText_dateOfRefuel = (EditText)findViewById(R.id.editText_dateOfRefuel); editText_timeOfRefuel = (EditText)findViewById(R.id.editText_timeOfRefuel); editText_comments = (EditText)findViewById(R.id.editText_comments); button_addRefuelRecord = (Button)findViewById(R.id.button_addRefuelRecord); button_cancelAddRefuelRecord = (Button)findViewById(R.id.button_cancelAddRefuelRecord); button_editDate = (Button)findViewById(R.id.button_editDate); button_editTime = (Button)findViewById(R.id.button_editTime); textView_oilUnit = (TextView)findViewById(R.id.textView_oilUnit); textView_distanceUnit = (TextView)findViewById(R.id.textView_distanceUnit); textView_moneyUnit = (TextView)findViewById(R.id.textView_moneyUnit); Intent i = getIntent(); setCAR_ID(i.getIntExtra("CAR_ID", 0)); setCAR_NAME(i.getStringExtra("CAR_NAME")); Log.d("onCreate", "got CAR_ID : " + String.valueOf(CAR_ID)); Log.d("onCreate", "gor CAR_NAME : " + CAR_NAME); } /* ( Javadoc) * @see android.app.Activity#onDestroy() */ @Override protected void onDestroy() { // TODO super.onDestroy(); closeCursor(); closeDB(db); } /* ( Javadoc) * @see android.app.Activity#onPause() */ @Override protected void onPause() { // TODO super.onPause(); closeCursor(); closeDB(db); } /* ( Javadoc) * @see android.app.Activity#onResume() */ @Override protected void onResume() { // TODO super.onResume(); /* * 1/2 * * onCreate() * Android */ int displayWidth = getWindowManager().getDefaultDisplay().getWidth(); button_addRefuelRecord.setWidth(displayWidth / 2); button_cancelAddRefuelRecord.setWidth(displayWidth / 2); // DBReadable db = dbman.getReadableDatabase(); // CAR_ID setSpinner(db, getCAR_NAME()); setUnitLabel(db, getCAR_ID()); spinner_carName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long rowId) { // CAR_ID String carName = getCarNameFromSpinner(); int carId = dbman.getCarId(db, carName); setUnitLabel(db, carId); } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO } }); button_addRefuelRecord.setOnClickListener(this); button_cancelAddRefuelRecord.setOnClickListener(this); button_editDate.setOnClickListener(this); button_editTime.setOnClickListener(this); // editText currentDateTime = dmngr.getNow(); setDateToEdit(currentDateTime); setTimeToEdit(currentDateTime); // DateSetLintener dpListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // currentDateTime currentDateTime.set(year, monthOfYear, dayOfMonth); // EditText setDateToEdit(currentDateTime); setTimeToEdit(currentDateTime); Log.d("onDateSet", "Current date has set to " + dmngr.getISO8601Date(currentDateTime, false)); } }; // TimePickerlistener tpListener = new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // currentDateTime currentDateTime.set(Calendar.HOUR, hourOfDay); currentDateTime.set(Calendar.MINUTE, minute); // TimePickerDialog currentDateTime.set(Calendar.SECOND, 0); // EditText setDateToEdit(currentDateTime); setTimeToEdit(currentDateTime); Log.d("onTimeSet", "Current datetime has set to " + dmngr.getISO8601Date(currentDateTime, true)); } }; } /** * DB * @param sqlitedb SQLiteDatabaseDB * @param focusCarName String */ private void setSpinner(SQLiteDatabase sqlitedb, String focusCarName) { cSpinnerCarList = dbman.getCarNameList(sqlitedb); List<String> lstSpinner = new ArrayList<String>(); // ArrayListCursor // getOffsetByName.... do { lstSpinner.add(cSpinnerCarList.getString(1)); cSpinnerCarList.moveToNext(); } while (cSpinnerCarList.isAfterLast() != true); // ArrayAdapter ArrayAdapter<String> aa = new ArrayAdapter<String> ( this, android.R.layout.simple_spinner_item, lstSpinner); aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner_carName.setAdapter(aa); aa.notifyDataSetChanged(); int pos = getOffsetByName(focusCarName, cSpinnerCarList); Log.d("setSpinner", "got spinner position : " + String.valueOf(pos)); spinner_carName.setSelection(pos); // Cursor cSpinnerCarList.moveToFirst(); } /** * @return cAR_ID */ public int getCAR_ID() { return CAR_ID; } /** * @param cAR_ID cAR_ID */ public void setCAR_ID(int cAR_ID) { CAR_ID = cAR_ID; } /** * @return cAR_NAME */ public String getCAR_NAME() { return CAR_NAME; } /** * @param cAR_NAME cAR_NAME */ public void setCAR_NAME(String cAR_NAME) { CAR_NAME = cAR_NAME; } /** * CursorcSpinnerCarList */ private void closeCursor() { if (cSpinnerCarList.isClosed() != true ) { cSpinnerCarList.close(); Log.d("CloseCursor", "cSpinnerCarList is closed."); } else { Log.d("closeCursor", "cSpinnerCarList is already closed."); } } /** * * @param db SQLiteDatabaseDB */ private void closeDB(SQLiteDatabase db) { if (db.isOpen()) { db.close(); Log.d("closeDB", "SQLiteDatabase is closed."); } else { Log.d("closeDB", "SQLiteDatabase is already closed."); } } /** * Cursor * @param carName String * @param cCarList CursorCursor * @return intCursor */ private int getOffsetByName(String carName, Cursor cCarList) { int offset = 0; int cnt = 0; String car; Log.d("getOffsetByName", "Inspecting as follow : " + carName); // Cursor cCarList.moveToFirst(); // cCarListCursorCursor // getCount()for.... do { car = cCarList.getString(1); Log.d("getOffsetByName", "got car name : " + car); if (car.equals(carName)) { offset = cnt; Log.d("getOffsetByName", "matched with " + carName + ", offset : " + String.valueOf(offset)); } cnt++; cCarList.moveToNext(); } while ( cCarList.isAfterLast() != true ); Log.d("getOffsetByName", "offset result : " + String.valueOf(offset)); Log.d("getOffsetByName", "counter result : " + String.valueOf(cnt)); return offset; } /** * DB * @return String */ private String getCarNameFromSpinner() { String carName = (String)spinner_carName.getSelectedItem(); Log.d("getCarNameFromSpinner", "now selected car is " + carName); return carName; } /** * editText * @param gcd CalendarCalendar */ private void setDateToEdit(Calendar gcd) { Date dd = gcd.getTime(); // AndroidAPIDateFormat // java.text.DateFormat Context ctx = getApplicationContext(); java.text.DateFormat df = android.text.format.DateFormat.getDateFormat(ctx); // EditText editText_dateOfRefuel.setText(df.format(dd)); } /** * editText * @param gcd CalendarCalendar */ private void setTimeToEdit(Calendar gcd) { Date dd = gcd.getTime(); // AndroidAPIDateFormat // java.text.DateFormat Context ctx = getApplicationContext(); java.text.DateFormat df = android.text.format.DateFormat.getTimeFormat(ctx); // EditText editText_timeOfRefuel.setText(df.format(dd)); } /** * CAR_ID * @param sqlitedb SQLiteDatabaseDB * @param carId intCAR_ID */ private void setUnitLabel(SQLiteDatabase sqlitedb, int carId) { textView_distanceUnit.setText(dbman.getDistanceUnitById(sqlitedb, carId)); textView_moneyUnit.setText(dbman.getPriceUnitById(sqlitedb, carId)); textView_oilUnit.setText(dbman.getVolumeUnitById(sqlitedb, carId)); } /** * int * @param inputStr * @return booleaninttruefalse */ private boolean isValidInt(String inputStr) { boolean result = false; Log.d("isValidInt", "Input text is " + inputStr); if (inputStr.equals(TEXT_BLANK)) { result = false; Log.e("isValidInt", "Input String is nothing to display. Parsing to Integer failed."); } try { int testValue = Integer.parseInt(inputStr); result = true; Log.d("isValidInt", "Parsing to Integer successful. Output number is " + String.valueOf(testValue)); } catch (NumberFormatException nfe) { result = false; Log.e("isValidInt", "NumberFormatException occured. Parsing to Integer failed."); } catch (Exception e) { result = false; Log.e("isValidInt", "Other Exception occured. Parsing to Integer failed."); } return result; } /** * long * @param inputStr * @return booleanlongtruefalse */ private boolean isValidLong(String inputStr) { boolean result = false; Log.d("isValidLong", "Input text is " + inputStr); if (inputStr.equals(TEXT_BLANK)) { result = false; Log.e("isValidLong", "Input String is nothing to display. Parsing to Long failed."); } try { long testValue = Long.parseLong(inputStr); result = true; Log.d("isValidLong", "Parsing to Long successful. Output number is " + String.valueOf(testValue)); } catch (NumberFormatException nfe) { result = false; Log.e("isValidLong", "NumberFormatException occured. Parsing to Long failed."); } catch (Exception e) { result = false; Log.e("isValidInt", "Other Exception occured. Parsing to Integer failed."); } return result; } /** * double * @param inputStr * @return booleandoubletruefalse */ private boolean isValidDouble(String inputStr) { boolean result = false; Log.d("isValidDouble", "Input text is " + inputStr); if (inputStr.equals(TEXT_BLANK)) { result = false; Log.e("isValidDouble", "Input String is nothing to display. Parsing to Double failed."); } try { double testValue = Double.parseDouble(inputStr); result = true; Log.d("isValidDouble", "Parsing to Double successful. Output number is " + String.valueOf(testValue)); } catch (NumberFormatException nfe) { result = false; Log.e("isValidLong", "NumberFormatException occured. Parsing to Double failed."); } catch (Exception e) { result = false; Log.e("isValidInt", "Other Exception occured. Parsing to Integer failed."); } return result; } /** * DB * @param db * @param carId * @param gcd * @param amountOfOil * @param odometer */ private void showToastMsg(SQLiteDatabase db, int carId, Calendar gcd, double amountOfOil, double tripMeter) { String line1, line2, line3, line4; // CAR_ID String carName = dbman.getCarNameById(db, carId); line1 = carName + getString(R.string.toastmsg_addmileage1); line2 = getString(R.string.toastmsg_addmileage2) + dmngr.getISO8601Date(gcd, true); line3 = getString(R.string.toastmsg_addmileage3) + String.valueOf(amountOfOil); line4 = getString(R.string.toastmsg_addmileage4) + String.valueOf(tripMeter); Toast.makeText(this, line1 + "\n" + line2 + "\n" + line3 + "\n" + line4, Toast.LENGTH_LONG).show(); } /** * OnClickListener * * @param v ViewView */ @Override public void onClick(View v) { // TODO int viewId = v.getId(); switch (viewId) { case R.id.button_addRefuelRecord: int targetCarId = dbman.getCarId(db, getCarNameFromSpinner()); double amountOfOil, tripMeter, unitPrice; double runningCosts = 0; long ret = 0; // EditText SpannableStringBuilder ssbAmountOfOil = (SpannableStringBuilder)editText_amountOfOil.getText(); SpannableStringBuilder ssbUnitPrice = (SpannableStringBuilder)editText_unitPrice.getText(); SpannableStringBuilder ssbComments = (SpannableStringBuilder)editText_comments.getText(); SpannableStringBuilder ssbOdometer = (SpannableStringBuilder)EditText_odometer.getText(); if (isValidDouble(ssbAmountOfOil.toString())) { amountOfOil = Double.parseDouble(ssbAmountOfOil.toString()); } else { amountOfOil = 0; } if (isValidDouble(ssbUnitPrice.toString())) { unitPrice = Double.parseDouble(ssbUnitPrice.toString()); } else { unitPrice = 0; } if (isValidDouble(ssbOdometer.toString())) { tripMeter = Double.parseDouble(ssbOdometer.toString()); } else { tripMeter = 0; } String comments = ssbComments.toString(); if (amountOfOil <= 0 || unitPrice <= 0 || tripMeter <= 0) { Log.w("onClick#R.id.button_addRefuelRecord", "Can't add mileage record(Maybe no value is set in one of the variables?)"); Log.w("onClick#R.id.button_addRefuelRecord", "amountOfOil : " + String.valueOf(amountOfOil)); Log.w("onClick#R.id.button_addRefuelRecord", "unitPrice : " + String.valueOf(unitPrice)); Log.w("onClick#R.id.button_addRefuelRecord", "tripMeter : " + String.valueOf(tripMeter)); ret = -1; } else { // currentDateTimegetInstance()(^^;) ret = dbman.addMileageById(db, targetCarId, amountOfOil, tripMeter, unitPrice, comments, currentDateTime); // TODO DB runningCosts = getRunningCostValue(amountOfOil, unitPrice, tripMeter); } if (ret == -1 ) { Log.d("button_addRefuelRecord_Click", "Failed to add Mileage record."); } else { Log.d("button_addRefuelRecord_Click", "Adding Mileage record successful. rowId = " + String.valueOf(ret)); showToastMsg(db, targetCarId, currentDateTime, amountOfOil, tripMeter); resetUi(); } break; case R.id.button_cancelAddRefuelRecord: resetUi(); break; case R.id.button_editDate: int year = currentDateTime.get(Calendar.YEAR); int month = currentDateTime.get(Calendar.MONTH); int dayOfMonth = currentDateTime.get(Calendar.DAY_OF_MONTH); dpDialog = new DatePickerDialog(this, dpListener, year, month, dayOfMonth); dpDialog.show(); break; case R.id.button_editTime: int hour = currentDateTime.get(Calendar.HOUR); int minute = currentDateTime.get(Calendar.MINUTE); // TimePickerDialog24 tpDialog = new TimePickerDialog(this, tpListener, hour, minute, isSetting24hourFormat()); tpDialog.show(); break; default: break; } } /** * 24 * @return boolean24true12false */ private boolean isSetting24hourFormat() { boolean result = false; // 1224StringString String str = Settings.System.getString(getApplicationContext().getContentResolver(), Settings.System.TIME_12_24); String hours24 = "24"; // 24true if (hours24.equals(str)) { result = true; } return result; } private void resetUi() { // EditText editText_amountOfOil.setText(TEXT_BLANK); editText_dateOfRefuel.setText(TEXT_BLANK); editText_unitPrice.setText(TEXT_BLANK); EditText_odometer.setText(TEXT_BLANK); editText_comments.setText(TEXT_BLANK); editText_timeOfRefuel.setText(TEXT_BLANK); // Cursor closeCursor(); setSpinner(db, CAR_NAME); // editText currentDateTime = dmngr.getNow(); setDateToEdit(currentDateTime); setTimeToEdit(currentDateTime); } /** * * @param amountOfOil double * @param unitPrice doble * @param tripMeter double * @return */ private double getRunningCostValue(double amountOfOil, double unitPrice, double tripMeter) { double ret = 0; double runningCost = amountOfOil * unitPrice / tripMeter; BigDecimal bd = new BigDecimal(runningCost); ret = bd.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); return ret; } }
package edu.umd.cs.findbugs.detect; import edu.umd.cs.findbugs.*; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.XFactory; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; import java.util.*; import java.util.regex.Pattern; import org.apache.bcel.Repository; import org.apache.bcel.classfile.*; import org.apache.bcel.generic.Type; public class UnreadFields extends BytecodeScanningDetector { private static final boolean DEBUG = SystemProperties.getBoolean("unreadfields.debug"); static class ProgramPoint { ProgramPoint(BytecodeScanningDetector v) { method = MethodAnnotation.fromVisitedMethod(v); sourceLine = SourceLineAnnotation .fromVisitedInstruction(v,v.getPC()); } MethodAnnotation method; SourceLineAnnotation sourceLine; } Map<XField,HashSet<ProgramPoint> > assumedNonNull = new HashMap<XField,HashSet<ProgramPoint>>(); Set<XField> nullTested = new HashSet<XField>(); Set<XField> staticFields = new HashSet<XField>(); Set<XField> declaredFields = new TreeSet<XField>(); Set<XField> containerFields = new TreeSet<XField>(); Set<String> abstractClasses = new HashSet<String>(); Set<String> hasNonAbstractSubClass = new HashSet<String>(); Set<XField> fieldsOfNativeClassed = new HashSet<XField>(); Set<XField> fieldsOfSerializableOrNativeClassed = new HashSet<XField>(); Set<XField> staticFieldsReadInThisMethod = new HashSet<XField>(); Set<XField> allMyFields = new TreeSet<XField>(); Set<XField> myFields = new TreeSet<XField>(); Set<XField> writtenFields = new HashSet<XField>(); Map<XField,SourceLineAnnotation> fieldAccess = new HashMap<XField, SourceLineAnnotation>(); Set<XField> writtenNonNullFields = new HashSet<XField>(); Set<String> calledFromConstructors = new HashSet<String>(); Set<XField> writtenInConstructorFields = new HashSet<XField>(); Set<XField> writtenOutsideOfConstructorFields = new HashSet<XField>(); Set<XField> readFields = new HashSet<XField>(); Set<XField> constantFields = new HashSet<XField>(); Set<XField> finalFields = new HashSet<XField>(); Set<String> needsOuterObjectInConstructor = new HashSet<String>(); Set<String> innerClassCannotBeStatic = new HashSet<String>(); boolean hasNativeMethods; boolean isSerializable; boolean sawSelfCallInConstructor; private BugReporter bugReporter; boolean publicOrProtectedConstructor; private XFactory xFactory = AnalysisContext.currentXFactory(); public Set<? extends XField> getReadFields() { return readFields; } public Set<? extends XField> getWrittenFields() { return writtenFields; } public Set<? extends XField> getWrittenOutsideOfConstructorFields() { return writtenOutsideOfConstructorFields; } static final int doNotConsider = ACC_PUBLIC | ACC_PROTECTED; public UnreadFields(BugReporter bugReporter) { this.bugReporter = bugReporter; AnalysisContext context = AnalysisContext.currentAnalysisContext(); context.setUnreadFields(this); } @Override public void visit(JavaClass obj) { calledFromConstructors.clear(); hasNativeMethods = false; sawSelfCallInConstructor = false; publicOrProtectedConstructor = false; isSerializable = false; if (obj.isAbstract()) { abstractClasses.add(getDottedClassName()); } else { String superClass = obj.getSuperclassName(); if (superClass != null) hasNonAbstractSubClass.add(superClass); } if (getSuperclassName().indexOf("$") >= 0 || getSuperclassName().indexOf("+") >= 0) { // System.out.println("hicfsc: " + betterClassName); innerClassCannotBeStatic.add(getDottedClassName()); // System.out.println("hicfsc: " + betterSuperclassName); innerClassCannotBeStatic.add(getDottedSuperclassName()); } // Does this class directly implement Serializable? String[] interface_names = obj.getInterfaceNames(); for (String interface_name : interface_names) { if (interface_name.equals("java.io.Externalizable")) { isSerializable = true; } else if (interface_name.equals("java.io.Serializable")) { isSerializable = true; break; } } // Does this class indirectly implement Serializable? if (!isSerializable) { try { if (Repository.instanceOf(obj, "java.io.Externalizable")) isSerializable = true; if (Repository.instanceOf(obj, "java.io.Serializable")) isSerializable = true; if (Repository.instanceOf(obj, "java.rmi.Remote")) { isSerializable = true; } } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } } // System.out.println(getDottedClassName() + " is serializable: " + isSerializable); super.visit(obj); } public static boolean classHasParameter(JavaClass obj) { for(Attribute a : obj.getAttributes()) if (a instanceof Signature) { String sig = ((Signature)a).getSignature(); return sig.charAt(0) == '<'; } return false; } @Override public void visitAfter(JavaClass obj) { declaredFields.addAll(myFields); if (hasNativeMethods) { fieldsOfSerializableOrNativeClassed.addAll(myFields); fieldsOfNativeClassed.addAll(myFields); } if (isSerializable) { fieldsOfSerializableOrNativeClassed.addAll(myFields); } if (sawSelfCallInConstructor) writtenInConstructorFields.addAll(myFields); myFields.clear(); allMyFields.clear(); calledFromConstructors.clear(); } @Override public void visit(Field obj) { super.visit(obj); XField f = XFactory.createXField(this); allMyFields.add(f); int flags = obj.getAccessFlags(); if ((flags & doNotConsider) == 0 && !getFieldName().equals("serialVersionUID")) { myFields.add(f); if (obj.isFinal()) finalFields.add(f); if (obj.isStatic()) staticFields.add(f); if (obj.getName().equals("_jspx_dependants")) containerFields.add(f); } } @Override public void visitAnnotation(String annotationClass, Map<String, Object> map, boolean runtimeVisible) { if (!visitingField()) return; if (annotationClass.startsWith("javax.annotation.") || annotationClass.startsWith("javax.ejb")|| annotationClass.equals("org.jboss.seam.annotations.In") || annotationClass.startsWith("javax.persistence")) { containerFields.add(XFactory.createXField(this)); } } @Override public void visit(ConstantValue obj) { // ConstantValue is an attribute of a field, so the instance variables // set during visitation of the Field are still valid here XField f = XFactory.createXField(this); constantFields.add(f); } int count_aload_1; private OpcodeStack opcodeStack = new OpcodeStack(); private int previousOpcode; private int previousPreviousOpcode; @Override public void visit(Code obj) { count_aload_1 = 0; previousOpcode = -1; previousPreviousOpcode = -1; nullTested.clear(); seenInvokeStatic = false; opcodeStack.resetForMethodEntry(this); staticFieldsReadInThisMethod.clear(); super.visit(obj); if (getMethodName().equals("<init>") && count_aload_1 > 1 && (getClassName().indexOf('$') >= 0 || getClassName().indexOf('+') >= 0)) { needsOuterObjectInConstructor.add(getDottedClassName()); // System.out.println(betterClassName + " needs outer object in constructor"); } } @Override public void visit(Method obj) { if (DEBUG) System.out.println("Checking " + getClassName() + "." + obj.getName()); if (getMethodName().equals("<init>") && (obj.isPublic() || obj.isProtected() )) publicOrProtectedConstructor = true; super.visit(obj); int flags = obj.getAccessFlags(); if ((flags & ACC_NATIVE) != 0) hasNativeMethods = true; } boolean seenInvokeStatic; @Override public void sawOpcode(int seen) { opcodeStack.mergeJumps(this); if (seen == GETSTATIC) { XField f = XFactory.createReferencedXField(this); staticFieldsReadInThisMethod.add(f); } else if (seen == INVOKESTATIC) { seenInvokeStatic = true; } else if (seen == PUTSTATIC && !getMethod().isStatic()) { XField f = XFactory.createReferencedXField(this); if (!staticFieldsReadInThisMethod.contains(f)) { int priority = LOW_PRIORITY; if (!publicOrProtectedConstructor) priority if (!seenInvokeStatic && staticFieldsReadInThisMethod.isEmpty()) priority if (getThisClass().isPublic() && getMethod().isPublic()) priority if (getThisClass().isPrivate() || getMethod().isPrivate()) priority++; if (getClassName().indexOf('$') != -1) priority++; bugReporter.reportBug(new BugInstance(this, "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", priority ) .addClassAndMethod(this) .addField(f) .addSourceLine(this) ); } } if (seen == INVOKEVIRTUAL || seen == INVOKEINTERFACE || seen == INVOKESPECIAL || seen==INVOKESTATIC ) { String sig = getSigConstantOperand(); String invokedClassName = getClassConstantOperand(); if (invokedClassName.equals(getClassName()) && (getMethodName().equals("<init>") || getMethodName().equals("<clinit>"))) { calledFromConstructors.add(getNameConstantOperand()+":"+sig); } int pos = PreorderVisitor.getNumberArguments(sig); if (opcodeStack.getStackDepth() > pos) { OpcodeStack.Item item = opcodeStack.getStackItem(pos); boolean superCall = seen == INVOKESPECIAL && !invokedClassName .equals(getClassName()); if (DEBUG) System.out.println("In " + getFullyQualifiedMethodName() + " saw call on " + item); boolean selfCall = item.getRegisterNumber() == 0 && !superCall; if (selfCall && getMethodName().equals("<init>")) { sawSelfCallInConstructor = true; if (DEBUG) System.out.println("Saw self call in " + getFullyQualifiedMethodName() + " to " + invokedClassName + "." + getNameConstantOperand() ); } } } if ((seen == IFNULL || seen == IFNONNULL) && opcodeStack.getStackDepth() > 0) { OpcodeStack.Item item = opcodeStack.getStackItem(0); XField f = item.getXField(); if (f != null) { nullTested.add(f); if (DEBUG) System.out.println(f + " null checked in " + getFullyQualifiedMethodName()); } } if (seen == GETFIELD || seen == INVOKEVIRTUAL || seen == INVOKEINTERFACE || seen == INVOKESPECIAL || seen == PUTFIELD || seen == IALOAD || seen == AALOAD || seen == BALOAD || seen == CALOAD || seen == SALOAD || seen == IASTORE || seen == AASTORE || seen == BASTORE || seen == CASTORE || seen == SASTORE || seen == ARRAYLENGTH) { int pos = 0; switch(seen) { case ARRAYLENGTH: case GETFIELD : pos = 0; break; case INVOKEVIRTUAL : case INVOKEINTERFACE: case INVOKESPECIAL: String sig = getSigConstantOperand(); pos = PreorderVisitor.getNumberArguments(sig); break; case PUTFIELD : case IALOAD : case AALOAD: case BALOAD: case CALOAD: case SALOAD: pos = 1; break; case IASTORE : case AASTORE: case BASTORE: case CASTORE: case SASTORE: pos = 2; break; default: throw new RuntimeException("Impossible"); } if (opcodeStack.getStackDepth() >= pos) { OpcodeStack.Item item = opcodeStack.getStackItem(pos); XField f = item.getXField(); if (DEBUG) System.out.println("RRR: " + f + " " + nullTested.contains(f) + " " + writtenInConstructorFields.contains(f) + " " + writtenNonNullFields.contains(f)); if (f != null && !nullTested.contains(f) && ! (writtenInConstructorFields.contains(f) && writtenNonNullFields.contains(f)) ) { ProgramPoint p = new ProgramPoint(this); HashSet <ProgramPoint> s = assumedNonNull.get(f); if (s == null) { s = new HashSet<ProgramPoint>(); assumedNonNull.put(f,s); } s.add(p); if (DEBUG) System.out.println(f + " assumed non-null in " + getFullyQualifiedMethodName()); } } } if (seen == ALOAD_1) { count_aload_1++; } else if (seen == GETFIELD || seen == GETSTATIC) { XField f = XFactory.createReferencedXField(this); if (DEBUG) System.out.println("get: " + f); readFields.add(f); if (!fieldAccess.containsKey(f)) fieldAccess.put(f, SourceLineAnnotation.fromVisitedInstruction(this)); } else if (seen == PUTFIELD || seen == PUTSTATIC) { XField f = XFactory.createReferencedXField(this); OpcodeStack.Item item = null; if (opcodeStack.getStackDepth() > 0) { item = opcodeStack.getStackItem(0); if (!item.isNull()) nullTested.add(f); } writtenFields.add(f); if (!fieldAccess.containsKey(f)) fieldAccess.put(f, SourceLineAnnotation.fromVisitedInstruction(this)); if (previousOpcode != ACONST_NULL || previousPreviousOpcode == GOTO ) { writtenNonNullFields.add(f); if (DEBUG) System.out.println("put nn: " + f); } else if (DEBUG) System.out.println("put: " + f); if ( getMethod().isStatic() == f.isStatic() && ( calledFromConstructors.contains(getMethodName()+":"+getMethodSig()) || getMethodName().equals("<init>") || getMethodName().equals("init") || getMethodName().equals("init") || getMethodName().equals("initialize") || getMethodName().equals("<clinit>") || getMethod().isPrivate())) { writtenInConstructorFields.add(f); if (previousOpcode != ACONST_NULL || previousPreviousOpcode == GOTO ) assumedNonNull.remove(f); } else { writtenOutsideOfConstructorFields.add(f); } } opcodeStack.sawOpcode(this, seen); previousPreviousOpcode = previousOpcode; previousOpcode = seen; if (false && DEBUG) { System.out.println("After " + OPCODE_NAMES[seen] + " opcode stack is"); System.out.println(opcodeStack); } } Pattern dontComplainAbout = Pattern.compile("class[$]"); @Override public void report() { Set<String> fieldNamesSet = new HashSet<String>(); for(XField f : writtenNonNullFields) fieldNamesSet.add(f.getName()); if (DEBUG) { System.out.println("read fields:" ); for(XField f : readFields) System.out.println(" " + f); if (!containerFields.isEmpty()) { System.out.println("ejb3 fields:" ); for(XField f : containerFields) System.out.println(" " + f); } System.out.println("written fields:" ); for (XField f : writtenFields) System.out.println(" " + f); System.out.println("written nonnull fields:" ); for (XField f : writtenNonNullFields) System.out.println(" " + f); System.out.println("assumed nonnull fields:" ); for (XField f : assumedNonNull.keySet()) System.out.println(" " + f); } // Don't report anything about ejb3Fields declaredFields.removeAll(containerFields); TreeSet<XField> notInitializedInConstructors = new TreeSet<XField>(declaredFields); notInitializedInConstructors.retainAll(readFields); notInitializedInConstructors.retainAll(writtenFields); notInitializedInConstructors.retainAll(assumedNonNull.keySet()); notInitializedInConstructors.removeAll(writtenInConstructorFields); // notInitializedInConstructors.removeAll(staticFields); TreeSet<XField> readOnlyFields = new TreeSet<XField>(declaredFields); readOnlyFields.removeAll(writtenFields); readOnlyFields.retainAll(readFields); TreeSet<XField> nullOnlyFields = new TreeSet<XField>(declaredFields); nullOnlyFields.removeAll(writtenNonNullFields); nullOnlyFields.retainAll(readFields); Set<XField> writeOnlyFields = declaredFields; writeOnlyFields.removeAll(readFields); for (XField f : notInitializedInConstructors) { String fieldName = f.getName(); String className = f.getClassName(); String fieldSignature = f.getSignature(); if (f.isResolved() && !fieldsOfNativeClassed.contains(f) && (fieldSignature.charAt(0) == 'L' || fieldSignature.charAt(0) == '[') ) { int priority = LOW_PRIORITY; // if (assumedNonNull.containsKey(f)) priority--; bugReporter.reportBug(new BugInstance(this, "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", priority) .addClass(className) .addField(f)); } } for (XField f : readOnlyFields) { String fieldName = f.getName(); String className = f.getClassName(); String fieldSignature = f.getSignature(); if (f.isResolved() && !fieldsOfNativeClassed.contains(f)) { int priority = NORMAL_PRIORITY; if (!(fieldSignature.charAt(0) == 'L' || fieldSignature.charAt(0) == '[')) priority++; bugReporter.reportBug(addClassFieldAndAccess(new BugInstance(this, "UWF_UNWRITTEN_FIELD", priority),f)); } } for (XField f : nullOnlyFields) { String fieldName = f.getName(); String className = f.getClassName(); String fieldSignature = f.getSignature(); if (DEBUG) { System.out.println("Null only: " + f); System.out.println(" : " + assumedNonNull.containsKey(f)); System.out.println(" : " + fieldsOfSerializableOrNativeClassed.contains(f)); System.out.println(" : " + fieldNamesSet.contains(f.getName())); System.out.println(" : " + abstractClasses.contains(f.getClassName())); System.out.println(" : " + hasNonAbstractSubClass.contains(f.getClassName())); System.out.println(" : " + f.isResolved()); } if (!f.isResolved()) continue; if (fieldsOfNativeClassed.contains(f)) continue; if (DEBUG) { System.out.println("Ready to report"); } int priority = NORMAL_PRIORITY; if (abstractClasses.contains(f.getClassName())) { priority++; if (! hasNonAbstractSubClass.contains(f.getClassName())) priority++; } // if (fieldNamesSet.contains(f.getName())) priority++; if (assumedNonNull.containsKey(f)) { priority for (ProgramPoint p : assumedNonNull.get(f)) bugReporter.reportBug(new BugInstance(this, "NP_UNWRITTEN_FIELD", NORMAL_PRIORITY) .addClassAndMethod(p.method) .addField(f) .addSourceLine(p.sourceLine) ); } else { if (f.isStatic()) priority++; if (finalFields.contains(f)) priority++; if (fieldsOfSerializableOrNativeClassed.contains(f)) priority++; } if (!readOnlyFields.contains(f)) bugReporter.reportBug( addClassFieldAndAccess(new BugInstance(this,"UWF_NULL_FIELD",priority), f) ); } for (XField f : writeOnlyFields) { String fieldName = f.getName(); String className = f.getClassName(); int lastDollar = Math.max(className.lastIndexOf('$'), className.lastIndexOf('+')); boolean isAnonymousInnerClass = (lastDollar > 0) && (lastDollar < className.length() - 1) && Character.isDigit(className.charAt(className.length() - 1)); if (DEBUG) { System.out.println("Checking write only field " + className + "." + fieldName + "\t" + constantFields.contains(f) + "\t" + f.isStatic() ); } if (!f.isResolved()) continue; if (dontComplainAbout.matcher(fieldName).find()) continue; if (fieldName.startsWith("this$") || fieldName.startsWith("this+")) { String outerClassName = className.substring(0, lastDollar); try { JavaClass outerClass = Repository.lookupClass(outerClassName); if (classHasParameter(outerClass)) continue; } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } if (!innerClassCannotBeStatic.contains(className)) { boolean easyChange = !needsOuterObjectInConstructor.contains(className); if (easyChange || !isAnonymousInnerClass) { // easyChange isAnonymousInnerClass // true false medium, SIC // true true low, SIC_ANON // false true not reported // false false low, SIC_THIS int priority = LOW_PRIORITY; if (easyChange && !isAnonymousInnerClass) priority = NORMAL_PRIORITY; String bug = "SIC_INNER_SHOULD_BE_STATIC"; if (isAnonymousInnerClass) bug = "SIC_INNER_SHOULD_BE_STATIC_ANON"; else if (!easyChange) bug = "SIC_INNER_SHOULD_BE_STATIC_NEEDS_THIS"; bugReporter.reportBug(new BugInstance(this, bug, priority) .addClass(className)); } } } else { if (constantFields.contains(f)) { if (!f.isStatic()) bugReporter.reportBug(addClassFieldAndAccess(new BugInstance(this, "SS_SHOULD_BE_STATIC", NORMAL_PRIORITY), f)); } else if (fieldsOfSerializableOrNativeClassed.contains(f)) { // ignore it } else if (!writtenFields.contains(f) && f.isResolved()) bugReporter.reportBug(new BugInstance(this, "UUF_UNUSED_FIELD", NORMAL_PRIORITY) .addClass(className) .addField(f)); else if (f.getName().toLowerCase().indexOf("guardian") < 0) { int priority = NORMAL_PRIORITY; if (f.isStatic()) priority++; if (finalFields.contains(f)) priority++; bugReporter.reportBug(addClassFieldAndAccess(new BugInstance(this, "URF_UNREAD_FIELD", priority),f)); } } } } /** * @param instance * @return */ private BugInstance addClassFieldAndAccess(BugInstance instance, XField f) { instance.addClass(f.getClassName()).addField(f); if (fieldAccess.containsKey(f)) instance.add(fieldAccess.get(f)); return instance; } }
package net.maizegenetics.analysis.gbs; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import net.maizegenetics.dna.BaseEncoder; /** * Takes a key file and then sets up the methods to decode a read from the sequencer. * The key file decribes how barcodes are related to their taxon. Generally, a keyfile * with all flowcells is included, and then the flowcell and lane to be processed are * indicated in the constructor. * * @author Ed Buckler, Jeff Glaubitz, and James Harriman * */ public class ParseBarcodeRead { private static int chunkSize = BaseEncoder.chunkSize; protected int maximumMismatchInBarcodeAndOverhang = 0; protected static String[] initialCutSiteRemnant = null; protected static int readEndCutSiteRemnantLength; static String nullS = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; protected static String[] likelyReadEnd = null; protected static String theEnzyme = null; static int maxBarcodeLength = 10; private Barcode[] theBarcodes; private long[] quickBarcodeList; private HashMap<Long, Integer> quickMap; /** * Create the barcode parsing object * @param keyFile file location for the keyfile * @param enzyme name of the enzyme * @param flowcell name of the flowcell to be processed * @param lane name of the lane to be processed */ public ParseBarcodeRead(String keyFile, String enzyme, String flowcell, String lane) { if (enzyme != null) { chooseEnzyme(enzyme); } else { chooseEnzyme(getKeyFileEnzyme(keyFile)); } int totalBarcodes = setupBarcodeFiles(new File(keyFile), flowcell, lane); System.out.println("Total barcodes found in lane:" + totalBarcodes); } /** * Determines which cut sites to look for, and sets them, based on the * enzyme used to generate the GBS library. For two-enzyme GBS both enzymes * MUST be specified and separated by a dash "-". e.g. PstI-MspI, SbfI-MspI * The enzyme pair "PstI-EcoT22I" uses the Elshire common adapter while * PstI-MspI, PstI-TaqI, and SbfI-MspI use a Y adapter (Poland et al. 2012) * * @param enzyme The name of the enzyme (case insensitive) */ //TODO these should all be private static final globals, then just use this set which one is active. public static void chooseEnzyme(String enzyme) { // Check for case-insensitive (?i) match to a known enzyme // The common adapter is: [readEndCutSiteRemnant]AGATCGGAAGAGCGGTTCAGCAGGAATGCCGAG if (enzyme.matches("(?i)apek[i1]")) { theEnzyme = "ApeKI"; initialCutSiteRemnant = new String[]{"CAGC", "CTGC"}; likelyReadEnd = new String[]{"GCAGC", "GCTGC", "GCAGAGAT", "GCTGAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 4; } else if (enzyme.matches("(?i)pst[i1]")) { theEnzyme = "PstI"; initialCutSiteRemnant = new String[]{"TGCAG"}; likelyReadEnd = new String[]{"CTGCAG", "CTGCAAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 5; } else if (enzyme.matches("(?i)ecot22[i1]")) { theEnzyme = "EcoT22I"; initialCutSiteRemnant = new String[]{"TGCAT"}; likelyReadEnd = new String[]{"ATGCAT", "ATGCAAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 5; } else if (enzyme.matches("(?i)pas[i1]")) { theEnzyme = "PasI"; initialCutSiteRemnant = new String[]{"CAGGG", "CTGGG"}; likelyReadEnd = new String[]{"CCCAGGG", "CCCTGGG", "CCCTGAGAT", "CCCAGAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 5; } else if (enzyme.matches("(?i)hpaii|(?i)hpa2")) { theEnzyme = "HpaII"; initialCutSiteRemnant = new String[]{"CGG"}; likelyReadEnd = new String[]{"CCGG", "CCGAGATCGG"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)msp[i1]")) { theEnzyme = "MspI"; // MspI and HpaII are isoschizomers (same recognition seq and overhang) initialCutSiteRemnant = new String[]{"CGG"}; likelyReadEnd = new String[]{"CCGG", "CCGAGATCGG"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)pst[i1]-apek[i1]")) { theEnzyme = "PstI-ApeKI"; initialCutSiteRemnant = new String[]{"TGCAG"}; likelyReadEnd = new String[]{"GCAGC", "GCTGC", "CTGCAG", "GCAGAGAT", "GCTGAGAT"}; // look for ApeKI site, PstI site, or common adapter for ApeKI readEndCutSiteRemnantLength = 4; } else if (enzyme.matches("(?i)pst[i1]-ecot22[i1]")) { theEnzyme = "PstI-EcoT22I"; initialCutSiteRemnant = new String[]{"TGCAG", "TGCAT"}; likelyReadEnd = new String[]{"ATGCAT", "CTGCAG", "CTGCAAGAT", "ATGCAAGAT"}; // look for EcoT22I site, PstI site, or common adapter for PstI/EcoT22I readEndCutSiteRemnantLength = 5; } else if (enzyme.matches("(?i)pst[i1]-msp[i1]")) { theEnzyme = "PstI-MspI"; initialCutSiteRemnant = new String[]{"TGCAG"}; // corrected, change from CCGAGATC to CCGCTCAGG, as Y adapter was used for MspI -QS likelyReadEnd = new String[]{"CCGG", "CTGCAG", "CCGCTCAGG"}; // look for MspI site, PstI site, or common adapter for MspI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)pst[i1]-taq[i1]")) { theEnzyme = "PstI-TaqI"; // corrected, change from TCGAGATC to TCGCTCAGG, as Y adapter was used for TaqI -QS initialCutSiteRemnant = new String[]{"TGCAG"}; likelyReadEnd = new String[]{"TCGA", "CTGCAG", "TCGCTCAGG"}; // look for TaqI site, PstI site, or common adapter for TaqI readEndCutSiteRemnantLength = 3; } else if(enzyme.matches("(?i)PaeR7[i1]-Hha[i1]")) { theEnzyme = "PaeR7I-HhaI"; // Requested by Ye, Songqing, use same Y adapter as Polland paper -QS initialCutSiteRemnant=new String[]{"TCGAG"}; likelyReadEnd = new String[]{"GCGC", "CTCGAG", "GCGAGATC"}; // look for HhaI site, PaeR7I site, or common adapter for HhaI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)sbf[i1]-msp[i1]")) { theEnzyme = "SbfI-MspI"; initialCutSiteRemnant = new String[]{"TGCAGG"}; // corrected, change from CCGAGATC to CCGCTCAGG, as Y adapter was used for MspI -QS likelyReadEnd = new String[]{"CCGG", "CCTGCAGG", "CCGCTCAGG"}; // look for MspI site, SbfI site, or common adapter for MspI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)asis[i1]-msp[i1]")) { theEnzyme = "AsiSI-MspI"; initialCutSiteRemnant = new String[]{"ATCGC"}; // likelyReadEnd for common adapter is CCGCTCAGG, as the Poland et al.(2012) Y adapter was used for MspI likelyReadEnd = new String[]{"CCGG", "GCGATCGC", "CCGCTCAGG"}; // look for MspI site, AsiSI site, or common adapter for MspI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)bsshii-msp[i1]|(?i)bssh2-msp[i1]")) { theEnzyme = "BssHII-MspI"; initialCutSiteRemnant = new String[]{"CGCGC"}; // likelyReadEnd for common adapter is CCGCTCAGG, as the Poland et al.(2012) Y adapter was used for MspI likelyReadEnd = new String[]{"CCGG", "GCGCGC", "CCGCTCAGG"}; // look for MspI site, BssHII site, or common adapter for MspI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)fse[i1]-msp[i1]")) { theEnzyme = "FseI-MspI"; initialCutSiteRemnant = new String[]{"CCGGCC"}; // likelyReadEnd for common adapter is CCGCTCAGG, as the Poland et al.(2012) Y adapter was used for MspI likelyReadEnd = new String[]{"CCGG", "GGCCGGCC", "CCGCTCAGG"}; // look for MspI site, FseI site, or common adapter for MspI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)sal[i1]-msp[i1]")) { theEnzyme = "SalI-MspI"; initialCutSiteRemnant = new String[]{"TCGAC"}; // likelyReadEnd for common adapter is CCGCTCAGG, as the Poland et al.(2012) Y adapter was used for MspI likelyReadEnd = new String[]{"CCGG", "GTCGAC", "CCGCTCAGG"}; // look for MspI site, SalI site, or common adapter for MspI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)ecor[i1]-msp[i1]")) { theEnzyme = "EcoRI-MspI"; // G^AATTC C^CGG initialCutSiteRemnant = new String[]{"AATTC"}; likelyReadEnd = new String[]{"CCGG", "GAATTC", "CCGAGATC"}; // look for MspI site, EcoRI site, or Poland et al. 2012 Y-adapter for MspI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)hindiii-msp[i1]|(?i)hind3-msp[i1]")) { theEnzyme = "HindIII-MspI"; // A^AGCTT C^CGG initialCutSiteRemnant = new String[]{"AGCTT"}; likelyReadEnd = new String[]{"CCGG", "AAGCTT", "CCGAGATC"}; // look for MspI site, HindIII site, or Poland et al. 2012 Y-adapter for MspI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)sexa[i1]-sau3a[i1]")) { theEnzyme = "SexAI-Sau3AI"; // A^CCWGGT ^GATC (not blunt) initialCutSiteRemnant = new String[]{"CCAGGT", "CCTGGT"}; likelyReadEnd = new String[]{"GATC", "ACCAGGT", "ACCTGGT", "GATCAGATC"}; // look for SexAI site, Sau3AI site, or Poland et al. 2012 Y-adapter for Sau3AI readEndCutSiteRemnantLength = 4; } else if (enzyme.matches("(?i)bamh[i1l]-mluc[i1]")) { theEnzyme = "BamHI-MluCI"; // G^GATCC ^AATT (not blunt) initialCutSiteRemnant = new String[]{"GATCC"}; likelyReadEnd = new String[]{"AATT", "GGATCC", "AATTAGATC"}; // look for MluCI site, BamHI site, or Poland et al. 2012 Y-adapter for MluCI readEndCutSiteRemnantLength = 4; } else if (enzyme.matches("(?i)psti-msei|(?i)pst1-mse1")) { theEnzyme = "PstI-MseI"; // CTGCA^G T^TAA initialCutSiteRemnant = new String[]{"TGCAG"}; likelyReadEnd = new String[]{"TTAA", "CTGCAG", "TTAAGATC"}; // look for MseI site, PstI site, or Poland et al. 2012 Y-adapter for MseI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)avaii-msei|(?i)ava2-mse1")) { theEnzyme = "AvaII-MseI"; // G^GWCC T^TAA W=AorT initialCutSiteRemnant = new String[]{"GACC", "GTCC"}; likelyReadEnd = new String[]{"TTAA", "GGACC", "GGTCC", "TTAAGATC"}; // look for MseI site, AvaII site, or Poland et al. 2012 Y-adapter for MseI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)ecori-msei|(?i)ecor1-mse1")) { theEnzyme = "EcoRI-MseI"; // G^AATTC T^TAA initialCutSiteRemnant = new String[]{"AATTC"}; likelyReadEnd = new String[]{"TTAA", "GAATTC", "TTAAGATC"}; // look for MseI site, EcoRI site, or Poland et al. 2012 Y-adapter for MseI readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)ecori-avaii|(?i)ecor1-ava2")) { theEnzyme = "EcoRI-AvaII"; // G^AATTC G^GWCC initialCutSiteRemnant = new String[]{"AATTC"}; likelyReadEnd = new String[]{"GGACC", "GGTCC", "GAATTC", "GGACAGATC", "GGTCAGATC"}; // look for AvaII site, EcoRI site, or Poland et al. 2012 Y-adapter for AvaII readEndCutSiteRemnantLength = 4; } else if (enzyme.matches("(?i)ecori-hinfi|(?i)ecor1-hinf1")) { theEnzyme = "EcoRI-HinfI"; // G^AATTC G^ANTC initialCutSiteRemnant = new String[]{"AATTC"}; likelyReadEnd = new String[]{"GAATC", "GACTC", "GAGTC", "GATTC", "GAATTC", "GAATAGATC", "GACTAGATC", "GAGTAGATC", "GATTAGATC"}; // look for HinfI site, EcoRI site, or Poland et al. 2012 Y-adapter for HinfI readEndCutSiteRemnantLength = 4; } else if (enzyme.matches("(?i)bbvci-mspi|(?i)bbvc1-msp1")) { theEnzyme = "BbvCI-MspI"; // CCTCAGC (-5/-2) C^CGG initialCutSiteRemnant = new String[]{"TCAGC"}; likelyReadEnd = new String[]{"CCGG", "CCTCAGC", "CCGAGATC"}; // look for MspI site, BbvCI site, or Poland et al. 2012 Y-adapter for MspI readEndCutSiteRemnantLength = 3; } else if(enzyme.matches("(?i)apo[i1]")){ theEnzyme = "ApoI"; initialCutSiteRemnant=new String[]{"AATTC","AATTT"}; likelyReadEnd = new String[]{"AAATTC","AAATTT","GAATTC","GAATTT","AAATTAGAT","GAATTAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 5; } else if (enzyme.matches("(?i)BamH[i1l]")) { theEnzyme = "BamHI"; initialCutSiteRemnant = new String[]{"GATCC"}; likelyReadEnd = new String[]{"GGATCC", "GGATCAGAT"}; // full cut site (from partial digest or chimera) or common adapter start // likelyReadEnd = new String[]{"GGATCC", "AGATCGGAA", "AGATCGGAAGAGCGGTTCAGCAGGAATGCCGAG"}; // <-- corrected from this by Jeff Glaubitz on 2012/09/12 readEndCutSiteRemnantLength = 5; } else if (enzyme.matches("(?i)mse[i1]")) { theEnzyme = "MseI"; initialCutSiteRemnant = new String[]{"TAA"}; likelyReadEnd = new String[]{"TTAA", "TTAAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 3; } else if(enzyme.matches("(?i)Sau3A[i1]")){ theEnzyme = "Sau3AI"; initialCutSiteRemnant=new String[]{"GATC"}; likelyReadEnd = new String[]{"GATC","GATCAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 4; } else if(enzyme.matches("(?i)nde[i1]")){ theEnzyme = "NdeI"; initialCutSiteRemnant=new String[]{"TATG"}; likelyReadEnd = new String[]{"CATATG","CATAAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 4; } else if(enzyme.matches("(?i)hinp1[i1]")){ theEnzyme = "HinP1I"; initialCutSiteRemnant=new String[]{"CGC"}; likelyReadEnd = new String[]{"GCGC","GCGAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 3; } else if(enzyme.matches("(?i)sbf[i1]")){ theEnzyme = "SbfI"; initialCutSiteRemnant=new String[]{"TGCAGG"}; likelyReadEnd = new String[]{"CCTGCAGG","CCTGCAAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 6; } else if (enzyme.matches("(?i)hindiii|(?i)hind3")) { theEnzyme = "HindIII"; // A^AGCTT initialCutSiteRemnant=new String[]{"AGCTT"}; likelyReadEnd = new String[]{"AAGCTT","AAGCTAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 5; } else if(enzyme.matches("(?i)ecor[i1]")) { theEnzyme = "EcoRI"; // G^AATTC initialCutSiteRemnant= new String[]{"AATTC"}; likelyReadEnd = new String[]{"GAATTC","GAATTAGAT"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 5; } else if(enzyme.matches("(?i)cviq[i1]")){ theEnzyme = "CviQI"; // CviQI and Csp6I are isoschizomers (same recognition seq and overhang) initialCutSiteRemnant=new String[]{"TAC"}; likelyReadEnd = new String[]{"GTAC","GTAAGATCGG"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 3; } else if(enzyme.matches("(?i)csp6[i1]")){ theEnzyme = "Csp6I"; // Csp6I and CviQI are isoschizomers (same recognition seq and overhang) initialCutSiteRemnant=new String[]{"TAC"}; likelyReadEnd = new String[]{"GTAC","GTAAGATCGG"}; // full cut site (from partial digest or chimera) or common adapter start readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)RBSTA")) { theEnzyme = "RBSTA"; initialCutSiteRemnant = new String[]{"TA"}; likelyReadEnd = new String[]{"TTAA", "GTAC", "CTAG", "TTAAGAT", "GTAAGAT", "CTAAGAT"}; // full cut site (from partial digest or chimera) of MseI, CVIQi, XspI or common adapter start readEndCutSiteRemnantLength = 3; } else if (enzyme.matches("(?i)RBSCG")) { theEnzyme = "RBSCG"; initialCutSiteRemnant = new String[]{"CG"}; likelyReadEnd = new String[]{"CCGC", "TCGA", "GCGC", "CCGG", "ACGT", "CCGAGAT", "TCGAGAT", "GCGAGAT", "ACGAGAT"}; // full cut site (from partial digest or chimera) of AciI, TaqaI, HinpI, HpaII, HpyCH4IV or common adapter start readEndCutSiteRemnantLength = 3; } else { System.out.println("The software didn't recognize your cut site.\n" +"Currently, only the following enzymes are recognized for single enzyme digests:\n" +" ApeKI" +"\n" +" ApoI" +"\n" +" BamHI" +"\n" +" Csp6I" +"\n" +" CviQI" +"\n" +" EcoRI" +"\n" +" EcoT22I" +"\n" +" HindIII" +"\n" +" HinP1I" +"\n" +" HpaII" +"\n" +" MseI" +"\n" +" MspI" +"\n" +" NdeI" +"\n" +" PasI" +"\n" +" PstI" +"\n" +" Sau3AI" +"\n" +" SbfI" +"\n" +" RBSTA" +"\n" +" RBSCG" +"\n" +"Or the following for two-enzyme digests:\n" +" AsiSI-MspI" +"\n" +" AvaII-MseI" +"\n" +" BamHI-MluCI" +"\n" +" BbvCI-MspI" +"\n" +" BssHII-MspI" +"\n" +" EcoRI-AvaII" +"\n" +" EcoRI-HinfI" +"\n" +" EcoRI-MseI" +"\n" +" EcoRI-MspI" +"\n" +" FseI-MspI" +"\n" +" HindIII-MspI" +"\n" +" HindIII-NlaIII" +"\n" +" PaeR7I-HhaI" +"\n" +" PstI-ApeKI" +"\n" +" PstI-EcoT22I" +"\n" +" PstI-MseI" +"\n" +" PstI-MspI" +"\n" +" PstI-TaqI" +"\n" +" SalI-MspI" +"\n" +" SbfI-MspI" +"\n" +" SexAI-Sau3AI" +"\n" ); System.out.println("For two-enzyme digest, enzyme names should be separated by a dash, e.g. PstI-MspI "); } System.out.println("Enzyme: " + theEnzyme); } private String getKeyFileEnzyme(String keyFileName) { String result = null; try { BufferedReader br = new BufferedReader(new FileReader(keyFileName), 65536); String temp; int currLine = 0; while (((temp = br.readLine()) != null)) { String[] s = temp.split("\\t"); //split by whitespace if (currLine > 0) { String enzymeName; if (s.length < 9) { enzymeName = ""; } else { enzymeName = s[8]; } if (!enzymeName.equals("")) { result = enzymeName; break; } } currLine++; } } catch (Exception e) { System.out.println("Couldn't open key file to read Enzyme: " + e); } return result; } /** * Reads in an Illumina key file, creates a linear array of {@link Barcode} objects * representing the barcodes in the key file, then creates a hash map containing * indices from the linear array indexed by sequence. The names of barcode objects * follow the pattern samplename:flowcell:lane:well, since sample names alone are not unique. * * @param keyFile Illumina key file. * @param flowcell Only barcodes from this flowcell will be added to the array. * @param lane Only barcodes from this lane will be added to the array. * @return Number of barcodes in the array. */ private int setupBarcodeFiles(File keyFile, String flowcell, String lane) { try { BufferedReader br = new BufferedReader(new FileReader(keyFile), 65536); ArrayList<Barcode> theBarcodesArrayList = new ArrayList<Barcode>(); String temp; while (((temp = br.readLine()) != null)) { String[] s = temp.split("\\t"); //split by whitespace Barcode theBC = null; if (s[0].equals(flowcell) && s[1].equals(lane)) { String well = (s[6].length() < 2) ? (s[5] + '0' + s[6]) : s[5] + s[6]; if (s.length < 8 || s[7] == null || s[7].equals("")) { // use the plate and well theBC = new Barcode(s[2], initialCutSiteRemnant, s[3] + ":" + s[0] + ":" + s[1] + ":" + s[4] + ":" + well, flowcell, lane); } else { // use the "libraryPlateWellID" or whatever is in column H of the key file, IF it is an integer try { int libPrepID = Integer.parseInt(s[7]); theBC = new Barcode(s[2], initialCutSiteRemnant, s[3] + ":" + s[0] + ":" + s[1] + ":" + libPrepID, flowcell, lane); } catch (NumberFormatException nfe) { theBC = new Barcode(s[2], initialCutSiteRemnant, s[3] + ":" + s[0] + ":" + s[1] + ":" + s[4] + ":" + well, flowcell, lane); } } theBarcodesArrayList.add(theBC); System.out.println(theBC.barcodeS + " " + theBC.taxaName); } } theBarcodes = new Barcode[theBarcodesArrayList.size()]; theBarcodesArrayList.toArray(theBarcodes); Arrays.sort(theBarcodes); int nBL = theBarcodes[0].barOverLong.length; quickBarcodeList = new long[theBarcodes.length * nBL]; quickMap = new HashMap(); for (int i = 0; i < theBarcodes.length; i++) { for (int j = 0; j < nBL; j++) { quickBarcodeList[i * nBL + j] = theBarcodes[i].barOverLong[j]; quickMap.put(theBarcodes[i].barOverLong[j], i); } } Arrays.sort(quickBarcodeList); } catch (Exception e) { System.out.println("Error with setupBarcodeFiles: " + e); } return theBarcodes.length; } /** * Returns the best barcode match for a given sequence. * @param queryS query sequence to be tested against all barcodes * @param maxDivergence maximum divergence to permit * @return best barcode match (null if no good match) */ Barcode findBestBarcode(String queryS, int maxDivergence) { long query = BaseEncoder.getLongFromSeq(queryS.substring(0, chunkSize)); //note because the barcodes are polyA after the sequence, they should always //sort ahead of the hit, this is the reason for the -(closestHit+2) int closestHit = Arrays.binarySearch(quickBarcodeList, query); /* THIS IS THE NEW PIPELINE APPROACH THAT DOES NOT WORK if(closestHit>-2) return null; //hit or perfect if((query&quickBarcodeList[-(closestHit+2)])!=quickBarcodeList[-(closestHit+2)]) return null; int index =quickMap.get(quickBarcodeList[-(closestHit+2)]); // System.out.println(theBarcodes[index].barcodeS); return theBarcodes[index]; //note to see if it is a perfect match you can just bit AND */ // Below is the old pipeline approach, which works (at least for maxDivergence of 0) if (closestHit < -1) { // should always be true, as the barcode+overhang is padded to 32 bases with polyA int index = quickMap.get(quickBarcodeList[-(closestHit + 2)]); if (theBarcodes[index].compareSequence(query, 1) == 0) { return theBarcodes[index]; } else if (maxDivergence == 0) { return null; // return null if not a perfect match } } else { return null; // should never go to this line } int maxLength = 0, minDiv = maxDivergence + 1, countBest = 0; Barcode bestBC = null; for (Barcode bc : theBarcodes) { int div = bc.compareSequence(query, maxDivergence + 1); if (div <= minDiv) { if ((div < minDiv) || (bc.barOverLength > maxLength)) { minDiv = div; maxLength = bc.barOverLength; bestBC = bc; countBest = 1; } else { //it is a tie, so return that not resolvable bestBC = null; countBest++; } } } return bestBC; } /** * The barcode libraries used for this study can include two types of * extraneous sequence at the end of reads. The first are chimeras created * with the free ends. These will recreate the restriction site. The second * are short regions (less than 64bp), so that will they will contain a * portion of site and the universal adapter. This finds the first of site * in likelyReadEnd, keeps the restriction site overhang and then sets * everything to polyA afterwards * * @param seq An unprocessed tag sequence. * @param maxLength The maximum number of bp in the processed sequence. * @return returnValue A ReadBarcodeResult object containing the unprocessed * tag, Cut site position, Processed tag, and Poly-A padded tag. */ public static ReadBarcodeResult removeSeqAfterSecondCutSite(String seq, byte maxLength) { //this looks for a second restriction site or the common adapter start, and then turns the remaining sequence to AAAA int cutSitePosition = 9999; ReadBarcodeResult returnValue = new ReadBarcodeResult(seq); //Look for cut sites, starting at a point past the length of the initial cut site remnant that all reads begin with String match = null; for (String potentialCutSite : likelyReadEnd) { int p = seq.indexOf(potentialCutSite, 1); if ((p > 1) && (p < cutSitePosition)) { cutSitePosition = p; match = potentialCutSite; } } if (theEnzyme.equalsIgnoreCase("ApeKI") && cutSitePosition == 2 && (match.equalsIgnoreCase("GCAGC") || match.equalsIgnoreCase("GCTGC"))) { // overlapping ApeKI cut site: GCWGCWGC seq = seq.substring(3, seq.length()); // trim off the initial GCW from GCWGCWGC cutSitePosition = 9999; returnValue.unprocessedSequence = seq; for (String potentialCutSite : likelyReadEnd) { int p = seq.indexOf(potentialCutSite, 1); if ((p > 1) && (p < cutSitePosition)) { cutSitePosition = p; } } } if (cutSitePosition < maxLength) { // Cut site found //Trim tag to sequence up to & including the cut site returnValue.length = (byte) (cutSitePosition + readEndCutSiteRemnantLength); returnValue.processedSequence = seq.substring(0, cutSitePosition + readEndCutSiteRemnantLength); } else { if (seq.length() <= 0) { //If cut site is missing because there is no sequence returnValue.processedSequence = ""; returnValue.length = 0; } else { //If cut site is missing because it is beyond the end of the sequence (or not present at all) returnValue.length = (byte) Math.min(seq.length(), maxLength); returnValue.processedSequence = (seq.substring(0, returnValue.length)); } } //Pad sequences shorter than max. length with A if (returnValue.length < maxLength) { returnValue.paddedSequence = returnValue.processedSequence + nullS; returnValue.paddedSequence = returnValue.paddedSequence.substring(0, maxLength); } else { //Truncate sequences longer than max. length returnValue.paddedSequence = returnValue.processedSequence.substring(0, maxLength); returnValue.length = maxLength; } return returnValue; } /** * Return a {@link ReadBarcodeResult} that captures the processed read and taxa * inferred by the barcode * @param seqS DNA sequence from the sequencer * @param qualS quality score string from the sequencer * @param fastq (fastq = true?; qseq=false?) * @param minQual minimum quality score * @return If barcode and cut site was found returns the result and * processed sequence, if the barcode and cut site were not found return * null */ public ReadBarcodeResult parseReadIntoTagAndTaxa(String seqS, String qualS, boolean fastq, int minQual) { long[] read = new long[2]; if ((minQual > 0) && (qualS != null)) { int firstBadBase = BaseEncoder.getFirstLowQualityPos(qualS, minQual); if (firstBadBase < (maxBarcodeLength + 2 * chunkSize)) { return null; } } int miss = -1; if (fastq) { miss = seqS.lastIndexOf('N', maxBarcodeLength + 2*chunkSize - 1); } else { miss = seqS.lastIndexOf('.', maxBarcodeLength + 2*chunkSize - 1); } if (miss != -1) { return null; //bad sequence so skip } Barcode bestBarcode = findBestBarcode(seqS, maximumMismatchInBarcodeAndOverhang); if (bestBarcode == null) { return null; //overhang missing so skip } String genomicSeq = seqS.substring(bestBarcode.barLength, seqS.length()); ReadBarcodeResult tagProcessingResults = removeSeqAfterSecondCutSite(genomicSeq, (byte) (2 * chunkSize)); String hap = tagProcessingResults.paddedSequence; //this is slow 20% of total time. Tag, cut site processed, padded with poly-A read = BaseEncoder.getLongArrayFromSeq(hap); int pos = tagProcessingResults.length; //TODO this instantiation should also include the orginal unprocessedSequence, processedSequence, and paddedSequence - the the object encode it ReadBarcodeResult rbr = new ReadBarcodeResult(read, (byte) pos, bestBarcode.getTaxaName()); return rbr; } /**Returns the number of barcodes for the flowcell and lane*/ public int getBarCodeCount() { return theBarcodes.length; } /**Returns the {@link Barcode} for the flowcell and lane*/ public Barcode getTheBarcodes(int index) { return theBarcodes[index]; } /**Returns the taxaNames for the flowcell and lane*/ public String[] getTaxaNames() { String[] result = new String[getBarCodeCount()]; for (int i = 0; i < result.length; i++) { result[i] = getTheBarcodes(i).getTaxaName(); } return result; } }
package com.iyzipay.model.sample; import com.iyzipay.model.*; import com.iyzipay.request.CreatePaymentRequest; import com.iyzipay.request.RetrievePaymentRequest; import org.junit.Test; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class PaymentSample extends Sample { @Test public void should_create_payment_with_physical_and_virtual_item_for_standard_merchant() { CreatePaymentRequest request = new CreatePaymentRequest(); request.setLocale(Locale.TR.getValue()); request.setConversationId("123456789"); request.setPrice(new BigDecimal("1")); request.setPaidPrice(new BigDecimal("1.1")); request.setInstallment(1); request.setBasketId("B67832"); request.setPaymentChannel(PaymentChannel.WEB.name()); request.setPaymentGroup(PaymentGroup.PRODUCT.name()); PaymentCard paymentCard = new PaymentCard(); paymentCard.setCardHolderName("John Doe"); paymentCard.setCardNumber("5528790000000008"); paymentCard.setExpireMonth("12"); paymentCard.setExpireYear("2030"); paymentCard.setCvc("123"); paymentCard.setRegisterCard(0); request.setPaymentCard(paymentCard); Buyer buyer = new Buyer(); buyer.setId("BY789"); buyer.setName("John"); buyer.setSurname("Doe"); buyer.setGsmNumber("+905350000000"); buyer.setEmail("email@email.com"); buyer.setIdentityNumber("74300864791"); buyer.setLastLoginDate("2015-10-05 12:43:35"); buyer.setRegistrationDate("2013-04-21 15:12:09"); buyer.setRegistrationAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); buyer.setIp("85.34.78.112"); buyer.setCity("Istanbul"); buyer.setCountry("Turkey"); buyer.setZipCode("34732"); request.setBuyer(buyer); Address shippingAddress = new Address(); shippingAddress.setContactName("Jane Doe"); shippingAddress.setCity("Istanbul"); shippingAddress.setCountry("Turkey"); shippingAddress.setAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); shippingAddress.setZipCode("34742"); request.setShippingAddress(shippingAddress); Address billingAddress = new Address(); billingAddress.setContactName("Jane Doe"); billingAddress.setCity("Istanbul"); billingAddress.setCountry("Turkey"); billingAddress.setAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); billingAddress.setZipCode("34742"); request.setBillingAddress(billingAddress); List<BasketItem> basketItems = new ArrayList<BasketItem>(); BasketItem firstBasketItem = new BasketItem(); firstBasketItem.setId("BI101"); firstBasketItem.setName("Binocular"); firstBasketItem.setCategory1("Collectibles"); firstBasketItem.setCategory2("Accessories"); firstBasketItem.setItemType(BasketItemType.PHYSICAL.name()); firstBasketItem.setPrice(new BigDecimal("0.3")); basketItems.add(firstBasketItem); BasketItem secondBasketItem = new BasketItem(); secondBasketItem.setId("BI102"); secondBasketItem.setName("Game code"); secondBasketItem.setCategory1("Game"); secondBasketItem.setCategory2("Online Game Items"); secondBasketItem.setItemType(BasketItemType.VIRTUAL.name()); secondBasketItem.setPrice(new BigDecimal("0.5")); basketItems.add(secondBasketItem); BasketItem thirdBasketItem = new BasketItem(); thirdBasketItem.setId("BI103"); thirdBasketItem.setName("Usb"); thirdBasketItem.setCategory1("Electronics"); thirdBasketItem.setCategory2("Usb / Cable"); thirdBasketItem.setItemType(BasketItemType.PHYSICAL.name()); thirdBasketItem.setPrice(new BigDecimal("0.2")); basketItems.add(thirdBasketItem); request.setBasketItems(basketItems); Payment payment = Payment.create(request, options); System.out.println(payment); assertNotNull(payment.getSystemTime()); assertEquals(Status.SUCCESS.getValue(), payment.getStatus()); assertEquals(Locale.TR.getValue(), payment.getLocale()); assertEquals("123456789", payment.getConversationId()); } @Test public void should_create_payment_with_physical_and_virtual_item_for_market_place() { CreatePaymentRequest request = new CreatePaymentRequest(); request.setLocale(Locale.TR.getValue()); request.setConversationId("123456789"); request.setPrice(new BigDecimal("1")); request.setPaidPrice(new BigDecimal("1.1")); request.setInstallment(1); request.setBasketId("B67832"); request.setPaymentChannel(PaymentChannel.WEB.name()); request.setPaymentGroup(PaymentGroup.PRODUCT.name()); PaymentCard paymentCard = new PaymentCard(); paymentCard.setCardHolderName("John Doe"); paymentCard.setCardNumber("5528790000000008"); paymentCard.setExpireMonth("12"); paymentCard.setExpireYear("2030"); paymentCard.setCvc("123"); paymentCard.setRegisterCard(0); request.setPaymentCard(paymentCard); Buyer buyer = new Buyer(); buyer.setId("BY789"); buyer.setName("John"); buyer.setSurname("Doe"); buyer.setGsmNumber("+905350000000"); buyer.setEmail("email@email.com"); buyer.setIdentityNumber("74300864791"); buyer.setLastLoginDate("2015-10-05 12:43:35"); buyer.setRegistrationDate("2013-04-21 15:12:09"); buyer.setRegistrationAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); buyer.setIp("85.34.78.112"); buyer.setCity("Istanbul"); buyer.setCountry("Turkey"); buyer.setZipCode("34732"); request.setBuyer(buyer); Address shippingAddress = new Address(); shippingAddress.setContactName("Jane Doe"); shippingAddress.setCity("Istanbul"); shippingAddress.setCountry("Turkey"); shippingAddress.setAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); shippingAddress.setZipCode("34742"); request.setShippingAddress(shippingAddress); Address billingAddress = new Address(); billingAddress.setContactName("Jane Doe"); billingAddress.setCity("Istanbul"); billingAddress.setCountry("Turkey"); billingAddress.setAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); billingAddress.setZipCode("34742"); request.setBillingAddress(billingAddress); List<BasketItem> basketItems = new ArrayList<BasketItem>(); BasketItem firstBasketItem = new BasketItem(); firstBasketItem.setId("BI101"); firstBasketItem.setName("Binocular"); firstBasketItem.setCategory1("Collectibles"); firstBasketItem.setCategory2("Accessories"); firstBasketItem.setItemType(BasketItemType.PHYSICAL.name()); firstBasketItem.setPrice(new BigDecimal("0.3")); firstBasketItem.setSubMerchantKey("sub merchant key"); firstBasketItem.setSubMerchantPrice(new BigDecimal("0.27")); basketItems.add(firstBasketItem); BasketItem secondBasketItem = new BasketItem(); secondBasketItem.setId("BI102"); secondBasketItem.setName("Game code"); secondBasketItem.setCategory1("Game"); secondBasketItem.setCategory2("Online Game Items"); secondBasketItem.setItemType(BasketItemType.VIRTUAL.name()); secondBasketItem.setPrice(new BigDecimal("0.5")); secondBasketItem.setSubMerchantKey("sub merchant key"); secondBasketItem.setSubMerchantPrice(new BigDecimal("0.42")); basketItems.add(secondBasketItem); BasketItem thirdBasketItem = new BasketItem(); thirdBasketItem.setId("BI103"); thirdBasketItem.setName("Usb"); thirdBasketItem.setCategory1("Electronics"); thirdBasketItem.setCategory2("Usb / Cable"); thirdBasketItem.setItemType(BasketItemType.PHYSICAL.name()); thirdBasketItem.setPrice(new BigDecimal("0.2")); thirdBasketItem.setSubMerchantKey("sub merchant key"); thirdBasketItem.setSubMerchantPrice(new BigDecimal("0.18")); basketItems.add(thirdBasketItem); request.setBasketItems(basketItems); Payment payment = Payment.create(request, options); System.out.println(payment); assertNotNull(payment.getSystemTime()); assertEquals(Status.SUCCESS.getValue(), payment.getStatus()); assertEquals(Locale.TR.getValue(), payment.getLocale()); assertEquals("123456789", payment.getConversationId()); } @Test public void should_create_payment_with_physical_and_virtual_item_for_listing_or_subscription() { CreatePaymentRequest request = new CreatePaymentRequest(); request.setLocale(Locale.TR.getValue()); request.setConversationId("123456789"); request.setPrice(new BigDecimal("1")); request.setPaidPrice(new BigDecimal("1.1")); request.setInstallment(1); request.setBasketId("B67832"); request.setPaymentChannel(PaymentChannel.WEB.name()); request.setPaymentGroup(PaymentGroup.SUBSCRIPTION.name()); PaymentCard paymentCard = new PaymentCard(); paymentCard.setCardHolderName("John Doe"); paymentCard.setCardNumber("5528790000000008"); paymentCard.setExpireMonth("12"); paymentCard.setExpireYear("2030"); paymentCard.setCvc("123"); paymentCard.setRegisterCard(0); request.setPaymentCard(paymentCard); Buyer buyer = new Buyer(); buyer.setId("BY789"); buyer.setName("John"); buyer.setSurname("Doe"); buyer.setGsmNumber("+905350000000"); buyer.setEmail("email@email.com"); buyer.setIdentityNumber("74300864791"); buyer.setLastLoginDate("2015-10-05 12:43:35"); buyer.setRegistrationDate("2013-04-21 15:12:09"); buyer.setRegistrationAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); buyer.setIp("85.34.78.112"); buyer.setCity("Istanbul"); buyer.setCountry("Turkey"); buyer.setZipCode("34732"); request.setBuyer(buyer); Address shippingAddress = new Address(); shippingAddress.setContactName("Jane Doe"); shippingAddress.setCity("Istanbul"); shippingAddress.setCountry("Turkey"); shippingAddress.setAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); shippingAddress.setZipCode("34742"); request.setShippingAddress(shippingAddress); Address billingAddress = new Address(); billingAddress.setContactName("Jane Doe"); billingAddress.setCity("Istanbul"); billingAddress.setCountry("Turkey"); billingAddress.setAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); billingAddress.setZipCode("34742"); request.setBillingAddress(billingAddress); List<BasketItem> basketItems = new ArrayList<BasketItem>(); BasketItem firstBasketItem = new BasketItem(); firstBasketItem.setId("BI101"); firstBasketItem.setName("Binocular"); firstBasketItem.setCategory1("Collectibles"); firstBasketItem.setCategory2("Accessories"); firstBasketItem.setItemType(BasketItemType.PHYSICAL.name()); firstBasketItem.setPrice(new BigDecimal("0.3")); basketItems.add(firstBasketItem); BasketItem secondBasketItem = new BasketItem(); secondBasketItem.setId("BI102"); secondBasketItem.setName("Game code"); secondBasketItem.setCategory1("Game"); secondBasketItem.setCategory2("Online Game Items"); secondBasketItem.setItemType(BasketItemType.VIRTUAL.name()); secondBasketItem.setPrice(new BigDecimal("0.5")); basketItems.add(secondBasketItem); BasketItem thirdBasketItem = new BasketItem(); thirdBasketItem.setId("BI103"); thirdBasketItem.setName("Usb"); thirdBasketItem.setCategory1("Electronics"); thirdBasketItem.setCategory2("Usb / Cable"); thirdBasketItem.setItemType(BasketItemType.VIRTUAL.name()); thirdBasketItem.setPrice(new BigDecimal("0.2")); basketItems.add(thirdBasketItem); request.setBasketItems(basketItems); Payment payment = Payment.create(request, options); System.out.println(payment); assertNotNull(payment.getSystemTime()); assertEquals(Status.SUCCESS.getValue(), payment.getStatus()); assertEquals(Locale.TR.getValue(), payment.getLocale()); assertEquals("123456789", payment.getConversationId()); } @Test public void should_retrieve_payment() { RetrievePaymentRequest retrievePaymentRequest = new RetrievePaymentRequest(); retrievePaymentRequest.setLocale(Locale.TR.getValue()); retrievePaymentRequest.setConversationId("123456879"); retrievePaymentRequest.setPaymentId("1"); retrievePaymentRequest.setPaymentConversationId("123456789"); Payment payment = Payment.retrieve(retrievePaymentRequest, options); System.out.println(payment.toString()); assertNotNull(payment.getSystemTime()); assertEquals(Status.SUCCESS.getValue(), payment.getStatus()); assertEquals(Locale.TR.getValue(), payment.getLocale()); assertEquals("123456879", payment.getConversationId()); } @Test public void should_create_IyziGate_payment_with_physical_and_virtual_item_for_standard_merchant() { CreatePaymentRequest request = new CreatePaymentRequest(); request.setLocale(Locale.TR.getValue()); request.setConversationId("123456789"); request.setPrice(new BigDecimal("1")); request.setPaidPrice(new BigDecimal("1.1")); request.setInstallment(1); request.setBasketId("B67832"); request.setPaymentChannel(PaymentChannel.WEB.name()); request.setPaymentGroup(PaymentGroup.PRODUCT.name()); request.setConnectorName("isbank"); request.setPosOrderId("1"); PaymentCard paymentCard = new PaymentCard(); paymentCard.setCardHolderName("John Doe"); paymentCard.setCardNumber("5528790000000008"); paymentCard.setExpireMonth("12"); paymentCard.setExpireYear("2030"); paymentCard.setCvc("123"); paymentCard.setRegisterCard(0); request.setPaymentCard(paymentCard); Buyer buyer = new Buyer(); buyer.setId("BY789"); buyer.setName("John"); buyer.setSurname("Doe"); buyer.setGsmNumber("+905350000000"); buyer.setEmail("email@email.com"); buyer.setIdentityNumber("74300864791"); buyer.setLastLoginDate("2015-10-05 12:43:35"); buyer.setRegistrationDate("2013-04-21 15:12:09"); buyer.setRegistrationAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); buyer.setIp("85.34.78.112"); buyer.setCity("Istanbul"); buyer.setCountry("Turkey"); buyer.setZipCode("34732"); request.setBuyer(buyer); Address shippingAddress = new Address(); shippingAddress.setContactName("Jane Doe"); shippingAddress.setCity("Istanbul"); shippingAddress.setCountry("Turkey"); shippingAddress.setAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); shippingAddress.setZipCode("34742"); request.setShippingAddress(shippingAddress); Address billingAddress = new Address(); billingAddress.setContactName("Jane Doe"); billingAddress.setCity("Istanbul"); billingAddress.setCountry("Turkey"); billingAddress.setAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); billingAddress.setZipCode("34742"); request.setBillingAddress(billingAddress); List<BasketItem> basketItems = new ArrayList<BasketItem>(); BasketItem firstBasketItem = new BasketItem(); firstBasketItem.setId("BI101"); firstBasketItem.setName("Binocular"); firstBasketItem.setCategory1("Collectibles"); firstBasketItem.setCategory2("Accessories"); firstBasketItem.setItemType(BasketItemType.PHYSICAL.name()); firstBasketItem.setPrice(new BigDecimal("0.3")); basketItems.add(firstBasketItem); BasketItem secondBasketItem = new BasketItem(); secondBasketItem.setId("BI102"); secondBasketItem.setName("Game code"); secondBasketItem.setCategory1("Game"); secondBasketItem.setCategory2("Online Game Items"); secondBasketItem.setItemType(BasketItemType.VIRTUAL.name()); secondBasketItem.setPrice(new BigDecimal("0.5")); basketItems.add(secondBasketItem); BasketItem thirdBasketItem = new BasketItem(); thirdBasketItem.setId("BI103"); thirdBasketItem.setName("Usb"); thirdBasketItem.setCategory1("Electronics"); thirdBasketItem.setCategory2("Usb / Cable"); thirdBasketItem.setItemType(BasketItemType.PHYSICAL.name()); thirdBasketItem.setPrice(new BigDecimal("0.2")); basketItems.add(thirdBasketItem); request.setBasketItems(basketItems); Payment payment = Payment.create(request, options); System.out.println(payment); assertNotNull(payment.getSystemTime()); assertEquals(Status.SUCCESS.getValue(), payment.getStatus()); assertEquals(Locale.TR.getValue(), payment.getLocale()); assertEquals("123456789", payment.getConversationId()); } @Test public void should_create_IyziGate_payment_with_physical_and_virtual_item_for_market_place() { CreatePaymentRequest request = new CreatePaymentRequest(); request.setLocale(Locale.TR.getValue()); request.setConversationId("123456789"); request.setPrice(new BigDecimal("1")); request.setPaidPrice(new BigDecimal("1.1")); request.setInstallment(1); request.setBasketId("B67832"); request.setPaymentChannel(PaymentChannel.WEB.name()); request.setPaymentGroup(PaymentGroup.PRODUCT.name()); request.setConnectorName("isbank"); request.setPosOrderId("1"); PaymentCard paymentCard = new PaymentCard(); paymentCard.setCardHolderName("John Doe"); paymentCard.setCardNumber("5528790000000008"); paymentCard.setExpireMonth("12"); paymentCard.setExpireYear("2030"); paymentCard.setCvc("123"); paymentCard.setRegisterCard(0); request.setPaymentCard(paymentCard); Buyer buyer = new Buyer(); buyer.setId("BY789"); buyer.setName("John"); buyer.setSurname("Doe"); buyer.setGsmNumber("+905350000000"); buyer.setEmail("email@email.com"); buyer.setIdentityNumber("74300864791"); buyer.setLastLoginDate("2015-10-05 12:43:35"); buyer.setRegistrationDate("2013-04-21 15:12:09"); buyer.setRegistrationAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); buyer.setIp("85.34.78.112"); buyer.setCity("Istanbul"); buyer.setCountry("Turkey"); buyer.setZipCode("34732"); request.setBuyer(buyer); Address shippingAddress = new Address(); shippingAddress.setContactName("Jane Doe"); shippingAddress.setCity("Istanbul"); shippingAddress.setCountry("Turkey"); shippingAddress.setAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); shippingAddress.setZipCode("34742"); request.setShippingAddress(shippingAddress); Address billingAddress = new Address(); billingAddress.setContactName("Jane Doe"); billingAddress.setCity("Istanbul"); billingAddress.setCountry("Turkey"); billingAddress.setAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); billingAddress.setZipCode("34742"); request.setBillingAddress(billingAddress); List<BasketItem> basketItems = new ArrayList<BasketItem>(); BasketItem firstBasketItem = new BasketItem(); firstBasketItem.setId("BI101"); firstBasketItem.setName("Binocular"); firstBasketItem.setCategory1("Collectibles"); firstBasketItem.setCategory2("Accessories"); firstBasketItem.setItemType(BasketItemType.PHYSICAL.name()); firstBasketItem.setPrice(new BigDecimal("0.3")); firstBasketItem.setSubMerchantKey("sub merchant key"); firstBasketItem.setSubMerchantPrice(new BigDecimal("0.27")); basketItems.add(firstBasketItem); BasketItem secondBasketItem = new BasketItem(); secondBasketItem.setId("BI102"); secondBasketItem.setName("Game code"); secondBasketItem.setCategory1("Game"); secondBasketItem.setCategory2("Online Game Items"); secondBasketItem.setItemType(BasketItemType.VIRTUAL.name()); secondBasketItem.setPrice(new BigDecimal("0.5")); secondBasketItem.setSubMerchantKey("sub merchant key"); secondBasketItem.setSubMerchantPrice(new BigDecimal("0.42")); basketItems.add(secondBasketItem); BasketItem thirdBasketItem = new BasketItem(); thirdBasketItem.setId("BI103"); thirdBasketItem.setName("Usb"); thirdBasketItem.setCategory1("Electronics"); thirdBasketItem.setCategory2("Usb / Cable"); thirdBasketItem.setItemType(BasketItemType.PHYSICAL.name()); thirdBasketItem.setPrice(new BigDecimal("0.2")); thirdBasketItem.setSubMerchantKey("sub merchant key"); thirdBasketItem.setSubMerchantPrice(new BigDecimal("0.18")); basketItems.add(thirdBasketItem); request.setBasketItems(basketItems); Payment payment = Payment.create(request, options); System.out.println(payment); assertNotNull(payment.getSystemTime()); assertEquals(Status.SUCCESS.getValue(), payment.getStatus()); assertEquals(Locale.TR.getValue(), payment.getLocale()); assertEquals("123456789", payment.getConversationId()); } @Test public void should_create_IyziGate_payment_with_physical_and_virtual_item_for_listing_or_subscription() { CreatePaymentRequest request = new CreatePaymentRequest(); request.setLocale(Locale.TR.getValue()); request.setConversationId("123456789"); request.setPrice(new BigDecimal("1")); request.setPaidPrice(new BigDecimal("1.1")); request.setInstallment(1); request.setBasketId("B67832"); request.setPaymentChannel(PaymentChannel.WEB.name()); request.setPaymentGroup(PaymentGroup.SUBSCRIPTION.name()); request.setConnectorName("isbank"); request.setPosOrderId("1"); PaymentCard paymentCard = new PaymentCard(); paymentCard.setCardHolderName("John Doe"); paymentCard.setCardNumber("5528790000000008"); paymentCard.setExpireMonth("12"); paymentCard.setExpireYear("2030"); paymentCard.setCvc("123"); paymentCard.setRegisterCard(0); request.setPaymentCard(paymentCard); Buyer buyer = new Buyer(); buyer.setId("BY789"); buyer.setName("John"); buyer.setSurname("Doe"); buyer.setGsmNumber("+905350000000"); buyer.setEmail("email@email.com"); buyer.setIdentityNumber("74300864791"); buyer.setLastLoginDate("2015-10-05 12:43:35"); buyer.setRegistrationDate("2013-04-21 15:12:09"); buyer.setRegistrationAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); buyer.setIp("85.34.78.112"); buyer.setCity("Istanbul"); buyer.setCountry("Turkey"); buyer.setZipCode("34732"); request.setBuyer(buyer); Address shippingAddress = new Address(); shippingAddress.setContactName("Jane Doe"); shippingAddress.setCity("Istanbul"); shippingAddress.setCountry("Turkey"); shippingAddress.setAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); shippingAddress.setZipCode("34742"); request.setShippingAddress(shippingAddress); Address billingAddress = new Address(); billingAddress.setContactName("Jane Doe"); billingAddress.setCity("Istanbul"); billingAddress.setCountry("Turkey"); billingAddress.setAddress("Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"); billingAddress.setZipCode("34742"); request.setBillingAddress(billingAddress); List<BasketItem> basketItems = new ArrayList<BasketItem>(); BasketItem firstBasketItem = new BasketItem(); firstBasketItem.setId("BI101"); firstBasketItem.setName("Binocular"); firstBasketItem.setCategory1("Collectibles"); firstBasketItem.setCategory2("Accessories"); firstBasketItem.setItemType(BasketItemType.PHYSICAL.name()); firstBasketItem.setPrice(new BigDecimal("0.3")); basketItems.add(firstBasketItem); BasketItem secondBasketItem = new BasketItem(); secondBasketItem.setId("BI102"); secondBasketItem.setName("Game code"); secondBasketItem.setCategory1("Game"); secondBasketItem.setCategory2("Online Game Items"); secondBasketItem.setItemType(BasketItemType.VIRTUAL.name()); secondBasketItem.setPrice(new BigDecimal("0.5")); basketItems.add(secondBasketItem); BasketItem thirdBasketItem = new BasketItem(); thirdBasketItem.setId("BI103"); thirdBasketItem.setName("Usb"); thirdBasketItem.setCategory1("Electronics"); thirdBasketItem.setCategory2("Usb / Cable"); thirdBasketItem.setItemType(BasketItemType.VIRTUAL.name()); thirdBasketItem.setPrice(new BigDecimal("0.2")); basketItems.add(thirdBasketItem); request.setBasketItems(basketItems); Payment payment = Payment.create(request, options); System.out.println(payment); assertNotNull(payment.getSystemTime()); assertEquals(Status.SUCCESS.getValue(), payment.getStatus()); assertEquals(Locale.TR.getValue(), payment.getLocale()); assertEquals("123456789", payment.getConversationId()); } }
package VASSAL.counters; import java.awt.Component; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Shape; import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.KeyStroke; import VASSAL.build.GameModule; import VASSAL.build.module.GlobalOptions; import VASSAL.build.module.documentation.HelpFile; import VASSAL.command.Command; import VASSAL.command.PlayAudioClipCommand; import VASSAL.configure.AudioClipConfigurer; import VASSAL.configure.BooleanConfigurer; import VASSAL.configure.NamedHotKeyConfigurer; import VASSAL.configure.StringConfigurer; import VASSAL.i18n.PieceI18nData; import VASSAL.i18n.Resources; import VASSAL.i18n.TranslatablePiece; import VASSAL.tools.AudioClip; import VASSAL.tools.FormattedString; import VASSAL.tools.NamedKeyStroke; import VASSAL.tools.SequenceEncoder; /** * A trait that plays a sound clip * * @author rkinney * */ public class PlaySound extends Decorator implements TranslatablePiece { public static final String ID = "playSound;"; protected String menuText; protected NamedKeyStroke stroke; protected boolean sendToOthers; protected KeyCommand command; protected KeyCommand[] commands; protected FormattedString format = new FormattedString(); public PlaySound() { this(ID, null); } public PlaySound(String type, GamePiece piece) { mySetType(type); setInner(piece); } @Override public void mySetState(String newState) { } @Override public String myGetState() { return ""; } @Override public String myGetType() { final SequenceEncoder se = new SequenceEncoder(';'); se.append(format.getFormat()) .append(menuText) .append(stroke) .append(sendToOthers); return ID + se.getValue(); } @Override protected KeyCommand[] myGetKeyCommands() { if (commands == null) { command = new KeyCommand(menuText, stroke, Decorator.getOutermost(this), this); if (menuText.length() > 0 && stroke != null && !stroke.isNull()) { commands = new KeyCommand[] {command}; } else { commands = new KeyCommand[0]; } } return commands; } @Override public Command myKeyEvent(KeyStroke stroke) { myGetKeyCommands(); Command c = null; if (command.matches(stroke)) { final String clipName = format.getText(Decorator.getOutermost(this)); c = new PlayAudioClipCommand(clipName); try { if (!GlobalOptions.getInstance().isSoundGlobalMute()) { final AudioClip clip = GameModule.getGameModule() .getDataArchive() .getCachedAudioClip(clipName); if (clip != null) { clip.play(); } } } catch (IOException e) { reportDataError(this, Resources.getString("Error.not_found", "Audio Clip"), "Clip=" + clipName, e); } } return c; } @Override public void draw(Graphics g, int x, int y, Component obs, double zoom) { piece.draw(g, x, y, obs, zoom); } @Override public Rectangle boundingBox() { return piece.boundingBox(); } @Override public Shape getShape() { return piece.getShape(); } @Override public String getName() { return piece.getName(); } @Override public String getDescription() { return format.getFormat().length() == 0 ? "Play Sound" : "Play Sound - " + format.getFormat(); } @Override public void mySetType(String type) { SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';'); st.nextToken(); format = new FormattedString(st.nextToken("")); menuText = st.nextToken("Play Sound"); stroke = st.nextNamedKeyStroke('P'); sendToOthers = st.nextBoolean(false); commands = null; } @Override public HelpFile getHelpFile() { return HelpFile.getReferenceManualPage("PlaySound.html"); } @Override public PieceEditor getEditor() { return new Ed(this); } @Override public PieceI18nData getI18nData() { return getI18nData(menuText, "Play Sound command"); } public static class Ed implements PieceEditor { private StringConfigurer menuConfig; private NamedHotKeyConfigurer keyConfig; private AudioClipConfigurer soundConfig; private BooleanConfigurer sendConfig; private JPanel panel; public Ed(PlaySound p) { menuConfig = new StringConfigurer(null, "Menu Text: ", p.menuText); keyConfig = new NamedHotKeyConfigurer(null, "Keyboard Command: ", p.stroke); soundConfig = new AudioClipConfigurer(null, "Sound Clip: ", GameModule.getGameModule().getArchiveWriter()); soundConfig.setValue(p.format.getFormat()); soundConfig.setEditable(true); sendConfig = new BooleanConfigurer(null, "Send sound to other players?", p.sendToOthers); panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(menuConfig.getControls()); panel.add(keyConfig.getControls()); panel.add(soundConfig.getControls()); panel.add(sendConfig.getControls()); } @Override public Component getControls() { return panel; } @Override public String getType() { SequenceEncoder se = new SequenceEncoder(';'); se.append(soundConfig.getValueString()).append(menuConfig.getValueString()).append(keyConfig.getValueString()).append(sendConfig.getValueString()); return ID + se.getValue(); } @Override public String getState() { return ""; } } /** * @return a list of any Named KeyStrokes referenced in the Decorator, if any (for search) */ @Override public List<NamedKeyStroke> getNamedKeyStrokeList() { return Arrays.asList(stroke); } /** * @return a list of any Menu Text strings referenced in the Decorator, if any (for search) */ @Override public List<String> getMenuTextList() { return List.of(menuText); } }
package integration; import com.codeborne.selenide.junit.ScreenShooter; import org.junit.After; import org.junit.Before; import org.junit.Rule; 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.Selectors.byText; import static com.codeborne.selenide.Selenide.$; import static com.codeborne.selenide.Selenide.open; import static com.codeborne.selenide.junit.ScreenShooter.failedTests; import static java.lang.Thread.currentThread; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class LongRunningAjaxRequestTest { @Rule public ScreenShooter screenShooter = failedTests(); @Before public void openTestPage() { timeout = 2500; open(currentThread().getContextClassLoader().getResource("long_ajax_request.html")); $(byText("Run long request")).click(); $(byText("Loading...")).should(exist); $("#loading").shouldHave(text("Loading"), text("...")); } @After public final void restoreTimeout() { timeout = 4000; } @Test public void dollarWaitsForElement() { $(byText("Result 1")).shouldBe(visible); } @Test public void dollarWaitsForElementWithIndex() { $("#results li", 1).shouldHave(text("Result 2")); } @Test public void dollarWaitsUntilElementDisappears() { $(byText("Loading...")).should(exist); $(byText("Loading...")).shouldNot(exist); } @Test public void userCanWaitUntilConditionIsMet() { timeout = 1000; assertFalse($(byText("Result 2")).isDisplayed()); $(byText("Result 2")).waitUntil(visible, 3000); assertTrue($(byText("Result 2")).isDisplayed()); } @Test @SuppressWarnings("deprecation") public void userCanWaitWhileConditionIsMet() { timeout = 1000; $(byText("Result 2")).waitWhile(notPresent, 3000); assertTrue($(byText("Result 2")).isDisplayed()); } @Test public void dollarWithParentWaitsUntilElementDisappears() { $($("#results"), "span#loading").should(exist); $($("#results"), "span#loading").shouldNot(exist); } @Test public void dollarWithParentAndIndexWaitsUntilElementDisappears() { $($("#results"), "span#loading", 0).should(exist); $($("#results"), "span#loading", 0).shouldNot(exist); $($("#results"), "span#loading", 666).shouldNot(exist); } @Test(expected = AssertionError.class) public void waitingTimeout() { $("#non-existing-element").should(exist); } @Test public void shouldWaitsForCondition() { $("#results").shouldHave(text("Result 1")); } @Test public void shouldWaitsForAllConditions() { $("#results").shouldHave(text("Result 1"), text("Result 2")); } @Test public void shouldNotExist() { $("#non-existing-element").shouldNot(exist); $("#non-existing-element", 7).shouldNot(exist); $(By.linkText("non-existing-link")).shouldNot(exist); $(By.linkText("non-existing-link"), 8).shouldNot(exist); } @Test public void findWaitsForConditions() { $("#results").find(byText("non-existing element")).shouldNot(exist); $("#results").find(byText("non-existing element"), 3).shouldNot(exist); $("#results").find(byText("Loading...")).shouldNot(exist); $("#results").find(byText("Loading..."), 0).shouldNot(exist); } @Test public void shouldNotExistWithinParentElement() { $($("body"), "#non-existing-element").shouldNot(exist); $($("body"), "#non-existing-element", 4).shouldNot(exist); } @Test public void shouldNotBeVisible() { $("#non-existing-element").shouldNotBe(visible); $("#non-existing-element", 7).shouldNotBe(visible); $(By.linkText("non-existing-link")).shouldNotBe(visible); $(By.linkText("non-existing-link"), 8).shouldNotBe(visible); } @Test public void shouldNotBeVisibleWithinParentElement() { $($("body"), "#non-existing-element").shouldNotBe(visible); $($("body"), "#non-existing-element", 4).shouldNotBe(visible); } }
package javax.time.calendar; import static javax.time.calendar.ISODateTimeRule.AMPM_OF_DAY; import static javax.time.calendar.ISODateTimeRule.CLOCK_HOUR_OF_AMPM; import static javax.time.calendar.ISODateTimeRule.CLOCK_HOUR_OF_DAY; import static javax.time.calendar.ISODateTimeRule.DAY_OF_MONTH; import static javax.time.calendar.ISODateTimeRule.DAY_OF_WEEK; import static javax.time.calendar.ISODateTimeRule.HOUR_OF_AMPM; import static javax.time.calendar.ISODateTimeRule.HOUR_OF_DAY; import static javax.time.calendar.ISODateTimeRule.MINUTE_OF_DAY; import static javax.time.calendar.ISODateTimeRule.MINUTE_OF_HOUR; import static javax.time.calendar.ISODateTimeRule.MONTH_OF_QUARTER; import static javax.time.calendar.ISODateTimeRule.MONTH_OF_YEAR; import static javax.time.calendar.ISODateTimeRule.NANO_OF_DAY; import static javax.time.calendar.ISODateTimeRule.NANO_OF_SECOND; import static javax.time.calendar.ISODateTimeRule.QUARTER_OF_YEAR; import static javax.time.calendar.ISODateTimeRule.SECOND_OF_DAY; import static javax.time.calendar.ISODateTimeRule.SECOND_OF_HOUR; import static javax.time.calendar.ISODateTimeRule.SECOND_OF_MINUTE; import static javax.time.calendar.ISODateTimeRule.YEAR; import static javax.time.calendar.ISODateTimeRule.ZERO_EPOCH_MONTH; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Test DateTimeFields. */ @Test public class TestDateTimeFields { private static final DateTimeRule NULL_RULE = null; // basics @Test(groups={"implementation"}) public void test_interfaces() { assertTrue(Calendrical.class.isAssignableFrom(DateTimeFields.class)); assertTrue(CalendricalMatcher.class.isAssignableFrom(DateTimeFields.class)); assertTrue(Iterable.class.isAssignableFrom(DateTimeFields.class)); assertTrue(Serializable.class.isAssignableFrom(DateTimeFields.class)); } @DataProvider(name="simple") Object[][] data_simple() { return new Object[][] { {DateTimeFields.EMPTY}, {DateTimeFields.of(YEAR, 2008)}, {DateTimeFields.of(YEAR, 2008, MONTH_OF_YEAR, 6)}, }; } @Test(dataProvider="simple", groups={"tck"}) public void test_serialization(DateTimeFields fields) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(fields); oos.close(); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream( baos.toByteArray())); if (fields.size() == 0) { assertSame(ois.readObject(), fields); } else { assertEquals(ois.readObject(), fields); } } @Test(groups={"tck"}) public void test_immutable() { Class<DateTimeFields> cls = DateTimeFields.class; assertTrue(Modifier.isPublic(cls.getModifiers())); assertTrue(Modifier.isFinal(cls.getModifiers())); Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { assertTrue(Modifier.isFinal(field.getModifiers()), "Field:" + field.getName()); if (Modifier.isStatic(field.getModifiers()) == false) { assertTrue(Modifier.isPrivate(field.getModifiers()), "Field:" + field.getName()); } } Constructor<?>[] cons = cls.getDeclaredConstructors(); for (Constructor<?> con : cons) { assertTrue(Modifier.isPrivate(con.getModifiers())); } } @Test(groups={"tck"}) public void singleton_empty() { DateTimeFields test = DateTimeFields.EMPTY; assertEquals(test.size(), 0); } @Test(groups={"implementation"}) public void singleton_empty_same() { assertSame(DateTimeFields.EMPTY, DateTimeFields.EMPTY); } // factories @Test(groups={"tck"}) public void factory_fields_onePair() { DateTimeFields test = DateTimeFields.of(YEAR, 2008); assertFields(test, YEAR, 2008); } @Test(groups={"tck"}) public void factory_fields_onePair_invalidValue() { DateTimeFields test = DateTimeFields.of(MONTH_OF_YEAR, 13); assertFields(test, MONTH_OF_YEAR, 13); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void factory_fields_onePair_null() { DateTimeFields.of(NULL_RULE, 1); } @Test(groups={"tck"}) public void factory_fields_twoPairs() { DateTimeFields test = DateTimeFields.of(YEAR, 2008, MONTH_OF_YEAR, 6); assertFields(test, YEAR, 2008, MONTH_OF_YEAR, 6); } @Test(groups={"tck"}) public void factory_fields_twoPairs_orderNotSignificant() { DateTimeFields test = DateTimeFields.of(MONTH_OF_YEAR, 6, YEAR, 2008); assertFields(test, YEAR, 2008, MONTH_OF_YEAR, 6); } @Test(expectedExceptions = IllegalArgumentException.class, groups={"tck"}) public void factory_fields_twoPairs_sameFieldOverwrites() { DateTimeFields.of(MONTH_OF_YEAR, 6, MONTH_OF_YEAR, 7); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void factory_fields_twoPairs_nullFirst() { DateTimeFields.of(NULL_RULE, 1, MONTH_OF_YEAR, 6); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void factory_fields_twoPairs_nullSecond() { DateTimeFields.of(MONTH_OF_YEAR, 6, NULL_RULE, 1); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void factory_fields_twoPairs_nullBoth() { DateTimeFields.of(NULL_RULE, 1, NULL_RULE, 6); } @Test(groups={"tck"}) public void factory_fields_array() { List<DateTimeField> list = new ArrayList<DateTimeField>(); list.add(DateTimeField.of(YEAR, 2008)); list.add(DateTimeField.of(MONTH_OF_YEAR, 6)); DateTimeFields test = DateTimeFields.of(list.toArray(new DateTimeField[0])); assertFields(test, YEAR, 2008, MONTH_OF_YEAR, 6); } @Test(groups={"tck"}) public void factory_fields_array_sorted() { List<DateTimeField> list = new ArrayList<DateTimeField>(); list.add(DateTimeField.of(MONTH_OF_YEAR, 6)); list.add(DateTimeField.of(YEAR, 2008)); DateTimeFields test = DateTimeFields.of(list.toArray(new DateTimeField[0])); assertFields(test, YEAR, 2008, MONTH_OF_YEAR, 6); } @Test(groups={"implementation"}) public void factory_fields_array_empty_singleton() { List<DateTimeField> list = new ArrayList<DateTimeField>(); assertSame(DateTimeFields.of(list.toArray(new DateTimeField[0])), DateTimeFields.EMPTY); } @Test(expectedExceptions=IllegalArgumentException.class, groups={"tck"}) public void factory_fields_array_duplicate() { List<DateTimeField> list = new ArrayList<DateTimeField>(); list.add(DateTimeField.of(YEAR, 2008)); list.add(DateTimeField.of(MONTH_OF_YEAR, 6)); list.add(DateTimeField.of(YEAR, 2008)); DateTimeFields.of(list.toArray(new DateTimeField[0])); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void factory_fields_array_null() { DateTimeFields.of((DateTimeField[]) null); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void factory_fields_array_nullContent() { List<DateTimeField> list = new ArrayList<DateTimeField>(); list.add(DateTimeField.of(YEAR, 2008)); list.add(null); DateTimeFields.of(list.toArray(new DateTimeField[0])); } @Test(groups={"tck"}) public void factory_fields_iterable() { List<DateTimeField> list = new CopyOnWriteArrayList<DateTimeField>(); // CopyOnWriteArrayList objects to nulls list.add(DateTimeField.of(YEAR, 2008)); list.add(DateTimeField.of(MONTH_OF_YEAR, 6)); DateTimeFields test = DateTimeFields.of(list); assertFields(test, YEAR, 2008, MONTH_OF_YEAR, 6); } @Test(groups={"tck"}) public void factory_fields_iterable_sorted() { List<DateTimeField> list = new ArrayList<DateTimeField>(); list.add(DateTimeField.of(MONTH_OF_YEAR, 6)); list.add(DateTimeField.of(YEAR, 2008)); DateTimeFields test = DateTimeFields.of(list); assertFields(test, YEAR, 2008, MONTH_OF_YEAR, 6); } @Test(groups={"tck"}) public void factory_fields_iterable_empty_singleton() { List<DateTimeField> list = new ArrayList<DateTimeField>(); assertSame(DateTimeFields.of(list), DateTimeFields.EMPTY); } @Test(expectedExceptions=IllegalArgumentException.class, groups={"tck"}) public void factory_fields_iterable_duplicate() { List<DateTimeField> list = new ArrayList<DateTimeField>(); list.add(DateTimeField.of(YEAR, 2008)); list.add(DateTimeField.of(MONTH_OF_YEAR, 6)); list.add(DateTimeField.of(YEAR, 2008)); DateTimeFields.of(list); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void factory_fields_iterable_null() { DateTimeFields.of((Iterable<DateTimeField>) null); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void factory_fields_iterable_nullContent() { List<DateTimeField> list = new ArrayList<DateTimeField>(); list.add(DateTimeField.of(YEAR, 2008)); list.add(null); DateTimeFields.of(list); } // size() @Test(groups={"tck"}) public void test_size0() { DateTimeFields test = DateTimeFields.EMPTY; assertEquals(test.size(), 0); } @Test(groups={"tck"}) public void test_size1() { DateTimeFields test = dtf(YEAR, 2008); assertEquals(test.size(), 1); } @Test(groups={"tck"}) public void test_size2() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(test.size(), 2); } // iterator() @Test(groups={"tck"}) public void test_iterator0() { DateTimeFields test = DateTimeFields.EMPTY; Iterator<DateTimeField> iterator = test.iterator(); assertEquals(iterator.hasNext(), false); } @Test(groups={"tck"}) public void test_iterator2() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); Iterator<DateTimeField> iterator = test.iterator(); assertEquals(iterator.hasNext(), true); assertEquals(iterator.next(), YEAR.field(2008)); assertEquals(iterator.hasNext(), true); assertEquals(iterator.next(), MONTH_OF_YEAR.field(6)); assertEquals(iterator.hasNext(), false); } @Test(expectedExceptions = UnsupportedOperationException.class, groups={"tck"}) public void test_iterator_immutable() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); Iterator<DateTimeField> iterator = test.iterator(); iterator.next(); iterator.remove(); } // contains() @Test(groups={"tck"}) public void test_contains() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(test.contains(YEAR), true); assertEquals(test.contains(MONTH_OF_YEAR), true); } @Test(groups={"tck"}) public void test_contains_null() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(test.contains(NULL_RULE), false); } @Test(groups={"tck"}) public void test_contains_fieldNotPresent() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(test.contains(DAY_OF_MONTH), false); } // getField() @Test(groups={"tck"}) public void test_getField() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(test.getField(YEAR), YEAR.field(2008)); assertEquals(test.getField(MONTH_OF_YEAR), MONTH_OF_YEAR.field(6)); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_getField_null() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); test.getField((DateTimeRule) null); } @Test(groups={"tck"}) public void test_getField_fieldNotDerived() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(test.getField(QUARTER_OF_YEAR), null); } @Test(groups={"tck"}) public void test_getField_fieldNotPresent() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(test.getField(DAY_OF_MONTH), null); } // getValue() @Test(groups={"tck"}) public void test_getValue() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(test.getValue(YEAR), 2008); assertEquals(test.getValue(MONTH_OF_YEAR), 6); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_getValue_null() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); test.getValue(NULL_RULE); } @Test(expectedExceptions=CalendricalRuleException.class, groups={"tck"}) public void test_getValue_fieldNotPresent() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); try { test.getValue(DAY_OF_MONTH); } catch (CalendricalRuleException ex) { assertEquals(ex.getRule(), DAY_OF_MONTH); throw ex; } } // getValidValue() @Test(groups={"tck"}) public void test_getValidValue() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(test.getValidValue(YEAR), 2008); assertEquals(test.getValidValue(MONTH_OF_YEAR), 6); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_getValidValue_null() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); test.getValidValue(NULL_RULE); } @Test(expectedExceptions=CalendricalRuleException.class, groups={"tck"}) public void test_getValidValue_fieldNotPresent() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); try { test.getValidValue(DAY_OF_MONTH); } catch (CalendricalRuleException ex) { assertEquals(ex.getRule(), DAY_OF_MONTH); throw ex; } } @Test(expectedExceptions=IllegalCalendarFieldValueException.class, groups={"tck"}) public void test_getValidValue_invalid() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 13); // out of range try { test.getValidValue(MONTH_OF_YEAR); } catch (IllegalCalendarFieldValueException ex) { assertEquals(ex.getRule(), MONTH_OF_YEAR); assertEquals(ex.getRule(), MONTH_OF_YEAR); throw ex; } } // getValidIntValue() @Test(groups={"tck"}) public void test_getValidIntValue() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(test.getValidIntValue(YEAR), 2008); assertEquals(test.getValidIntValue(MONTH_OF_YEAR), 6); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_getValidIntValue_null() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); test.getValidIntValue(NULL_RULE); } @Test(expectedExceptions=CalendricalRuleException.class, groups={"tck"}) public void test_getValidIntValue_fieldNotPresent() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); try { test.getValidIntValue(DAY_OF_MONTH); } catch (CalendricalRuleException ex) { assertEquals(ex.getRule(), DAY_OF_MONTH); throw ex; } } @Test(expectedExceptions=IllegalCalendarFieldValueException.class, groups={"tck"}) public void test_getValidIntValue_invalid() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 13); // out of range try { test.getValidIntValue(MONTH_OF_YEAR); } catch (IllegalCalendarFieldValueException ex) { assertEquals(ex.getRule(), MONTH_OF_YEAR); assertEquals(ex.getRule(), MONTH_OF_YEAR); throw ex; } } // with() @Test(groups={"tck"}) public void test_with() { DateTimeFields base = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); DateTimeFields test = base.with(DAY_OF_MONTH, 30); assertFields(test, YEAR, 2008, MONTH_OF_YEAR, 6, DAY_OF_MONTH, 30); // check original immutable assertFields(base, YEAR, 2008, MONTH_OF_YEAR, 6); } @Test(groups={"tck"}) public void test_with_invalidValue() { DateTimeFields base = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); DateTimeFields test = base.with(DAY_OF_MONTH, 123); assertFields(test, YEAR, 2008, MONTH_OF_YEAR, 6, DAY_OF_MONTH, 123); } @Test(groups={"tck"}) public void test_with_sameFieldOverwrites() { DateTimeFields base = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); DateTimeFields test = base.with(MONTH_OF_YEAR, 1); assertFields(test, YEAR, 2008, MONTH_OF_YEAR, 1); } @Test(groups={"tck"}) public void test_with_sameFieldNoChange() { DateTimeFields base = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); DateTimeFields test = base.with(MONTH_OF_YEAR, 6); assertFields(test, YEAR, 2008, MONTH_OF_YEAR, 6); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_with_null() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); test.with(NULL_RULE, 30); } // // with(Map) // public void test_with_map() { // // using Hashtable checks for incorrect null checking // DateTimeFields base = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // Map<DateTimeFieldRule, Integer> map = new Hashtable<DateTimeFieldRule, Integer>(); // map.put(DOM_RULE, 30); // DateTimeFields test = base.with(map); // assertFields(test, YEAR_RULE, 2008, MOY_RULE, 6, DOM_RULE, 30); // // check original immutable // assertFields(base, YEAR_RULE, 2008, MOY_RULE, 6); // public void test_with_map_empty() { // DateTimeFields base = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // Map<DateTimeFieldRule, Integer> map = new HashMap<DateTimeFieldRule, Integer>(); // DateTimeFields test = base.with(map); // assertSame(test, base); // public void test_with_map_invalidValue() { // DateTimeFields base = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // Map<DateTimeFieldRule, Integer> map = new HashMap<DateTimeFieldRule, Integer>(); // map.put(DOM_RULE, -1); // try { // base.with(map); // assertEquals(ex.getFieldRule(), DOM_RULE); // assertFields(base, YEAR_RULE, 2008, MOY_RULE, 6); // throw ex; // public void test_with_map_sameFieldOverwrites() { // DateTimeFields base = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // Map<DateTimeFieldRule, Integer> map = new HashMap<DateTimeFieldRule, Integer>(); // map.put(MOY_RULE, 1); // DateTimeFields test = base.with(map); // assertFields(test, YEAR_RULE, 2008, MOY_RULE, 1); // @Test(expectedExceptions=NullPointerException.class) // public void test_with_map_null() { // DateTimeFields test = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // test.with(NULL_MAP); // @Test(expectedExceptions=NullPointerException.class) // public void test_with_map_nullKey() { // DateTimeFields test = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // Map<DateTimeFieldRule, Integer> map = new HashMap<DateTimeFieldRule, Integer>(); // map.put(null, 1); // test.with(map); // @Test(expectedExceptions=NullPointerException.class) // public void test_with_map_nullValue() { // DateTimeFields test = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // Map<DateTimeFieldRule, Integer> map = new HashMap<DateTimeFieldRule, Integer>(); // map.put(DOM_RULE, null); // test.with(map); // @Test(expectedExceptions=NullPointerException.class) // public void test_with_map_nullBoth() { // DateTimeFields test = DateTimeFields.fields(YEAR_RULE, 2008, MOY_RULE, 6); // Map<DateTimeFieldRule, Integer> map = new HashMap<DateTimeFieldRule, Integer>(); // map.put(null, null); // test.with(map); // // with(DateTimeFields) // public void test_with_fields() { // DateTimeFields base = dtf(YEAR_RULE, 2008, MOY_RULE, 6); // DateTimeFields fields = dtf(DOM_RULE, 30); // DateTimeFields test = base.with(fields); // assertFields(test, YEAR_RULE, 2008, MOY_RULE, 6, DOM_RULE, 30); // // check original immutable // assertFields(base, YEAR_RULE, 2008, MOY_RULE, 6); // public void test_with_fields_sameFieldOverwrites() { // DateTimeFields base = dtf(YEAR_RULE, 2008, MOY_RULE, 6); // DateTimeFields fields = dtf(MOY_RULE, 1); // DateTimeFields test = base.with(fields); // assertFields(test, YEAR_RULE, 2008, MOY_RULE, 1); // public void test_with_fields_self() { // DateTimeFields base = dtf(YEAR_RULE, 2008, MOY_RULE, 6); // DateTimeFields test = base.with(base); // assertSame(test, base); // public void test_with_fields_emptyAdd() { // DateTimeFields base = dtf(YEAR_RULE, 2008, MOY_RULE, 6); // DateTimeFields test = base.with(DateTimeFields.EMPTY); // assertSame(test, base); // @Test(expectedExceptions=NullPointerException.class) // public void test_with_fields_null() { // DateTimeFields test = dtf(YEAR_RULE, 2008, MOY_RULE, 6); // DateTimeFields fields = null; // test.with(fields); // without() @Test(groups={"tck"}) public void test_without() { DateTimeFields base = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); DateTimeFields test = base.without(MONTH_OF_YEAR); assertFields(test, YEAR, 2008); // check original immutable assertFields(base, YEAR, 2008, MONTH_OF_YEAR, 6); } @Test(groups={"implementation"}) public void test_without_fieldNotPresent() { DateTimeFields base = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); DateTimeFields test = base.without(DAY_OF_MONTH); assertSame(test, base); } @Test(groups={"implementation"}) public void test_without_emptySingleton() { DateTimeFields base = dtf(YEAR, 2008); DateTimeFields test = base.without(YEAR); assertSame(test, DateTimeFields.EMPTY); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_without_null() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); test.without(NULL_RULE); } // derive(DateTimeRule) @DataProvider(name="derive") Object[][] data_derive() { return new Object[][] { // single field // request original {dtf(YEAR, 2008), YEAR, 2008}, {dtf(NANO_OF_DAY, 12345678901L), NANO_OF_DAY, 12345678901L}, // no convert {dtf(YEAR, 2008), MONTH_OF_YEAR, null}, {dtf(HOUR_OF_AMPM, 6), HOUR_OF_DAY, null}, // convert {dtf(MONTH_OF_YEAR, 6), QUARTER_OF_YEAR, 2}, {dtf(MONTH_OF_YEAR, 6), MONTH_OF_QUARTER, 3}, {dtf(ZERO_EPOCH_MONTH, 2012 * 12 + 3), MONTH_OF_YEAR, 4}, {dtf(ZERO_EPOCH_MONTH, 2012 * 12 + 3), YEAR, 2012}, {dtf(HOUR_OF_DAY, 14), HOUR_OF_AMPM, 2}, {dtf(SECOND_OF_DAY, 15 * 3600 + 74), HOUR_OF_DAY, 15}, {dtf(SECOND_OF_DAY, 3 * 3600 + 74), MINUTE_OF_HOUR, 1}, {dtf(SECOND_OF_DAY, 3 * 3600 + 74), SECOND_OF_MINUTE, 14}, {dtf(NANO_OF_DAY, (3 * 3600 + 74) * 1000000000L + 123), NANO_OF_SECOND, 123}, {dtf(NANO_OF_DAY, (3 * 3600 + 74) * 1000000000L + 123), SECOND_OF_MINUTE, 14}, // normalize {dtf(CLOCK_HOUR_OF_DAY, 24), HOUR_OF_DAY, 0}, {dtf(HOUR_OF_DAY, 0), CLOCK_HOUR_OF_DAY, 24}, {dtf(CLOCK_HOUR_OF_DAY, 23), HOUR_OF_AMPM, 11}, {dtf(MockBigClockHourOfDayFieldRule.INSTANCE, 1500), HOUR_OF_DAY, 15}, // normalize - un-normalize {dtf(MockReversedHourOfDayFieldRule.INSTANCE, 7), HOUR_OF_DAY, 17}, {dtf(MockReversedHourOfDayFieldRule.INSTANCE, 18), CLOCK_HOUR_OF_DAY, 6}, {dtf(MockReversedHourOfDayFieldRule.INSTANCE, 3), CLOCK_HOUR_OF_AMPM, 9}, {dtf(MockReversedHourOfDayFieldRule.INSTANCE, 4), MockBigClockHourOfDayFieldRule.INSTANCE, 2000}, {dtf(MockBigClockHourOfDayFieldRule.INSTANCE, 1900), MockReversedHourOfDayFieldRule.INSTANCE, 5}, // convert - un-normalize {dtf(NANO_OF_DAY, (4 * 3600 + 74) * 1000000000L + 123), MockBigClockHourOfDayFieldRule.INSTANCE, 400}, {dtf(NANO_OF_DAY, (4 * 3600 + 74) * 1000000000L + 123), MockReversedHourOfDayFieldRule.INSTANCE, 20}, // two fields simple {dtf(HOUR_OF_DAY, 14, MINUTE_OF_HOUR, 30), HOUR_OF_DAY, 14}, {dtf(HOUR_OF_DAY, 14, MINUTE_OF_HOUR, 30), HOUR_OF_AMPM, 2}, {dtf(HOUR_OF_DAY, 14, MINUTE_OF_HOUR, 30), MINUTE_OF_DAY, 14 * 60 + 30}, {dtf(HOUR_OF_DAY, 14, MINUTE_OF_HOUR, 30), SECOND_OF_DAY, null}, {dtf(HOUR_OF_DAY, 14, MINUTE_OF_HOUR, 61), HOUR_OF_DAY, 15}, {dtf(HOUR_OF_DAY, 14, MINUTE_OF_HOUR, 61), MINUTE_OF_HOUR, 1}, // two fields no join {dtf(HOUR_OF_DAY, 14, SECOND_OF_MINUTE, 30), HOUR_OF_DAY, 14}, {dtf(HOUR_OF_DAY, 14, SECOND_OF_MINUTE, 30), HOUR_OF_AMPM, 2}, {dtf(HOUR_OF_DAY, 14, SECOND_OF_MINUTE, 30), MINUTE_OF_DAY, null}, {dtf(HOUR_OF_DAY, 14, SECOND_OF_MINUTE, 30), SECOND_OF_DAY, null}, {dtf(HOUR_OF_DAY, 14, DAY_OF_MONTH, 12), HOUR_OF_DAY, 14}, // two fields clash {dtf(HOUR_OF_DAY, 14, MINUTE_OF_DAY, 14 * 60 + 30), HOUR_OF_DAY, 14}, {dtf(HOUR_OF_DAY, 14, MINUTE_OF_DAY, 14 * 60 + 30), MINUTE_OF_HOUR, 30}, {dtf(HOUR_OF_DAY, 14, MINUTE_OF_DAY, 99), HOUR_OF_DAY, null}, {dtf(HOUR_OF_DAY, 14, MINUTE_OF_DAY, 99), MINUTE_OF_HOUR, null}, {dtf(MINUTE_OF_DAY, 14 * 60 + 30, SECOND_OF_HOUR, 30 * 60 + 9), HOUR_OF_DAY, 14}, {dtf(MINUTE_OF_DAY, 14 * 60 + 30, SECOND_OF_HOUR, 30 * 60 + 9), MINUTE_OF_HOUR, 30}, {dtf(MINUTE_OF_DAY, 14 * 60 + 30, SECOND_OF_HOUR, 30 * 60 + 9), SECOND_OF_MINUTE, 9}, {dtf(MINUTE_OF_DAY, 14 * 60 + 30, SECOND_OF_HOUR, 3600 + 30 * 60 + 9), HOUR_OF_DAY, 15}, {dtf(MINUTE_OF_DAY, 14 * 60 + 30, SECOND_OF_HOUR, 3600 + 30 * 60 + 9), MINUTE_OF_HOUR, 30}, {dtf(MINUTE_OF_DAY, 14 * 60 + 30, SECOND_OF_HOUR, 3600 + 30 * 60 + 9), SECOND_OF_MINUTE, 9}, {dtf(MINUTE_OF_DAY, 14 * 60 + 30, SECOND_OF_HOUR, 999), HOUR_OF_DAY, null}, {dtf(MINUTE_OF_DAY, 14 * 60 + 30, SECOND_OF_HOUR, 999), MINUTE_OF_HOUR, null}, {dtf(MINUTE_OF_DAY, 14 * 60 + 30, SECOND_OF_HOUR, 999), SECOND_OF_MINUTE, null}, // three fields simple {dtf(HOUR_OF_DAY, 14, MINUTE_OF_HOUR, 15, SECOND_OF_MINUTE, 30), SECOND_OF_DAY, 14 * 3600 + 15 * 60 + 30}, // three fields clash {dtf(HOUR_OF_DAY, 14, MINUTE_OF_HOUR, 15, SECOND_OF_HOUR, 15 * 60 + 39), HOUR_OF_DAY, 14}, {dtf(HOUR_OF_DAY, 14, MINUTE_OF_HOUR, 15, SECOND_OF_HOUR, 15 * 60 + 39), MINUTE_OF_HOUR, 15}, {dtf(HOUR_OF_DAY, 14, MINUTE_OF_HOUR, 15, SECOND_OF_HOUR, 15 * 60 + 39), SECOND_OF_MINUTE, 39}, {dtf(HOUR_OF_DAY, 14, SECOND_OF_MINUTE, 39, SECOND_OF_HOUR, 39), HOUR_OF_DAY, 14}, {dtf(HOUR_OF_DAY, 14, SECOND_OF_MINUTE, 39, SECOND_OF_HOUR, 39), MINUTE_OF_HOUR, 0}, {dtf(HOUR_OF_DAY, 14, SECOND_OF_MINUTE, 39, SECOND_OF_HOUR, 39), SECOND_OF_MINUTE, 39}, {dtf(HOUR_OF_DAY, 14, SECOND_OF_MINUTE, 9, SECOND_OF_HOUR, 3600 + 3 * 60 + 9), HOUR_OF_DAY, 15}, {dtf(HOUR_OF_DAY, 14, SECOND_OF_MINUTE, 9, SECOND_OF_HOUR, 3600 + 3 * 60 + 9), MINUTE_OF_HOUR, 3}, {dtf(HOUR_OF_DAY, 14, SECOND_OF_MINUTE, 9, SECOND_OF_HOUR, 3600 + 3 * 60 + 9), SECOND_OF_MINUTE, 9}, {dtf(HOUR_OF_DAY, 14, MINUTE_OF_HOUR, 15, SECOND_OF_HOUR, 99), HOUR_OF_DAY, null}, {dtf(HOUR_OF_DAY, 14, MINUTE_OF_HOUR, 15, SECOND_OF_HOUR, 99), HOUR_OF_AMPM, null}, {dtf(HOUR_OF_DAY, 14, MINUTE_OF_HOUR, 15, SECOND_OF_HOUR, 99), MINUTE_OF_HOUR, null}, }; } @Test(dataProvider = "derive", groups={"tck"}) public void test_get_derive(DateTimeFields input, DateTimeRule rule, Number output) { if (output == null) { assertEquals(input.get(rule), null); } else { assertEquals(input.get(rule),rule.field(output.longValue())); } } // get() @Test(groups={"tck"}) public void test_get() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(test.get(YEAR), YEAR.field(2008)); assertEquals(test.get(MONTH_OF_YEAR), MONTH_OF_YEAR.field(6)); } @Test(groups={"tck"}) public void test_get_derived() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(test.get(QUARTER_OF_YEAR), QUARTER_OF_YEAR.field(2)); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_get_null() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); test.get((CalendricalRule<?>) null); } @Test(groups={"tck"}) public void test_get_fieldNotPresent() { DateTimeFields test = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(test.get(DAY_OF_MONTH), null); } // matchesCalendrical() @Test(groups={"tck"}) public void test_matchesCalendrical_ymd_date() { DateTimeFields test = DateTimeFields.EMPTY .with(YEAR, 2008) .with(MONTH_OF_YEAR, 6) .with(DAY_OF_MONTH, 30); LocalDate date = LocalDate.of(2008, 6, 30); assertEquals(test.matchesCalendrical(date), true); // check original immutable assertFields(test, YEAR, 2008, MONTH_OF_YEAR, 6, DAY_OF_MONTH, 30); } @Test(groups={"tck"}) public void test_matchesCalendrical_dowMatches() { DateTimeFields test = DateTimeFields.EMPTY .with(YEAR, 2008) .with(MONTH_OF_YEAR, 6) .with(DAY_OF_MONTH, 30) .with(DAY_OF_WEEK, 1); LocalDate date = LocalDate.of(2008, 6, 30); assertEquals(test.matchesCalendrical(date), true); } @Test(groups={"tck"}) public void test_matchesCalendrical_dowNotMatches() { DateTimeFields test = DateTimeFields.EMPTY .with(YEAR, 2008) .with(MONTH_OF_YEAR, 6) .with(DAY_OF_MONTH, 30) .with(DAY_OF_WEEK, 2); // 2008-06-30 is Monday not Tuesday LocalDate date = LocalDate.of(2008, 6, 30); assertEquals(test.matchesCalendrical(date), false); } @Test(groups={"tck"}) public void test_matchesCalendrical_ym_date_partialMatch() { DateTimeFields test = DateTimeFields.EMPTY .with(YEAR, 2008) .with(MONTH_OF_YEAR, 6); LocalDate date = LocalDate.of(2008, 6, 30); assertEquals(test.matchesCalendrical(date), true); } @Test(groups={"tck"}) public void test_matchesCalendrical_timeIgnored() { DateTimeFields test = DateTimeFields.EMPTY .with(YEAR, 2008) .with(MONTH_OF_YEAR, 6) .with(DAY_OF_MONTH, 30) .with(HOUR_OF_DAY, 12); LocalDate date = LocalDate.of(2008, 6, 30); assertEquals(test.matchesCalendrical(date), true); } @Test(groups={"tck"}) public void test_matchesCalendrical_invalidDay() { DateTimeFields test = DateTimeFields.EMPTY .with(YEAR, 2008) .with(MONTH_OF_YEAR, 6) .with(DAY_OF_MONTH, 31); LocalDate date = LocalDate.of(2008, 6, 30); assertEquals(test.matchesCalendrical(date), false); } @Test(groups={"tck"}) public void test_matchesCalendrical_hm_time() { DateTimeFields test = DateTimeFields.EMPTY .with(HOUR_OF_DAY, 11) .with(MINUTE_OF_HOUR, 30); LocalTime time = LocalTime.of(11, 30); assertEquals(test.matchesCalendrical(time), true); // check original immutable assertFields(test, HOUR_OF_DAY, 11, MINUTE_OF_HOUR, 30); } @Test(groups={"tck"}) public void test_matchesCalendrical_amPmMatches() { DateTimeFields test = DateTimeFields.EMPTY .with(HOUR_OF_DAY, 11) .with(MINUTE_OF_HOUR, 30) .with(AMPM_OF_DAY, 0); LocalTime time = LocalTime.of(11, 30); assertEquals(test.matchesCalendrical(time), true); } @Test(groups={"tck"}) public void test_matchesCalendrical_amPmNotMatches() { DateTimeFields test = DateTimeFields.EMPTY .with(HOUR_OF_DAY, 11) .with(MINUTE_OF_HOUR, 30) .with(AMPM_OF_DAY, 1); // time is 11:30, but this says PM LocalTime time = LocalTime.of(11, 30); assertEquals(test.matchesCalendrical(time), false); } @Test(groups={"tck"}) public void test_matchesCalendrical_h_time_partialMatch() { DateTimeFields test = DateTimeFields.EMPTY .with(HOUR_OF_DAY, 11); LocalTime time = LocalTime.of(11, 30); assertEquals(test.matchesCalendrical(time), true); } @Test(groups={"tck"}) public void test_matchesCalendrical_dateIgnored() { DateTimeFields test = DateTimeFields.EMPTY .with(HOUR_OF_DAY, 11) .with(MINUTE_OF_HOUR, 30) .with(YEAR, 2008); LocalTime time = LocalTime.of(11, 30); assertEquals(test.matchesCalendrical(time), true); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_matchesCalendrical_null() { DateTimeFields test = DateTimeFields.EMPTY .with(HOUR_OF_DAY, 11) .with(MINUTE_OF_HOUR, 30); test.matchesCalendrical(null); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_matchesCalendrical_null_emptyFields() { DateTimeFields test = DateTimeFields.EMPTY; test.matchesCalendrical((LocalTime) null); } // equals() / hashCode() @Test(groups={"tck"}) public void test_equals0() { DateTimeFields a = DateTimeFields.EMPTY; DateTimeFields b = DateTimeFields.EMPTY; assertEquals(a.equals(b), true); assertEquals(a.hashCode() == b.hashCode(), true); assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } @Test(groups={"tck"}) public void test_equals1_equal() { DateTimeFields a = dtf(YEAR, 2008); DateTimeFields b = dtf(YEAR, 2008); assertEquals(a.equals(b), true); assertEquals(a.hashCode() == b.hashCode(), true); assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } @Test(groups={"tck"}) public void test_equals1_notEqualValue() { DateTimeFields a = dtf(YEAR, 2008); DateTimeFields b = dtf(YEAR, 2007); assertEquals(a.equals(b), false); //assertEquals(a.hashCode() == b.hashCode(), false); // doesn't have to be so assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } @Test(groups={"tck"}) public void test_equals1_notEqualField() { DateTimeFields a = dtf(MONTH_OF_YEAR, 3); DateTimeFields b = dtf(DAY_OF_MONTH, 3); assertEquals(a.equals(b), false); //assertEquals(a.hashCode() == b.hashCode(), false); // doesn't have to be so assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } @Test(groups={"tck"}) public void test_equals2_equal() { DateTimeFields a = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); DateTimeFields b = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(a.equals(b), true); assertEquals(a.hashCode() == b.hashCode(), true); assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } @Test(groups={"tck"}) public void test_equals2_notEqualOneValue() { DateTimeFields a = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); DateTimeFields b = dtf(YEAR, 2007, MONTH_OF_YEAR, 6); assertEquals(a.equals(b), false); //assertEquals(a.hashCode() == b.hashCode(), false); // doesn't have to be so assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } @Test(groups={"tck"}) public void test_equals2_notEqualTwoValues() { DateTimeFields a = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); DateTimeFields b = dtf(YEAR, 2007, MONTH_OF_YEAR, 5); assertEquals(a.equals(b), false); //assertEquals(a.hashCode() == b.hashCode(), false); // doesn't have to be so assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } @Test(groups={"tck"}) public void test_equals2_notEqualField() { DateTimeFields a = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); DateTimeFields b = dtf(YEAR, 2008, DAY_OF_MONTH, 6); assertEquals(a.equals(b), false); //assertEquals(a.hashCode() == b.hashCode(), false); // doesn't have to be so assertEquals(a.equals(a), true); assertEquals(b.equals(b), true); } @Test(groups={"tck"}) public void test_equals_otherType() { DateTimeFields a = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(a.equals("Rubbish"), false); } @Test(groups={"tck"}) public void test_equals_null() { DateTimeFields a = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); assertEquals(a.equals(null), false); } // toString() @Test(groups={"tck"}) public void test_toString0() { DateTimeFields base = DateTimeFields.EMPTY; String test = base.toString(); assertEquals(test, "[]"); } @Test(groups={"tck"}) public void test_toString1() { DateTimeFields base = dtf(YEAR, 2008); String test = base.toString(); assertEquals(test, "[Year 2008]"); } @Test(groups={"tck"}) public void test_toString2() { DateTimeFields base = dtf(YEAR, 2008, MONTH_OF_YEAR, 6); String test = base.toString(); assertEquals(test, "[Year 2008, MonthOfYear 6]"); } private DateTimeFields dtf(DateTimeRule r1, long v1) { return DateTimeFields.of(DateTimeField.of(r1, v1)); } private DateTimeFields dtf(DateTimeRule r1, long v1, DateTimeRule r2, long v2) { return DateTimeFields.of(DateTimeField.of(r1, v1), DateTimeField.of(r2, v2)); } private DateTimeFields dtf(DateTimeRule r1, long v1, DateTimeRule r2, long v2, DateTimeRule r3, long v3) { return DateTimeFields.of(DateTimeField.of(r1, v1), DateTimeField.of(r2, v2), DateTimeField.of(r3, v3)); } // private DateTimeFields dtf(DateTimeRule r1, long v1, DateTimeRule r2, long v2, DateTimeRule r3, long v3, DateTimeRule r4, long v4) { // return DateTimeFields.of(DateTimeField.of(r1, v1), DateTimeField.of(r2, v2), DateTimeField.of(r3, v3), DateTimeField.of(r4, v4)); private void assertFields( DateTimeFields fields, DateTimeRule rule1, Integer value1) { List<DateTimeField> list = Arrays.asList(DateTimeField.of(rule1, value1)); assertEquals(fields.size(), 1); assertEquals(fields.getField(rule1), list.get(0)); assertEquals(fields.toString(), list.toString()); } private void assertFields( DateTimeFields fields, DateTimeRule rule1, Integer value1, DateTimeRule rule2, Integer value2) { List<DateTimeField> list = Arrays.asList(DateTimeField.of(rule1, value1), DateTimeField.of(rule2, value2)); assertEquals(fields.size(), 2); assertEquals(fields.getField(rule1), list.get(0)); assertEquals(fields.getField(rule2), list.get(1)); assertEquals(fields.toString(), list.toString()); } private void assertFields( DateTimeFields fields, DateTimeRule rule1, Integer value1, DateTimeRule rule2, Integer value2, DateTimeRule rule3, Integer value3) { List<DateTimeField> list = Arrays.asList(DateTimeField.of(rule1, value1), DateTimeField.of(rule2, value2), DateTimeField.of(rule3, value3)); assertEquals(fields.size(), 3); assertEquals(fields.getField(rule1), list.get(0)); assertEquals(fields.getField(rule2), list.get(1)); assertEquals(fields.getField(rule3), list.get(2)); assertEquals(fields.toString(), list.toString()); } }
package jenkins.security; import org.junit.rules.ExternalResource; import org.junit.rules.TemporaryFolder; /** * Test rule that injects a temporary {@link DefaultConfidentialStore} * * @author Kohsuke Kawaguchi */ // TODO remove this when available from the test harness public class ConfidentialStoreRule extends ExternalResource { private final TemporaryFolder tmp = new TemporaryFolder(); @Override protected void before() throws Throwable { tmp.create(); ConfidentialStore.TEST = new ThreadLocal<ConfidentialStore>(); ConfidentialStore.TEST.set(new DefaultConfidentialStore(tmp.getRoot())); } @Override protected void after() { ConfidentialStore.TEST.set(null); ConfidentialStore.TEST = null; tmp.delete(); } }
package net.sitemorph.queue; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import net.sitemorph.protostore.CrudStore; import net.sitemorph.protostore.InMemoryStore; import net.sitemorph.protostore.SortOrder; import net.sitemorph.queue.Message.Task; import com.beust.jcommander.internal.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.Test; import java.util.List; /** * Tests for the task dispatcher. * * @author damien@sitemorph.net */ public class TaskDispatcherTest { private Logger log = LoggerFactory.getLogger("TaskDispatcherTest"); TaskDispatcher getDispatcher(final CrudTaskQueue queue, List<TaskWorker> workers) throws QueueException { TaskDispatcher.Builder builder = TaskDispatcher.newBuilder(); builder.setSleepInterval(1000) .setTaskTimeout(10000) .setWorkerPoolSize(1) .setTaskQueueFactory(new TaskQueueFactory() { @Override public TaskQueue getTaskQueue() { return queue; } @Override public void returnTaskQueue(TaskQueue queue) { } }); for (TaskWorker worker : workers) { builder.registerTaskWorker(worker); } return builder.build(); } CrudTaskQueue getQueue() throws QueueException { CrudStore<Task> taskStore = new InMemoryStore.Builder<Task>() .setPrototype(Task.newBuilder()) .setUrnField("urn") .addIndexField("runTime") .addIndexField("path") .setSortOrder("runTime", SortOrder.ASCENDING) .build(); CrudTaskQueue queue = CrudTaskQueue.fromCrudStore(taskStore); queue.push(Task.newBuilder() .setPath("/") .setRunTime(System.currentTimeMillis()) .setData("") .setUrn("abc")); return queue; } @Test(groups = "slowTest") public void testTasksRun() throws InterruptedException, QueueException { log.debug("TEST TASK RUN SHUTDOWN STARTING"); List<TaskWorker> workers = Lists.newArrayList(); TestTaskWorker worker = new TestTaskWorker(); workers.add(worker); CrudTaskQueue queue = getQueue(); TaskDispatcher dispatcher = getDispatcher(queue, workers); worker.setShutdownDispatcher(dispatcher); Thread thread = new Thread(dispatcher); thread.start(); Thread.sleep(1500); assertTrue(worker.hasRun(), "Worker was not run"); assertNotNull(queue.peek(), "Task list should still have the task " + "as the scheduler was shutdown before the run was complete"); log.debug("TEST TASK RUN SHUTDOWN DONE"); } @Test(groups = "slowTest") public void testTaskRunComplete() throws InterruptedException, QueueException { log.debug("TEST TASK RUN SUCCESSFUL STARTING"); CrudTaskQueue queue = getQueue(); List<TaskWorker> workers = Lists.newArrayList(); NullTaskWorker worker = new NullTaskWorker(); workers.add(worker); TaskDispatcher dispatcher = getDispatcher(queue, workers); // don't set the shudown dispatcher, just let it run Thread thread = new Thread(dispatcher); thread.start(); Thread.sleep(2500); assertTrue(worker.getStatus() == TaskStatus.DONE, "Worker should have been run"); assertNull(queue.peek(), "Task queue should be empty after success"); dispatcher.shutdown(); log.debug("TEST TASK RUN SUCCESSFUL DONE"); } @Test(groups = "slowTest") public void testTwoTaskOneFailNoRun() throws QueueException, InterruptedException { CrudTaskQueue queue = getQueue(); List<TaskWorker> workers = Lists.newArrayList(); workers.add(new TestTaskWorker()); workers.add(new TestTaskWorker()); ((TestTaskWorker) workers.get(0)).setOverrideStatus(TaskStatus.STOPPED); TaskDispatcher dispatcher = getDispatcher(queue, workers); Thread thread = new Thread(dispatcher); thread.start(); Thread.sleep(1500); log.debug("Test sleeping to wait for shutdown"); dispatcher.shutdown(); log.debug("Test shutdown complete"); assertTrue(((TestTaskWorker) workers.get(0)).hasRun(), "Worker 0 was not run"); assertTrue(((TestTaskWorker) workers.get(1)).hasRun(), "Worker 1 was not run"); assertNotNull(queue.peek(), "Queue should not have been emptied"); } @Test(groups = "slowTest") public void testFutureTaskNotRun() throws QueueException, InterruptedException { CrudTaskQueue queue = getQueue(); // remove the current test task queue.pop(); queue.push(Task.newBuilder() .setPath("/") .setRunTime(System.currentTimeMillis() + 1000000) .setData("") .setUrn("abc")); List<TaskWorker> workers = Lists.newArrayList(); workers.add(new TestTaskWorker()); TaskDispatcher dispatcher = getDispatcher(queue, workers); Thread thread = new Thread(dispatcher); thread.start(); Thread.sleep(1500); log.debug("Test sleeping to wait for shutdown"); dispatcher.shutdown(); log.debug("Test shutdown complete"); assertFalse(((TestTaskWorker) workers.get(0)).hasRun(), "Worker 0 was not run"); assertNotNull(queue.peek(), "Queue should not have been emptied"); } @Test(groups = "slowTest") public void testTaskReturnsConnectionToFactoryOnEmpty() throws InterruptedException, QueueException { final CrudTaskQueue queue = getQueue(); queue.pop(); List<TestTaskWorker> workers = Lists.newArrayList(); workers.add(new TestTaskWorker()); final boolean[] returnedQueue = new boolean[1]; returnedQueue[0] = false; TaskDispatcher.Builder builder = TaskDispatcher.newBuilder(); builder.setSleepInterval(1000) .setTaskTimeout(10000) .setWorkerPoolSize(1) .setTaskQueueFactory(new TaskQueueFactory() { @Override public TaskQueue getTaskQueue() { return queue; } @Override public void returnTaskQueue(TaskQueue queue) { returnedQueue[0] = true; } }); for (TaskWorker worker : workers) { builder.registerTaskWorker(worker); } TaskDispatcher dispatcher = builder.build(); Thread thread = new Thread(dispatcher); thread.start(); Thread.sleep(1500); log.debug("Test sleeping to wait for shutdown"); dispatcher.shutdown(); log.debug("Test shutdown complete"); assertTrue(returnedQueue[0], "Expected task queue to be returned"); } }
package org.carcv.persistence; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; /** * @deprecated use beans directly * @author oskopek * */ public class OldHibernateUtil { private static SessionFactory sessionFactory; private static ServiceRegistry serviceRegistry; private static SessionFactory configureSessionFactory() { Configuration configuration = new Configuration(); configuration.configure(); serviceRegistry = new StandardServiceRegistryBuilder().applySettings( configuration.getProperties()).build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } private static SessionFactory configureSessionFactory( String configureFilename) { Configuration configuration = new Configuration(); configuration.configure(configureFilename); serviceRegistry = new StandardServiceRegistryBuilder().applySettings( configuration.getProperties()).build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } public static SessionFactory getSessionFactory() { return configureSessionFactory(); } public static SessionFactory getSessionFactory(String configureFilename) { return configureSessionFactory(configureFilename); } }
package org.opencompare; import org.junit.Test; import org.opencompare.api.java.PCM; import org.opencompare.api.java.PCMContainer; import org.opencompare.api.java.impl.io.KMFJSONLoader; import org.opencompare.api.java.io.PCMLoader; import org.trimou.Mustache; import org.trimou.engine.MustacheEngine; import org.trimou.engine.MustacheEngineBuilder; import org.trimou.engine.locator.FileSystemTemplateLocator; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.util.*; import java.util.logging.Logger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class RandomProductChartTest { private final static Logger _log = Logger.getLogger("RandomProductChartTest"); /* * a folder with thousands of PCMs */ private static File inputPCMDirectory = new File("/Users/macher1/Downloads/model/"); @Test public void testProductChart1() throws Exception { String chartTargetFolder = "outputNokia"; String fileName = "pcms/Comparison_of_Nikon_DSLR_cameras_0.pcm"; // precondition: output folder exist File f = new File(chartTargetFolder); if (!f.exists() || !f.isDirectory()) assertTrue(f.mkdir()); _buildRandomProductChart(PCMUtils.loadPCM(fileName), "NokiaRandom2", chartTargetFolder, 2); _buildRandomProductChart(PCMUtils.loadPCM(fileName), "NokiaRandom3", chartTargetFolder, 3); } @Test public void testProductChart2() throws Exception { String chartTargetFolder = "outputPokemon"; // precondition: output folder exist File f = new File(chartTargetFolder); if (!f.exists() || !f.isDirectory()) assertTrue(f.mkdir()); _buildRandomProductChart(PCMTestUtil.mkPokemonPCM(), "Pokemon2", chartTargetFolder, 2); _buildRandomProductChart(PCMTestUtil.mkPokemonPCM(), "Pokemon3", chartTargetFolder, 3); } @Test public void testProductCharts1() throws Exception { String chartTargetFolder = "outputAll"; int chartDimension = 2; // X, Y, or Z (bubble size) _buildRandomProductCharts(collectPCMContainersInAFolder(inputPCMDirectory), chartTargetFolder, chartDimension); } @Test public void testProductCharts2() throws Exception { String chartTargetFolder = "outputAllBubble"; int chartDimension = 3; // X, Y, or Z (bubble size) _buildRandomProductCharts(collectPCMContainersInAFolder(inputPCMDirectory), chartTargetFolder, chartDimension); } // CSV folder of Pokemon: "/Users/macher1/Downloads/pokeapi-master/data/v2" /** * Generate a produch chart for each PCM in the collection * The output folder is chartTargetFolder * user can specify if she wants two or three dimensions * @param allPcmContainers * @param chartTargetFolder * @param chartDimension * @throws IOException */ private void _buildRandomProductCharts(Collection<PCMContainer> allPcmContainers, String chartTargetFolder, int chartDimension) throws IOException { assertTrue(chartDimension == 2 || chartDimension == 3); // precondition: output folder exist File f = new File(chartTargetFolder); if (!f.exists() || !f.isDirectory()) assertTrue(f.mkdir()); for (PCMContainer pcmContainer : allPcmContainers) { PCM pcm = pcmContainer.getPcm(); assertNotNull(pcm); if (!_buildRandomProductChart(pcm, pcm.getName(), chartTargetFolder, chartDimension)) break; } } /** * collect PCMs of a folder (and set the PCM name with the name file) * each .pcm is loaded * note that a .pcm can contain several PCMContainers * @param dir * @return * @throws IOException */ private Collection<PCMContainer> collectPCMContainersInAFolder(File dir) throws IOException { assertTrue(dir.isDirectory()); Collection<PCMContainer> containers = new ArrayList<PCMContainer>(); File[] pcms = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".pcm"); } }); assertTrue(pcms.length > 0); for (File pcmFile : pcms) { PCMLoader loader = new KMFJSONLoader(); List<PCMContainer> pcmContainers = loader.load(pcmFile); for (PCMContainer pc : pcmContainers) { containers.add(pc); pc.getPcm().setName(pcmFile.getName()); } } return containers; } /** * * build a product chart for a specific PCM with a random strategy for picking random, numerical features * @param pcm * @param pcmName * @param chartTargetFolder * @param chartDimension * @return * @throws IOException */ private boolean _buildRandomProductChart(PCM pcm, String pcmName, String chartTargetFolder, int chartDimension) throws IOException { MustacheEngine engine = MustacheEngineBuilder .newBuilder() .addTemplateLocator(new FileSystemTemplateLocator(1, "template/", "html")) .build(); Collection<String> candidateFts = new PCMHelper().collectUniformAndNumericalFeatures(pcm); if (candidateFts.size() < chartDimension) { _log.warning("Impossible to produce a product chart for PCM: " + pcmName); return false; } List<String> lCandidateFts = new ArrayList<String>(candidateFts); Collections.shuffle(lCandidateFts); List<String> lfts = lCandidateFts.subList(0, chartDimension); assertTrue(lfts.size() <= chartDimension); String xFeature = lfts.get(0); String yFeature = lfts.get(1); String zFeature = null; ProductChartBuilder pchart = null ; if (chartDimension == 2) pchart = new ProductChartBuilder(pcm, xFeature, yFeature); else { assertEquals(3, chartDimension); zFeature = lfts.get(2); pchart = new ProductChartBuilder(pcm, xFeature, yFeature, zFeature); } String data = pchart.buildData(); Optional<String> basicStats = _mkBasicStats(pcm); Mustache mustache = engine.getMustache("index"); Map<String, String> valueTemplates = new HashMap<String, String>(); valueTemplates.put("pcmData", data); valueTemplates.put("pcmTitle", pcmName); valueTemplates.put("xFeature", xFeature); valueTemplates.put("yFeature", yFeature); valueTemplates.put("zFeature", zFeature); valueTemplates.put("basicSummary", basicStats.orElse("")); String output = mustache.render(valueTemplates); FileWriter fw = new FileWriter(new File(chartTargetFolder + "/" + "index-" + pcmName + ".html")); fw.write(output); fw.close(); return true; } private Optional<String> _mkBasicStats(PCM pcm) { return PCMTestUtil.mkBasicStats(pcm); } }
package uk.co.benjiweber.expressions; import org.junit.Test; import java.util.List; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static uk.co.benjiweber.expressions.Times.times; public class TimesTest { @Test public void times_collection_size() { List<String> aCollection = asList("one", "two", "three"); times(aCollection.size()).invoke(this::foo); assertEquals(3, numberOfTimesFooWasInvoked); } @Test public void times_literal() { times(6).invoke(this::bar); assertEquals(6, numberOfTimesBarWasInvoked); } int numberOfTimesFooWasInvoked = 0; private void foo() { numberOfTimesFooWasInvoked++; } int numberOfTimesBarWasInvoked = 0; private void bar() { numberOfTimesBarWasInvoked++; } }
package vaeke.restcountries.v1; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import org.junit.Rule; import org.junit.runner.RunWith; import vaeke.restcountries.v1.domain.DesCountry; import com.eclipsesource.restfuse.Assert; import com.eclipsesource.restfuse.Destination; import com.eclipsesource.restfuse.HttpJUnitRunner; import com.eclipsesource.restfuse.Method; import com.eclipsesource.restfuse.Response; import com.eclipsesource.restfuse.annotation.Context; import com.eclipsesource.restfuse.annotation.HttpTest; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; @RunWith(HttpJUnitRunner.class) public class CountryRestTest { @Rule public Destination destination = new Destination(this, "http://localhost:8080/rest/v1"); @Context private Response response; @HttpTest(method = Method.GET, path = "/") public void checkOnlineStatus() { Assert.assertOk(response); } @HttpTest(method = Method.GET, path = "/alpha/co") public void alpha2() { Assert.assertOk(response); DesCountry country = deserialize(response.getBody()); org.junit.Assert.assertEquals("CO", country.getAlpha2Code()); } @HttpTest(method = Method.GET, path = "/alpha/col") public void alpha3() { Assert.assertOk(response); DesCountry country = deserialize(response.getBody()); org.junit.Assert.assertEquals("COL", country.getAlpha3Code()); } @HttpTest(method = Method.GET, path = "/currency/eur") public void currency() { Assert.assertOk(response); List<DesCountry> countries = deserializeList(response.getBody()); org.junit.Assert.assertFalse(countries.isEmpty()); for(DesCountry country : countries) { org.junit.Assert.assertTrue(country.getCurrencies().contains("EUR")); } } @HttpTest(method = Method.GET, path = "/callingcode/1") public void callingcode() { Assert.assertOk(response); List<DesCountry> countries = deserializeList(response.getBody()); org.junit.Assert.assertFalse(countries.isEmpty()); for(DesCountry country : countries) { org.junit.Assert.assertTrue(country.getCallingCodes().contains("1")); } } @HttpTest(method = Method.GET, path = "/capital/washington") public void capital() { Assert.assertOk(response); List<DesCountry> countries = deserializeList(response.getBody()); org.junit.Assert.assertFalse(countries.isEmpty()); for(DesCountry country : countries) { org.junit.Assert.assertEquals("washington d.c.", country.getCapital().toLowerCase()); } } @HttpTest(method = Method.GET, path = "/region/europe") public void region() { Assert.assertOk(response); List<DesCountry> countries = deserializeList(response.getBody()); for(DesCountry country : countries) { org.junit.Assert.assertEquals("europe", country.getRegion().toLowerCase()); } } @HttpTest(method = Method.GET, path = "/lang/en") public void language() { Assert.assertOk(response); List<DesCountry> countries = deserializeList(response.getBody()); for(DesCountry country : countries) { org.junit.Assert.assertTrue(country.getLanguages().contains("en")); } } @HttpTest(method = Method.GET, path = "/alpha?codes=ar;be;fr;it") public void alphaList() { Assert.assertOk(response); List<DesCountry> countries = deserializeList(response.getBody()); org.junit.Assert.assertFalse(countries.isEmpty()); org.junit.Assert.assertEquals(4, countries.size()); org.junit.Assert.assertEquals("AR", countries.get(0).getAlpha2Code()); org.junit.Assert.assertEquals("BE", countries.get(1).getAlpha2Code()); org.junit.Assert.assertEquals("FR", countries.get(2).getAlpha2Code()); org.junit.Assert.assertEquals("IT", countries.get(3).getAlpha2Code()); } @HttpTest(method = Method.GET, path = "/name/russia") public void name() { Assert.assertOk(response); List<DesCountry> countries = deserializeList(response.getBody()); org.junit.Assert.assertFalse(countries.isEmpty()); for(DesCountry c : countries) { org.junit.Assert.assertEquals("Russia", c.getName()); } } @HttpTest(method = Method.GET, path = "/name/russian%20federation?searchFullText=true") public void nameFulltext() { Assert.assertOk(response); List<DesCountry> countries = deserializeList(response.getBody()); org.junit.Assert.assertFalse(countries.isEmpty()); for(DesCountry c : countries) { org.junit.Assert.assertEquals("Russia", c.getName()); } } @HttpTest(method = Method.GET, path = "/name/russian%20fed?fullText=true") public void nameFulltextNotFound() { Assert.assertNotFound(response); } @HttpTest(method = Method.GET, path = "/alpha/co") public void getBorders() { Assert.assertOk(response); DesCountry country = deserialize(response.getBody()); org.junit.Assert.assertFalse(country == null); List<String> bordercountry = country.getBorders(); org.junit.Assert.assertTrue(bordercountry.size() == 5); Collection<String> c = new HashSet<String>(); c.add("BRA"); c.add("ECU"); c.add("PAN"); c.add("PER"); c.add("VEN"); org.junit.Assert.assertTrue(bordercountry.containsAll(c)); } private DesCountry deserialize(String json) { Gson gson = new Gson(); DesCountry country = gson.fromJson(json, DesCountry.class); return country; } private List<DesCountry> deserializeList(String json) { Gson gson = new Gson(); Type listType = new TypeToken<ArrayList<DesCountry>>() {}.getType(); List<DesCountry> countries = gson.fromJson(json, listType); return countries; } }
package com.grarak.kerneladiutor.utils; import android.app.ActivityManager; import android.app.UiModeManager; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.StringRes; import android.support.v4.view.ViewCompat; import android.text.Html; import android.util.Base64; import android.util.Log; import android.view.View; import android.widget.Toast; import com.grarak.kerneladiutor.BuildConfig; import com.grarak.kerneladiutor.activities.StartActivity; import com.grarak.kerneladiutor.utils.root.RootFile; import com.grarak.kerneladiutor.utils.root.RootUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Locale; public class Utils { private static final String TAG = Utils.class.getSimpleName(); public static boolean DONATED = BuildConfig.DEBUG; public static boolean DARK_THEME; public static boolean isTv(Context context) { return ((UiModeManager) context.getSystemService(Context.UI_MODE_SERVICE)) .getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION; } public static boolean isEmulator() { return Build.FINGERPRINT.startsWith("generic") || Build.FINGERPRINT.startsWith("unknown") || Build.MODEL.contains("google_sdk") || Build.MODEL.contains("Emulator") || Build.MODEL.contains("Android SDK built for x86") || Build.MANUFACTURER.contains("Genymotion") || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")) || "google_sdk".equals(Build.PRODUCT); } public static void setStartActivity(boolean material, Context context) { PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(new ComponentName(context, StartActivity.class), material ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED : PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); pm.setComponentEnabledSetting(new ComponentName(BuildConfig.APPLICATION_ID, BuildConfig.APPLICATION_ID + ".activities.StartActivity-Material"), material ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } public static boolean hideStartActivity() { RootUtils.SU su = new RootUtils.SU(false, null); String prop = su.runCommand("getprop ro.kerneladiutor.hide"); su.close(); return prop != null && prop.equals("true"); } public static boolean isServiceRunning(Class<?> serviceClass, Context context) { ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } public static String decodeString(String text) { try { return new String(Base64.decode(text, Base64.DEFAULT), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } public static String encodeString(String text) { try { return Base64.encodeToString(text.getBytes("UTF-8"), Base64.DEFAULT); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } public static void setLocale(String lang, Context context) { Locale locale = new Locale(lang); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; context.getApplicationContext().getResources().updateConfiguration(config, null); } public static boolean hasCMSDK() { return cyanogenmod.os.Build.CM_VERSION.SDK_INT >= cyanogenmod.os.Build.CM_VERSION_CODES.APRICOT; } public static CharSequence htmlFrom(String text) { //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // return Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY); //} else { return Html.fromHtml(text); } public static String getPath(Uri uri, Context context) { String path = null; String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndex(filePathColumn[0]); path = cursor.getString(columnIndex); } cursor.close(); } return path; } public static String getExternalStorage() { String path = RootUtils.runCommand("echo ${SECONDARY_STORAGE%%:*}"); return path.contains("/") ? path : null; } public static String getInternalStorage() { String dataPath = existFile("/data/media/0", true) ? "/data/media/0" : "/data/media"; if (!new RootFile(dataPath).isEmpty()) { return dataPath; } if (existFile("/sdcard", true)) { return "/sdcard"; } return Environment.getExternalStorageDirectory().getPath(); } public static String getInternalDataStorage() { return Environment.getExternalStorageDirectory().toString() + "/Android/data/" + BuildConfig.APPLICATION_ID; } // Sorry pirates! public static boolean isPatched(ApplicationInfo applicationInfo) { try { boolean withBase = new File(applicationInfo.publicSourceDir).getName().equals("base.apk"); if (withBase) { RootFile parent = new RootFile(applicationInfo.publicSourceDir).getParentFile(); RootFile odex = findExtension(parent, ".odex"); if (odex != null) { String text = RootUtils.runCommand("strings " + odex.toString()); if (text.contains("--dex-file") || text.contains("--oat-file")) { return true; } } String dex = "/data/dalvik-cache/*/data@app@" + applicationInfo.packageName + "*@classes.dex"; if (Utils.existFile(dex)) { String path = RootUtils.runCommand("realpath " + dex); if (path != null) { String text = RootUtils.runCommand("strings " + path); if (text.contains("--dex-file") || text.contains("--oat-file")) { return true; } } } } else if (Utils.existFile(applicationInfo.publicSourceDir.replace(".apk", ".odex"))) { new RootFile(applicationInfo.publicSourceDir.replace(".apk", ".odex")).delete(); RootUtils.runCommand("pkill " + applicationInfo.packageName); return false; } } catch (Exception ignored) { } return false; } private static RootFile findExtension(RootFile path, String extension) { for (RootFile file : path.listFiles()) { if (file != null) { String name; if (file.isDirectory()) { RootFile rootFile = findExtension(file, extension); if (rootFile != null) return rootFile; } else if ((name = file.getName()) != null && name.endsWith(extension)) { return file; } } } return null; } // MD5 code from public static boolean checkMD5(String md5, File updateFile) { if (md5 == null || updateFile == null || md5.isEmpty()) { Log.e(TAG, "MD5 string empty or updateFile null"); return false; } String calculatedDigest = calculateMD5(updateFile); if (calculatedDigest == null) { Log.e(TAG, "calculatedDigest null"); return false; } return calculatedDigest.equalsIgnoreCase(md5); } private static String calculateMD5(File updateFile) { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "Exception while getting digest", e); return null; } InputStream is; try { is = new FileInputStream(updateFile); } catch (FileNotFoundException e) { Log.e(TAG, "Exception while getting FileInputStream", e); return null; } byte[] buffer = new byte[8192]; int read; try { while ((read = is.read(buffer)) > 0) { digest.update(buffer, 0, read); } byte[] md5sum = digest.digest(); BigInteger bigInt = new BigInteger(1, md5sum); String output = bigInt.toString(16); // Fill to 32 chars output = String.format("%32s", output).replace(' ', '0'); return output; } catch (IOException e) { throw new RuntimeException("Unable to process file for MD5", e); } finally { try { is.close(); } catch (IOException e) { Log.e(TAG, "Exception on closing MD5 input stream", e); } } } public static boolean isTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; } public static String readAssetFile(Context context, String file) { InputStream input = null; BufferedReader buf = null; try { StringBuilder s = new StringBuilder(); input = context.getAssets().open(file); buf = new BufferedReader(new InputStreamReader(input)); String str; while ((str = buf.readLine()) != null) { s.append(str).append("\n"); } return s.toString().trim(); } catch (IOException e) { Log.e(TAG, "Unable to read " + file); } finally { try { if (input != null) input.close(); if (buf != null) buf.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } public static boolean useFahrenheit(Context context) { return Prefs.getBoolean("useretardedmeasurement", false, context); } public static double celsiusToFahrenheit(double celsius) { return (9d / 5d) * celsius + 32; } public static double roundTo2Decimals(double val) { BigDecimal bd = new BigDecimal(val); bd = bd.setScale(2, RoundingMode.HALF_UP); return bd.doubleValue(); } public static String strFormat(String text, Object... format) { return String.format(text, format); } public static Long strToLong(String text) { try { return Long.parseLong(text); } catch (NumberFormatException ignored) { return 0L; } } public static int strToInt(String text) { try { return Integer.parseInt(text); } catch (NumberFormatException ignored) { return 0; } } public static boolean isRTL(View view) { return ViewCompat.getLayoutDirection(view) == ViewCompat.LAYOUT_DIRECTION_RTL; } public static void toast(String message, Context context) { toast(message, context, Toast.LENGTH_SHORT); } public static void toast(@StringRes int id, Context context) { toast(context.getString(id), context); } public static void toast(@StringRes int id, Context context, int duration) { toast(context.getString(id), context, duration); } public static void toast(String message, Context context, int duration) { Toast.makeText(context, message, duration).show(); } public static void launchUrl(String url, Context context) { try { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); context.startActivity(i); } catch (ActivityNotFoundException e) { e.printStackTrace(); } } public static int getOrientation(Context context) { return context.getResources().getConfiguration().orientation; } public static boolean isPropRunning(String key) { return isPropRunning(key, RootUtils.getSU()); } public static boolean isPropRunning(String key, RootUtils.SU su) { try { return su.runCommand("getprop | grep " + key).split("]:")[1].contains("running"); } catch (Exception ignored) { return false; } } public static boolean hasProp(String key) { return hasProp(key, RootUtils.getSU()); } public static boolean hasProp(String key, RootUtils.SU su) { try { return su.runCommand("getprop | grep " + key).split("]:").length > 1; } catch (Exception ignored) { return false; } } public static void writeFile(String path, String text, boolean append, boolean asRoot) { if (asRoot) { new RootFile(path).write(text, append); return; } FileWriter writer = null; try { writer = new FileWriter(path, append); writer.write(text); writer.flush(); } catch (IOException e) { Log.e(TAG, "Failed to write " + path); } finally { try { if (writer != null) writer.close(); } catch (IOException e) { e.printStackTrace(); } } } public static String readFile(String file) { return readFile(file, true); } public static String readFile(String file, boolean root) { return readFile(file, root ? RootUtils.getSU() : null); } public static String readFile(String file, RootUtils.SU su) { if (su != null) return new RootFile(file, su).readFile(); StringBuilder s = null; FileReader fileReader = null; BufferedReader buf = null; try { fileReader = new FileReader(file); buf = new BufferedReader(fileReader); String line; s = new StringBuilder(); while ((line = buf.readLine()) != null) s.append(line).append("\n"); } catch (FileNotFoundException ignored) { Log.e(TAG, "File does not exist " + file); } catch (IOException e) { Log.e(TAG, "Failed to read " + file); } finally { try { if (fileReader != null) fileReader.close(); if (buf != null) buf.close(); } catch (IOException e) { e.printStackTrace(); } } return s == null ? null : s.toString().trim(); } public static boolean existFile(String file) { return existFile(file, true); } public static boolean existFile(String file, boolean root) { return existFile(file, root ? RootUtils.getSU() : null); } public static boolean existFile(String file, RootUtils.SU su) { return su == null ? new File(file).exists() : new RootFile(file, su).exists(); } }
package dateadog.dateadog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.widget.DatePicker; import java.util.Date; import java.util.GregorianCalendar; /** * A simple {@link Fragment} subclass. * Use the {@link DatePickerFragment} factory method to * create an instance of this fragment. */ public class DatePickerFragment extends DialogFragment { private DatePicker datePicker; public interface DateDialogListener { void onFinishDialog(Date date); } @Override public Dialog onCreateDialog(Bundle savedInstanceState){ View v = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_date_picker, null); datePicker = (DatePicker) v.findViewById(R.id.dialog_date_date_picker); AlertDialog dialog = new android.support.v7.app.AlertDialog.Builder(getActivity()) .setView(v) .setTitle(R.string.date_time_question) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } }) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { int year = datePicker.getYear(); int month = datePicker.getMonth(); int day = datePicker.getDayOfMonth(); Date date = new GregorianCalendar(year, month, day).getTime(); DateDialogListener activity = (DateDialogListener) getActivity(); activity.onFinishDialog(date); dismiss(); } }) .create(); /* dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); final Window window = getDialog().getWindow(); lp.copyFrom(window.getAttributes()); final View picker = window.findViewById(R.id.dialog_date_date_picker); lp.width = picker.getWidth(); lp.height = picker.getHeight(); window.setAttributes(lp); } }); */ return dialog; } }
package dev.blunch.blunch.activity; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import dev.blunch.blunch.R; import dev.blunch.blunch.services.CollaborativeMenuService; import dev.blunch.blunch.services.PaymentMenuService; import dev.blunch.blunch.utils.Repository; public class ListMenus extends AppCompatActivity { CollaborativeMenuService collaborativeMenuService; PaymentMenuService paymentMenuService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_menus); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setTitle("Ofertas de menú"); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); collaborativeMenuService.setOnChangedListener(new Repository.OnChangedListener() { @Override public void onChanged(EventType type) { if (type.equals(EventType.Full)) { } } }); } }
package fr.neamar.kiss.result; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.provider.ContactsContract; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.PopupMenu; import android.widget.TextView; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import fr.neamar.kiss.KissApplication; import fr.neamar.kiss.R; import fr.neamar.kiss.adapter.RecordAdapter; import fr.neamar.kiss.pojo.ContactsPojo; import fr.neamar.kiss.searcher.QueryInterface; import fr.neamar.kiss.ui.ImprovedQuickContactBadge; public class ContactsResult extends Result { private final ContactsPojo contactPojo; private final QueryInterface queryInterface; public ContactsResult(QueryInterface queryInterface, ContactsPojo contactPojo) { super(); this.pojo = this.contactPojo = contactPojo; this.queryInterface = queryInterface; } @Override public View display(Context context, int position, View v) { if (v == null) v = inflateFromId(context, R.layout.item_contact); // Contact name TextView contactName = (TextView) v.findViewById(R.id.item_contact_name); contactName.setText(enrichText(contactPojo.displayName)); // Contact phone TextView contactPhone = (TextView) v.findViewById(R.id.item_contact_phone); contactPhone.setText(contactPojo.phone); // Contact photo ImprovedQuickContactBadge contactIcon = (ImprovedQuickContactBadge) v .findViewById(R.id.item_contact_icon); contactIcon.setImageDrawable(getDrawable(context)); contactIcon.assignContactUri(Uri.withAppendedPath( ContactsContract.Contacts.CONTENT_LOOKUP_URI, String.valueOf(contactPojo.lookupKey))); contactIcon.setExtraOnClickListener(new OnClickListener() { @Override public void onClick(View v) { recordLaunch(v.getContext()); queryInterface.launchOccurred(-1, ContactsResult.this); } }); // Phone action ImageButton phoneButton = (ImageButton) v.findViewById(R.id.item_contact_action_phone); // Message action ImageButton messageButton = (ImageButton) v.findViewById(R.id.item_contact_action_message); PackageManager pm = context.getPackageManager(); if (pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) { phoneButton.setVisibility(View.VISIBLE); messageButton.setVisibility(View.VISIBLE); phoneButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { launchCall(v.getContext()); } }); messageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { launchMessaging(v.getContext()); } }); messageButton.setVisibility(View.VISIBLE); } else { phoneButton.setVisibility(View.INVISIBLE); messageButton.setVisibility(View.INVISIBLE); } return v; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override protected PopupMenu buildPopupMenu(Context context, final RecordAdapter parent, View parentView) { return inflatePopupMenu(R.menu.menu_item_contact, context, parentView); } @Override protected Boolean popupMenuClickHandler(Context context, RecordAdapter parent, MenuItem item) { switch (item.getItemId()) { case R.id.item_contact_copy_phone: copyPhone(context, contactPojo); return true; } return super.popupMenuClickHandler(context, parent, item); } @SuppressWarnings("deprecation") private void copyPhone(Context context, ContactsPojo contactPojo) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(contactPojo.phone); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText( "Phone number for " + contactPojo.displayName, contactPojo.phone); clipboard.setPrimaryClip(clip); } } @SuppressWarnings("deprecation") @Override public Drawable getDrawable(Context context) { if (contactPojo.icon != null) { InputStream inputStream = null; try { inputStream = context.getContentResolver().openInputStream(contactPojo.icon); return Drawable.createFromStream(inputStream, null); } catch (FileNotFoundException ignored) { } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ignored) { } } } } // Default icon return context.getResources().getDrawable(R.drawable.ic_contact); } @Override public void doLaunch(Context context, View v) { Intent viewContact = new Intent(Intent.ACTION_VIEW); viewContact.setData(Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, String.valueOf(contactPojo.lookupKey))); viewContact.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); viewContact.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); context.startActivity(viewContact); } private void launchMessaging(final Context context) { String url = "sms:" + Uri.encode(contactPojo.phone); Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse(url)); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { recordLaunch(context); queryInterface.launchOccurred(-1, ContactsResult.this); } }, KissApplication.TOUCH_DELAY); } private void launchCall(final Context context) { String url = "tel:" + Uri.encode(contactPojo.phone); Intent i = new Intent(Intent.ACTION_CALL, Uri.parse(url)); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { recordLaunch(context); queryInterface.launchOccurred(-1, ContactsResult.this); } }, KissApplication.TOUCH_DELAY); } }
package org.mozilla.focus.webkit; import android.content.res.Resources; import android.support.v4.util.ArrayMap; import android.support.v4.util.Pair; import android.webkit.WebView; import android.webkit.WebViewClient; import org.mozilla.focus.R; import org.mozilla.focus.utils.HtmlLoader; import java.util.HashMap; import java.util.Map; public class ErrorPage { private static final HashMap<Integer, Pair<Integer, Integer>> errorDescriptionMap; static { errorDescriptionMap = new HashMap<>(); // Chromium's mapping (internal error code, to Android WebView error code) is described at: errorDescriptionMap.put(WebViewClient.ERROR_UNKNOWN, new Pair<>(R.string.error_connectionfailure_title, R.string.error_connectionfailure_message)); // This is probably the most commonly shown error. If there's no network, we inevitably // show this. errorDescriptionMap.put(WebViewClient.ERROR_HOST_LOOKUP, new Pair<>(R.string.error_hostLookup_title, R.string.error_hostLookup_message)); // WebViewClient.ERROR_UNSUPPORTED_AUTH_SCHEME // TODO: we don't actually handle this in firefox - does this happen in real life? // WebViewClient.ERROR_AUTHENTICATION // TODO: there's no point in implementing this until we actually support http auth (#159) errorDescriptionMap.put(WebViewClient.ERROR_CONNECT, new Pair<>(R.string.error_connect_title, R.string.error_connect_message)); // It's unclear what this actually means - it's not well documented. Based on looking at // ErrorCodeConversionHelper this could happen if networking is disabled during load, in which // case the generic error is good enough: errorDescriptionMap.put(WebViewClient.ERROR_IO, new Pair<>(R.string.error_connectionfailure_title, R.string.error_connectionfailure_message)); errorDescriptionMap.put(WebViewClient.ERROR_TIMEOUT, new Pair<>(R.string.error_timeout_title, R.string.error_timeout_message)); errorDescriptionMap.put(WebViewClient.ERROR_REDIRECT_LOOP, new Pair<>(R.string.error_redirectLoop_title, R.string.error_redirectLoop_message)); // We already try to handle external URLs if possible (i.e. we offer to open the corresponding // app, if available for a given scheme). If we end up here that means no app exists. // We could consider showing an "open google play" link here, but ultimately it's hard // to know whether that's the right step, especially if there are no good apps for actually // handling such a protocol there - moreover there doesn't seem to be a good way to search // google play for apps supporting a given scheme. errorDescriptionMap.put(WebViewClient.ERROR_UNSUPPORTED_SCHEME, new Pair<>(R.string.error_unsupportedprotocol_title, R.string.error_unsupportedprotocol_message)); errorDescriptionMap.put(WebViewClient.ERROR_FAILED_SSL_HANDSHAKE, new Pair<>(R.string.error_sslhandshake_title, R.string.error_sslhandshake_message)); errorDescriptionMap.put(WebViewClient.ERROR_BAD_URL, new Pair<>(R.string.error_malformedURI_title, R.string.error_malformedURI_message)); // WebView returns ERROR_UNKNOWN when we try to access a file:/// on Android (with the error string // containing access denied), so I'm not too sure why these codes exist: // sure why these error codes exit // WebViewClient.ERROR_FILE; // WebViewClient.ERROR_FILE_NOT_FOUND; // Seems to be an indication of OOM, insufficient resources, or too many queued DNS queries errorDescriptionMap.put(WebViewClient.ERROR_TOO_MANY_REQUESTS, new Pair<>(R.string.error_generic_title, R.string.error_generic_message)); } public static boolean supportsErrorCode(final int errorCode) { return (errorDescriptionMap.get(errorCode) != null); } public static void loadErrorPage(final WebView webView, final String desiredURL, final int errorCode) { final Pair<Integer, Integer> errorResourceIDs = errorDescriptionMap.get(errorCode); if (errorResourceIDs == null) { throw new IllegalArgumentException("Cannot load error description for unsupported errorcode=" + errorCode); } // This is quite hacky: ideally we'd just load the css file directly using a '<link rel="stylesheet"'. // If mixed content blocking is enabled (which is probably what we want in Focus), then webkit // will block file:///android_res/ links from being loaded - which blocks our css from being loaded. // We could hack around that by enabling mixed content when loading an error page (and reenabling it // once that's loaded), but doing that correctly and reliably isn't particularly simple. Loading // the css data and stuffing it into our html is much simpler, especially since we're already doing // string substitutions. // As an added bonus: file:/// URIs are broken if the app-ID != app package, see: // references when running debug builds, and probably klar too) - which means this wouldn't // be possible even if we hacked around the mixed content issues. final String cssString = HtmlLoader.loadResourceFile(webView.getContext(), R.raw.errorpage_style, null); final Map<String, String> substitutionMap = new ArrayMap<>(); final Resources resources = webView.getContext().getResources(); substitutionMap.put("%page-title%", resources.getString(R.string.errorpage_title)); substitutionMap.put("%button%", resources.getString(R.string.errorpage_refresh)); substitutionMap.put("%messageShort%", resources.getString(errorResourceIDs.first)); substitutionMap.put("%messageLong%", resources.getString(errorResourceIDs.second, desiredURL)); substitutionMap.put("%css%", cssString); final String errorPage = HtmlLoader.loadResourceFile(webView.getContext(), R.raw.errorpage, substitutionMap); // We could load the raw html file directly into the webview using a file:///android_res/ // URI - however we'd then need to do some JS hacking to do our String substitutions. Moreover // we'd have to deal with the mixed-content issues detailed above in that case. webView.loadDataWithBaseURL(desiredURL, errorPage, "text/html", "UTF8", desiredURL); } }
package org.biojava.spice.gui; import java.awt.Color; import java.awt.Dimension; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JCheckBox; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JScrollPane; import javax.swing.JTextField; //import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.border.Border; import org.biojava.bio.Annotation; import org.biojava.bio.structure.Chain; import org.biojava.bio.structure.Structure; import org.biojava.bio.structure.StructureException; import org.biojava.bio.structure.jama.Matrix; import org.biojava.spice.manypanel.eventmodel.StructureAlignmentListener; import org.biojava.dasobert.eventmodel.SequenceEvent; import org.biojava.dasobert.eventmodel.SequenceListener; import org.biojava.dasobert.eventmodel.StructureEvent; import org.biojava.dasobert.eventmodel.StructureListener; import org.biojava.spice.StructureAlignment; import org.biojava.spice.panel.StructurePanel; import org.biojava.spice.panel.StructurePanelListener; import org.jmol.api.JmolViewer; import javax.vecmath.Matrix3f; /** a JPanel that contains radio buttons to choose, which structures to show superimposed * * @author Andreas Prlic * @since 10:14:51 AM * @version %I% %G% */ public class StructureAlignmentChooser extends JPanel implements ItemListener, StructureAlignmentListener { static final long serialVersionUID = 65937284545329877l; public static Logger logger = Logger.getLogger("org.biojava.spice"); List checkButtons; StructureAlignment structureAlignment; Box vBox; List structureListeners; List pdbSequenceListeners; int referenceStructure; // the structure at that position is the first one JTextField searchBox; JScrollPane scroller; StructurePanel structurePanel; public final static float radiansPerDegree = (float) (2 * Math.PI / 360); public final static float degreesPerRadian = (float) (360 / (2 * Math.PI)); boolean sortReverse; JMenu parent; JMenuItem sort; JMenuItem filter; public StructureAlignmentChooser(JMenu parent) { super(); this.parent = parent; structureListeners = new ArrayList(); structureAlignment = new StructureAlignment(null); checkButtons = new ArrayList(); pdbSequenceListeners = new ArrayList(); vBox = Box.createVerticalBox(); this.add(vBox); referenceStructure = -1; searchBox = new JTextField(); searchBox.setEditable(true); searchBox.setMaximumSize(new Dimension(Short.MAX_VALUE,30)); searchBox.addKeyListener(new MyKeyListener(this)); } public void setStructurePanel(StructurePanel panel){ this.structurePanel = panel; } public void setScroller(JScrollPane scroll){ this.scroller = scroll; } public void setSortReverse(boolean direction){ sortReverse = direction; } protected JScrollPane getScroller(){ return scroller; } public JTextField getSearchBox() { return searchBox; } public void clearListeners(){ structureAlignment = new StructureAlignment(null); structureListeners.clear(); pdbSequenceListeners.clear(); parent = null; } public void addStructureListener(StructureListener li){ structureListeners.add(li); } public void addPDBSequenceListener(SequenceListener li){ pdbSequenceListeners.add(li); } private void clearButtons(){ Iterator iter = checkButtons.iterator(); while (iter.hasNext()){ JCheckBox b = (JCheckBox)iter.next(); b.removeItemListener(this); vBox.remove(b); } checkButtons.clear(); vBox.repaint(); } public StructureAlignment getStructureAlignment(){ return structureAlignment; } private void updateMenuItems(){ if ( parent == null) { return; } if ( sort != null) parent.remove(sort); if ( filter != null) parent.remove(filter); AlignmentSortPopup sorter = new AlignmentSortPopup(structureAlignment, this, false); AlignmentFilterActionListener filterAction = new AlignmentFilterActionListener(this); sort = MenuAlignmentListener.getSortMenuFromAlignment(structureAlignment.getAlignment(),sorter); parent.add(sort); filter = MenuAlignmentListener.getFilterMenuFromAlignment(structureAlignment.getAlignment(),filterAction); parent.add(filter); } private String getButtonTooltip(Annotation anno){ String tooltip = ""; List details = new ArrayList(); // System.out.println(anno); try { details = (List) anno.getProperty("details"); } catch (NoSuchElementException e){} if ( details != null) { Iterator iter = details.iterator(); while ( iter.hasNext()) { Annotation d = (Annotation) iter.next(); String prop = (String) d.getProperty("property"); if ( prop.equals(MenuAlignmentListener.filterProperty)) continue; String det = (String) d.getProperty("detail"); if (! tooltip.equals("")) tooltip += " | "; tooltip += prop + " " + det; } } return tooltip; } /** return true if it should be displayed * * @param object * @param filterBy * @return flag if is visible or not */ private boolean isVisibleAfterFilter(Annotation object, String filterBy){ boolean show = true; if ( filterBy == null) return true; if ( filterBy.equalsIgnoreCase(MenuAlignmentListener.showAllObjects)) return true; List details = (List) object.getProperty("details"); Iterator iter = details.iterator(); while ( iter.hasNext()) { Annotation d = (Annotation) iter.next(); String prop = (String) d.getProperty("property"); if (! prop.equals(MenuAlignmentListener.filterProperty)) continue; String det = (String) d.getProperty("detail"); if (! det.equalsIgnoreCase(filterBy)){ return false; } } return show; } public void setStructureAlignment(StructureAlignment ali){ structureAlignment = ali; //logger.info("got new structure alignment"); if ( (ali != null) && ( ali.getIds().length > 0) ) System.setProperty("SPICE:drawStructureRegion","true"); clearButtons(); if ( ali == null) { clearButtons(); repaint(); return; } updateMenuItems(); AlignmentSortPopup sorter = new AlignmentSortPopup(ali,this, sortReverse); Annotation[] objects = structureAlignment.getAlignment().getObjects(); boolean[] selectedArr = ali.getSelection(); String[] ids = ali.getIds(); Color background = getBackground(); for ( int i=0; i< ids.length;i++){ String id = ids[i]; Color col = structureAlignment.getColor(i); if ( ( i == 0 ) || (structureAlignment.isSelected(i))){ UIManager.put("CheckBox.background", col); UIManager.put("CheckBox.interiorBackground", col); UIManager.put("CheckBox.highlite", col); } else { UIManager.put("CheckBox.background", background); UIManager.put("CheckBox.interiorBackground", background); UIManager.put("CheckBox.highlite", background); } JCheckBox b = new JCheckBox(id); b.addMouseListener(sorter); // get tooltip String tooltip = getButtonTooltip(objects[i]); boolean doShow = isVisibleAfterFilter(objects[i],structureAlignment.getFilterBy()); if ( ! doShow) { b.setVisible(false); } b.setToolTipText(tooltip); boolean selected = false; if (selectedArr[i]) { selected = true; // always show selected / even if filtered out! b.setVisible(true); } if ( i == 0) { selected = true; referenceStructure = 0; structureAlignment.select(0); System.setProperty("SPICE:StructureRegionColor",new Integer(col.getRGB()).toString()); try { structureAlignment.getStructure(i); } catch (StructureException e){ selected = false; }; } b.setSelected(selected); vBox.add(b); checkButtons.add(b); b.addItemListener(this); } // update the structure alignment in the structure display. Structure newStruc = structureAlignment.createArtificalStructure(); // execute Rasmol cmd... String cmd = structureAlignment.getRasmolScript(); if ( newStruc.size() < 1) return; StructureEvent event = new StructureEvent(newStruc); Iterator iter2 = structureListeners.iterator(); while (iter2.hasNext()){ StructureListener li = (StructureListener)iter2.next(); li.newStructure(event); if ( li instanceof StructurePanelListener){ StructurePanelListener pli = (StructurePanelListener)li; pli.executeCmd(cmd); } } repaint(); } /** recalculate the displayed alignment. e.g. can be called after toggle full structure * * */ public void recalcAlignmentDisplay() { logger.info("recalculating the alignment display"); Structure newStruc = structureAlignment.createArtificalStructure(referenceStructure); String cmd = structureAlignment.getRasmolScript(referenceStructure); StructureEvent event = new StructureEvent(newStruc); Iterator iter2 = structureListeners.iterator(); while (iter2.hasNext()){ StructureListener li = (StructureListener)iter2.next(); li.newStructure(event); if ( li instanceof StructurePanelListener){ StructurePanelListener pli = (StructurePanelListener)li; pli.executeCmd(cmd); } } } protected List getCheckBoxes() { return checkButtons; } public void itemStateChanged(ItemEvent e) { Object source = e.getItemSelectable(); Iterator iter = checkButtons.iterator(); int i=-1; while (iter.hasNext()){ i++; Object o = iter.next(); JCheckBox box =(JCheckBox)o; if ( o.equals(source)){ String[] ids = structureAlignment.getIds(); String id = ids[i]; //System.out.println("do something with " + id); if (e.getStateChange() == ItemEvent.DESELECTED) { // remove structure from alignment structureAlignment.deselect(i); box.setBackground(this.getBackground()); box.repaint(); // display the first one that is selected // set the color to that one //int j = structureAlignment.getFirstSelectedPos(); int j = structureAlignment.getLastSelectedPos(); if ( j > -1) { Color col = structureAlignment.getColor(j); System.setProperty("SPICE:StructureRegionColor",new Integer(col.getRGB()).toString()); } referenceStructure = j; } else { structureAlignment.select(i); // add structure to alignment Color col = structureAlignment.getColor(i); System.setProperty("SPICE:StructureRegionColor",new Integer(col.getRGB()).toString()); UIManager.put("CheckBox.background", col); UIManager.put("CheckBox.interiorBackground", col); UIManager.put("CheckBox.highlite", col); box.setBackground(col); box.repaint(); // check if we can get the structure... Structure struc = null; try { struc = structureAlignment.getStructure(i); referenceStructure = i; if ( struc.size() > 0) { Chain c1 = struc.getChain(0); String sequence = c1.getSequence(); String ac = id + "." + c1.getName(); SequenceEvent sevent = new SequenceEvent(ac,sequence); Iterator iter3 = pdbSequenceListeners.iterator(); while (iter3.hasNext()){ SequenceListener li = (SequenceListener)iter3.next(); li.newSequence(sevent); } } else { logger.warning("could not load structure at position " +i ); JCheckBox b = (JCheckBox) source; b.setSelected(false); } } catch (StructureException ex){ ex.printStackTrace(); structureAlignment.deselect(i); //return; JCheckBox b = (JCheckBox) source; b.setSelected(false); } } Matrix jmolRotation = getJmolRotation(); Structure newStruc = null; // execute Rasmol cmd... String cmd = null; // update the structure alignment in the structure display. if (e.getStateChange() == ItemEvent.DESELECTED) { newStruc = structureAlignment.createArtificalStructure(); cmd = structureAlignment.getRasmolScript(); } else { newStruc = structureAlignment.createArtificalStructure(i); cmd = structureAlignment.getRasmolScript(i); } // if ( newStruc != null){ // if ( jmolRotation != null){ // Structure clonedStruc = (Structure) newStruc.clone(); // Calc.rotate(clonedStruc,jmolRotation); // newStruc = clonedStruc; StructureEvent event = new StructureEvent(newStruc); Iterator iter2 = structureListeners.iterator(); while (iter2.hasNext()){ StructureListener li = (StructureListener)iter2.next(); li.newStructure(event); if ( li instanceof StructurePanelListener){ StructurePanelListener pli = (StructurePanelListener)li; pli.executeCmd(cmd); } } rotateJmol(jmolRotation); } } } public void rotateJmol(Matrix jmolRotation) { if ( structurePanel != null){ if ( jmolRotation != null) { double[] zyz = getZYZEuler(jmolRotation); String script = "reset; rotate z "+zyz[0] +"; rotate y " + zyz[1] +"; rotate z"+zyz[2]+";"; structurePanel.executeCmd(script); /*structurePanel.executeCmd("show orientation"); JmolViewer viewer = structurePanel.getViewer(); System.out.println("rotating jmol ... " + script); viewer.homePosition(); viewer.rotateToZ(Math.round(zyz[0])); viewer.rotateToY(Math.round(zyz[1])); viewer.rotateToZ(Math.round(zyz[2])); */ } } } /** get the rotation out of Jmol * * @return the jmol rotation matrix */ public Matrix getJmolRotation(){ Matrix jmolRotation = null; if ( structurePanel != null){ //structurePanel.executeCmd("show orientation;"); JmolViewer jmol = structurePanel.getViewer(); Object obj = jmol.getProperty(null,"transformInfo",""); //System.out.println(obj); if ( obj instanceof Matrix3f ) { Matrix3f max = (Matrix3f) obj; jmolRotation = new Matrix(3,3); for (int x=0; x<3;x++) { for (int y=0 ; y<3;y++){ float val = max.getElement(x,y); //System.out.println("x " + x + " y " + y + " " + val); jmolRotation.set(x,y,val); } } } } return jmolRotation; } public static double[] getXYZEuler(Matrix m){ double heading, attitude, bank; // Assuming the angles are in radians. if (m.get(1,0) > 0.998) { // singularity at north pole heading = Math.atan2(m.get(0,2),m.get(2,2)); attitude = Math.PI/2; bank = 0; } else if (m.get(1,0) < -0.998) { // singularity at south pole heading = Math.atan2(m.get(0,2),m.get(2,2)); attitude = -Math.PI/2; bank = 0; } else { heading = Math.atan2(-m.get(2,0),m.get(0,0)); bank = Math.atan2(-m.get(1,2),m.get(1,1)); attitude = Math.asin(m.get(1,0)); } return new double[] { heading, attitude, bank }; } /** get euler angles for a matrix given in ZYZ convention * * @param m * @return the euler values for a rotation around Z, Y, Z in degrees... */ public static double[] getZYZEuler(Matrix m) { double m22 = m.get(2,2); double rY = (float) Math.acos(m22) * degreesPerRadian; double rZ1, rZ2; if (m22 > .999d || m22 < -.999d) { rZ1 = (double) Math.atan2(m.get(1,0), m.get(1,1)) * degreesPerRadian; rZ2 = 0; } else { rZ1 = (double) Math.atan2(m.get(2,1), -m.get(2,0)) * degreesPerRadian; rZ2 = (double) Math.atan2(m.get(1,2), m.get(0,2)) * degreesPerRadian; } return new double[] {rZ1,rY,rZ2}; } public static Matrix matrixFromEuler(double heading, double attitude, double bank) { // Assuming the angles are in radians. double ch = Math.cos(heading); double sh = Math.sin(heading); double ca = Math.cos(attitude); double sa = Math.sin(attitude); double cb = Math.cos(bank); double sb = Math.sin(bank); Matrix m = new Matrix(3,3); m.set(0,0, ch * ca); m.set(0,1, sh*sb - ch*sa*cb); m.set(0,2, ch*sa*sb + sh*cb); m.set(1,0, sa); m.set(1,1, ca*cb); m.set(1,2, -ca*sb); m.set(2,0, -sh*ca); m.set(2,1, sh*sa*cb + ch*sb); m.set(2,2, -sh*sa*sb + ch*cb); return m; } } class MyKeyListener extends KeyAdapter { StructureAlignmentChooser chooser; public MyKeyListener(StructureAlignmentChooser chooser){ this.chooser = chooser; } public void keyPressed(KeyEvent evt) { JTextField txt = (JTextField) evt.getSource(); char ch = evt.getKeyChar(); String search = txt.getText(); // If a printable character add to search text if (ch != KeyEvent.CHAR_UNDEFINED) { if ( ch != KeyEvent.VK_ENTER ) if ( ch != KeyEvent.VK_HOME ) search += ch; } //System.out.println("search text: " + search); StructureAlignment ali = chooser.getStructureAlignment(); String[] ids = ali.getIds(); if ( search.equals("")){ search = "no search provided"; } Border b = BorderFactory.createMatteBorder(3,3,3,3,Color.blue); List checkBoxes = chooser.getCheckBoxes(); boolean firstFound = false; JScrollPane scroller = chooser.getScroller(); int h = 0; for (int i=0; i <ids.length;i++){ JCheckBox box = (JCheckBox) checkBoxes.get(i); if ( ids[i].indexOf(search) > -1) { // this is the selected label //System.out.println("selected label " + ids[i]); box.setBorder(b); box.setBorderPainted(true); if ( ! firstFound ) { // scroll to this position if ( scroller != null){ scroller.getViewport().setViewPosition(new Point (0,h)); } } firstFound = true; } else { // clear checkbutton box.setBorderPainted(false); } box.repaint(); h+= box.getHeight(); } if (! firstFound) { if ( ( search.length() > 0) && (ch != KeyEvent.CHAR_UNDEFINED) ) { if (! (ch == KeyEvent.VK_BACK_SPACE)) { Toolkit.getDefaultToolkit().beep(); } } } } }
package st.gaw.db; import java.io.File; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import android.annotation.SuppressLint; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteDatabaseCorruptException; import android.database.sqlite.SQLiteOpenHelper; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.util.Pair; /** * the main helper class that saves/restore item in memory using a DB storage * <p> * the storage handling is done in a separate thread * @author Steve Lhomme * * @param <E> the type of items stored in memory */ public abstract class AsynchronousDbHelper<E> extends SQLiteOpenHelper { protected final static String TAG = "MemoryDb"; protected final static String STARTUP_TAG = "Startup"; protected final static boolean DEBUG_DB = false; private final Handler saveStoreHandler; private static final int MSG_LOAD_IN_MEMORY = 100; private static final int MSG_STORE_ITEM = 101; private static final int MSG_STORE_ITEMS = 102; private static final int MSG_REMOVE_ITEM = 103; private static final int MSG_UPDATE_ITEM = 104; private static final int MSG_CLEAR_DATABASE = 105; private static final int MSG_SWAP_ITEMS = 106; private static final int MSG_REPLACE_ITEMS = 107; private static final int MSG_CUSTOM_OPERATION = 108; private WeakReference<AsynchronousDbErrorHandler<E>> mErrorHandler; // not protected for now private final CopyOnWriteArrayList<WeakReference<InMemoryDbListener<E>>> mDbListeners = new CopyOnWriteArrayList<WeakReference<InMemoryDbListener<E>>>(); private final AtomicBoolean mDataLoaded = new AtomicBoolean(); private final AtomicInteger modifyingTransactionLevel = new AtomicInteger(0); /** * @param context Used to open or create the database * @param name Database filename on disk * @param version Version number of the database (starting at 1); if the database is older, * {@link #onUpgrade} will be used to upgrade the database; if the database is * newer, {@link #onDowngrade} will be used to downgrade the database * @param logger The {@link Logger} to use for all logs (can be null for the default Android logs) * @param initCookie Cookie to pass to {@link #preloadInit(Object, Logger)} */ @SuppressLint("HandlerLeak") protected AsynchronousDbHelper(Context context, final String name, int version, Logger logger, Object initCookie) { this(context, name, null, version, logger, initCookie); } /** * @param context Used to open or create the database * @param name Database filename on disk * @param factory to use for creating cursor objects, or null for the default * @param version Version number of the database (starting at 1); if the database is older, * {@link #onUpgrade} will be used to upgrade the database; if the database is * newer, {@link #onDowngrade} will be used to downgrade the database * @param logger The {@link Logger} to use for all logs (can be null for the default Android logs) * @param initCookie Cookie to pass to {@link #preloadInit(Object, Logger)} */ @SuppressLint("HandlerLeak") protected AsynchronousDbHelper(final Context context, final String name, CursorFactory factory, int version, Logger logger, Object initCookie) { super(context, name, factory, version); preloadInit(initCookie, logger); HandlerThread handlerThread = new HandlerThread(name, android.os.Process.THREAD_PRIORITY_BACKGROUND); handlerThread.start(); saveStoreHandler = new Handler(handlerThread.getLooper()) { public void handleMessage(Message msg) { SQLiteDatabase db; ContentValues addValues; switch (msg.what) { case MSG_LOAD_IN_MEMORY: if (shouldReloadAllData()) { startLoadingInMemory(); try { db = getWritableDatabase(); try { Cursor c = db.query(getMainTableName(), null, null, null, null, null, null); if (c!=null) try { if (c.moveToFirst()) { startLoadingFromCursor(c); do { addCursorInMemory(c); } while (c.moveToNext()); } } finally { c.close(); } } catch (SQLException e) { LogManager.logger.w(STARTUP_TAG, "Can't query table "+getMainTableName()+" in "+name, e); } } catch (SQLException e) { if (e instanceof SQLiteDatabaseCorruptException || e.getCause() instanceof SQLiteDatabaseCorruptException) notifyDatabaseCorrupted(context, name, e); else LogManager.logger.w(STARTUP_TAG, "Can't open database "+name, e); } finally { finishLoadingInMemory(); } } break; case MSG_CLEAR_DATABASE: try { db = getWritableDatabase(); db.delete(getMainTableName(), "1", null); } catch (Throwable e) { LogManager.logger.w(TAG,"Failed to empty table "+getMainTableName()+" in "+name, e); } finally { sendEmptyMessage(MSG_LOAD_IN_MEMORY); // reload the DB into memory } SQLiteDatabase.releaseMemory(); break; case MSG_STORE_ITEM: @SuppressWarnings("unchecked") E itemToAdd = (E) msg.obj; addValues = null; try { db = getWritableDatabase(); addValues = getValuesFromData(itemToAdd, db); if (addValues!=null) { directStoreItem(db, addValues); } } catch (Throwable e) { notifyAddItemFailed(itemToAdd, addValues, e); } break; case MSG_STORE_ITEMS: @SuppressWarnings("unchecked") Collection<? extends E> itemsToAdd = (Collection<? extends E>) msg.obj; for (E item : itemsToAdd) { addValues = null; try { db = getWritableDatabase(); addValues = getValuesFromData(item, db); if (addValues!=null) { directStoreItem(db, addValues); } } catch (Throwable e) { notifyAddItemFailed(item, addValues, e); } } break; case MSG_REMOVE_ITEM: @SuppressWarnings("unchecked") E itemToDelete = (E) msg.obj; try { db = getWritableDatabase(); if (DEBUG_DB) LogManager.logger.d(TAG, name+" remove "+itemToDelete); if (db.delete(getMainTableName(), getItemSelectClause(itemToDelete), getItemSelectArgs(itemToDelete))==0) notifyRemoveItemFailed(itemToDelete, new RuntimeException("No item "+itemToDelete+" in "+name)); } catch (Throwable e) { notifyRemoveItemFailed(itemToDelete, e); } break; case MSG_UPDATE_ITEM: @SuppressWarnings("unchecked") E itemToUpdate = (E) msg.obj; ContentValues updateValues = null; try { db = getWritableDatabase(); updateValues = getValuesFromData(itemToUpdate, db); if (!directUpdate(db, itemToUpdate, updateValues)) { notifyUpdateItemFailed(itemToUpdate, updateValues, new RuntimeException("Can't update "+updateValues+" in "+name)); } } catch (Throwable e) { notifyUpdateItemFailed(itemToUpdate, updateValues, e); } break; case MSG_REPLACE_ITEMS: @SuppressWarnings("unchecked") Pair<E,E> itemsToReplace = (Pair<E,E>) msg.obj; try { db = getWritableDatabase(); ContentValues newValues = getValuesFromData(itemsToReplace.first, db); directUpdate(db, itemsToReplace.second, newValues); } catch (Throwable e) { notifyReplaceItemFailed(itemsToReplace.first, itemsToReplace.second, e); } break; case MSG_SWAP_ITEMS: @SuppressWarnings("unchecked") Pair<E,E> itemsToSwap = (Pair<E,E>) msg.obj; ContentValues newValuesA = null; try { db = getWritableDatabase(); newValuesA = getValuesFromData(itemsToSwap.second, db); if (newValuesA!=null) { if (DEBUG_DB) LogManager.logger.d(TAG, name+" update "+itemsToSwap.second+" with "+newValuesA); directUpdate(db, itemsToSwap.first, newValuesA); } } catch (Throwable e) { notifyUpdateItemFailed(itemsToSwap.first, newValuesA, e); } ContentValues newValuesB = null; try { db = getWritableDatabase(); newValuesB = getValuesFromData(itemsToSwap.first, db); if (newValuesB!=null) { if (DEBUG_DB) LogManager.logger.d(TAG, name+" update "+itemsToSwap.first+" with "+newValuesB); directUpdate(db, itemsToSwap.second, newValuesB); } } catch (Throwable e) { notifyUpdateItemFailed(itemsToSwap.second, newValuesB, e); } break; case MSG_CUSTOM_OPERATION: try { @SuppressWarnings("unchecked") AsynchronousDbOperation<E> operation = (AsynchronousDbOperation<E>) msg.obj; operation.runInMemoryDbOperation(AsynchronousDbHelper.this); } catch (Exception e) { LogManager.logger.w(TAG, name+" failed to run operation "+msg.obj, e); } break; } super.handleMessage(msg); } }; saveStoreHandler.sendEmptyMessage(MSG_LOAD_IN_MEMORY); } /** * Method to call to insert data directly in the database * @param db Database where data will be written * @param addValues Values that will be written in the database * @return {@code true} if the data were written successfully * @throws RuntimeException if the insertion failed */ protected boolean directStoreItem(SQLiteDatabase db, ContentValues addValues) throws SQLException { long id = db.insertOrThrow(getMainTableName(), null, addValues); if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" insert "+addValues+" = "+id); if (id==-1) throw new RuntimeException("failed to add values "+addValues+" in "+db.getPath()); return id!=-1; } /** * Method to call to update the data directly in the database * @param db Database where data will be updated * @param itemToUpdate Item in the database that needs to be updated * @param updateValues Values that will be updated in the database * @return {@code true} if the data were updated successfully */ protected boolean directUpdate(SQLiteDatabase db, E itemToUpdate, ContentValues updateValues) { if (updateValues!=null) { if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" update "+updateValues+" for "+itemToUpdate); return db.update(getMainTableName(), updateValues, getItemSelectClause(itemToUpdate), getItemSelectArgs(itemToUpdate)/*, SQLiteDatabase.CONFLICT_NONE*/)!=0; } return false; } /** * Method called at the end of constructor, just before the data start loading * @param cookie Data that may be needed to initialize all internal storage * @param logger The {@link Logger} to use for all logs (can be null for the default Android logs) */ protected void preloadInit(Object cookie, Logger logger) { if (logger!=null) LogManager.setLogger(logger); } /** * tell the InMemory database that we are about to modify its data * <p> see also {@link #popModifyingTransaction()} */ protected void pushModifyingTransaction() { modifyingTransactionLevel.incrementAndGet(); } /** * tell the InMemory database we have finish modifying the data at this level. * Once the pop matches all the push {@link #notifyDatabaseChanged()} is called * <p> this is useful to avoid multiple calls to {@link #notifyDatabaseChanged()} during a batch of changes * <p> see also {@link #pushModifyingTransaction()} */ protected void popModifyingTransaction() { if (modifyingTransactionLevel.decrementAndGet()==0) { notifyDatabaseChanged(); } } protected void clearDataInMemory() {} @Override @Deprecated public SQLiteDatabase getReadableDatabase() { return super.getReadableDatabase(); } /** * set the listener that will receive error events * @param listener null to remove the listener */ public void setDbErrorHandler(AsynchronousDbErrorHandler<E> listener) { if (listener==null) mErrorHandler = null; else mErrorHandler = new WeakReference<AsynchronousDbErrorHandler<E>>(listener); } public void addListener(InMemoryDbListener<E> listener) { for (WeakReference<InMemoryDbListener<E>> l : mDbListeners) { if (l.get()==null) mDbListeners.remove(l); else if (l.get()==listener) return; } if (mDataLoaded.get()) listener.onMemoryDbChanged(this); mDbListeners.add(new WeakReference<InMemoryDbListener<E>>(listener)); } public void removeListener(InMemoryDbListener<E> listener) { for (WeakReference<InMemoryDbListener<E>> l : mDbListeners) { if (l.get()==null) mDbListeners.remove(l); else if (l.get()==listener) mDbListeners.remove(l); } } /** * delete all the data in memory and in the database */ public final void clear() { pushModifyingTransaction(); clearDataInMemory(); popModifyingTransaction(); saveStoreHandler.sendEmptyMessage(MSG_CLEAR_DATABASE); } private void notifyAddItemFailed(E item, ContentValues values, Throwable cause) { LogManager.logger.i(TAG, this+" failed to add item "+item+(DEBUG_DB ? (" values"+values) : ""), cause); if (mErrorHandler!=null) { final AsynchronousDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onAddItemFailed(this, item, values, cause); } pushModifyingTransaction(); popModifyingTransaction(); } private void notifyReplaceItemFailed(E srcItem, E replacement, Throwable cause) { LogManager.logger.i(TAG, this+" failed to replace item "+srcItem+" with "+replacement, cause); if (mErrorHandler!=null) { final AsynchronousDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onReplaceItemFailed(this, srcItem, replacement, cause); } pushModifyingTransaction(); popModifyingTransaction(); } private void notifyUpdateItemFailed(E item, ContentValues values, Throwable cause) { LogManager.logger.i(TAG, this+" failed to update item "+item+(DEBUG_DB ? (" values"+values) : ""), cause); if (mErrorHandler!=null) { final AsynchronousDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onAddItemFailed(this, item, values, cause); } pushModifyingTransaction(); popModifyingTransaction(); } private void notifyRemoveItemFailed(E item, Throwable cause) { LogManager.logger.i(TAG, this+" failed to remove item "+item, cause); if (mErrorHandler!=null) { final AsynchronousDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onRemoveItemFailed(this, item, cause); } pushModifyingTransaction(); popModifyingTransaction(); } private void notifyDatabaseCorrupted(Context context, String name, Throwable cause) { LogManager.logger.e(STARTUP_TAG, "table "+getMainTableName()+" is corrupted in "+name); if (mErrorHandler!=null) { final AsynchronousDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onCorruption(this); } pushModifyingTransaction(); File corruptedDbFile = context.getDatabasePath(name); corruptedDbFile.delete(); popModifyingTransaction(); } /** * the name of the main table corresponding to the inMemory elements * @return the name of the main table */ protected abstract String getMainTableName(); /** * use the data in the {@link Cursor} to store them in the memory storage * @param c the Cursor to use * @see #getValuesFromData(Object, SQLiteDatabase) */ protected abstract void addCursorInMemory(Cursor c); /** * transform the element in memory into {@link ContentValues} that can be saved in the database * <p> you can return null and fill the database yourself if you need to * @param data the data to transform * @param dbToFill the database that will receive new items * @return a ContentValues element with all data that can be used to restore the data later from the database * @see #addCursorInMemory(Cursor) */ protected abstract ContentValues getValuesFromData(E data, SQLiteDatabase dbToFill) throws RuntimeException; /** * the where clause that should be used to update/delete the item * <p> see {@link #getItemSelectArgs(Object)} * @param itemToSelect the item about to be selected in the database * @return a string for the whereClause in {@link SQLiteDatabase#update(String, ContentValues, String, String[])} or {@link SQLiteDatabase#delete(String, String, String[])} */ protected abstract String getItemSelectClause(E itemToSelect); /** * the where arguments that should be used to update/delete the item * <p> see {@link #getItemSelectClause(Object)} * @param itemToSelect the item about to be selected in the database * @return a string array for the whereArgs in {@link SQLiteDatabase#update(String, ContentValues, String, String[])} or {@link SQLiteDatabase#delete(String, String, String[])} */ protected abstract String[] getItemSelectArgs(E itemToSelect); /** * Request to store the item in the database asynchronously * <p>Will call the {@link AsynchronousDbErrorHandler#onAddItemFailed(AsynchronousDbHelper, Object, ContentValues, Throwable) AsynchronousDbErrorHandler.onAddItemFailed()} on failure * @param item to add */ protected final void scheduleAddOperation(E item) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_STORE_ITEM, item)); pushModifyingTransaction(); popModifyingTransaction(); } /** * Request to store the items in the database asynchronously * <p>Will call {@link AsynchronousDbErrorHandler#onAddItemFailed(AsynchronousDbHelper, Object, ContentValues, Throwable) AsynchronousDbErrorHandler.onAddItemFailed()} on each item failing * @param items to add */ protected final void scheduleAddOperation(Collection<? extends E> items) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_STORE_ITEMS, items)); pushModifyingTransaction(); popModifyingTransaction(); } /** * Request to update the item in the database asynchronously * <p>{@link AsynchronousDbHelper#getItemSelectArgs(Object) getItemSelectArgs()} is used to find the matching item in the database * <p>Will call {@link AsynchronousDbErrorHandler#onUpdateItemFailed(AsynchronousDbHelper, Object, Throwable) AsynchronousDbErrorHandler.onUpdateItemFailed()} on failure * @see #getValuesFromData(Object, SQLiteDatabase) * @param item to update */ protected final void scheduleUpdateOperation(E item) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_UPDATE_ITEM, item)); pushModifyingTransaction(); popModifyingTransaction(); } /** * Request to replace an item in the databse with another asynchronously * <p>{@link AsynchronousDbHelper#getItemSelectArgs(Object) getItemSelectArgs()} is used to find the matching item in the database * <p>Will call {@link AsynchronousDbErrorHandler#onReplaceItemFailed(AsynchronousDbHelper, Object, Object, Throwable) AsynchronousDbErrorHandler.onReplaceItemFailed()} on failure * @param original Item to replace * @param replacement Item to replace with */ protected final void scheduleReplaceOperation(E original, E replacement) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_REPLACE_ITEMS, new Pair<E,E>(original, replacement))); pushModifyingTransaction(); popModifyingTransaction(); } protected final void scheduleSwapOperation(E itemA, E itemB) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_SWAP_ITEMS, new Pair<E,E>(itemA, itemB))); pushModifyingTransaction(); popModifyingTransaction(); } /** * Request to delete the item from the database * <p>Will call the {@link AsynchronousDbErrorHandler#onRemoveItemFailed(AsynchronousDbHelper, Object, Throwable) AsynchronousDbErrorHandler.onRemoveItemFailed()} on failure * @param item to remove */ protected final void scheduleRemoveOperation(E item) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_REMOVE_ITEM, item)); pushModifyingTransaction(); popModifyingTransaction(); } /** * run the operation in the internal thread * @param operation */ protected final void scheduleCustomOperation(AsynchronousDbOperation<E> operation) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_CUSTOM_OPERATION, operation)); } /** * called when we are about to read all items from the disk */ protected void startLoadingInMemory() { pushModifyingTransaction(); mDataLoaded.set(false); } /** * called when we have the cursor to read the data from * <p> * useful to prepare the amount of data needed or get the index of the column we need * @param c the {@link Cursor} that will be used to read the data */ protected void startLoadingFromCursor(Cursor c) {} /** * called after all items have been read from the disk */ protected void finishLoadingInMemory() { mDataLoaded.set(true); popModifyingTransaction(); } /** * Tell whether the database loading should be done or not * <p>If you don't store the elements in memory, you don't need to load the whole data */ protected boolean shouldReloadAllData() { return true; } protected void notifyDatabaseChanged() { for (WeakReference<InMemoryDbListener<E>> l : mDbListeners) { final InMemoryDbListener<E> listener = l.get(); if (listener==null) mDbListeners.remove(l); else listener.onMemoryDbChanged(this); } } public boolean isDataLoaded() { return mDataLoaded.get(); } /** Wait until the data are loaded */ public void waitForDataLoaded() {} @Override public String toString() { StringBuilder sb = new StringBuilder(48); sb.append('{'); sb.append(getClass().getSimpleName()); sb.append(' '); sb.append(Integer.toHexString(System.identityHashCode(this))); sb.append('}'); return sb.toString(); } }
// this will go to another package but // creating a new pom.xml for maven is beyond me... package morflogik.speller; import static morfologik.fsa.MatchResult.EXACT_MATCH; import static morfologik.fsa.MatchResult.SEQUENCE_IS_A_PREFIX; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CodingErrorAction; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import morfologik.fsa.FSA; import morfologik.fsa.FSATraversal; import morfologik.fsa.MatchResult; import morfologik.stemming.Dictionary; import morfologik.stemming.DictionaryMetadata; import morfologik.util.BufferUtils; /** * Find suggestions by using K. Oflazer's algorithm. See Jan Daciuk's <code>s_fsa</code> * package. */ public class Speller { private final int editDistance; private int e_d; // effective edit distance private final hMatrix H; public static int MAX_WORD_LENGTH = 120; private byte[] candidate; /* current replacement */ private int candLen; private int wordLen; /* length of word being processed */ private byte[] word_ff; /* word being processed */ private final List<String> candidates = new ArrayList<String>(); protected final char separatorChar; /** * Internal reusable buffer for encoding words into byte arrays using * {@link #encoder}. */ private ByteBuffer byteBuffer = ByteBuffer.allocate(0); /** * Internal reusable buffer for encoding words into byte arrays using * {@link #encoder}. */ private CharBuffer charBuffer = CharBuffer.allocate(0); /** * Reusable match result. */ private final MatchResult matchResult = new MatchResult(); /** * Features of the compiled dictionary. * * @see DictionaryMetadata */ private final DictionaryMetadata dictionaryMetadata; /** * Charset encoder for the FSA. */ private final CharsetEncoder encoder; /** * Charset decoder for the FSA. */ protected final CharsetDecoder decoder; /** An FSA used for lookups. */ private final FSATraversal matcher; /** FSA's root node. */ private final int rootNode; /** * The FSA we are using. */ protected final FSA fsa; public Speller(final Dictionary dictionary) { this(dictionary, 1); } public Speller(final Dictionary dictionary, final int editDistance) { this(dictionary, editDistance, true); } public Speller(final Dictionary dictionary, final int editDistance, final boolean convertCase) { this.editDistance = editDistance; H = new hMatrix(editDistance, MAX_WORD_LENGTH); this.dictionaryMetadata = dictionary.metadata; this.rootNode = dictionary.fsa.getRootNode(); this.fsa = dictionary.fsa; this.matcher = new FSATraversal(fsa); if (rootNode == 0) { throw new IllegalArgumentException( "Dictionary must have at least the root node."); } if (dictionaryMetadata == null) { throw new IllegalArgumentException( "Dictionary metadata must not be null."); } try { Charset charset = Charset.forName(dictionaryMetadata.encoding); encoder = charset.newEncoder(); decoder = charset.newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT); } catch (UnsupportedCharsetException e) { throw new RuntimeException( "FSA's encoding charset is not supported: " + dictionaryMetadata.encoding); } try { CharBuffer decoded = decoder.decode(ByteBuffer .wrap(new byte[] { dictionaryMetadata.separator })); if (decoded.remaining() != 1) { throw new RuntimeException( "FSA's separator byte takes more than one character after conversion " + " of byte 0x" + Integer .toHexString(dictionaryMetadata.separator) + " using encoding " + dictionaryMetadata.encoding); } this.separatorChar = decoded.get(); } catch (CharacterCodingException e) { throw new RuntimeException( "FSA's separator character cannot be decoded from byte value 0x" + Integer.toHexString(dictionaryMetadata.separator) + " using encoding " + dictionaryMetadata.encoding, e); } } /** * Encode a character sequence into a byte buffer, optionally expanding * buffer. */ protected ByteBuffer charsToBytes(CharBuffer chars, ByteBuffer bytes) { bytes.clear(); final int maxCapacity = (int) (chars.remaining() * encoder .maxBytesPerChar()); if (bytes.capacity() <= maxCapacity) { bytes = ByteBuffer.allocate(maxCapacity); } chars.mark(); encoder.reset(); encoder.encode(chars, bytes, true); bytes.flip(); chars.reset(); return bytes; } public boolean isInDictionary(CharSequence word) { // Encode word characters into bytes in the same encoding as the FSA's. charBuffer.clear(); charBuffer = BufferUtils.ensureCapacity(charBuffer, word.length()); for (int i = 0; i < word.length(); i++) { char chr = word.charAt(i); charBuffer.put(chr); } charBuffer.flip(); byteBuffer = charsToBytes(charBuffer, byteBuffer); // Try to find a partial match in the dictionary. final MatchResult match = matcher.match(matchResult, byteBuffer.array(), 0, byteBuffer.remaining(), rootNode); return (match.kind == SEQUENCE_IS_A_PREFIX || match.kind == EXACT_MATCH); } /** * Propose suggestions for misspelled runon words. This algorithm comes from * spell.cc in s_fsa package by Jan Daciuk. * * @param original * The original misspelled word. * @return The list of suggested pairs, as space-concatenated strings. */ public List<String> replaceRunOnWords(final String original) { final List<String> candidates = new ArrayList<String>(); if (!isInDictionary(original)) { CharSequence ch = original; for (int i = 2; i < ch.length(); i++) { // chop from left to right CharSequence firstCh = ch.subSequence(0, i); if (isInDictionary(firstCh) && isInDictionary(ch.subSequence(i, ch.length()))) { candidates.add(firstCh + " " + ch.subSequence(i, ch.length())); } } } return candidates; } /** * Find suggestions by using K. Oflazer's algorithm. See Jan Daciuk's s_fsa * package, spell.cc for further explanation. * * @param word * The original misspelled word. * @return A list of suggested replacements. * @throws CharacterCodingException */ public List<String> findReplacements(final CharSequence word) throws CharacterCodingException { candidates.clear(); if (!isInDictionary(word)) { CharBuffer ch = CharBuffer.allocate(word.length()); ch.put(CharBuffer.wrap(word)); ch.flip(); ByteBuffer bb1 = ByteBuffer.allocate(word.length()); bb1 = charsToBytes(ch, bb1); word_ff = bb1.array(); wordLen = word_ff.length; candidate = word_ff.clone(); candLen = candidate.length; e_d = (wordLen <= editDistance ? (wordLen - 1) : editDistance); findRepl(0, fsa.getRootNode()); } return candidates; } private void findRepl(final int depth, final int node) throws CharacterCodingException { int dist = 0; // not yet used, might be useful for sorting suggestions if (depth + 1 >= candLen) { candidate = Arrays.copyOf(candidate, MAX_WORD_LENGTH); } for (int arc = fsa.getFirstArc(node); arc != 0; arc = fsa.getNextArc(arc)) { if (!fsa.isArcTerminal(arc)) { candidate[depth] = fsa.getArcLabel(arc); if (cuted(depth) <= e_d) { // TODO: shouldn't findRepl be invoked _after_ a check // for a potential suggestion? After you return from recursion // the candidate array may be corrupted/ filled with junk data? findRepl(depth + 1, fsa.getEndNode(arc)); if (Math.abs(wordLen - 1 - depth) <= e_d && (dist = ed(wordLen - 1, depth)) <= e_d && (fsa.isArcFinal(arc) || isBeforeSeparator(arc))) { ByteBuffer bb1 = ByteBuffer.allocate(MAX_WORD_LENGTH); bb1.put(candidate); bb1.limit(depth + 1); bb1.flip(); CharBuffer ch = decoder.decode(bb1); candidates.add(ch.toString()); } } } } return; } private boolean isBeforeSeparator(int arc) { int arc1 = fsa.getEndNode(arc); if (arc1 != 0 && !fsa.isArcTerminal(arc1)) { return fsa.getArcLabel(arc1) == dictionaryMetadata.separator; } return false; } /** * Calculates edit distance. * * @param i * -(i) length of first word (here: misspelled)-1; * @param j * -(i) length of second word (here: candidate)-1. * @return Edit distance between the two words. Remarks: See Oflazer. */ public int ed(final int i, final int j) { int result; int a, b, c; // not really necessary if (word_ff[i] == candidate[j]) { // last characters are the same result = H.get(i, j); } else if (i > 0 && j > 0 && word_ff[i] == candidate[j - 1] && word_ff[i - 1] == candidate[j]) { // last two characters are transposed a = H.get(i - 1, j - 1); // transposition, e.g. ababab, ababba b = H.get(i + 1, j); // deletion, e.g. abab, aba c = H.get(i, j + 1); // insertion e.g. aba, abab result = 1 + min(a, b, c); } else { // otherwise a = H.get(i, j); // replacement, e.g. ababa, ababb b = H.get(i + 1, j); // deletion, e.g. ab, a c = H.get(i, j + 1); // insertion e.g. a, ab result = 1 + min(a, b, c); } H.set(i + 1, j + 1, result); return result; } /** * Calculates cut-off edit distance. * * @param depth * - (int) current length of candidates. * @return Cut-off edit distance. Remarks: See Oflazer. */ public int cuted(final int depth) { int l = Math.max(0, depth - e_d); // min chars from word to consider - 1 int u = Math.min(wordLen - 1, depth + e_d);// max chars from word to // consider - 1 int min_ed = e_d + 1; // what is to be computed int d; for (int i = l; i <= u; i++) { if ((d = ed(i, depth)) < min_ed) min_ed = d; } return min_ed; } private int min(final int a, final int b, final int c) { return Math.min(a, Math.min(b, c)); } /** * Keeps track of already computed values of edit distance.<br/> * Remarks: To save space, the matrix is kept in a vector. */ private class hMatrix { private int[] p; /* the vector */ private int rowLength; /* row length of matrix */ int columnHeight; /* column height of matrix */ int editDistance; /* edit distance */ /** * Allocates memory and initializes matrix (constructor). * * @param distance (int) max edit distance allowed for * candidates; * @param maxLength (int) max length of words. * @return: Nothing. Remarks: See Oflazer. To save space, the matrix is * stored as a vector. To save time, additional raws and * columns are added. They are initialized to their distance in * the matrix, so that no bound checking is necessary during * access. */ public hMatrix(final int distance, final int maxLength) { rowLength = maxLength + 2; columnHeight = 2 * distance + 3; editDistance = distance; int size = rowLength * columnHeight; p = new int[size]; // Initialize edges of the diagonal band to distance + 1 (i.e. // distance too big) for (int i = 0; i < rowLength - distance - 1; i++) { p[i] = distance + 1; // H(distance + j, j) = distance + 1 p[size - i - 1] = distance + 1; // H(i, distance + i) = distance } // Initialize items H(i,j) with at least one index equal to zero to // |i - j| for (int j = 0; j < 2 * distance + 1; j++) { p[j * rowLength] = distance + 1 - j; // H(i=0..distance+1,0)=i //FIXME: dla distance == 2 tu mamy wykroczenie poza rozmiar tablicy p[Math.min(p.length - 1, (j + distance + 1) * rowLength + j)] = j; // H(0,j=0..distance+1)=j } } public int get(final int i, final int j) { return p[(j - i + editDistance + 1) * rowLength + j]; } /** * Set an item in hMatrix. * * @param i * - (int) row number; * @param j * - (int) column number; * @param val * - (int) value to put there. * @return: Nothing. * * No checking for i & j is done. They must be correct. */ public void set(final int i, final int j, final int val) { p[(j - i + editDistance + 1) * rowLength + j] = val; } } }
package org.concord.datagraph.state; import java.awt.Component; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Insets; import javax.swing.JComponent; import org.concord.datagraph.engine.DataGraphAutoScaler; import org.concord.datagraph.ui.DataGraph; import org.concord.framework.otrunk.OTObject; import org.concord.framework.otrunk.view.AbstractOTJComponentView; import org.concord.framework.otrunk.view.OTDefaultComponentProvider; import org.concord.framework.otrunk.view.OTJComponentViewContext; import org.concord.framework.otrunk.view.OTJComponentViewContextAware; import org.concord.framework.otrunk.view.OTLabbookViewProvider; /** * @author scott * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class OTDataCollectorView extends AbstractOTJComponentView implements OTJComponentViewContextAware, OTDefaultComponentProvider, OTLabbookViewProvider { AbstractOTJComponentView view; OTDataCollector dataCollector; boolean multipleGraphableEnabled = false; protected OTJComponentViewContext jComponentViewContext; /* (non-Javadoc) * @see org.concord.framework.otrunk.view.OTJComponentView#getComponent(boolean) */ public JComponent getComponent(OTObject otObject) { setup(otObject); return view.getComponent(otObject); } /** * Initializes the basic variables. Refactored from getComponent method * so that labbook methods can use it as well. * @param otObject */ private void setup(OTObject otObject){ this.dataCollector = (OTDataCollector)otObject; if(dataCollector.getSingleValue()) { view = new SingleValueDataView(dataCollector); } else { view = new DataCollectorView(dataCollector, getControllable(), true); } view.setViewContext(viewContext); if (view instanceof OTJComponentViewContextAware){ ((OTJComponentViewContextAware)view).setOTJComponentViewContext(jComponentViewContext); } } /* (non-Javadoc) * @see org.concord.framework.otrunk.view.OTJComponentView#viewClosed() */ public void viewClosed() { if(view != null) { view.viewClosed(); } } public void setOTJComponentViewContext(OTJComponentViewContext viewContext) { this.jComponentViewContext = viewContext; } public boolean getControllable() { return dataCollector.getShowControlBar(); } public DataCollectorView getDataCollectorView(){ if (view instanceof DataCollectorView){ return (DataCollectorView)view; } else { return null; } } public Component getDefaultComponent() { if (view instanceof DataCollectorView) return ((DataCollectorView)view).getDataGraph().getGraph(); else return view.getComponent(dataCollector); } /** * For OTLabbookViewProvider. Here we just clone the object */ public OTObject copyObjectForSnapshot(OTObject otObject) { try { OTObject copy = otObject.getOTObjectService().copyObject(otObject, -1); if (copy instanceof OTDataCollector){ ((OTDataCollector)copy).setMultipleGraphableEnabled(false); } return copy; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return otObject; } /** * For OTLabbookViewProvider. */ public boolean drawtoolNeededForAlbum() { // TODO Auto-generated method stub return false; } /** * For OTLabbookViewProvider. This returns the regular view with the graph set to not * be controllable */ public JComponent getLabbookView(OTObject otObject) { ((OTDataCollector)otObject).getSource().setControllable(false); setup(otObject); // view.getComponent(otObject); if (view instanceof DataCollectorView){ DataGraph graph = ((DataCollectorView)view).getDataGraph(true, false); graph.setAutoFitMode(DataGraph.AUTO_SCALE_MODE); final DataGraphAutoScaler autoscaler = graph.getAutoScaler(); // autoscaler.setAutoScaleX(true); // autoscaler.setAutoScaleY(true); return graph; } else return view.getComponent(dataCollector); } /** * For OTLabbookViewProvider. This returns a scaled-down graph without the toolbars and * with a smaller title. */ public JComponent getThumbnailView(OTObject otObject, int height) { ((OTDataCollector)otObject).getSource().setControllable(false); setup(otObject); // view.getComponent(otObject); if (view instanceof DataCollectorView){ DataGraph graph = ((DataCollectorView)view).getDataGraph(false, false); graph.setScale(2, 2); graph.setAutoFitMode(DataGraph.AUTO_SCALE_MODE); graph.setInsets(new Insets(0,8,8,0)); graph.setTitle(graph.getTitle(), 9); graph.setPreferredSize(new Dimension((int) (height*1.3), height)); return graph; } else return view.getComponent(dataCollector); } }
package st.gaw.db; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import android.annotation.SuppressLint; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.util.Pair; /** * the main helper class that saves/restore item in memory using a DB storage * <p> * the storage handling is done in a separate thread * @author Steve Lhomme * * @param <E> the type of items stored in memory */ public abstract class AsynchronousDbHelper<E> extends SQLiteOpenHelper { protected final static String TAG = "MemoryDb"; protected final static String STARTUP_TAG = "Startup"; protected final static boolean DEBUG_DB = false; private final Handler saveStoreHandler; private static final int MSG_LOAD_IN_MEMORY = 100; private static final int MSG_STORE_ITEM = 101; private static final int MSG_STORE_ITEMS = 102; private static final int MSG_REMOVE_ITEM = 103; private static final int MSG_UPDATE_ITEM = 104; private static final int MSG_CLEAR_DATABASE = 105; private static final int MSG_SWAP_ITEMS = 106; private static final int MSG_REPLACE_ITEMS = 107; private static final int MSG_CUSTOM_OPERATION = 108; private WeakReference<InMemoryDbErrorHandler<E>> mErrorHandler; // not protected for now private final CopyOnWriteArrayList<WeakReference<InMemoryDbListener<E>>> mDbListeners = new CopyOnWriteArrayList<WeakReference<InMemoryDbListener<E>>>(); private AtomicBoolean mDataLoaded = new AtomicBoolean(); private final AtomicInteger modifyingTransactionLevel = new AtomicInteger(0); /** * @param context Used to open or create the database * @param name Database filename on disk * @param version Version number of the database (starting at 1); if the database is older, * {@link #onUpgrade} will be used to upgrade the database; if the database is * newer, {@link #onDowngrade} will be used to downgrade the database * @param logger The {@link Logger} to use for all logs (can be null for the default Android logs) * @param initCookie Cookie to pass to {@link #preloadInit(Object)} */ @SuppressLint("HandlerLeak") protected AsynchronousDbHelper(Context context, String name, int version, Logger logger, Object initCookie) { super(context, name, null, version); if (logger!=null) LogManager.setLogger(logger); preloadInit(initCookie); HandlerThread handlerThread = new HandlerThread(getClass().getSimpleName(), android.os.Process.THREAD_PRIORITY_BACKGROUND); handlerThread.start(); saveStoreHandler = new Handler(handlerThread.getLooper()) { public void handleMessage(Message msg) { SQLiteDatabase db; ContentValues addValues; switch (msg.what) { case MSG_LOAD_IN_MEMORY: startLoadingInMemory(); try { db = getWritableDatabase(); Cursor c = db.query(getMainTableName(), null, null, null, null, null, null); if (c!=null) try { if (c.moveToFirst()) { startLoadingFromCursor(c); do { addCursorInMemory(c); } while (c.moveToNext()); } } finally { c.close(); } } catch (SQLException e) { LogManager.logger.w(STARTUP_TAG,"Can't query table "+getMainTableName()+" in "+AsynchronousDbHelper.this, e); } finally { finishLoadingInMemory(); } break; case MSG_CLEAR_DATABASE: try { db = getWritableDatabase(); db.delete(getMainTableName(), "1", null); } catch (Throwable e) { LogManager.logger.w(TAG,"Failed to empty table "+getMainTableName()+" in "+AsynchronousDbHelper.this, e); sendEmptyMessage(MSG_LOAD_IN_MEMORY); // reload the DB into memory } SQLiteDatabase.releaseMemory(); break; case MSG_STORE_ITEM: @SuppressWarnings("unchecked") E itemToAdd = (E) msg.obj; addValues = null; try { db = getWritableDatabase(); addValues = getValuesFromData(itemToAdd, db); if (addValues!=null) { long id = db.insertOrThrow(getMainTableName(), null, addValues); if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" insert "+addValues+" = "+id); if (id==-1) throw new RuntimeException("failed to add values "+addValues+" in "+AsynchronousDbHelper.this.getClass().getSimpleName()); } } catch (Throwable e) { notifyAddItemFailed(itemToAdd, addValues, e); } break; case MSG_STORE_ITEMS: @SuppressWarnings("unchecked") Collection<? extends E> itemsToAdd = (Collection<? extends E>) msg.obj; for (E item : itemsToAdd) { addValues = null; try { db = getWritableDatabase(); addValues = getValuesFromData(item, db); if (addValues!=null) { long id = db.insertOrThrow(getMainTableName(), null, addValues); if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" insert "+addValues+" = "+id); if (id==-1) throw new RuntimeException("failed to add values "+addValues+" in "+AsynchronousDbHelper.this.getClass().getSimpleName()); } } catch (Throwable e) { notifyAddItemFailed(item, addValues, e); } } break; case MSG_REMOVE_ITEM: @SuppressWarnings("unchecked") E itemToDelete = (E) msg.obj; try { db = getWritableDatabase(); if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" remove "+itemToDelete); if (db.delete(getMainTableName(), getItemSelectClause(itemToDelete), getItemSelectArgs(itemToDelete))==0) notifyRemoveItemFailed(itemToDelete, new RuntimeException("No item "+itemToDelete+" in "+AsynchronousDbHelper.this.getClass().getSimpleName())); } catch (Throwable e) { notifyRemoveItemFailed(itemToDelete, e); } break; case MSG_UPDATE_ITEM: @SuppressWarnings("unchecked") E itemToUpdate = (E) msg.obj; ContentValues updateValues = null; try { db = getWritableDatabase(); updateValues = getValuesFromData(itemToUpdate, db); if (updateValues!=null) { if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" update "+updateValues+" for "+itemToUpdate); if (db.update(getMainTableName(), updateValues, getItemSelectClause(itemToUpdate), getItemSelectArgs(itemToUpdate)/*, SQLiteDatabase.CONFLICT_NONE*/)==0) { notifyUpdateItemFailed(itemToUpdate, updateValues, new RuntimeException("Can't update "+updateValues+" in "+AsynchronousDbHelper.this.getClass().getSimpleName())); } } } catch (Throwable e) { notifyUpdateItemFailed(itemToUpdate, updateValues, e); } break; case MSG_REPLACE_ITEMS: @SuppressWarnings("unchecked") Pair<E,E> itemsToReplace = (Pair<E,E>) msg.obj; try { db = getWritableDatabase(); ContentValues newValues = getValuesFromData(itemsToReplace.first, db); if (newValues!=null) { if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" replace "+itemsToReplace+" with "+newValues); db.update(getMainTableName(), newValues, getItemSelectClause(itemsToReplace.second), getItemSelectArgs(itemsToReplace.second)); } } catch (Throwable e) { notifyReplaceItemFailed(itemsToReplace.first, itemsToReplace.second, e); } break; case MSG_SWAP_ITEMS: @SuppressWarnings("unchecked") Pair<E,E> itemsToSwap = (Pair<E,E>) msg.obj; ContentValues newValuesA = null; try { db = getWritableDatabase(); newValuesA = getValuesFromData(itemsToSwap.second, db); if (newValuesA!=null) { if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" update "+itemsToSwap.second+" with "+newValuesA); db.update(getMainTableName(), newValuesA, getItemSelectClause(itemsToSwap.first), getItemSelectArgs(itemsToSwap.first)); } } catch (Throwable e) { notifyUpdateItemFailed(itemsToSwap.first, newValuesA, e); } ContentValues newValuesB = null; try { db = getWritableDatabase(); newValuesB = getValuesFromData(itemsToSwap.first, db); if (newValuesB!=null) { if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" update "+itemsToSwap.first+" with "+newValuesB); db.update(getMainTableName(), newValuesB, getItemSelectClause(itemsToSwap.second), getItemSelectArgs(itemsToSwap.second)); } } catch (Throwable e) { notifyUpdateItemFailed(itemsToSwap.second, newValuesB, e); } break; case MSG_CUSTOM_OPERATION: try { @SuppressWarnings("unchecked") AsynchronousDbOperation<E> operation = (AsynchronousDbOperation<E>) msg.obj; operation.runInMemoryDbOperation(AsynchronousDbHelper.this); } catch (Throwable e) { LogManager.logger.w(TAG, AsynchronousDbHelper.this+" failed to run operation "+msg.obj,e); } break; } super.handleMessage(msg); } }; saveStoreHandler.sendEmptyMessage(MSG_LOAD_IN_MEMORY); } /** * Method called at the end of constructor, just before the data start loading * @param cookie Data that may be needed to initialize all internal storage */ protected void preloadInit(Object cookie) {} /** * tell the InMemory database that we are about to modify its data * <p> see also {@link #popModifyingTransaction()} */ protected void pushModifyingTransaction() { modifyingTransactionLevel.incrementAndGet(); } /** * tell the InMemory database we have finish modifying the data at this level. * Once the pop matches all the push {@link #notifyDatabaseChanged()} is called * <p> this is useful to avoid multiple calls to {@link #notifyDatabaseChanged()} during a batch of changes * <p> see also {@link #pushModifyingTransaction()} */ protected void popModifyingTransaction() { if (modifyingTransactionLevel.decrementAndGet()==0) { notifyDatabaseChanged(); } } protected void clearDataInMemory() {} @Override @Deprecated public SQLiteDatabase getReadableDatabase() { return super.getReadableDatabase(); } /** * set the listener that will receive error events * @param listener null to remove the listener */ public void setDbErrorHandler(InMemoryDbErrorHandler<E> listener) { if (listener==null) mErrorHandler = null; else mErrorHandler = new WeakReference<InMemoryDbErrorHandler<E>>(listener); } public void addListener(InMemoryDbListener<E> listener) { for (WeakReference<InMemoryDbListener<E>> l : mDbListeners) { if (l.get()==null) mDbListeners.remove(l); else if (l.get()==listener) return; } if (mDataLoaded.get()) listener.onMemoryDbChanged(this); mDbListeners.add(new WeakReference<InMemoryDbListener<E>>(listener)); } public void removeListener(InMemoryDbListener<E> listener) { for (WeakReference<InMemoryDbListener<E>> l : mDbListeners) { if (l.get()==null) mDbListeners.remove(l); else if (l.get()==listener) mDbListeners.remove(l); } } /** * delete all the data in memory and in the database */ public final void clear() { pushModifyingTransaction(); clearDataInMemory(); popModifyingTransaction(); saveStoreHandler.sendEmptyMessage(MSG_CLEAR_DATABASE); } private void notifyAddItemFailed(E item, ContentValues values, Throwable cause) { LogManager.logger.i(TAG, this+" failed to add item "+item+(DEBUG_DB ? (" values"+values) : ""), cause); if (mErrorHandler!=null) { final InMemoryDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onAddItemFailed(this, item, values, cause); } pushModifyingTransaction(); popModifyingTransaction(); } private void notifyReplaceItemFailed(E srcItem, E replacement, Throwable cause) { LogManager.logger.i(TAG, this+" failed to replace item "+srcItem+" with "+replacement, cause); if (mErrorHandler!=null) { final InMemoryDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onReplaceItemFailed(this, srcItem, replacement, cause); } pushModifyingTransaction(); popModifyingTransaction(); } private void notifyUpdateItemFailed(E item, ContentValues values, Throwable cause) { LogManager.logger.i(TAG, this+" failed to update item "+item+(DEBUG_DB ? (" values"+values) : ""), cause); if (mErrorHandler!=null) { final InMemoryDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onAddItemFailed(this, item, values, cause); } pushModifyingTransaction(); popModifyingTransaction(); } private void notifyRemoveItemFailed(E item, Throwable cause) { LogManager.logger.i(TAG, this+" failed to remove item "+item, cause); if (mErrorHandler!=null) { final InMemoryDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onRemoveItemFailed(this, item, cause); } pushModifyingTransaction(); popModifyingTransaction(); } /** * the name of the main table corresponding to the inMemory elements * @return the name of the main table */ protected abstract String getMainTableName(); /** * use the data in the {@link Cursor} to store them in the memory storage * @param c the Cursor to use * @see #getValuesFromData(Object, SQLiteDatabase) */ protected abstract void addCursorInMemory(Cursor c); /** * transform the element in memory into {@link ContentValues} that can be saved in the database * <p> you can return null and fill the database yourself if you need to * @param data the data to transform * @param dbToFill the database that will receive new items * @return a ContentValues element with all data that can be used to restore the data later from the database * @see #addCursorInMemory(Cursor) */ protected abstract ContentValues getValuesFromData(E data, SQLiteDatabase dbToFill) throws RuntimeException; /** * the where clause that should be used to update/delete the item * <p> see {@link #getItemSelectArgs(Object)} * @param itemToSelect the item about to be selected in the database * @return a string for the whereClause in {@link SQLiteDatabase#update(String, ContentValues, String, String[])} or {@link SQLiteDatabase#delete(String, String, String[])} */ protected abstract String getItemSelectClause(E itemToSelect); /** * the where arguments that should be used to update/delete the item * <p> see {@link #getItemSelectClause(Object)} * @param itemToSelect the item about to be selected in the database * @return a string array for the whereArgs in {@link SQLiteDatabase#update(String, ContentValues, String, String[])} or {@link SQLiteDatabase#delete(String, String, String[])} */ protected abstract String[] getItemSelectArgs(E itemToSelect); /** * request to store the item in the database, it should be kept in synch with the in memory storage * <p> * will call the {@link InMemoryDbErrorHandler} in case of error * @param item */ protected final void scheduleAddOperation(E item) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_STORE_ITEM, item)); pushModifyingTransaction(); popModifyingTransaction(); } protected final void scheduleAddOperation(Collection<? extends E> items) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_STORE_ITEMS, items)); pushModifyingTransaction(); popModifyingTransaction(); } protected final void scheduleUpdateOperation(E item) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_UPDATE_ITEM, item)); pushModifyingTransaction(); popModifyingTransaction(); } protected final void scheduleReplaceOperation(E original, E replacement) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_REPLACE_ITEMS, new Pair<E,E>(original, replacement))); pushModifyingTransaction(); popModifyingTransaction(); } protected final void scheduleSwapOperation(E itemA, E itemB) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_SWAP_ITEMS, new Pair<E,E>(itemA, itemB))); pushModifyingTransaction(); popModifyingTransaction(); } /** * request to delete the item from the database, it should be kept in synch with the in memory storage * <p> * will call the {@link InMemoryDbErrorHandler} in case of error * @param item */ protected final void scheduleRemoveOperation(E item) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_REMOVE_ITEM, item)); pushModifyingTransaction(); popModifyingTransaction(); } /** * run the operation in the internal thread * @param operation */ protected final void scheduleCustomOperation(AsynchronousDbOperation<E> operation) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_CUSTOM_OPERATION, operation)); } /** * called when we are about to read all items from the disk */ protected void startLoadingInMemory() { pushModifyingTransaction(); mDataLoaded.set(false); } /** * called when we have the cursor to read the data from * <p> * useful to prepare the amount of data needed or get the index of the column we need * @param c the {@link Cursor} that will be used to read the data */ protected void startLoadingFromCursor(Cursor c) {} /** * called after all items have been read from the disk */ protected void finishLoadingInMemory() { mDataLoaded.set(true); popModifyingTransaction(); } protected void notifyDatabaseChanged() { for (WeakReference<InMemoryDbListener<E>> l : mDbListeners) { final InMemoryDbListener<E> listener = l.get(); if (listener==null) mDbListeners.remove(l); else listener.onMemoryDbChanged(this); } } public boolean isDataLoaded() { return mDataLoaded.get(); } /** Wait until the data are loaded */ public void waitForDataLoaded() {} @Override public String toString() { StringBuilder sb = new StringBuilder(48); sb.append('{'); sb.append(getClass().getSimpleName()); sb.append(' '); sb.append(Integer.toHexString(System.identityHashCode(this))); sb.append('}'); return sb.toString(); } }
package st.gaw.db; import java.lang.ref.WeakReference; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import android.annotation.SuppressLint; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; /** * the main helper class that saves/restore item in memory using a DB storage * <p> * the storage handling is done in a separate thread * @author Steve Lhomme * * @param <E> the type of items stored in memory */ public abstract class AsynchronousDbHelper<E> extends SQLiteOpenHelper { protected final static String TAG = "MemoryDb"; protected final static String STARTUP_TAG = "Startup"; protected final static boolean DEBUG_DB = false; private final Handler saveStoreHandler; private static final int MSG_LOAD_IN_MEMORY = 100; private static final int MSG_STORE_ITEM = 101; private static final int MSG_REMOVE_ITEM = 102; private static final int MSG_UPDATE_ITEM = 103; private static final int MSG_CLEAR_DATABASE = 104; private static final int MSG_SWAP_ITEMS = 106; private static final int MSG_REPLACE_ITEMS = 107; private static final int MSG_CUSTOM_OPERATION = 108; private WeakReference<InMemoryDbErrorHandler<E>> mErrorHandler; // not protected for now private final CopyOnWriteArrayList<WeakReference<InMemoryDbListener<E>>> mDbListeners = new CopyOnWriteArrayList<WeakReference<InMemoryDbListener<E>>>(); private boolean mDataLoaded; private final AtomicInteger modifyingTransactionLevel = new AtomicInteger(0); /** * @param context to use to open or create the database * @param name of the database file, or null for an in-memory database * @param version number of the database (starting at 1); if the database is older, * {@link #onUpgrade} will be used to upgrade the database; if the database is * newer, {@link #onDowngrade} will be used to downgrade the database * @param logger the {@link Logger} to use for all logs (can be null for the default Android logs) */ @SuppressLint("HandlerLeak") protected AsynchronousDbHelper(Context context, String name, int version, Logger logger) { super(context, name, null, version); if (logger!=null) LogManager.setLogger(logger); preloadInit(); HandlerThread handlerThread = new HandlerThread(getClass().getSimpleName(), android.os.Process.THREAD_PRIORITY_BACKGROUND); handlerThread.start(); saveStoreHandler = new Handler(handlerThread.getLooper()) { public void handleMessage(Message msg) { SQLiteDatabase db; switch (msg.what) { case MSG_LOAD_IN_MEMORY: startLoadingInMemory(); try { Cursor c = getReadableDatabase().query(getMainTableName(), null, null, null, null, null, null); if (c!=null) try { if (c.moveToFirst()) { startLoadingFromCursor(c); do { addCursorInMemory(c); } while (c.moveToNext()); } } finally { c.close(); } } catch (SQLException e) { LogManager.logger.w(STARTUP_TAG,"Can't query table "+getMainTableName()+" in "+AsynchronousDbHelper.this, e); } finally { finishLoadingInMemory(); } break; case MSG_CLEAR_DATABASE: try { db = getWritableDatabase(); db.delete(getMainTableName(), "1", null); } catch (Throwable e) { LogManager.logger.w(TAG,"Failed to empty table "+getMainTableName()+" in "+AsynchronousDbHelper.this, e); sendEmptyMessage(MSG_LOAD_IN_MEMORY); // reload the DB into memory } SQLiteDatabase.releaseMemory(); break; case MSG_STORE_ITEM: @SuppressWarnings("unchecked") E itemToAdd = (E) msg.obj; ContentValues addValues = null; try { db = getWritableDatabase(); addValues = getValuesFromData(itemToAdd, db); if (addValues!=null) { long id = db.insertOrThrow(getMainTableName(), null, addValues); if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" insert "+addValues+" = "+id); if (id==-1) throw new RuntimeException("failed to add values "+addValues+" in "+AsynchronousDbHelper.this.getClass().getSimpleName()); } } catch (Throwable e) { notifyAddItemFailed(itemToAdd, addValues, e); } break; case MSG_REMOVE_ITEM: @SuppressWarnings("unchecked") E itemToDelete = (E) msg.obj; try { db = getWritableDatabase(); if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" remove "+itemToDelete); if (db.delete(getMainTableName(), getItemSelectClause(itemToDelete), getItemSelectArgs(itemToDelete))==0) notifyRemoveItemFailed(itemToDelete, new RuntimeException("No item "+itemToDelete+" in "+AsynchronousDbHelper.this.getClass().getSimpleName())); } catch (Throwable e) { notifyRemoveItemFailed(itemToDelete, e); } break; case MSG_UPDATE_ITEM: @SuppressWarnings("unchecked") E itemToUpdate = (E) msg.obj; ContentValues updateValues = null; try { db = getWritableDatabase(); updateValues = getValuesFromData(itemToUpdate, db); if (updateValues!=null) { if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" update "+updateValues+" for "+itemToUpdate); db.update(getMainTableName(), updateValues, getItemSelectClause(itemToUpdate), getItemSelectArgs(itemToUpdate)); } } catch (Throwable e) { notifyUpdateItemFailed(itemToUpdate, updateValues, e); } break; case MSG_REPLACE_ITEMS: @SuppressWarnings("unchecked") DoubleItems itemsToReplace = (DoubleItems) msg.obj; try { db = getWritableDatabase(); ContentValues newValues = getValuesFromData(itemsToReplace.itemA, db); if (newValues!=null) { if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" replace "+itemsToReplace+" with "+newValues); db.update(getMainTableName(), newValues, getItemSelectClause(itemsToReplace.itemB), getItemSelectArgs(itemsToReplace.itemB)); } } catch (Throwable e) { notifyReplaceItemFailed(itemsToReplace.itemA, itemsToReplace.itemB, e); } break; case MSG_SWAP_ITEMS: @SuppressWarnings("unchecked") DoubleItems itemsToSwap = (DoubleItems) msg.obj; ContentValues newValuesA = null; try { db = getWritableDatabase(); newValuesA = getValuesFromData(itemsToSwap.itemB, db); if (newValuesA!=null) { if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" update "+itemsToSwap.itemB+" with "+newValuesA); db.update(getMainTableName(), newValuesA, getItemSelectClause(itemsToSwap.itemA), getItemSelectArgs(itemsToSwap.itemA)); } } catch (Throwable e) { notifyUpdateItemFailed(itemsToSwap.itemA, newValuesA, e); } ContentValues newValuesB = null; try { db = getWritableDatabase(); newValuesB = getValuesFromData(itemsToSwap.itemA, db); if (newValuesB!=null) { if (DEBUG_DB) LogManager.logger.d(TAG, AsynchronousDbHelper.this+" update "+itemsToSwap.itemA+" with "+newValuesB); db.update(getMainTableName(), newValuesB, getItemSelectClause(itemsToSwap.itemB), getItemSelectArgs(itemsToSwap.itemB)); } } catch (Throwable e) { notifyUpdateItemFailed(itemsToSwap.itemB, newValuesB, e); } break; case MSG_CUSTOM_OPERATION: try { @SuppressWarnings("unchecked") AsynchronousDbOperation<E> operation = (AsynchronousDbOperation<E>) msg.obj; operation.runInMemoryDbOperation(AsynchronousDbHelper.this); } catch (Throwable e) { LogManager.logger.w(TAG, AsynchronousDbHelper.this+" failed to run operation "+msg.obj,e); } break; } super.handleMessage(msg); } }; saveStoreHandler.sendEmptyMessage(MSG_LOAD_IN_MEMORY); } /** * Method called at the end of constructor, just before the data start loading */ protected void preloadInit() {} /** * tell the InMemory database that we are about to modify its data * <p> see also {@link #popModifyingTransaction()} */ protected void pushModifyingTransaction() { modifyingTransactionLevel.incrementAndGet(); } /** * tell the InMemory database we have finish modifying the data at this level. * Once the pop matches all the push {@link #notifyDatabaseChanged()} is called * <p> this is useful to avoid multiple calls to {@link #notifyDatabaseChanged()} during a batch of changes * <p> see also {@link #pushModifyingTransaction()} */ protected void popModifyingTransaction() { if (modifyingTransactionLevel.decrementAndGet()==0) { notifyDatabaseChanged(); } } protected void clearDataInMemory() {} protected void preloadInit() {} /** * set the listener that will receive error events * @param listener null to remove the listener */ public void setDbErrorHandler(InMemoryDbErrorHandler<E> listener) { if (listener==null) mErrorHandler = null; else mErrorHandler = new WeakReference<InMemoryDbErrorHandler<E>>(listener); } public void addListener(InMemoryDbListener<E> listener) { for (WeakReference<InMemoryDbListener<E>> l : mDbListeners) { if (l.get()==null) mDbListeners.remove(listener); else if (l.get()==listener) return; } if (mDataLoaded) listener.onMemoryDbChanged(this); mDbListeners.add(new WeakReference<InMemoryDbListener<E>>(listener)); } /** * delete all the data in memory and in the database */ public final void clear() { pushModifyingTransaction(); clearDataInMemory(); popModifyingTransaction(); saveStoreHandler.sendEmptyMessage(MSG_CLEAR_DATABASE); } private void notifyAddItemFailed(E item, ContentValues values, Throwable cause) { LogManager.logger.i(TAG, this+" failed to add item "+item+(DEBUG_DB ? (" values"+values) : ""), cause); if (mErrorHandler!=null) { final InMemoryDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onAddItemFailed(this, item, values, cause); } pushModifyingTransaction(); popModifyingTransaction(); } private void notifyReplaceItemFailed(E srcItem, E replacement, Throwable cause) { LogManager.logger.i(TAG, this+" failed to replace item "+srcItem+" with "+replacement, cause); if (mErrorHandler!=null) { final InMemoryDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onReplaceItemFailed(this, srcItem, replacement, cause); } pushModifyingTransaction(); popModifyingTransaction(); } private void notifyUpdateItemFailed(E item, ContentValues values, Throwable cause) { LogManager.logger.i(TAG, this+" failed to update item "+item+(DEBUG_DB ? (" values"+values) : ""), cause); if (mErrorHandler!=null) { final InMemoryDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onAddItemFailed(this, item, values, cause); } pushModifyingTransaction(); popModifyingTransaction(); } private void notifyRemoveItemFailed(E item, Throwable cause) { LogManager.logger.i(TAG, this+" failed to remove item "+item, cause); if (mErrorHandler!=null) { final InMemoryDbErrorHandler<E> listener = mErrorHandler.get(); if (listener==null) mErrorHandler = null; else listener.onRemoveItemFailed(this, item, cause); } pushModifyingTransaction(); popModifyingTransaction(); } /** * the name of the main table corresponding to the inMemory elements * @return the name of the main table */ protected abstract String getMainTableName(); /** * use the data in the {@link Cursor} to store them in the memory storage * @param c the Cursor to use * @see #getValuesFromData(Object, SQLiteDatabase) */ protected abstract void addCursorInMemory(Cursor c); /** * transform the element in memory into {@link ContentValues} that can be saved in the database * <p> you can return null and fill the database yourself if you need to * @param data the data to transform * @param dbToFill the database that will receive new items * @return a ContentValues element with all data that can be used to restore the data later from the database * @see #addCursorInMemory(Cursor) */ protected abstract ContentValues getValuesFromData(E data, SQLiteDatabase dbToFill) throws RuntimeException; /** * the where clause that should be used to update/delete the item * <p> see {@link #getItemSelectArgs(Object)} * @param itemToSelect the item about to be selected in the database * @return a string for the whereClause in {@link SQLiteDatabase#update(String, ContentValues, String, String[])} or {@link SQLiteDatabase#delete(String, String, String[])} */ protected abstract String getItemSelectClause(E itemToSelect); /** * the where arguments that should be used to update/delete the item * <p> see {@link #getItemSelectClause(Object)} * @param itemToSelect the item about to be selected in the database * @return a string array for the whereArgs in {@link SQLiteDatabase#update(String, ContentValues, String, String[])} or {@link SQLiteDatabase#delete(String, String, String[])} */ protected abstract String[] getItemSelectArgs(E itemToSelect); /** * request to store the item in the database, it should be kept in synch with the in memory storage * <p> * will call the {@link InMemoryDbErrorHandler} in case of error * @param item */ protected final void scheduleAddOperation(E item) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_STORE_ITEM, item)); pushModifyingTransaction(); popModifyingTransaction(); } protected final void scheduleUpdateOperation(E item) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_UPDATE_ITEM, item)); pushModifyingTransaction(); popModifyingTransaction(); } private class DoubleItems { final E itemA; final E itemB; public DoubleItems(E itemA, E itemB) { this.itemA = itemA; this.itemB = itemB; } } protected final void scheduleReplaceOperation(E original, E replacement) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_REPLACE_ITEMS, new DoubleItems(original, replacement))); pushModifyingTransaction(); popModifyingTransaction(); } protected final void scheduleSwapOperation(E itemA, E itemB) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_SWAP_ITEMS, new DoubleItems(itemA, itemB))); pushModifyingTransaction(); popModifyingTransaction(); } /** * request to delete the item from the database, it should be kept in synch with the in memory storage * <p> * will call the {@link InMemoryDbErrorHandler} in case of error * @param item */ protected final void scheduleRemoveOperation(E item) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_REMOVE_ITEM, item)); pushModifyingTransaction(); popModifyingTransaction(); } /** * run the operation in the internal thread * @param operation */ protected final void scheduleCustomOperation(AsynchronousDbOperation<E> operation) { saveStoreHandler.sendMessage(Message.obtain(saveStoreHandler, MSG_CUSTOM_OPERATION, operation)); } /** * called when we are about to read all items from the disk */ protected void startLoadingInMemory() { pushModifyingTransaction(); mDataLoaded = false; } /** * called when we have the cursor to read the data from * <p> * useful to prepare the amount of data needed or get the index of the column we need * @param c the {@link Cursor} that will be used to read the data */ protected void startLoadingFromCursor(Cursor c) {} /** * called after all items have been read from the disk */ protected void finishLoadingInMemory() { mDataLoaded = true; popModifyingTransaction(); } protected void notifyDatabaseChanged() { for (WeakReference<InMemoryDbListener<E>> l : mDbListeners) { final InMemoryDbListener<E> listener = l.get(); if (listener==null) mDbListeners.remove(l); else listener.onMemoryDbChanged(this); } } @Override public String toString() { StringBuilder sb = new StringBuilder(48); sb.append('{'); sb.append(getClass().getSimpleName()); sb.append(' '); sb.append(Integer.toHexString(System.identityHashCode(this))); sb.append('}'); return sb.toString(); } }
package edu.wustl.xipHost.avt2ext; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.junit.After; import org.junit.BeforeClass; import org.junit.Test; import edu.wustl.xipHost.iterator.IterationTarget; import edu.wustl.xipHost.iterator.IteratorElementEvent; import edu.wustl.xipHost.iterator.IteratorEvent; import edu.wustl.xipHost.iterator.TargetElement; import edu.wustl.xipHost.iterator.TargetIteratorRunner; import edu.wustl.xipHost.iterator.TargetIteratorListener; import edu.wustl.xipHost.dataAccess.Query; import edu.wustl.xipHost.dataModel.Patient; import edu.wustl.xipHost.dataModel.SearchResult; import edu.wustl.xipHost.dataModel.Series; import edu.wustl.xipHost.dataModel.Study; /** * @author Jaroslaw Krych * */ public class CreateIteratorTest implements TargetIteratorListener { final static Logger logger = Logger.getLogger(CreateIteratorTest.class); static Query avtQuery; static SearchResult selectedDataSearchResult; static SearchResult selectedDataSearchResultForSubqueries; TargetElement targetElement; File tmpDir; @BeforeClass public static void setUp() throws Exception { avtQuery = new AVTQueryStub(null, null, null, null, null); SearchResultSetup result = new SearchResultSetup(); selectedDataSearchResult = result.getSearchResult(); SearchResultSetupSubqueries resultForSubqueries = new SearchResultSetupSubqueries(); selectedDataSearchResultForSubqueries = resultForSubqueries.getSearchResult(); DOMConfigurator.configure("log4j.xml"); } @After public void tearDown() throws Exception { } //TargetIteratorRunner - basic flow. //Parameters: valid //IterationTarget.PATIEN //@Ignore @Test public void testCreateIterator_1A(){ TargetIteratorRunner targetIter = new TargetIteratorRunner(selectedDataSearchResult, IterationTarget.PATIENT, avtQuery, this); try { Thread t = new Thread(targetIter); t.start(); t.join(); } catch(Exception e) { logger.error(e, e); } synchronized(targetElements){ while(targetElements.size() < 3){ try { targetElements.wait(); } catch (InterruptedException e) { logger.error(e, e); } } } assertTrue("All parameters were valid but TargetIteratorRunner " + "did not produce expected result for IterationTarget.PATIENT.", assertIteratorTargetPatient(iter)); } //TargetIteratorRunner - basic flow. //Parameters: valid //IterationTarget.STUDY @Test public void testCreateIterator_1B(){ TargetIteratorRunner targetIter = new TargetIteratorRunner(selectedDataSearchResult, IterationTarget.STUDY, avtQuery, this); try { Thread t = new Thread(targetIter); t.start(); t.join(); } catch(Exception e) { logger.error(e, e); } synchronized(targetElements){ while(targetElements.size() < 6){ try { targetElements.wait(); } catch (InterruptedException e) { logger.error(e, e); } } } assertTrue("All parameters were valid but TargetIteratorRunner " + "did not produce expected result for IterationTarget.STUDY.", assertIteratorTargetStudy(iter)); } //TargetIteratorRunner - basic flow. //Parameters: valid //IterationTarget.SERIES @Test public void testCreateIterator_1C(){ TargetIteratorRunner targetIter = new TargetIteratorRunner(selectedDataSearchResult, IterationTarget.SERIES, avtQuery, this); try { Thread t = new Thread(targetIter); t.start(); t.join(); } catch(Exception e) { logger.error(e, e); } synchronized(targetElements){ while(targetElements.size() < 6){ try { targetElements.wait(); } catch (InterruptedException e) { logger.error(e, e); } } } assertTrue("All parameters were valid but TargetIteratorRunner " + "did not produce expected result for IterationTarget.SERIES.", assertIteratorTargetSeries(iter)); } //TargetIteratorRunner - alternative flow. //Parameters: valid //Subqueries needed. Connection ON. //IterationTarget: PATIENT @Test public void testCreateIterator_2A(){ Query avtQuery = new AVTQueryStub(null, null, null, null, null); TargetIteratorRunner targetIter = new TargetIteratorRunner(selectedDataSearchResultForSubqueries, IterationTarget.PATIENT, avtQuery, this); try { Thread t = new Thread(targetIter); t.start(); t.join(); } catch(Exception e) { logger.error(e, e); } synchronized(targetElements){ while(targetElements.size() < 3){ try { targetElements.wait(); } catch (InterruptedException e) { logger.error(e, e); } } } assertTrue("All parameters were valid but TargetIteratorRunner " + "did not produce expected result for IterationTarget.PATIENT.", assertIteratorTargetPatient(iter)); } //TargetIteratorRunner - alternative flow. //Parameters: selectedDataSearchResult, IterationTarget are valid. //Subqueries needed. Connection ON. //IterationTarget: STUDY @Test public void testCreateIterator_2B(){ Query avtQuery = new AVTQueryStub(null, null, null, null, null); TargetIteratorRunner targetIter = new TargetIteratorRunner(selectedDataSearchResultForSubqueries, IterationTarget.STUDY, avtQuery, this); try { Thread t = new Thread(targetIter); t.start(); t.join(); } catch(Exception e) { logger.error(e, e); } synchronized(targetElements){ while(targetElements.size() < 6){ try { targetElements.wait(); } catch (InterruptedException e) { logger.error(e, e); } } } assertTrue("All parameters were valid but TargetIteratorRunner " + "did not produce expected result for IterationTarget.STUDY.", assertIteratorTargetStudy(iter)); } //TargetIteratorRunner - alternative flow. //Parameters: selectedDataSearchResult, IterationTarget are valid. //Subqueries needed. Connection ON. //IterationTarget: SERIES @Test public void testCreateIterator_2C(){ Query avtQuery = new AVTQueryStub(null, null, null, null, null); TargetIteratorRunner targetIter = new TargetIteratorRunner(selectedDataSearchResultForSubqueries, IterationTarget.SERIES, avtQuery, this); try { Thread t = new Thread(targetIter); t.start(); t.join(); } catch(Exception e) { logger.error(e, e); } synchronized(targetElements){ while(targetElements.size() < 6){ try { targetElements.wait(); } catch (InterruptedException e) { logger.error(e, e); } } } assertTrue("All parameters were valid but TargetIteratorRunner " + "did not produce expected result for IterationTarget.SERIES.", assertIteratorTargetSeries(iter)); } Iterator<TargetElement> iter; @SuppressWarnings("unchecked") @Override public void fullIteratorAvailable(IteratorEvent e) { iter = (Iterator<TargetElement>) e.getSource(); } List<TargetElement> targetElements = new ArrayList<TargetElement>(); @Override public void targetElementAvailable(IteratorElementEvent e) { synchronized(targetElements){ TargetElement element = (TargetElement) e.getSource(); logger.debug("TargetElement available. ID: " + element.getId() + " at time " + System.currentTimeMillis()); targetElements.add(element); targetElements.notify(); } } private boolean assertIteratorTargetPatient(Iterator<TargetElement> iter){ int numberOfElements = 0; boolean blnPatient1Atts = false; boolean blnPatient2Atts = false; boolean blnPatient3Atts = false; while(iter.hasNext()){ TargetElement element = iter.next(); numberOfElements ++; String id = element.getId(); boolean blnId1 = false; boolean blnId2 = false; boolean blnId3 = false; if(id.equalsIgnoreCase("111")){ //Assert original criteria //Assert IterationTarget //Assert subSearchResult blnId1 = true; Map<Integer, Object> dicomCriteria1 = element.getSubSearchResult().getOriginalCriteria().getDICOMCriteria(); boolean blnDicomCriteriaSize1 = (dicomCriteria1.size() == 1); if(blnDicomCriteriaSize1 == false){ logger.warn("Incorrect number of DICOM criteria for Patient1, subelement 1. Expected 4, actual " + dicomCriteria1.size()); } Object value1 = dicomCriteria1.get(new Integer(1048592)); //patientName boolean blnValue1 = value1.toString().equalsIgnoreCase("*"); if(blnValue1 == false){ logger.warn("Incorrect criteria values"); logger.warn("PatientName: expected '*', actual " + "'" + value1 + "'"); } Map<String, Object> aimCriteria1 = element.getSubSearchResult().getOriginalCriteria().getAIMCriteria(); boolean blnAimCriteriaSize1 = (aimCriteria1.size() == 0); if(blnAimCriteriaSize1 == false){ logger.warn("Invalid size of AIM criteria for Patient1, subelement 1. Expected size 0, actual " + aimCriteria1.size()); } IterationTarget target = element.getTarget(); boolean blnTarget = target.toString().equalsIgnoreCase("PATIENT"); if(blnTarget == false){ logger.warn("Invalid IterationTarget. Expected PATIENT, actual " + target.toString()); } //assert subSearchResult SearchResult subSearchResult = element.getSubSearchResult(); List<Patient> patients = subSearchResult.getPatients(); boolean numbPatients = (patients.size() == 1); boolean numbStudies = false; boolean studiesAssert = false; for(Patient patient : patients){ boolean study1Assert = false; boolean study2Assert = false; List<Study> studies = patient.getStudies(); numbStudies = (studies.size() == 2); if(numbStudies){ for(Study study : studies){ List<Series> series = study.getSeries(); if(study.getStudyInstanceUID().equalsIgnoreCase("101.101")){ for(Series oneSeries : series){ String seriesInstanceUID = oneSeries.getSeriesInstanceUID(); if(seriesInstanceUID.equalsIgnoreCase("101.101.1")){ study1Assert = true; } } } else if (study.getStudyInstanceUID().equalsIgnoreCase("202.202")){ for(Series oneSeries : series){ String seriesInstanceUID = oneSeries.getSeriesInstanceUID(); if(seriesInstanceUID.equalsIgnoreCase("202.202.1")){ study2Assert = true; } } } } } if(study1Assert == true && study2Assert == true){ studiesAssert = true; } } blnPatient1Atts = (blnId1 == true && blnDicomCriteriaSize1 == true && blnValue1 == true && blnAimCriteriaSize1 == true && blnTarget == true && numbPatients == true && studiesAssert == true); } else if(id.equalsIgnoreCase("222") ){ //Assert original criteria //Assert IterationTarget //Assert subSearchResult blnId2 = true; Map<Integer, Object> dicomCriteria1 = element.getSubSearchResult().getOriginalCriteria().getDICOMCriteria(); boolean blnDicomCriteriaSize1 = (dicomCriteria1.size() == 1); if(blnDicomCriteriaSize1 == false){ logger.warn("Incorrect number of DICOM criteria for Patient2, subelement 1. Expected 4, actual " + dicomCriteria1.size()); } Object value1 = dicomCriteria1.get(new Integer(1048592)); //patientName boolean blnValue1 = value1.toString().equalsIgnoreCase("*"); if(blnValue1 == false){ logger.warn("Incorrect criteria values"); logger.warn("PatientName: expected '*', actual " + "'" + value1 + "'"); } Map<String, Object> aimCriteria1 = element.getSubSearchResult().getOriginalCriteria().getAIMCriteria(); boolean blnAimCriteriaSize1 = (aimCriteria1.size() == 0); if(blnAimCriteriaSize1 == false){ logger.warn("Invalid size of AIM criteria for Patient 2, subelement 1. Expected size 0, actual " + aimCriteria1.size()); } IterationTarget target = element.getTarget(); boolean blnTarget = target.toString().equalsIgnoreCase("PATIENT"); if(blnTarget == false){ logger.warn("Invalid IterationTarget. Expected PATIENT, actual " + target.toString()); } //assert subSearchResult SearchResult subSearchResult = element.getSubSearchResult(); List<Patient> patients = subSearchResult.getPatients(); boolean numbPatients = (patients.size() == 1); boolean numbStudies = false; boolean studiesAssert = false; for(Patient patient : patients){ boolean series3Assert = false; boolean series4Assert = false; boolean series5Assert = false; List<Study> studies = patient.getStudies(); numbStudies = (studies.size() == 1); if(numbStudies){ for(Study study : studies){ List<Series> series = study.getSeries(); if(study.getStudyInstanceUID().equalsIgnoreCase("303.303")){ for(Series oneSeries : series){ String seriesInstanceUID = oneSeries.getSeriesInstanceUID(); if(seriesInstanceUID.equalsIgnoreCase("303.303.1")){ series3Assert = true; } else if(seriesInstanceUID.equalsIgnoreCase("404.404.1")){ series4Assert = true; } else if (seriesInstanceUID.equalsIgnoreCase("505.505.1")){ series5Assert = true; } } } } } if(numbStudies == true && series3Assert == true && series4Assert == true && series5Assert == true){ studiesAssert = true; } } blnPatient2Atts = (blnId2 == true && blnDicomCriteriaSize1 == true && blnValue1 == true && blnAimCriteriaSize1 == true && blnTarget == true && numbPatients == true && studiesAssert == true); } else if (id.equalsIgnoreCase("333")){ //Assert original criteria //Assert IterationTarget //Assert subSearchResult blnId3 = true; Map<Integer, Object> dicomCriteria1 = element.getSubSearchResult().getOriginalCriteria().getDICOMCriteria(); boolean blnDicomCriteriaSize1 = (dicomCriteria1.size() == 1); if(blnDicomCriteriaSize1 == false){ logger.warn("Incorrect number of DICOM criteria for Patient3, subelement 1. Expected 4, actual " + dicomCriteria1.size()); } Object value1 = dicomCriteria1.get(new Integer(1048592)); //patientName boolean blnValue1 = value1.toString().equalsIgnoreCase("*"); if(blnValue1 == false){ logger.warn("Incorrect criteria values"); logger.warn("PatientName: expected '*', actual " + "'" + value1 + "'"); } Map<String, Object> aimCriteria1 = element.getSubSearchResult().getOriginalCriteria().getAIMCriteria(); boolean blnAimCriteriaSize1 = (aimCriteria1.size() == 0); if(blnAimCriteriaSize1 == false){ logger.warn("Invalid size of AIM criteria for Patient 3, subelement 1. Expected size 0, actual " + aimCriteria1.size()); } IterationTarget target = element.getTarget(); boolean blnTarget = target.toString().equalsIgnoreCase("PATIENT"); if(blnTarget == false){ logger.warn("Invalid IterationTarget. Expected PATIENT, actual " + target.toString()); } //assert subSearchResult SearchResult subSearchResult = element.getSubSearchResult(); List<Patient> patients = subSearchResult.getPatients(); boolean numbPatients = (patients.size() == 1); boolean numbStudies = false; boolean studiesAssert = false; for(Patient patient : patients){ boolean series6Assert = false; boolean series7Assert = false; boolean series8Assert = false; boolean series9Assert = false; boolean series10Assert = false; boolean series11Assert = false; boolean series12Assert = false; boolean series13Assert = false; boolean series14Assert = false; List<Study> studies = patient.getStudies(); numbStudies = (studies.size() == 3); if(numbStudies){ for(Study study : studies){ List<Series> series = study.getSeries(); if(study.getStudyInstanceUID().equalsIgnoreCase("404.404")){ for(Series oneSeries : series){ String seriesInstanceUID = oneSeries.getSeriesInstanceUID(); if(seriesInstanceUID.equalsIgnoreCase("606.606.1")){ series6Assert = true; } else if(seriesInstanceUID.equalsIgnoreCase("707.707.1")){ series7Assert = true; } else if (seriesInstanceUID.equalsIgnoreCase("808.808.1")){ series8Assert = true; } } } else if (study.getStudyInstanceUID().equalsIgnoreCase("505.505")){ for(Series oneSeries : series){ String seriesInstanceUID = oneSeries.getSeriesInstanceUID(); if(seriesInstanceUID.equalsIgnoreCase("909.909.1")){ series9Assert = true; } else if(seriesInstanceUID.equalsIgnoreCase("10.10.1")){ series10Assert = true; } else if (seriesInstanceUID.equalsIgnoreCase("11.11.1")){ series11Assert = true; } } } else if (study.getStudyInstanceUID().equalsIgnoreCase("606.606")){ for(Series oneSeries : series){ String seriesInstanceUID = oneSeries.getSeriesInstanceUID(); if(seriesInstanceUID.equalsIgnoreCase("12.12.1")){ series12Assert = true; } else if(seriesInstanceUID.equalsIgnoreCase("13.13.1")){ series13Assert = true; } else if (seriesInstanceUID.equalsIgnoreCase("14.14.1")){ series14Assert = true; } } } } } if(numbStudies == true && series6Assert == true && series7Assert == true && series8Assert == true && series9Assert == true && series10Assert == true && series11Assert == true && series12Assert == true && series13Assert == true && series14Assert == true){ studiesAssert = true; } } blnPatient3Atts = (blnId3 == true && blnDicomCriteriaSize1 == true && blnValue1 == true && blnAimCriteriaSize1 == true && blnTarget == true && numbPatients == true && studiesAssert == true); } } //Assert iterator //Number of iterator's elements = 3 boolean blnNumberOfElements = (numberOfElements == 3); assertTrue("Expected number of elements is 3, but actual number is " + numberOfElements, blnNumberOfElements); assertTrue ("", blnPatient1Atts == true && blnPatient2Atts == true && blnPatient3Atts == true); if (blnNumberOfElements && (blnPatient1Atts == true && blnPatient2Atts == true && blnPatient3Atts == true)) { return true; } else { return false; } } private boolean assertIteratorTargetStudy(Iterator<TargetElement> iter){ boolean blnStudy1Atts = false; boolean blnStudy3Atts = false; boolean blnStudy6Atts = false; int numberOfElements = 0; while(iter.hasNext()){ TargetElement element = iter.next(); numberOfElements ++; String id = element.getId(); boolean blnId1 = false; boolean blnId3 = false; boolean blnId6 = false; if(id.equalsIgnoreCase("101.101")){ //Assert original criteria //Assert IterationTarget //Assert subSearchResult blnId1 = true; Map<Integer, Object> dicomCriteria1 = element.getSubSearchResult().getOriginalCriteria().getDICOMCriteria(); boolean blnDicomCriteriaSize1 = (dicomCriteria1.size() == 1); if(blnDicomCriteriaSize1 == false){ logger.warn("Incorrect number of DICOM criteria for Study1, subelement 1. Expected 4, actual " + dicomCriteria1.size()); } Object value1 = dicomCriteria1.get(new Integer(1048592)); //patientName boolean blnValue1 = value1.toString().equalsIgnoreCase("*"); if(blnValue1 == false){ logger.warn("Incorrect criteria values"); logger.warn("PatientName: expected '*', actual " + "'" + value1 + "'"); } Map<String, Object> aimCriteria1 = element.getSubSearchResult().getOriginalCriteria().getAIMCriteria(); boolean blnAimCriteriaSize1 = (aimCriteria1.size() == 0); if(blnAimCriteriaSize1 == false){ logger.warn("Invalid size of AIM criteria for Study1, subelement 1. Expected size 0, actual " + aimCriteria1.size()); } IterationTarget target = element.getTarget(); boolean blnTarget = target.toString().equalsIgnoreCase("STUDY"); if(blnTarget == false){ logger.warn("Invalid IterationTarget. Expected STUDY, actual " + target.toString()); } //assert subSearchResult SearchResult subSearchResult = element.getSubSearchResult(); List<Patient> patients = subSearchResult.getPatients(); boolean numbPatients = (patients.size() == 1); boolean patientAssert = false; boolean numbStudies = false; boolean studiesAssert = false; for(Patient patient : patients){ if(patient.getPatientID().equalsIgnoreCase("111")){ patientAssert = true; } boolean series1Assert = false; List<Study> studies = patient.getStudies(); numbStudies = (studies.size() == 1); if(numbStudies){ for(Study study : studies){ List<Series> series = study.getSeries(); if(study.getStudyInstanceUID().equalsIgnoreCase("101.101")){ for(Series oneSeries : series){ String seriesInstanceUID = oneSeries.getSeriesInstanceUID(); if(seriesInstanceUID.equalsIgnoreCase("101.101.1")){ series1Assert = true; } } } } } if(numbStudies == true && series1Assert == true){ studiesAssert = true; } } blnStudy1Atts = (blnId1 == true && blnDicomCriteriaSize1 == true && blnValue1 == true && blnAimCriteriaSize1 == true && blnTarget == true && numbPatients == true && patientAssert == true && studiesAssert == true); if(blnStudy1Atts == false){ logger.warn("Invalid attributes in Study1."); } } else if(id.equalsIgnoreCase("303.303") ){ //Assert original criteria //Assert IterationTarget //Assert subSearchResult blnId3 = true; Map<Integer, Object> dicomCriteria1 = element.getSubSearchResult().getOriginalCriteria().getDICOMCriteria(); boolean blnDicomCriteriaSize1 = (dicomCriteria1.size() == 1); if(blnDicomCriteriaSize1 == false){ logger.warn("Incorrect number of DICOM criteria for Study3, subelement 1. Expected 4, actual " + dicomCriteria1.size()); } Object value1 = dicomCriteria1.get(new Integer(1048592)); //patientName boolean blnValue1 = value1.toString().equalsIgnoreCase("*"); if(blnValue1 == false){ logger.warn("Incorrect criteria values"); logger.warn("PatientName: expected '*', actual " + "'" + value1 + "'"); } Map<String, Object> aimCriteria1 = element.getSubSearchResult().getOriginalCriteria().getAIMCriteria(); boolean blnAimCriteriaSize1 = (aimCriteria1.size() == 0); if(blnAimCriteriaSize1 == false){ logger.warn("Invalid size of AIM criteria for Study3, subelement 1. Expected size 0, actual " + aimCriteria1.size()); } IterationTarget target = element.getTarget(); boolean blnTarget = target.toString().equalsIgnoreCase("STUDY"); if(blnTarget == false){ logger.warn("Invalid IterationTarget. Expected STUDY, actual " + target.toString()); } //assert subSearchResult SearchResult subSearchResult = element.getSubSearchResult(); List<Patient> patients = subSearchResult.getPatients(); boolean numbPatients = (patients.size() == 1); boolean patientAssert = false; boolean numbStudies = false; boolean studiesAssert = false; for(Patient patient : patients){ if(patient.getPatientID().equalsIgnoreCase("222")){ patientAssert = true; } boolean series3Assert = false; boolean series4Assert = false; boolean series5Assert = false; List<Study> studies = patient.getStudies(); numbStudies = (studies.size() == 1); if(numbStudies){ for(Study study : studies){ List<Series> series = study.getSeries(); if(study.getStudyInstanceUID().equalsIgnoreCase("303.303")){ for(Series oneSeries : series){ String seriesInstanceUID = oneSeries.getSeriesInstanceUID(); if(seriesInstanceUID.equalsIgnoreCase("303.303.1")){ series3Assert = true; } else if(seriesInstanceUID.equalsIgnoreCase("404.404.1")){ series4Assert = true; } else if(seriesInstanceUID.equalsIgnoreCase("505.505.1")){ series5Assert = true; } } } } } if(numbStudies == true && series3Assert == true && series4Assert == true && series5Assert == true){ studiesAssert = true; } } blnStudy3Atts = (blnId3 == true && blnDicomCriteriaSize1 == true && blnValue1 == true && blnAimCriteriaSize1 == true && blnTarget == true && numbPatients == true && patientAssert == true && studiesAssert == true); if(blnStudy3Atts == false){ logger.warn("Invalid attributes in Study3."); } } else if(id.equalsIgnoreCase("606.606") ){ //Assert original criteria //Assert IterationTarget //Assert subSearchResult blnId6 = true; Map<Integer, Object> dicomCriteria1 = element.getSubSearchResult().getOriginalCriteria().getDICOMCriteria(); boolean blnDicomCriteriaSize1 = (dicomCriteria1.size() == 1); if(blnDicomCriteriaSize1 == false){ logger.warn("Incorrect number of DICOM criteria for Study6, subelement 1. Expected 4, actual " + dicomCriteria1.size()); } Object value2 = dicomCriteria1.get(new Integer(1048592)); //patientName boolean blnValue2 = value2.toString().equalsIgnoreCase("*"); if(blnValue2 == false){ logger.warn("Incorrect criteria values"); logger.warn("PatientName: expected '*', actual " + "'" + value2 + "'"); } Map<String, Object> aimCriteria1 = element.getSubSearchResult().getOriginalCriteria().getAIMCriteria(); boolean blnAimCriteriaSize1 = (aimCriteria1.size() == 0); if(blnAimCriteriaSize1 == false){ logger.warn("Invalid size of AIM criteria for Study6, subelement 1. Expected size 0, actual " + aimCriteria1.size()); } IterationTarget target = element.getTarget(); boolean blnTarget = target.toString().equalsIgnoreCase("STUDY"); if(blnTarget == false){ logger.warn("Invalid IterationTarget. Expected STUDY, actual " + target.toString()); } //assert subSearchResult SearchResult subSearchResult = element.getSubSearchResult(); List<Patient> patients = subSearchResult.getPatients(); boolean numbPatients = (patients.size() == 1); boolean patientAssert = false; boolean numbStudies = false; boolean studiesAssert = false; for(Patient patient : patients){ if(patient.getPatientID().equalsIgnoreCase("333")){ patientAssert = true; } boolean series12Assert = false; boolean series13Assert = false; boolean series14Assert = false; List<Study> studies = patient.getStudies(); numbStudies = (studies.size() == 1); if(numbStudies){ for(Study study : studies){ List<Series> series = study.getSeries(); if(study.getStudyInstanceUID().equalsIgnoreCase("606.606")){ for(Series oneSeries : series){ String seriesInstanceUID = oneSeries.getSeriesInstanceUID(); if(seriesInstanceUID.equalsIgnoreCase("12.12.1")){ series12Assert = true; } else if(seriesInstanceUID.equalsIgnoreCase("13.13.1")){ series13Assert = true; } else if(seriesInstanceUID.equalsIgnoreCase("14.14.1")){ series14Assert = true; } } } } } if(numbStudies == true && series12Assert == true && series13Assert == true && series14Assert == true){ studiesAssert = true; } } blnStudy6Atts = (blnId6 == true && blnDicomCriteriaSize1 == true && blnValue2 == true && blnAimCriteriaSize1 == true && blnTarget == true && numbPatients == true && patientAssert == true && studiesAssert == true); if(blnStudy6Atts == false){ logger.warn("Invalid attributes in Study6."); } } } //Assert iterator //Number of iterator's elements = 6 boolean blnNumberOfElements = (numberOfElements == 6); assertTrue("Expected number of elements is 6, but actual number is " + numberOfElements, blnNumberOfElements); assertTrue ("", blnStudy1Atts == true && blnStudy3Atts == true && blnStudy6Atts == true); if (blnNumberOfElements && (blnStudy1Atts == true && blnStudy3Atts == true && blnStudy6Atts == true)) { return true; } else { return false; } } private boolean assertIteratorTargetSeries(Iterator<TargetElement> iter){ boolean blnSeries1Atts = false; boolean blnSeries4Atts = false; boolean blnSeries13Atts = false; int numberOfElements = 0; while(iter.hasNext()){ TargetElement element = iter.next(); numberOfElements ++; String id = element.getId(); boolean blnId1 = false; boolean blnId4 = false; boolean blnId13 = false; if(id.equalsIgnoreCase("101.101.1")){ //Assert original criteria //Assert IterationTarget //Assert subSearchResult blnId1 = true; Map<Integer, Object> dicomCriteria1 = element.getSubSearchResult().getOriginalCriteria().getDICOMCriteria(); boolean blnDicomCriteriaSize1 = (dicomCriteria1.size() == 1); if(blnDicomCriteriaSize1 == false){ logger.warn("Incorrect number of DICOM criteria for Series1, subelement 1. Expected 4, actual " + dicomCriteria1.size()); } Object value1 = dicomCriteria1.get(new Integer(1048592)); //patientName boolean blnValue1 = value1.toString().equalsIgnoreCase("*"); if(blnValue1 == false){ logger.warn("Incorrect criteria values"); logger.warn("PatientName: expected '*', actual " + "'" + value1 + "'"); } Map<String, Object> aimCriteria1 = element.getSubSearchResult().getOriginalCriteria().getAIMCriteria(); boolean blnAimCriteriaSize1 = (aimCriteria1.size() == 0); if(blnAimCriteriaSize1 == false){ logger.warn("Invalid size of AIM criteria for Series1, subelement 1. Expected size 0, actual " + aimCriteria1.size()); } IterationTarget target = element.getTarget(); boolean blnTarget = target.toString().equalsIgnoreCase("SERIES"); if(blnTarget == false){ logger.warn("Invalid IterationTarget. Expected SERIES, actual " + target.toString()); } //assert subSearchResult SearchResult subSearchResult = element.getSubSearchResult(); List<Patient> patients = subSearchResult.getPatients(); boolean numbPatients = (patients.size() == 1); boolean patientAssert = false; boolean numbStudies = false; boolean studiesAssert = false; for(Patient patient : patients){ if(patient.getPatientID().equalsIgnoreCase("111")){ patientAssert = true; } boolean series1Assert = false; List<Study> studies = patient.getStudies(); numbStudies = (studies.size() == 1); if(numbStudies){ for(Study study : studies){ List<Series> series = study.getSeries(); if(study.getStudyInstanceUID().equalsIgnoreCase("101.101")){ for(Series oneSeries : series){ String seriesInstanceUID = oneSeries.getSeriesInstanceUID(); if(seriesInstanceUID.equalsIgnoreCase("101.101.1")){ series1Assert = true; } } } } } if(numbStudies == true && series1Assert == true){ studiesAssert = true; } } blnSeries1Atts = (blnId1 == true && blnDicomCriteriaSize1 == true && blnValue1 == true && blnAimCriteriaSize1 == true && blnTarget == true && numbPatients == true && patientAssert == true && studiesAssert == true); if(blnSeries1Atts == false){ logger.warn("Invalid attributes in Series1."); } } if(id.equalsIgnoreCase("404.404.1")){ //Assert original criteria //Assert IterationTarget //Assert subSearchResult blnId4 = true; Map<Integer, Object> dicomCriteria1 = element.getSubSearchResult().getOriginalCriteria().getDICOMCriteria(); boolean blnDicomCriteriaSize1 = (dicomCriteria1.size() == 1); if(blnDicomCriteriaSize1 == false){ logger.warn("Incorrect number of DICOM criteria for Series4, subelement 1. Expected 4, actual " + dicomCriteria1.size()); } Object value1 = dicomCriteria1.get(new Integer(1048592)); //patientName boolean blnValue1 = value1.toString().equalsIgnoreCase("*"); if(blnValue1 == false){ logger.warn("Incorrect criteria values"); logger.warn("PatientName: expected '*', actual " + "'" + value1 + "'"); } Map<String, Object> aimCriteria1 = element.getSubSearchResult().getOriginalCriteria().getAIMCriteria(); boolean blnAimCriteriaSize1 = (aimCriteria1.size() == 0); if(blnAimCriteriaSize1 == false){ logger.warn("Invalid size of AIM criteria for Series4, subelement 1. Expected size 0, actual " + aimCriteria1.size()); } IterationTarget target = element.getTarget(); boolean blnTarget = target.toString().equalsIgnoreCase("SERIES"); if(blnTarget == false){ logger.warn("Invalid IterationTarget. Expected SERIES, actual " + target.toString()); } //assert subSearchResult SearchResult subSearchResult = element.getSubSearchResult(); List<Patient> patients = subSearchResult.getPatients(); boolean numbPatients = (patients.size() == 1); boolean patientAssert = false; boolean numbStudies = false; boolean studiesAssert = false; for(Patient patient : patients){ if(patient.getPatientID().equalsIgnoreCase("222")){ patientAssert = true; } boolean series4Assert = false; List<Study> studies = patient.getStudies(); numbStudies = (studies.size() == 1); if(numbStudies){ for(Study study : studies){ List<Series> series = study.getSeries(); if(study.getStudyInstanceUID().equalsIgnoreCase("303.303")){ for(Series oneSeries : series){ String seriesInstanceUID = oneSeries.getSeriesInstanceUID(); if(seriesInstanceUID.equalsIgnoreCase("404.404.1")){ series4Assert = true; } } } } } if(numbStudies == true && series4Assert == true){ studiesAssert = true; } } blnSeries4Atts = (blnId4 == true && blnDicomCriteriaSize1 == true && blnValue1 == true && blnAimCriteriaSize1 == true && blnTarget == true && numbPatients == true && patientAssert == true && studiesAssert == true); if(blnSeries1Atts == false){ logger.warn("Invalid attributes in Series4."); } } if(id.equalsIgnoreCase("13.13.1")){ //Assert original criteria //Assert IterationTarget //Assert subSearchResult blnId13 = true; Map<Integer, Object> dicomCriteria1 = element.getSubSearchResult().getOriginalCriteria().getDICOMCriteria(); boolean blnDicomCriteriaSize1 = (dicomCriteria1.size() == 1); if(blnDicomCriteriaSize1 == false){ logger.warn("Incorrect number of DICOM criteria for Series13, subelement 1. Expected 4, actual " + dicomCriteria1.size()); } Object value1 = dicomCriteria1.get(new Integer(1048592)); //patientName boolean blnValue1 = value1.toString().equalsIgnoreCase("*"); if(blnValue1 == false){ logger.warn("Incorrect criteria values"); logger.warn("PatientName: expected '*', actual " + "'" + value1 + "'"); } Map<String, Object> aimCriteria1 = element.getSubSearchResult().getOriginalCriteria().getAIMCriteria(); boolean blnAimCriteriaSize1 = (aimCriteria1.size() == 0); if(blnAimCriteriaSize1 == false){ logger.warn("Invalid size of AIM criteria for Series13, subelement 1. Expected size 0, actual " + aimCriteria1.size()); } IterationTarget target = element.getTarget(); boolean blnTarget = target.toString().equalsIgnoreCase("SERIES"); if(blnTarget == false){ logger.warn("Invalid IterationTarget. Expected SERIES, actual " + target.toString()); } //assert subSearchResult SearchResult subSearchResult = element.getSubSearchResult(); List<Patient> patients = subSearchResult.getPatients(); boolean numbPatients = (patients.size() == 1); boolean patientAssert = false; boolean numbStudies = false; boolean studiesAssert = false; for(Patient patient : patients){ if(patient.getPatientID().equalsIgnoreCase("333")){ patientAssert = true; } boolean series13Assert = false; List<Study> studies = patient.getStudies(); numbStudies = (studies.size() == 1); if(numbStudies){ for(Study study : studies){ List<Series> series = study.getSeries(); if(study.getStudyInstanceUID().equalsIgnoreCase("606.606")){ for(Series oneSeries : series){ String seriesInstanceUID = oneSeries.getSeriesInstanceUID(); if(seriesInstanceUID.equalsIgnoreCase("13.13.1")){ series13Assert = true; } } } } } if(numbStudies == true && series13Assert == true){ studiesAssert = true; } } blnSeries13Atts = (blnId13 == true && blnDicomCriteriaSize1 == true && blnValue1 == true && blnAimCriteriaSize1 == true && blnTarget == true && numbPatients == true && patientAssert == true && studiesAssert == true); if(blnSeries13Atts == false){ logger.warn("Invalid attributes in Series13."); } } } //Assert iterator //Number of iterator's elements = 6 boolean blnNumberOfElements = (numberOfElements == 14); assertTrue("Expected number of elements is 6, but actual number is " + numberOfElements, blnNumberOfElements); assertTrue ("", blnSeries1Atts == true && blnSeries4Atts == true && blnSeries13Atts == true); if (blnNumberOfElements && (blnSeries1Atts == true && blnSeries4Atts == true && blnSeries13Atts == true)) { return true; } else { return false; } } }
import java.math.BigInteger; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import static java.util.stream.Collectors.toList; import java.util.stream.Stream; public class Solution { final double logOf5 = Math.log10(5); LinkedList<String> knownPowers; final String[] knownPowersArray = new String[]{"1", "101", "11001", "1111101", "1001110001", "110000110101", "11110100001001", "10011000100101101", "1011111010111100001", "111011100110101100101", "100101010000001011111001", "10111010010000111011011101", "1110100011010100101001010001", "1001000110000100111001110010101", "101101011110011000100000111101001", "11100011010111111010100100110001101", "10001110000110111100100110111111000001", "1011000110100010101111000010111011000101", "110111100000101101101011001110100111011001"}; public Solution() { this.knownPowers = new LinkedList<>(); knownPowers.addAll(Arrays.asList(knownPowersArray)); } /** * Takes in an array of strings, and returns an array of answers * * @param s - string input array * @return - array of int answers of how many powers of five fit into each * string in the array */ public int[] getMin(String[] s) { int[] results = findPower(s); return results; } // Uncomment for sequential execution // public int[] getMin(String[] s) { // int[] results = new int[s.length]; // int counter = 0; // for (String string : s) { // results[counter++] // = isPoweredOfFive(string); // return results; /** * We will use Java 8's CompletableFutures to asynchronously execute the * computation for each binary string provided. The performance gains between the * multithreaded async and single threaded sequential are negligible - the setup overhead * of the multithreading might contribute to that. * * @param values * @return */ public int[] findPower(String[] values) { //Uncomment to support custom executor //Executor executor = Executors.newFixedThreadPool(6, new ThreadFactory() { // public Thread newThread(Runnable r) { // Thread thread = new Thread(r); // thread.setDaemon(true); // return thread; List<CompletableFuture<Integer>> results = Stream.of(values) .map(value -> CompletableFuture.supplyAsync(() -> isPoweredOfFive(value.trim()))) .collect(toList()); List<Integer> exit = results.stream().map(CompletableFuture::join).collect(toList()); int[] exitValues = exit.stream().mapToInt(x -> x).toArray(); return exitValues; } /** * Steps: * 1. Check if supplied value is a valid binary (with 0s and 1s); exit if it is. * 2. Convert to decimal and use the change of base log formula to determine if supplied value is a whole power of five; exit if it is * 3. If not(3), look for known powers of five within the supplied string. * @param value * @return */ private int isPoweredOfFive(String value) { int powersOfFive = 0; if (!isValidBinary(value) || value.charAt(0) == '0') { return --powersOfFive; //not a valid binary, shortcircuit algo. } BigInteger decimalValue = convertToDecimal(value); float result = (float) (Math.log10(decimalValue.doubleValue()) / logOf5); // use change of base logarithm rule to determine if number is power of five if ((int) result == result) { return ++powersOfFive; //supplied binary is a whole power of 5, shortcircuit algo. } else { /** * Dynamic Programming: we will advance a pointer in increments of * the length known multiples of five that are found in the supplied * binary text until we run out of known multiples to search by. The * search will be conducted in reverse i.e. from the longest known * multiple to the shortest. */ int currentIndex = 0; while (currentIndex < value.length()) { String currentToken = value.substring(currentIndex); char initChar = currentToken.charAt(0); if (initChar != '0') { for (int i = knownPowers.size() - 1; i >= 0; i String nextKnownPower = knownPowers.get(i); if (nextKnownPower.length() <= currentToken.length()) { boolean foundIndex = currentToken.startsWith(nextKnownPower); if (foundIndex) { ++powersOfFive; currentIndex += currentToken.indexOf(nextKnownPower) + nextKnownPower.length(); break; } } } } else { powersOfFive = -1; break; } } } } return powersOfFive; } private BigInteger convertToDecimal(String binary) { BigInteger result = null; result = new BigInteger(binary, 2); return result; } private boolean isValidBinary(String value) { boolean valid = false; if (value.matches("[01]+")) { valid = true; } return valid; } }
package org.helioviewer.jhv; import java.awt.Dimension; import java.awt.Insets; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.Date; import java.util.Properties; import javax.swing.BorderFactory; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextArea; import javax.swing.JTextPane; import org.apache.log4j.NDC; import org.helioviewer.jhv.base.logging.Log; import org.helioviewer.jhv.gui.ClipBoardCopier; class JHVUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { private static final String BUG_URL = "https://github.com/Helioviewer-Project/JHelioviewer-SWHV/issues"; private static final String MAIL_URL = "swhv@sidc.be"; private static final int default_width = 600; private static final int default_height = 400; private static final JHVUncaughtExceptionHandler instance = new JHVUncaughtExceptionHandler(); private JHVUncaughtExceptionHandler() { try (InputStream is = JHVUncaughtExceptionHandler.class.getResourceAsStream("/sentry.properties")) { Properties p = new Properties(); p.load(is); for (String key : p.stringPropertyNames()) System.setProperty(key, p.getProperty(key)); } catch (Exception e) { e.printStackTrace(); } } /** * This method sets the default uncaught exception handler. Thus, this * method should be called once when the application starts. */ public static void setupHandlerForThread() { Thread.setDefaultUncaughtExceptionHandler(instance); } private static void showErrorDialog(String msg) { ArrayList<Object> objects = new ArrayList<>(); JTextPane report = new JTextPane(); report.setContentType("text/html"); report.setEditable(false); report.setOpaque(false); report.addHyperlinkListener(JHVGlobals.hyperOpenURL); report.putClientProperty(JTextPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); report.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 10)); report.setText("Fatal error detected." + "<p>Please email this report at <a href='mailto:" + MAIL_URL + "'>" + MAIL_URL + "</a> " + "or use it to open an issue at <a href='" + BUG_URL + "'>" + BUG_URL + "</a>.<br/>" + "This report was sent to swhv.oma.be."); objects.add(report); JLabel copyToClipboard = new JLabel("<html><a href=''>Click here to copy the error report to the clipboard."); copyToClipboard.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent me) { ClipBoardCopier.getSingletonInstance().setString(msg); JOptionPane.showMessageDialog(null, "Error report copied to clipboard."); } }); JTextArea textArea = new JTextArea(); textArea.setMargin(new Insets(5, 5, 5, 5)); textArea.setText(msg); textArea.setEditable(false); JScrollPane sp = new JScrollPane(textArea); sp.setPreferredSize(new Dimension(default_width, default_height)); objects.add(copyToClipboard); objects.add(new JSeparator()); objects.add(sp); JOptionPane optionPane = new JOptionPane(); optionPane.setMessage(objects.toArray()); optionPane.setMessageType(JOptionPane.ERROR_MESSAGE); optionPane.setOptions(new String[] { "Quit JHelioviewer", "Continue" }); JDialog dialog = optionPane.createDialog(null, "JHelioviewer: Fatal Error"); dialog.setVisible(true); if ("Quit JHelioviewer".equals(optionPane.getValue())) System.exit(1); } // we do not use the logger here, since it should work even before logging initialization @Override public void uncaughtException(Thread t, Throwable e) { String className = e.getClass().getCanonicalName() + "\n"; StringBuilder stackTrace = new StringBuilder(className); for (StackTraceElement el : e.getStackTrace()) { stackTrace.append("at ").append(el).append('\n'); } String msg = ""; StringBuilder sb = new StringBuilder(); File logFile; String logName = Log.getCurrentLogFile(); if (logName != null && (logFile = new File(logName)).canRead()) { Log.error("Runtime exception", e); try (BufferedReader input = Files.newBufferedReader(logFile.toPath(), StandardCharsets.UTF_8)) { String line; while ((line = input.readLine()) != null) { sb.append(line).append('\n'); } NDC.push(sb.toString()); } catch (IOException ex) { ex.printStackTrace(); } } else { System.err.println("Runtime exception"); System.err.println(stackTrace); msg += "Uncaught Exception in " + JHVGlobals.userAgent; msg += "\nDate: " + new Date(); msg += "\nThread: " + t; msg += "\nMessage: " + e.getMessage(); msg += "\nStacktrace:\n"; msg += stackTrace + "\n"; } Log.fatal(null, e); showErrorDialog(msg + "Log:\n" + sb); } }
package cgeo.geocaching; import butterknife.ButterKnife; import butterknife.InjectView; import cgeo.geocaching.activity.AbstractActivity; import cgeo.geocaching.activity.AbstractActivity.ActivitySharingInterface; import cgeo.geocaching.activity.AbstractViewPagerActivity; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.trackable.TrackableConnector; import cgeo.geocaching.connector.trackable.TravelBugConnector; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.geopoint.Units; import cgeo.geocaching.network.HtmlImage; import cgeo.geocaching.ui.AbstractCachingPageViewCreator; import cgeo.geocaching.ui.AnchorAwareLinkMovementMethod; import cgeo.geocaching.ui.CacheDetailsCreator; import cgeo.geocaching.ui.ImagesList; import cgeo.geocaching.ui.UserActionsClickListener; import cgeo.geocaching.ui.UserNameClickListener; import cgeo.geocaching.ui.logs.TrackableLogsViewCreator; import cgeo.geocaching.utils.Formatter; import cgeo.geocaching.utils.HtmlUtils; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.RxUtils; import cgeo.geocaching.utils.UnknownTagsHandler; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import rx.Observable; import rx.android.observables.AndroidObservable; import rx.android.observables.ViewObservable; import rx.functions.Action1; import rx.functions.Func0; import rx.subscriptions.CompositeSubscription; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.view.ActionMode; import android.text.Html; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class TrackableActivity extends AbstractViewPagerActivity<TrackableActivity.Page> implements ActivitySharingInterface { private CompositeSubscription createSubscriptions; public enum Page { DETAILS(R.string.detail), LOGS(R.string.cache_logs), IMAGES(R.string.cache_images); private final int resId; Page(final int resId) { this.resId = resId; } } private Trackable trackable = null; private String geocode = null; private String name = null; private String guid = null; private String id = null; private LayoutInflater inflater = null; private ProgressDialog waitDialog = null; private CharSequence clickedItemText = null; private ImagesList imagesList = null; /** * Action mode of the current contextual action bar (e.g. for copy and share actions). */ private ActionMode currentActionMode; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState, R.layout.viewpager_activity); // set title in code, as the activity needs a hard coded title due to the intent filters setTitle(res.getString(R.string.trackable)); // get parameters final Bundle extras = getIntent().getExtras(); final Uri uri = getIntent().getData(); // try to get data from extras if (extras != null) { geocode = extras.getString(Intents.EXTRA_GEOCODE); name = extras.getString(Intents.EXTRA_NAME); guid = extras.getString(Intents.EXTRA_GUID); id = extras.getString(Intents.EXTRA_ID); } // try to get data from URI if (geocode == null && guid == null && id == null && uri != null) { geocode = ConnectorFactory.getTrackableFromURL(uri.toString()); final String uriHost = uri.getHost().toLowerCase(Locale.US); if (uriHost.contains("geocaching.com")) { geocode = uri.getQueryParameter("tracker"); guid = uri.getQueryParameter("guid"); id = uri.getQueryParameter("id"); if (StringUtils.isNotBlank(geocode)) { geocode = geocode.toUpperCase(Locale.US); guid = null; id = null; } else if (StringUtils.isNotBlank(guid)) { geocode = null; guid = guid.toLowerCase(Locale.US); id = null; } else if (StringUtils.isNotBlank(id)) { geocode = null; guid = null; id = id.toLowerCase(Locale.US); } else { showToast(res.getString(R.string.err_tb_details_open)); finish(); return; } } else if (uriHost.contains("coord.info")) { final String uriPath = uri.getPath().toLowerCase(Locale.US); if (StringUtils.startsWith(uriPath, "/tb")) { geocode = uriPath.substring(1).toUpperCase(Locale.US); guid = null; id = null; } else { showToast(res.getString(R.string.err_tb_details_open)); finish(); return; } } } // no given data if (geocode == null && guid == null && id == null) { showToast(res.getString(R.string.err_tb_display)); finish(); return; } String message; if (StringUtils.isNotBlank(name)) { message = Html.fromHtml(name).toString(); } else if (StringUtils.isNotBlank(geocode)) { message = geocode; } else { message = res.getString(R.string.trackable); } // If we have a newer Android device setup Android Beam for easy cache sharing initializeAndroidBeam(this); createViewPager(0, new OnPageSelectedListener() { @Override public void onPageSelected(final int position) { // Lazy loading of trackable images if (getPage(position) == Page.IMAGES) { loadTrackableImages(); } } }); waitDialog = ProgressDialog.show(this, message, res.getString(R.string.trackable_details_loading), true, true); createSubscriptions = new CompositeSubscription(); createSubscriptions.add(AndroidObservable.bindActivity(this, loadTrackable(geocode, guid, id)).singleOrDefault(null).subscribe(new Action1<Trackable>() { @Override public void call(final Trackable trackable) { TrackableActivity.this.trackable = trackable; displayTrackable(); } })); } @Override public String getAndroidBeamUri() { return trackable != null ? trackable.getUrl() : null; } @Override public boolean onCreateOptionsMenu(final Menu menu) { getMenuInflater().inflate(R.menu.trackable_activity, menu); return true; } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.menu_log_touch: LogTrackableActivity.startActivity(this, trackable); return true; case R.id.menu_browser_trackable: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(trackable.getUrl()))); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onPrepareOptionsMenu(final Menu menu) { if (trackable != null) { menu.findItem(R.id.menu_log_touch).setVisible(StringUtils.isNotBlank(geocode) && trackable.isLoggable()); menu.findItem(R.id.menu_browser_trackable).setVisible(StringUtils.isNotBlank(trackable.getUrl())); } return super.onPrepareOptionsMenu(menu); } private static Observable<Trackable> loadTrackable(final String geocode, final String guid, final String id) { return Observable.defer(new Func0<Observable<Trackable>>() { @Override public Observable<Trackable> call() { if (StringUtils.isNotEmpty(geocode)) { // iterate over the connectors as some codes may be handled by multiple connectors for (final TrackableConnector trackableConnector : ConnectorFactory.getTrackableConnectors()) { if (trackableConnector.canHandleTrackable(geocode)) { final Trackable trackable = trackableConnector.searchTrackable(geocode, guid, id); if (trackable != null) { return Observable.just(trackable); } } } // Check local storage (offline case) final Trackable trackable = DataStore.loadTrackable(geocode); if (trackable != null) { return Observable.just(trackable); } } // Fall back to GC search by GUID final Trackable trackable = TravelBugConnector.getInstance().searchTrackable(geocode, guid, id); return trackable != null ? Observable.just(trackable) : Observable.<Trackable>empty(); } }).subscribeOn(RxUtils.networkScheduler); } public void displayTrackable() { if (trackable == null) { if (waitDialog != null) { waitDialog.dismiss(); } if (StringUtils.isNotBlank(geocode)) { showToast(res.getString(R.string.err_tb_find) + " " + geocode + "."); } else { showToast(res.getString(R.string.err_tb_find_that)); } finish(); return; } try { inflater = getLayoutInflater(); geocode = trackable.getGeocode(); if (StringUtils.isNotBlank(trackable.getName())) { setTitle(Html.fromHtml(trackable.getName()).toString()); } else { setTitle(trackable.getName()); } invalidateOptionsMenuCompatible(); reinitializeViewPager(); } catch (final Exception e) { Log.e("TrackableActivity.loadTrackableHandler: ", e); } if (waitDialog != null) { waitDialog.dismiss(); } } private void setupIcon(final ActionBar actionBar, final String url) { final HtmlImage imgGetter = new HtmlImage(HtmlImage.SHARED, false, 0, false); AndroidObservable.bindActivity(this, imgGetter.fetchDrawable(url)).subscribe(new Action1<BitmapDrawable>() { @Override public void call(final BitmapDrawable image) { if (actionBar != null) { final int height = actionBar.getHeight(); image.setBounds(0, 0, height, height); actionBar.setIcon(image); } } }); } public static void startActivity(final AbstractActivity fromContext, final String guid, final String geocode, final String name) { final Intent trackableIntent = new Intent(fromContext, TrackableActivity.class); trackableIntent.putExtra(Intents.EXTRA_GUID, guid); trackableIntent.putExtra(Intents.EXTRA_GEOCODE, geocode); trackableIntent.putExtra(Intents.EXTRA_NAME, name); fromContext.startActivity(trackableIntent); } @Override protected PageViewCreator createViewCreator(final Page page) { switch (page) { case DETAILS: return new DetailsViewCreator(); case LOGS: return new TrackableLogsViewCreator(this); case IMAGES: return new ImagesViewCreator(); } throw new IllegalStateException(); // cannot happen as long as switch case is enum complete } private class ImagesViewCreator extends AbstractCachingPageViewCreator<View> { @Override public View getDispatchedView(final ViewGroup parentView) { view = getLayoutInflater().inflate(R.layout.cachedetail_images_page, parentView, false); return view; } } private void loadTrackableImages() { if (imagesList != null) { return; } final PageViewCreator creator = getViewCreator(Page.IMAGES); if (creator == null) { return; } final View imageView = creator.getView(null); if (imageView == null) { return; } imagesList = new ImagesList(this, trackable.getGeocode()); createSubscriptions.add(imagesList.loadImages(imageView, trackable.getImages(), false)); } @Override protected String getTitle(final Page page) { return res.getString(page.resId); } @Override protected Pair<List<? extends Page>, Integer> getOrderedPages() { final List<Page> pages = new ArrayList<>(); pages.add(Page.DETAILS); if (CollectionUtils.isNotEmpty(trackable.getLogs())) { pages.add(Page.LOGS); } if (CollectionUtils.isNotEmpty(trackable.getImages())) { pages.add(Page.IMAGES); } return new ImmutablePair<List<? extends Page>, Integer>(pages, 0); } public class DetailsViewCreator extends AbstractCachingPageViewCreator<ScrollView> { @InjectView(R.id.goal_box) protected LinearLayout goalBox; @InjectView(R.id.goal) protected TextView goalTextView; @InjectView(R.id.details_box) protected LinearLayout detailsBox; @InjectView(R.id.details) protected TextView detailsTextView; @InjectView(R.id.image_box) protected LinearLayout imageBox; @InjectView(R.id.details_list) protected LinearLayout detailsList; @InjectView(R.id.image) protected LinearLayout imageView; @Override public ScrollView getDispatchedView(final ViewGroup parentView) { view = (ScrollView) getLayoutInflater().inflate(R.layout.trackable_details_view, parentView, false); ButterKnife.inject(this, view); final CacheDetailsCreator details = new CacheDetailsCreator(TrackableActivity.this, detailsList); // action bar icon if (StringUtils.isNotBlank(trackable.getIconUrl())) { setupIcon(getSupportActionBar(), trackable.getIconUrl()); } // trackable name addContextMenu(details.add(R.string.trackable_name, StringUtils.isNotBlank(trackable.getName()) ? Html.fromHtml(trackable.getName()).toString() : res.getString(R.string.trackable_unknown))); // trackable type String tbType; if (StringUtils.isNotBlank(trackable.getType())) { tbType = Html.fromHtml(trackable.getType()).toString(); } else { tbType = res.getString(R.string.trackable_unknown); } details.add(R.string.trackable_type, tbType); // trackable geocode addContextMenu(details.add(R.string.trackable_code, trackable.getGeocode())); // trackable owner final TextView owner = details.add(R.string.trackable_owner, res.getString(R.string.trackable_unknown)); if (StringUtils.isNotBlank(trackable.getOwner())) { owner.setText(Html.fromHtml(trackable.getOwner()), TextView.BufferType.SPANNABLE); owner.setOnClickListener(new UserActionsClickListener(trackable)); } // trackable spotted if (StringUtils.isNotBlank(trackable.getSpottedName()) || trackable.getSpottedType() == Trackable.SPOTTED_UNKNOWN || trackable.getSpottedType() == Trackable.SPOTTED_OWNER) { boolean showTimeSpan = true; StringBuilder text; if (trackable.getSpottedType() == Trackable.SPOTTED_CACHE) { text = new StringBuilder(res.getString(R.string.trackable_spotted_in_cache) + ' ' + Html.fromHtml(trackable.getSpottedName()).toString()); } else if (trackable.getSpottedType() == Trackable.SPOTTED_USER) { text = new StringBuilder(res.getString(R.string.trackable_spotted_at_user) + ' ' + Html.fromHtml(trackable.getSpottedName()).toString()); } else if (trackable.getSpottedType() == Trackable.SPOTTED_UNKNOWN) { text = new StringBuilder(res.getString(R.string.trackable_spotted_unknown_location)); } else if (trackable.getSpottedType() == Trackable.SPOTTED_OWNER) { text = new StringBuilder(res.getString(R.string.trackable_spotted_owner)); } else { text = new StringBuilder("N/A"); showTimeSpan = false; } // days since last spotting if (showTimeSpan && trackable.getLogs() != null) { for (final LogEntry log : trackable.getLogs()) { if (log.type == LogType.RETRIEVED_IT || log.type == LogType.GRABBED_IT || log.type == LogType.DISCOVERED_IT || log.type == LogType.PLACED_IT) { final int days = log.daysSinceLog(); text.append(" (").append(res.getQuantityString(R.plurals.days_ago, days, days)).append(')'); break; } } } final TextView spotted = details.add(R.string.trackable_spotted, text.toString()); spotted.setClickable(true); if (Trackable.SPOTTED_CACHE == trackable.getSpottedType()) { spotted.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View arg0) { if (StringUtils.isNotBlank(trackable.getSpottedGuid())) { CacheDetailActivity.startActivityGuid(TrackableActivity.this, trackable.getSpottedGuid(), trackable.getSpottedName()); } else { // for geokrety we only know the cache geocode final String cacheCode = trackable.getSpottedName(); if (ConnectorFactory.canHandle(cacheCode)) { CacheDetailActivity.startActivity(TrackableActivity.this, cacheCode); } } } }); } else if (Trackable.SPOTTED_USER == trackable.getSpottedType()) { spotted.setOnClickListener(new UserNameClickListener(trackable, Html.fromHtml(trackable.getSpottedName()).toString())); } else if (Trackable.SPOTTED_OWNER == trackable.getSpottedType()) { spotted.setOnClickListener(new UserNameClickListener(trackable, Html.fromHtml(trackable.getOwner()).toString())); } } // trackable origin if (StringUtils.isNotBlank(trackable.getOrigin())) { final TextView origin = details.add(R.string.trackable_origin, ""); origin.setText(Html.fromHtml(trackable.getOrigin()), TextView.BufferType.SPANNABLE); addContextMenu(origin); } // trackable released if (trackable.getReleased() != null) { addContextMenu(details.add(R.string.trackable_released, Formatter.formatDate(trackable.getReleased().getTime()))); } // trackable distance if (trackable.getDistance() >= 0) { addContextMenu(details.add(R.string.trackable_distance, Units.getDistanceFromKilometers(trackable.getDistance()))); } // trackable goal if (StringUtils.isNotBlank(HtmlUtils.extractText(trackable.getGoal()))) { goalBox.setVisibility(View.VISIBLE); goalTextView.setVisibility(View.VISIBLE); goalTextView.setText(Html.fromHtml(trackable.getGoal(), new HtmlImage(geocode, true, 0, false, goalTextView), null), TextView.BufferType.SPANNABLE); goalTextView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance()); addContextMenu(goalTextView); } // trackable details if (StringUtils.isNotBlank(HtmlUtils.extractText(trackable.getDetails()))) { detailsBox.setVisibility(View.VISIBLE); detailsTextView.setVisibility(View.VISIBLE); detailsTextView.setText(Html.fromHtml(trackable.getDetails(), new HtmlImage(geocode, true, 0, false, detailsTextView), new UnknownTagsHandler()), TextView.BufferType.SPANNABLE); detailsTextView.setMovementMethod(AnchorAwareLinkMovementMethod.getInstance()); addContextMenu(detailsTextView); } // trackable image if (StringUtils.isNotBlank(trackable.getImage())) { imageBox.setVisibility(View.VISIBLE); final ImageView trackableImage = (ImageView) inflater.inflate(R.layout.trackable_image, imageView, false); trackableImage.setImageResource(R.drawable.image_not_loaded); trackableImage.setClickable(true); ViewObservable.clicks(trackableImage, false).subscribe(new Action1<View>() { @Override public void call(final View view) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(trackable.getImage()))); } }); AndroidObservable.bindActivity(TrackableActivity.this, new HtmlImage(geocode, true, 0, false).fetchDrawable(trackable.getImage())).subscribe(new Action1<BitmapDrawable>() { @Override public void call(final BitmapDrawable bitmapDrawable) { trackableImage.setImageDrawable(bitmapDrawable); } }); imageView.addView(trackableImage); } return view; } } @Override public void addContextMenu(final View view) { view.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(final View v) { return startContextualActionBar(view); } }); view.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { startContextualActionBar(view); } }); } private boolean startContextualActionBar(final View view) { if (currentActionMode != null) { return false; } currentActionMode = startSupportActionMode(new ActionMode.Callback() { @Override public boolean onPrepareActionMode(final ActionMode actionMode, final Menu menu) { final int viewId = view.getId(); assert view instanceof TextView; clickedItemText = ((TextView) view).getText(); switch (viewId) { case R.id.value: // name, TB-code, origin, released, distance final CharSequence itemTitle = ((TextView) ((View) view.getParent()).findViewById(R.id.name)).getText(); buildDetailsContextMenu(actionMode, menu, clickedItemText, itemTitle, true); return true; case R.id.goal: buildDetailsContextMenu(actionMode, menu, clickedItemText, res.getString(R.string.trackable_goal), false); return true; case R.id.details: buildDetailsContextMenu(actionMode, menu, clickedItemText, res.getString(R.string.trackable_details), false); return true; case R.id.log: buildDetailsContextMenu(actionMode, menu, clickedItemText, res.getString(R.string.cache_logs), false); return true; } return false; } @Override public void onDestroyActionMode(final ActionMode actionMode) { currentActionMode = null; } @Override public boolean onCreateActionMode(final ActionMode actionMode, final Menu menu) { actionMode.getMenuInflater().inflate(R.menu.details_context, menu); return true; } @Override public boolean onActionItemClicked(final ActionMode actionMode, final MenuItem menuItem) { return onClipboardItemSelected(actionMode, menuItem, clickedItemText); } }); return false; } @Override protected void onResume() { super.onResume(); // refresh the logs view after coming back from logging a trackable if (trackable != null) { final Trackable updatedTrackable = DataStore.loadTrackable(trackable.getGeocode()); trackable.setLogs(updatedTrackable.getLogs()); reinitializeViewPager(); } } @Override protected void onDestroy() { createSubscriptions.unsubscribe(); super.onDestroy(); } public Trackable getTrackable() { return trackable; } }
package org.nschmidt.ldparteditor.data; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.widgets.Event; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector4f; import org.nschmidt.ldparteditor.composites.Composite3D; import org.nschmidt.ldparteditor.enums.LDConfig; import org.nschmidt.ldparteditor.enums.ObjectMode; import org.nschmidt.ldparteditor.enums.Threshold; import org.nschmidt.ldparteditor.enums.View; import org.nschmidt.ldparteditor.helpers.Cocoa; import org.nschmidt.ldparteditor.helpers.LDPartEditorException; import org.nschmidt.ldparteditor.helpers.composite3d.PerspectiveCalculator; import org.nschmidt.ldparteditor.helpers.composite3d.SelectorSettings; import org.nschmidt.ldparteditor.helpers.math.HashBiMap; import org.nschmidt.ldparteditor.helpers.math.MathHelper; import org.nschmidt.ldparteditor.helpers.math.PowerRay; import org.nschmidt.ldparteditor.helpers.math.ThreadsafeSortedMap; import org.nschmidt.ldparteditor.helpers.math.Vector3d; import org.nschmidt.ldparteditor.i18n.I18n; import org.nschmidt.ldparteditor.logger.NLogger; import org.nschmidt.ldparteditor.shells.editor3d.Editor3DWindow; import org.nschmidt.ldparteditor.text.DatParser; import org.nschmidt.ldparteditor.text.StringHelper; import org.nschmidt.ldparteditor.workbench.WorkbenchManager; class VM01SelectHelper extends VM01Select { protected VM01SelectHelper(DatFile linkedDatFile) { super(linkedDatFile); } /** * @return {@code true} if the selection did not use a rubber band */ public synchronized boolean selectVertices(final Composite3D c3d, boolean addSomething, boolean forceRayTest) { final boolean noTrans = Editor3DWindow.getWindow().hasNoTransparentSelection(); final boolean noCondlineVerts = !c3d.isShowingCondlineControlPoints(); if (!(c3d.getKeys().isCtrlPressed() || (Cocoa.IS_COCOA && c3d.getKeys().isCmdPressed())) && !addSomething || addSomething) { clearSelection2(); } final Vector4f selectionStart = new Vector4f(c3d.getSelectionStart()); final Vector4f selectionWidth = new Vector4f(c3d.getSelectionWidth()); final Vector4f selectionHeight = new Vector4f(c3d.getSelectionHeight()); final Vector4f selectionDepth; final boolean needRayTest; { boolean needRayTest2 = false; if (Math.abs(selectionWidth.x) < 0.001f && Math.abs(selectionWidth.y) < 0.001f && Math.abs(selectionWidth.z) < 0.001f) needRayTest2 = true; if (Math.abs(selectionHeight.x) < 0.001f && Math.abs(selectionHeight.y) < 0.001f && Math.abs(selectionHeight.z) < 0.001f) needRayTest2 = true; needRayTest = needRayTest2 || forceRayTest; } if (needRayTest) { Vector4f zAxis4f = new Vector4f(0, 0, c3d.hasNegDeterminant() ^ c3d.isWarpedSelection() ? -1f : 1f, 1f); Matrix4f ovrInverse2 = Matrix4f.invert(c3d.getRotation(), null); Matrix4f.transform(ovrInverse2, zAxis4f, zAxis4f); selectionDepth = (Vector4f) new Vector4f(zAxis4f.x, zAxis4f.y, zAxis4f.z, 0f).normalise(); selectionDepth.w = 1f; final float discr = 1f / c3d.getZoom(); final long complexity = c3d.isShowingHiddenVertices() ? vertexLinkedToPositionInFile.size() : vertexLinkedToPositionInFile.size() * ((long) triangles.size() + (long) quads.size()); if (complexity < View.NUM_CORES * 100L) { for (Vertex vertex : vertexLinkedToPositionInFile.keySet()) { if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; MathHelper.crossProduct(selectionDepth, Vector4f.sub(vertex.toVector4f(), selectionStart, null), selectionWidth); if (selectionWidth.x * selectionWidth.x + selectionWidth.y * selectionWidth.y + selectionWidth.z * selectionWidth.z < discr) { selectVerticesHelper(c3d, vertex, selectionDepth, powerRay, noTrans, needRayTest); } } } else { // Multithreaded selection for many faces backupSelection(); final int chunks = View.NUM_CORES; final Thread[] threads = new Thread[chunks]; final AtomicBoolean dialogCanceled = new AtomicBoolean(false); final Vertex[] verts = vertexLinkedToPositionInFile.keySet().toArray(new Vertex[0]); final int iterations = verts.length; int lastend = 0; for (int j = 0; j < chunks; ++j) { final int[] i = new int[1]; final int[] start = new int[] { lastend }; lastend = iterations / chunks * (j + 1); final int[] end = new int[] { lastend }; if (j == chunks - 1) { end[0] = iterations; } i[0] = j; threads[j] = new Thread(() -> { final PowerRay powerRay = new PowerRay(); int s = start[0]; int e = end[0]; Vector4f result = new Vector4f(); for (int k = s; k < e; k++) { Vertex vertex = verts[k]; if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; MathHelper.crossProduct(selectionDepth, Vector4f.sub(vertex.toVector4f(), selectionStart, null), result); if (result.x * result.x + result.y * result.y + result.z * result.z < discr) { if (dialogCanceled.get()) return; selectVerticesHelper(c3d, vertex, selectionDepth, powerRay, noTrans, needRayTest); } } }); threads[j].start(); } boolean isRunning = true; int counter = 0; while (isRunning) { try { this.wait(100); counter++; if (counter == 50) break; } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new LDPartEditorException(ie); } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) isRunning = true; } } if (counter == 50) { linkedDatFile.setDrawSelection(false); try { new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor m) throws InvocationTargetException, InterruptedException { try { m.beginTask(I18n.VM_SELECTING, IProgressMonitor.UNKNOWN); boolean isRunning = true; while (isRunning) { try { Thread.sleep(100); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new LDPartEditorException(ie); } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) { isRunning = true; } } if (m.isCanceled()) { dialogCanceled.set(true); } } } finally { if (m.isCanceled()) { restoreSelection(); } else { backupSelectionClear(); } m.done(); } } }); } catch (InvocationTargetException consumed) { } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new LDPartEditorException(ie); } linkedDatFile.setDrawSelection(true); } } } else { selectionDepth = new Vector4f(); MathHelper.crossProduct(selectionHeight, selectionWidth, selectionDepth); selectionDepth.w = 0f; selectionDepth.normalise(); if (c3d.hasNegDeterminant() ^ c3d.isWarpedSelection()) { selectionDepth.negate(); } selectionDepth.w = 1f; final long complexity = c3d.isShowingHiddenVertices() ? vertexLinkedToPositionInFile.size() : vertexLinkedToPositionInFile.size() * ((long) triangles.size() + (long) quads.size()); if (complexity < View.NUM_CORES * 100L) { float[][] a = new float[3][3]; float[] b = new float[3]; for (Vertex vertex : vertexLinkedToPositionInFile.keySet()) { if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; a[0][0] = selectionWidth.x; a[1][0] = selectionWidth.y; a[2][0] = selectionWidth.z; a[0][1] = selectionHeight.x; a[1][1] = selectionHeight.y; a[2][1] = selectionHeight.z; a[0][2] = selectionDepth.x; a[1][2] = selectionDepth.y; a[2][2] = selectionDepth.z; b[0] = vertex.x - selectionStart.x; b[1] = vertex.y - selectionStart.y; b[2] = vertex.z - selectionStart.z; b = MathHelper.gaussianElimination(a, b); if (b[0] <= 1f && b[0] >= 0f && b[1] >= 0f && b[1] <= 1f) { selectVerticesHelper(c3d, vertex, selectionDepth, powerRay, noTrans, needRayTest); } } } else { // Multithreaded selection for many, many faces backupSelection(); final int chunks = View.NUM_CORES; final Thread[] threads = new Thread[chunks]; final AtomicBoolean dialogCanceled = new AtomicBoolean(false); final Vertex[] verts = vertexLinkedToPositionInFile.keySet().toArray(new Vertex[0]); final int iterations = verts.length; int lastend = 0; for (int j = 0; j < chunks; ++j) { final int[] i = new int[1]; final int[] start = new int[] { lastend }; lastend = iterations / chunks * (j + 1); final int[] end = new int[] { lastend }; if (j == chunks - 1) { end[0] = iterations; } i[0] = j; threads[j] = new Thread(() -> { final PowerRay powerRay = new PowerRay(); int s = start[0]; int e = end[0]; float[][] a = new float[3][3]; float[] b = new float[3]; for (int k = s; k < e; k++) { Vertex vertex = verts[k]; if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; a[0][0] = selectionWidth.x; a[1][0] = selectionWidth.y; a[2][0] = selectionWidth.z; a[0][1] = selectionHeight.x; a[1][1] = selectionHeight.y; a[2][1] = selectionHeight.z; a[0][2] = selectionDepth.x; a[1][2] = selectionDepth.y; a[2][2] = selectionDepth.z; b[0] = vertex.x - selectionStart.x; b[1] = vertex.y - selectionStart.y; b[2] = vertex.z - selectionStart.z; b = MathHelper.gaussianElimination(a, b); if (b[0] <= 1f && b[0] >= 0f && b[1] >= 0f && b[1] <= 1f) { if (dialogCanceled.get()) return; selectVerticesHelper(c3d, vertex, selectionDepth, powerRay, noTrans, needRayTest); } } }); threads[j].start(); } boolean isRunning = true; int counter = 0; while (isRunning) { try { this.wait(100); counter++; if (counter == 50) break; } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new LDPartEditorException(ie); } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) isRunning = true; } } if (counter == 50) { linkedDatFile.setDrawSelection(false); try { new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor m) throws InvocationTargetException, InterruptedException { try { m.beginTask(I18n.VM_SELECTING, IProgressMonitor.UNKNOWN); boolean isRunning = true; while (isRunning) { try { Thread.sleep(100); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new LDPartEditorException(ie); } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) isRunning = true; } if (m.isCanceled()) { dialogCanceled.set(true); } } } finally { if (m.isCanceled()) { restoreSelection(); } else { backupSelectionClear(); } m.done(); } } }); }catch (InvocationTargetException consumed) { } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new LDPartEditorException(ie); } linkedDatFile.setDrawSelection(true); } } } if (addSomething) { SortedSet<Vertex> nearVertices = new TreeSet<>(); float zoom = c3d.getZoom() * 1000f; NLogger.debug(getClass(), zoom); final PerspectiveCalculator pc = c3d.getPerspectiveCalculator(); List<Vector4f> vertsOnScreen = new ArrayList<>(selectedVertices.size()); List<Vertex> verts = new ArrayList<>(selectedVertices.size()); for (Vertex v : selectedVertices) { vertsOnScreen.add(pc.getScreenCoordinatesFrom3D(v.x, v.y, v.z)); verts.add(v); } final float EPSILON_SQR = (float) Math.pow(WorkbenchManager.getUserSettingState().getFuzziness2D(), 2.0); NLogger.debug(getClass(), "2D EPSILON² around selection is {0}", EPSILON_SQR); //$NON-NLS-1$ if (EPSILON_SQR > 1f) { final List<Vector4f> nearVertices2 = new ArrayList<>(); final int size = selectedVertices.size(); for (int i = 0; i < size; i++) { final Vector4f sv = vertsOnScreen.get(i); final float svx = sv.x; final float svy = sv.y; boolean isNear = false; for (Vector4f sv2 : nearVertices2) { final float dx = svx - sv2.x; final float dy = svy - sv2.y; float dist = dx * dx + dy * dy; // NLogger.debug(getClass(), "DIST is {0}", dist); //$NON-NLS-1$ if (dist < EPSILON_SQR) { isNear = true; break; } } nearVertices2.add(sv); if (!isNear) { nearVertices.add(verts.get(i)); } } selectedVertices.clear(); selectedVertices.addAll(nearVertices); } if (BigDecimal.ZERO.compareTo(WorkbenchManager.getUserSettingState().getFuzziness3D()) < 0) { nearVertices.clear(); final List<Vertex> nearVertices2 = new ArrayList<>(); BigDecimal epsilon; epsilon = WorkbenchManager.getUserSettingState().getFuzziness3D(); epsilon = epsilon.multiply(epsilon, Threshold.MC); NLogger.debug(getClass(), "3D EPSILON² around selection is {0}", epsilon); //$NON-NLS-1$ for (Vertex v : selectedVertices) { Vector3d v1 = new Vector3d(v); boolean isNear = false; for (Vertex key : nearVertices2) { Vector3d v2 = new Vector3d(key); BigDecimal dist = Vector3d.distSquare(v1, v2); if (dist.compareTo(epsilon) < 0f) { isNear = true; break; } } nearVertices2.add(v); if (!isNear) { nearVertices.add(v); } } selectedVertices.clear(); selectedVertices.addAll(nearVertices); } } else if (Editor3DWindow.getWindow().isMovingAdjacentData() && Editor3DWindow.getWindow().getWorkingType() == ObjectMode.VERTICES) { { Map<GData, Integer> occurMap = new HashMap<>(); for (Vertex vertex : selectedVertices) { Set<VertexManifestation> occurences = vertexLinkedToPositionInFile.get(vertex); if (occurences == null) continue; for (VertexManifestation vm : occurences) { GData g = vm.getGdata(); int val = 1; if (occurMap.containsKey(g)) { val = occurMap.get(g); val++; } occurMap.put(g, val); switch (g.type()) { case 2: GData2 line = (GData2) g; if (val == 2) { selectedLines.add(line); selectedData.add(g); } break; case 3: GData3 triangle = (GData3) g; if (val == 3) { selectedTriangles.add(triangle); selectedData.add(g); } break; case 4: GData4 quad = (GData4) g; if (val == 4) { selectedQuads.add(quad); selectedData.add(g); } break; case 5: GData5 condline = (GData5) g; if (val == 4) { selectedCondlines.add(condline); selectedData.add(g); } break; default: break; } } } } } return needRayTest; } /** * ONLY FOR SELECT SUBFILES * @param c3d */ private synchronized void selectVertices2(final Composite3D c3d) { final boolean noTrans = Editor3DWindow.getWindow().hasNoTransparentSelection(); final boolean noCondlineVerts = !c3d.isShowingCondlineControlPoints(); final Vector4f selectionStart = new Vector4f(c3d.getSelectionStart()); final Vector4f selectionWidth = new Vector4f(c3d.getSelectionWidth()); final Vector4f selectionHeight = new Vector4f(c3d.getSelectionHeight()); final Vector4f selectionDepth; boolean needRayTest = false; if (Math.abs(selectionWidth.x) < 0.001f && Math.abs(selectionWidth.y) < 0.001f && Math.abs(selectionWidth.z) < 0.001f) needRayTest = true; if (Math.abs(selectionHeight.x) < 0.001f && Math.abs(selectionHeight.y) < 0.001f && Math.abs(selectionHeight.z) < 0.001f) needRayTest = true; if (needRayTest) { Vector4f zAxis4f = new Vector4f(0, 0, c3d.hasNegDeterminant() ^ c3d.isWarpedSelection() ? -1f : 1f, 1f); Matrix4f ovrInverse2 = Matrix4f.invert(c3d.getRotation(), null); Matrix4f.transform(ovrInverse2, zAxis4f, zAxis4f); selectionDepth = (Vector4f) new Vector4f(zAxis4f.x, zAxis4f.y, zAxis4f.z, 0f).normalise(); selectionDepth.w = 1f; final float discr = 1f / c3d.getZoom(); final long complexity = c3d.isShowingHiddenVertices() ? vertexLinkedToPositionInFile.size() : vertexLinkedToPositionInFile.size() * ((long) triangles.size() + (long) quads.size()); if (complexity < View.NUM_CORES * 100L) { for (Vertex vertex : vertexLinkedToPositionInFile.keySet()) { if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; MathHelper.crossProduct(selectionDepth, Vector4f.sub(vertex.toVector4f(), selectionStart, null), selectionWidth); if (selectionWidth.x * selectionWidth.x + selectionWidth.y * selectionWidth.y + selectionWidth.z * selectionWidth.z < discr) { selectVertices2Helper(c3d, vertex, selectionDepth, powerRay, noTrans); } } } else { // Multithreaded selection for many faces final int chunks = View.NUM_CORES; final Thread[] threads = new Thread[chunks]; final AtomicBoolean dialogCanceled = new AtomicBoolean(false); final Vertex[] verts = vertexLinkedToPositionInFile.keySet().toArray(new Vertex[0]); final int iterations = verts.length; int lastend = 0; for (int j = 0; j < chunks; ++j) { final int[] i = new int[1]; final int[] start = new int[] { lastend }; lastend = iterations / chunks * (j + 1); final int[] end = new int[] { lastend }; if (j == chunks - 1) { end[0] = iterations; } i[0] = j; threads[j] = new Thread(() -> { final PowerRay powerRay = new PowerRay(); int s = start[0]; int e = end[0]; Vector4f result = new Vector4f(); for (int k = s; k < e; k++) { Vertex vertex = verts[k]; if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; MathHelper.crossProduct(selectionDepth, Vector4f.sub(vertex.toVector4f(), selectionStart, null), result); if (result.x * result.x + result.y * result.y + result.z * result.z < discr) { if (dialogCanceled.get()) return; selectVertices2Helper(c3d, vertex, selectionDepth, powerRay, noTrans); } } }); threads[j].start(); } boolean isRunning = true; int counter = 0; while (isRunning) { try { this.wait(100); counter++; if (counter == 50) break; } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new LDPartEditorException(ie); } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) isRunning = true; } } if (counter == 50) { linkedDatFile.setDrawSelection(false); try { new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor m) throws InvocationTargetException, InterruptedException { try { m.beginTask(I18n.VM_SELECTING, IProgressMonitor.UNKNOWN); boolean isRunning = true; while (isRunning) { try { Thread.sleep(100); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new LDPartEditorException(ie); } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) isRunning = true; } if (m.isCanceled()) { dialogCanceled.set(true); } } } finally { if (m.isCanceled()) { clearSelection2(); } m.done(); } } }); } catch (InvocationTargetException consumed) { } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new LDPartEditorException(ie); } linkedDatFile.setDrawSelection(true); } } } else { selectionDepth = new Vector4f(); MathHelper.crossProduct(selectionHeight, selectionWidth, selectionDepth); selectionDepth.w = 0f; selectionDepth.normalise(); if (c3d.hasNegDeterminant() ^ c3d.isWarpedSelection()) { selectionDepth.negate(); } selectionDepth.w = 1f; final long complexity = c3d.isShowingHiddenVertices() ? vertexLinkedToPositionInFile.size() : vertexLinkedToPositionInFile.size() * ((long) triangles.size() + (long) quads.size()); if (complexity < View.NUM_CORES * 100L) { float[][] a = new float[3][3]; float[] b = new float[3]; for (Vertex vertex : vertexLinkedToPositionInFile.keySet()) { if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; a[0][0] = selectionWidth.x; a[1][0] = selectionWidth.y; a[2][0] = selectionWidth.z; a[0][1] = selectionHeight.x; a[1][1] = selectionHeight.y; a[2][1] = selectionHeight.z; a[0][2] = selectionDepth.x; a[1][2] = selectionDepth.y; a[2][2] = selectionDepth.z; b[0] = vertex.x - selectionStart.x; b[1] = vertex.y - selectionStart.y; b[2] = vertex.z - selectionStart.z; b = MathHelper.gaussianElimination(a, b); if (b[0] <= 1f && b[0] >= 0f && b[1] >= 0f && b[1] <= 1f) { selectVertices2Helper(c3d, vertex, selectionDepth, powerRay, noTrans); } } } else { // Multithreaded selection for many faces backupSelection(); final int chunks = View.NUM_CORES; final Thread[] threads = new Thread[chunks]; final AtomicBoolean dialogCanceled = new AtomicBoolean(false); final Vertex[] verts = vertexLinkedToPositionInFile.keySet().toArray(new Vertex[0]); final int iterations = verts.length; int lastend = 0; for (int j = 0; j < chunks; ++j) { final int[] i = new int[1]; final int[] start = new int[] { lastend }; lastend = iterations / chunks * (j + 1); final int[] end = new int[] { lastend }; if (j == chunks - 1) { end[0] = iterations; } i[0] = j; threads[j] = new Thread(() -> { final PowerRay powerRay = new PowerRay(); int s = start[0]; int e = end[0]; float[][] a = new float[3][3]; float[] b = new float[3]; for (int k = s; k < e; k++) { Vertex vertex = verts[k]; if (hiddenVertices.contains(vertex) || noCondlineVerts && isPureCondlineControlPoint(vertex)) continue; a[0][0] = selectionWidth.x; a[1][0] = selectionWidth.y; a[2][0] = selectionWidth.z; a[0][1] = selectionHeight.x; a[1][1] = selectionHeight.y; a[2][1] = selectionHeight.z; a[0][2] = selectionDepth.x; a[1][2] = selectionDepth.y; a[2][2] = selectionDepth.z; b[0] = vertex.x - selectionStart.x; b[1] = vertex.y - selectionStart.y; b[2] = vertex.z - selectionStart.z; b = MathHelper.gaussianElimination(a, b); if (b[0] <= 1f && b[0] >= 0f && b[1] >= 0f && b[1] <= 1f) { if (dialogCanceled.get()) return; selectVertices2Helper(c3d, vertex, selectionDepth, powerRay, noTrans); } } }); threads[j].start(); } boolean isRunning = true; int counter = 0; while (isRunning) { try { this.wait(100); counter++; if (counter == 50) break; } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new LDPartEditorException(ie); } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) isRunning = true; } } if (counter == 50) { linkedDatFile.setDrawSelection(false); try { new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor m) throws InvocationTargetException, InterruptedException { try { m.beginTask(I18n.VM_SELECTING, IProgressMonitor.UNKNOWN); boolean isRunning = true; while (isRunning) { try { Thread.sleep(100); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new LDPartEditorException(ie); } isRunning = false; for (Thread thread : threads) { if (thread.isAlive()) isRunning = true; } if (m.isCanceled()) { dialogCanceled.set(true); } } } finally { if (m.isCanceled()) { restoreSelection(); } else { backupSelectionClear(); } m.done(); } } }); }catch (InvocationTargetException consumed) { } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new LDPartEditorException(ie); } linkedDatFile.setDrawSelection(true); } } } } private void selectVerticesHelper(final Composite3D c3d, final Vertex vertex, final Vector4f rayDirection, PowerRay powerRay, boolean noTrans, boolean needRayTest) { final Set<GData3> tris = triangles.keySet(); final Set<GData4> qs = quads.keySet(); if (c3d.isShowingHiddenVertices()) { if (selectedVertices.contains(vertex)) { if (needRayTest || c3d.getKeys().isAltPressed()) { selectedVertices.remove(vertex); } } else { selectedVertices.add(vertex); if (Editor3DWindow.getWindow().getWorkingType() == ObjectMode.VERTICES) lastSelectedVertex = vertex; } } else { final Vector4f point = vertex.toVector4f(); boolean vertexIsShown = true; for (GData3 triangle : tris) { if (noTrans && triangle.a < 1f || hiddenData.contains(triangle)) continue; Vertex[] tverts = triangles.get(triangle); if (!tverts[0].equals(vertex) && !tverts[1].equals(vertex) && !tverts[2].equals(vertex) && powerRay.triangleIntersect(point, rayDirection, tverts[0], tverts[1], tverts[2])) { vertexIsShown = false; break; } } if (vertexIsShown) { for (GData4 quad : qs) { if (noTrans && quad.a < 1f || hiddenData.contains(quad)) continue; Vertex[] tverts = quads.get(quad); if (!tverts[0].equals(vertex) && !tverts[1].equals(vertex) && !tverts[2].equals(vertex) && !tverts[3].equals(vertex) && (powerRay.triangleIntersect(point, rayDirection, tverts[0], tverts[1], tverts[2]) || powerRay.triangleIntersect(point, rayDirection, tverts[2], tverts[3], tverts[0]))) { vertexIsShown = false; break; } } } if (vertexIsShown) { if (selectedVertices.contains(vertex)) { if (needRayTest || c3d.getKeys().isAltPressed()) { selectedVertices.remove(vertex); } } else { selectedVertices.add(vertex); if (Editor3DWindow.getWindow().getWorkingType() == ObjectMode.VERTICES) lastSelectedVertex = vertex; } } } } private void selectVertices2Helper(final Composite3D c3d, final Vertex vertex, final Vector4f rayDirection, PowerRay powerRay, boolean noTrans) { final Set<GData3> tris = triangles.keySet(); final Set<GData4> qs = quads.keySet(); if (c3d.isShowingHiddenVertices()) { selectedVerticesForSubfile.add(vertex); } else { final Vector4f point = vertex.toVector4f(); boolean vertexIsShown = true; for (GData3 triangle : tris) { if (noTrans && triangle.a < 1f || hiddenData.contains(triangle)) continue; Vertex[] tverts = triangles.get(triangle); if (!tverts[0].equals(vertex) && !tverts[1].equals(vertex) && !tverts[2].equals(vertex) && powerRay.triangleIntersect(point, rayDirection, tverts[0], tverts[1], tverts[2])) { vertexIsShown = false; break; } } if (vertexIsShown) { for (GData4 quad : qs) { if (noTrans && quad.a < 1f || hiddenData.contains(quad)) continue; Vertex[] tverts = quads.get(quad); if (!tverts[0].equals(vertex) && !tverts[1].equals(vertex) && !tverts[2].equals(vertex) && !tverts[3].equals(vertex) && (powerRay.triangleIntersect(point, rayDirection, tverts[0], tverts[1], tverts[2]) || powerRay.triangleIntersect(point, rayDirection, tverts[2], tverts[3], tverts[0]))) { vertexIsShown = false; break; } } } if (vertexIsShown) { selectedVerticesForSubfile.add(vertex); } } } private boolean isVertexVisible(Composite3D c3d, Vertex vertex, Vector4f rayDirection, boolean noTrans) { if (!c3d.isShowingHiddenVertices()) { final Vector4f point = vertex.toVector4f(); Vertex[] triQuadVerts; for (Entry<GData3, Vertex[]> entry : triangles.entrySet()) { GData3 triangle = entry.getKey(); if (noTrans && triangle.a < 1f || hiddenData.contains(triangle)) continue; triQuadVerts = entry.getValue(); if (!triQuadVerts[0].equals(vertex) && !triQuadVerts[1].equals(vertex) && !triQuadVerts[2].equals(vertex) && powerRay.triangleIntersect(point, rayDirection, triQuadVerts[0], triQuadVerts[1], triQuadVerts[2])) { return false; } } for (Entry<GData4, Vertex[]> entry : quads.entrySet()) { GData4 quad = entry.getKey(); if (noTrans && quad.a < 1f || hiddenData.contains(quad)) continue; triQuadVerts = entry.getValue(); if (!triQuadVerts[0].equals(vertex) && !triQuadVerts[1].equals(vertex) && !triQuadVerts[2].equals(vertex) && !triQuadVerts[3].equals(vertex) && (powerRay.triangleIntersect(point, rayDirection, triQuadVerts[0], triQuadVerts[1], triQuadVerts[2]) || powerRay.triangleIntersect(point, rayDirection, triQuadVerts[2], triQuadVerts[3], triQuadVerts[0]))) { return false; } } } return true; } public synchronized void selectLines(Composite3D c3d, SelectorSettings sels) { final boolean noTrans = Editor3DWindow.getWindow().hasNoTransparentSelection(); if (!(c3d.getKeys().isCtrlPressed() || (Cocoa.IS_COCOA && c3d.getKeys().isCmdPressed()))) { clearSelection2(); } Set<Vertex> selectedVerticesTemp = Collections.newSetFromMap(new ThreadsafeSortedMap<>()); selectedVerticesTemp.addAll(selectedVertices); selectedVertices.clear(); Vector4f selectionWidth = new Vector4f(c3d.getSelectionWidth()); Vector4f selectionHeight = new Vector4f(c3d.getSelectionHeight()); selectVertices(c3d, false, false); boolean allVertsFromLine = false; boolean needRayTest = false; if (Math.abs(selectionWidth.x) < 0.001f && Math.abs(selectionWidth.y) < 0.001f && Math.abs(selectionWidth.z) < 0.001f) needRayTest = true; if (Math.abs(selectionHeight.x) < 0.001f && Math.abs(selectionHeight.y) < 0.001f && Math.abs(selectionHeight.z) < 0.001f) needRayTest = true; if (selectedVertices.size() < 2 || needRayTest) { if (selectedVertices.size() == 1) { Vertex selectedVertex = selectedVertices.iterator().next(); if (sels.isLines() || !sels.isCondlines()) { for (Entry<GData2, Vertex[]> entry : lines.entrySet()) { GData2 line = entry.getKey(); if (hiddenData.contains(line)) continue; for (Vertex tvertex : entry.getValue()) { if (selectedVertex.equals(tvertex)) { if (selectedLines.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedLines.remove(line); } else { selectedData.add(line); selectedLines.add(line); } } } } } if (sels.isCondlines() || !sels.isLines()) { for (Entry<GData5, Vertex[]> entry : condlines.entrySet()) { GData5 line = entry.getKey(); if (hiddenData.contains(line)) continue; for (Vertex tvertex : entry.getValue()) { if (selectedVertex.equals(tvertex)) { if (selectedCondlines.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedCondlines.remove(line); } else { selectedData.add(line); selectedCondlines.add(line); } } } } } } else { Vector4f selectionStart = new Vector4f(c3d.getSelectionStart()); Vector4f selectionDepth; Vector4f zAxis4f = new Vector4f(0, 0, 1f, 1f); Matrix4f ovrInverse2 = Matrix4f.invert(c3d.getRotation(), null); Matrix4f.transform(ovrInverse2, zAxis4f, zAxis4f); selectionDepth = (Vector4f) new Vector4f(zAxis4f.x, zAxis4f.y, zAxis4f.z, 0f).normalise(); selectionDepth.w = 1f; // selectionDepth = ray direction // Line from Ray // x(t) = s + dt float discr = 1f / c3d.getZoom(); float[] s = new float[3]; s[0] = selectionStart.x; s[1] = selectionStart.y; s[2] = selectionStart.z; float[] d = new float[3]; d[0] = selectionDepth.x; d[1] = selectionDepth.y; d[2] = selectionDepth.z; // Segment line // x(u) = a + (g - a)u // Difference // x(t) - x(u) = (s - a) + dt + (a - g)u // x(t) - x(u) = e + dt + f u float[] a = new float[3]; float[] g = new float[3]; float[] e = new float[3]; float[] f = new float[3]; float[][] m = new float[2][2]; float[] b = new float[] { 0f, 0f }; if (sels.isLines() || !sels.isCondlines()) { for (Entry<GData2, Vertex[]> entry : lines.entrySet()) { GData2 line = entry.getKey(); if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : entry.getValue()) { if (allVertsFromLine) { f[0] = a[0] - tvertex.x; f[1] = a[1] - tvertex.y; f[2] = a[2] - tvertex.z; g[0] = tvertex.x; g[1] = tvertex.y; g[2] = tvertex.z; } else { a[0] = tvertex.x; a[1] = tvertex.y; a[2] = tvertex.z; e[0] = s[0] - a[0]; e[1] = s[1] - a[1]; e[2] = s[2] - a[2]; } allVertsFromLine = true; } m[0][0] = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; m[0][1] = d[0] * f[0] + d[1] * f[1] + d[2] * f[2]; m[1][0] = m[0][1]; m[1][1] = f[0] * f[0] + f[1] * f[1] + f[2] * f[2]; b[0] = -(d[0] * e[0] + d[1] * e[1] + d[2] * e[2]); // constant b[1] = -(e[0] * f[0] + e[1] * f[1] + e[2] * f[2]); // constant try { float[] solution = MathHelper.gaussianElimination(m, b); if (solution[1] >= 0f && solution[1] <= 1f) { float distanceSquared = (float) (Math.pow(e[0] + d[0] * solution[0] + f[0] * solution[1], 2) + Math.pow(e[1] + d[1] * solution[0] + f[1] * solution[1], 2) + Math.pow(e[2] + d[2] * solution[0] + f[2] * solution[1], 2)); if (distanceSquared < discr) { if (!isVertexVisible(c3d, new Vertex(MathHelper.getNearestPointToLineSegment(a[0], a[1], a[2], g[0], g[1], g[2], a[0] - f[0] * solution[1], a[1] - f[1] * solution[1], a[2] - f[2] * solution[1])), selectionDepth, noTrans)) continue; if (selectedLines.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedLines.remove(line); } else { selectedData.add(line); selectedLines.add(line); } } } } catch (RuntimeException re1) { } } } if (sels.isCondlines() || !sels.isLines()) { for (Entry<GData5, Vertex[]> entry : condlines.entrySet()) { GData5 line = entry.getKey(); if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : entry.getValue()) { if (allVertsFromLine) { f[0] = a[0] - tvertex.x; f[1] = a[1] - tvertex.y; f[2] = a[2] - tvertex.z; g[0] = tvertex.x; g[1] = tvertex.y; g[2] = tvertex.z; break; } else { a[0] = tvertex.x; a[1] = tvertex.y; a[2] = tvertex.z; e[0] = s[0] - a[0]; e[1] = s[1] - a[1]; e[2] = s[2] - a[2]; } allVertsFromLine = true; } m[0][0] = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; m[0][1] = d[0] * f[0] + d[1] * f[1] + d[2] * f[2]; m[1][0] = m[0][1]; m[1][1] = f[0] * f[0] + f[1] * f[1] + f[2] * f[2]; b[0] = -(d[0] * e[0] + d[1] * e[1] + d[2] * e[2]); // constant b[1] = -(e[0] * f[0] + e[1] * f[1] + e[2] * f[2]); // constant try { float[] solution = MathHelper.gaussianElimination(m, b); if (solution[1] >= 0f && solution[1] <= 1f) { float distanceSquared = (float) (Math.pow(e[0] + d[0] * solution[0] + f[0] * solution[1], 2) + Math.pow(e[1] + d[1] * solution[0] + f[1] * solution[1], 2) + Math.pow( e[2] + d[2] * solution[0] + f[2] * solution[1], 2)); if (distanceSquared < discr) { if (!isVertexVisible(c3d, new Vertex(MathHelper.getNearestPointToLineSegment(a[0], a[1], a[2], g[0], g[1], g[2], a[0] - f[0] * solution[1], a[1] - f[1] * solution[1], a[2] - f[2] * solution[1])), selectionDepth, noTrans)) continue; if (selectedCondlines.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedCondlines.remove(line); } else { selectedData.add(line); selectedCondlines.add(line); } } } } catch (RuntimeException re2) { } } } } } else { if (sels.isLines() || !sels.isCondlines()) { for (Entry<GData2, Vertex[]> entry : lines.entrySet()) { GData2 line = entry.getKey(); if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : entry.getValue()) { if (!selectedVertices.contains(tvertex)) break; if (allVertsFromLine) { if (selectedLines.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedLines.remove(line); } else { selectedData.add(line); selectedLines.add(line); } } allVertsFromLine = true; } } } if (sels.isCondlines() || !sels.isLines()) { for (Entry<GData5, Vertex[]> entry : condlines.entrySet()) { GData5 line = entry.getKey(); if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : entry.getValue()) { if (!selectedVertices.contains(tvertex)) break; if (allVertsFromLine) { if (selectedCondlines.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedCondlines.remove(line); } else { selectedData.add(line); selectedCondlines.add(line); } } allVertsFromLine = true; } } } } selectedVertices.clear(); selectedVertices.addAll(selectedVerticesTemp); } /** * ONLY FOR SELECT SUBFILES * @param c3d * @param selectionHeight * @param selectionWidth */ private synchronized void selectLines2(Composite3D c3d, Vector4f selectionWidth, Vector4f selectionHeight) { final boolean noTrans = Editor3DWindow.getWindow().hasNoTransparentSelection(); Set<Vertex> tmpVerts = Collections.newSetFromMap(new ThreadsafeSortedMap<>()); tmpVerts.addAll(selectedVerticesForSubfile); selectedVerticesForSubfile.clear(); selectVertices2(c3d); boolean allVertsFromLine = false; boolean needRayTest = false; if (Math.abs(selectionWidth.x) < 0.001f && Math.abs(selectionWidth.y) < 0.001f && Math.abs(selectionWidth.z) < 0.001f) needRayTest = true; if (Math.abs(selectionHeight.x) < 0.001f && Math.abs(selectionHeight.y) < 0.001f && Math.abs(selectionHeight.z) < 0.001f) needRayTest = true; if (selectedVerticesForSubfile.size() < 2 || needRayTest) { if (selectedVerticesForSubfile.size() == 1) { Vertex selectedVertex = selectedVerticesForSubfile.iterator().next(); for (Entry<GData2, Vertex[]> entry : lines.entrySet()) { GData2 line = entry.getKey(); if (hiddenData.contains(line)) continue; for (Vertex tvertex : entry.getValue()) { if (selectedVertex.equals(tvertex)) { selectedLinesForSubfile.add(line); } } } for (Entry<GData5, Vertex[]> entry : condlines.entrySet()) { GData5 line = entry.getKey(); if (hiddenData.contains(line)) continue; for (Vertex tvertex : entry.getValue()) { if (selectedVertex.equals(tvertex)) { selectedCondlinesForSubfile.add(line); } } } } else { Vector4f selectionStart = new Vector4f(c3d.getSelectionStart()); Vector4f selectionDepth; Vector4f zAxis4f = new Vector4f(0, 0, 1f, 1f); Matrix4f ovrInverse2 = Matrix4f.invert(c3d.getRotation(), null); Matrix4f.transform(ovrInverse2, zAxis4f, zAxis4f); selectionDepth = (Vector4f) new Vector4f(zAxis4f.x, zAxis4f.y, zAxis4f.z, 0f).normalise(); selectionDepth.w = 1f; // selectionDepth = ray direction // Line from Ray // x(t) = s + dt float discr = 1f / c3d.getZoom(); float[] s = new float[3]; s[0] = selectionStart.x; s[1] = selectionStart.y; s[2] = selectionStart.z; float[] d = new float[3]; d[0] = selectionDepth.x; d[1] = selectionDepth.y; d[2] = selectionDepth.z; // Segment line // x(u) = a + (g - a)u // Difference // x(t) - x(u) = (s - a) + dt + (a - g)u // x(t) - x(u) = e + dt + f u float[] a = new float[3]; float[] g = new float[3]; float[] e = new float[3]; float[] f = new float[3]; float[][] m = new float[2][2]; float[] b = new float[] { 0f, 0f }; for (Entry<GData2, Vertex[]> entry : lines.entrySet()) { GData2 line = entry.getKey(); if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : entry.getValue()) { if (allVertsFromLine) { f[0] = a[0] - tvertex.x; f[1] = a[1] - tvertex.y; f[2] = a[2] - tvertex.z; g[0] = tvertex.x; g[1] = tvertex.y; g[2] = tvertex.z; } else { a[0] = tvertex.x; a[1] = tvertex.y; a[2] = tvertex.z; e[0] = s[0] - a[0]; e[1] = s[1] - a[1]; e[2] = s[2] - a[2]; } allVertsFromLine = true; } m[0][0] = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; m[0][1] = d[0] * f[0] + d[1] * f[1] + d[2] * f[2]; m[1][0] = m[0][1]; m[1][1] = f[0] * f[0] + f[1] * f[1] + f[2] * f[2]; b[0] = -(d[0] * e[0] + d[1] * e[1] + d[2] * e[2]); // constant b[1] = -(e[0] * f[0] + e[1] * f[1] + e[2] * f[2]); // constant try { float[] solution = MathHelper.gaussianElimination(m, b); if (solution[1] >= 0f && solution[1] <= 1f) { float distanceSquared = (float) (Math.pow(e[0] + d[0] * solution[0] + f[0] * solution[1], 2) + Math.pow(e[1] + d[1] * solution[0] + f[1] * solution[1], 2) + Math.pow( e[2] + d[2] * solution[0] + f[2] * solution[1], 2)); if (distanceSquared < discr) { if (!isVertexVisible(c3d, new Vertex(MathHelper.getNearestPointToLineSegment(a[0], a[1], a[2], g[0], g[1], g[2], a[0] - f[0] * solution[1], a[1] - f[1] * solution[1], a[2] - f[2] * solution[1])), selectionDepth, noTrans)) continue; selectedLinesForSubfile.add(line); } } } catch (RuntimeException re1) { } } for (Entry<GData5, Vertex[]> entry : condlines.entrySet()) { GData5 line = entry.getKey(); if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : entry.getValue()) { if (allVertsFromLine) { f[0] = a[0] - tvertex.x; f[1] = a[1] - tvertex.y; f[2] = a[2] - tvertex.z; g[0] = tvertex.x; g[1] = tvertex.y; g[2] = tvertex.z; break; } else { a[0] = tvertex.x; a[1] = tvertex.y; a[2] = tvertex.z; e[0] = s[0] - a[0]; e[1] = s[1] - a[1]; e[2] = s[2] - a[2]; } allVertsFromLine = true; } m[0][0] = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; m[0][1] = d[0] * f[0] + d[1] * f[1] + d[2] * f[2]; m[1][0] = m[0][1]; m[1][1] = f[0] * f[0] + f[1] * f[1] + f[2] * f[2]; b[0] = -(d[0] * e[0] + d[1] * e[1] + d[2] * e[2]); // constant b[1] = -(e[0] * f[0] + e[1] * f[1] + e[2] * f[2]); // constant try { float[] solution = MathHelper.gaussianElimination(m, b); if (solution[1] >= 0f && solution[1] <= 1f) { float distanceSquared = (float) (Math.pow(e[0] + d[0] * solution[0] + f[0] * solution[1], 2) + Math.pow(e[1] + d[1] * solution[0] + f[1] * solution[1], 2) + Math.pow( e[2] + d[2] * solution[0] + f[2] * solution[1], 2)); if (distanceSquared < discr) { if (!isVertexVisible(c3d, new Vertex(MathHelper.getNearestPointToLineSegment(a[0], a[1], a[2], g[0], g[1], g[2], a[0] - f[0] * solution[1], a[1] - f[1] * solution[1], a[2] - f[2] * solution[1])), selectionDepth, noTrans)) continue; selectedCondlinesForSubfile.add(line); } } } catch (RuntimeException re2) { } } } } else { for (Entry<GData2, Vertex[]> entry : lines.entrySet()) { GData2 line = entry.getKey(); if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : entry.getValue()) { if (!selectedVerticesForSubfile.contains(tvertex)) break; if (allVertsFromLine) { selectedLinesForSubfile.add(line); } allVertsFromLine = true; } } for (Entry<GData5, Vertex[]> entry : condlines.entrySet()) { GData5 line = entry.getKey(); if (hiddenData.contains(line)) continue; allVertsFromLine = false; for (Vertex tvertex : entry.getValue()) { if (!selectedVerticesForSubfile.contains(tvertex)) break; if (allVertsFromLine) { selectedCondlinesForSubfile.add(line); } allVertsFromLine = true; } } } selectedVerticesForSubfile.clear(); selectedVerticesForSubfile.addAll(tmpVerts); } public synchronized void selectFaces(Composite3D c3d, Event event, SelectorSettings sels) { if (!(c3d.getKeys().isCtrlPressed() || (Cocoa.IS_COCOA && c3d.getKeys().isCmdPressed()))) { clearSelection2(); } Set<Vertex> selectedVerticesTemp = Collections.newSetFromMap(new ThreadsafeSortedMap<>()); selectedVerticesTemp.addAll(selectedVertices); selectedVertices.clear(); boolean allVertsFromLine = false; Vector4f selectionWidth = new Vector4f(c3d.getSelectionWidth()); Vector4f selectionHeight = new Vector4f(c3d.getSelectionHeight()); selectVertices(c3d, false, false); boolean needRayTest = false; if (Math.abs(selectionWidth.x) < 0.001f && Math.abs(selectionWidth.y) < 0.001f && Math.abs(selectionWidth.z) < 0.001f) needRayTest = true; if (Math.abs(selectionHeight.x) < 0.001f && Math.abs(selectionHeight.y) < 0.001f && Math.abs(selectionHeight.z) < 0.001f) needRayTest = true; if (selectedVertices.size() < 2 || needRayTest) { if (selectedVertices.size() == 1) { Vertex selectedVertex = selectedVertices.iterator().next(); if (sels.isTriangles() || !sels.isQuads()) { for (Entry<GData3, Vertex[]> entry : triangles.entrySet()) { GData3 line = entry.getKey(); if (hiddenData.contains(line)) continue; for (Vertex tvertex : entry.getValue()) { if (selectedVertex.equals(tvertex)) { if (selectedTriangles.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedTriangles.remove(line); } else { selectedData.add(line); selectedTriangles.add(line); } } } } } if (sels.isQuads() || !sels.isTriangles()) { for (Entry<GData4, Vertex[]> entry : quads.entrySet()) { GData4 line = entry.getKey(); if (hiddenData.contains(line)) continue; for (Vertex tvertex : entry.getValue()) { if (selectedVertex.equals(tvertex)) { if (selectedQuads.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedQuads.remove(line); } else { selectedData.add(line); selectedQuads.add(line); } } } } } } else { GData selection = selectFacesHelper(c3d, event); if (selection != null) { if (selection.type() == 4 && sels.isQuads()) { GData4 gd4 = (GData4) selection; if (selectedQuads.contains(gd4)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(gd4); if (needRayTest || c3d.getKeys().isAltPressed()) selectedQuads.remove(gd4); } else { selectedData.add(gd4); selectedQuads.add(gd4); } } else if (selection.type() == 3 && (sels.isTriangles() || !sels.isQuads())) { GData3 gd3 = (GData3) selection; if (selectedTriangles.contains(gd3)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(gd3); if (needRayTest || c3d.getKeys().isAltPressed()) selectedTriangles.remove(gd3); } else { selectedData.add(gd3); selectedTriangles.add(gd3); } } } } } else { if (sels.isTriangles() || !sels.isQuads()) { for (Entry<GData3, Vertex[]> entry : triangles.entrySet()) { GData3 line = entry.getKey(); if (hiddenData.contains(line)) continue; allVertsFromLine = true; for (Vertex tvertex : entry.getValue()) { if (!selectedVertices.contains(tvertex)) { allVertsFromLine = false; break; } } if (allVertsFromLine) { if (selectedTriangles.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedTriangles.remove(line); } else { selectedData.add(line); selectedTriangles.add(line); } } } } if (sels.isQuads() || !sels.isTriangles()) { for (Entry<GData4, Vertex[]> entry : quads.entrySet()) { GData4 line = entry.getKey(); if (hiddenData.contains(line)) continue; allVertsFromLine = true; for (Vertex tvertex : entry.getValue()) { if (!selectedVertices.contains(tvertex)) { allVertsFromLine = false; break; } } if (allVertsFromLine) { if (selectedQuads.contains(line)) { if (needRayTest || c3d.getKeys().isAltPressed()) selectedData.remove(line); if (needRayTest || c3d.getKeys().isAltPressed()) selectedQuads.remove(line); } else { selectedData.add(line); selectedQuads.add(line); } } } } } selectedVertices.clear(); selectedVertices.addAll(selectedVerticesTemp); } /** * ONLY FOR SELECT SUBFILES * @param c3d * @param event * @param selectionHeight * @param selectionWidth */ private synchronized void selectFaces2(Composite3D c3d, Event event, Vector4f selectionWidth, Vector4f selectionHeight) { Set<Vertex> selVert4sTemp = Collections.newSetFromMap(new ThreadsafeSortedMap<>()); selVert4sTemp.addAll(selectedVerticesForSubfile); selectedVerticesForSubfile.clear(); selectVertices2(c3d); boolean allVertsFromLine = false; boolean needRayTest = false; if (Math.abs(selectionWidth.x) < 0.001f && Math.abs(selectionWidth.y) < 0.001f && Math.abs(selectionWidth.z) < 0.001f) needRayTest = true; if (Math.abs(selectionHeight.x) < 0.001f && Math.abs(selectionHeight.y) < 0.001f && Math.abs(selectionHeight.z) < 0.001f) needRayTest = true; if (selectedVerticesForSubfile.size() < 2 || needRayTest) { if (selectedVerticesForSubfile.size() == 1) { Vertex selectedVertex = selectedVerticesForSubfile.iterator().next(); for (Entry<GData3, Vertex[]> entry : triangles.entrySet()) { GData3 line = entry.getKey(); if (hiddenData.contains(line)) continue; for (Vertex tvertex : entry.getValue()) { if (selectedVertex.equals(tvertex)) { selectedTrianglesForSubfile.add(line); } } } for (Entry<GData4, Vertex[]> entry : quads.entrySet()) { GData4 line = entry.getKey(); if (hiddenData.contains(line)) continue; for (Vertex tvertex : entry.getValue()) { if (selectedVertex.equals(tvertex)) { selectedQuadsForSubfile.add(line); } } } } else { GData selection = selectFacesHelper(c3d, event); if (selection != null) { if (selection.type() == 4) { GData4 gd4 = (GData4) selection; selectedQuadsForSubfile.add(gd4); } else if (selection.type() == 3) { GData3 gd3 = (GData3) selection; selectedTrianglesForSubfile.add(gd3); } } } } else { for (Entry<GData3, Vertex[]> entry : triangles.entrySet()) { GData3 line = entry.getKey(); if (hiddenData.contains(line)) continue; allVertsFromLine = true; for (Vertex tvertex : entry.getValue()) { if (!selectedVerticesForSubfile.contains(tvertex)) { allVertsFromLine = false; break; } } if (allVertsFromLine) { selectedTrianglesForSubfile.add(line); } } for (Entry<GData4, Vertex[]> entry : quads.entrySet()) { GData4 line = entry.getKey(); if (hiddenData.contains(line)) continue; allVertsFromLine = true; for (Vertex tvertex : entry.getValue()) { if (!selectedVerticesForSubfile.contains(tvertex)) { allVertsFromLine = false; break; } } if (allVertsFromLine) { selectedQuadsForSubfile.add(line); } } } selectedVerticesForSubfile.clear(); selectedVerticesForSubfile.addAll(selVert4sTemp); } private synchronized GData selectFacesHelper(Composite3D c3d, Event event) { final boolean noTrans = Editor3DWindow.getWindow().hasNoTransparentSelection(); PerspectiveCalculator perspective = c3d.getPerspectiveCalculator(); Matrix4f viewportRotation = c3d.getRotation(); Vector4f zAxis4f = new Vector4f(0, 0, -1f, 1f); Matrix4f ovrInverse2 = Matrix4f.invert(viewportRotation, null); Matrix4f.transform(ovrInverse2, zAxis4f, zAxis4f); Vector4f rayDirection = (Vector4f) new Vector4f(zAxis4f.x, zAxis4f.y, zAxis4f.z, 0f).normalise(); rayDirection.w = 1f; Vertex[] triQuadVerts; Vector4f orig = perspective.get3DCoordinatesFromScreen(event.x, event.y); Vector4f point = new Vector4f(orig); double minDist = Double.MAX_VALUE; final double[] dist = new double[1]; GData result = null; for (Entry<GData3, Vertex[]> entry : triangles.entrySet()) { GData3 triangle = entry.getKey(); if (hiddenData.contains(triangle)) continue; if (noTrans && triangle.a < 1f && !c3d.isShowingHiddenVertices()) continue; triQuadVerts = entry.getValue(); if (powerRay.triangleIntersect(orig, rayDirection, triQuadVerts[0], triQuadVerts[1], triQuadVerts[2], point, dist) && dist[0] < minDist) { if (triangle.isTriangle) minDist = dist[0]; if (triangle.isTriangle || result == null) result = triangle; } } for (Entry<GData4, Vertex[]> entry : quads.entrySet()) { GData4 quad = entry.getKey(); if (hiddenData.contains(quad)) continue; if (noTrans && quad.a < 1f && !c3d.isShowingHiddenVertices()) continue; triQuadVerts = entry.getValue(); if ((powerRay.triangleIntersect(orig, rayDirection, triQuadVerts[0], triQuadVerts[1], triQuadVerts[2], point, dist) || powerRay.triangleIntersect(orig, rayDirection, triQuadVerts[2], triQuadVerts[3], triQuadVerts[0], point, dist)) && dist[0] < minDist) { minDist = dist[0]; result = quad; } } return result; } synchronized void selectWholeSubfiles() { Set<GData1> subfilesToAdd = new HashSet<>(); for (GData g : selectedData) { subfilesToAdd.add(g.parent.firstRef); } subfilesToAdd.remove(View.DUMMY_REFERENCE); for (GData1 g : subfilesToAdd) { removeSubfileFromSelection(g); } for (GData1 g : subfilesToAdd) { addSubfileToSelection(g); } } public void removeSubfileFromSelection(GData1 subf) { selectedData.remove(subf); selectedSubfiles.remove(subf); Set<VertexInfo> vis = lineLinkedToVertices.get(subf); if (vis == null) return; for (VertexInfo vertexInfo : vis) { selectedVertices.remove(vertexInfo.getVertex()); GData g = vertexInfo.getLinkedData(); selectedData.remove(g); switch (g.type()) { case 2: selectedLines.remove(g); break; case 3: selectedTriangles.remove(g); break; case 4: selectedQuads.remove(g); break; case 5: selectedCondlines.remove(g); break; default: break; } } } public void addSubfileToSelection(GData1 subf) { selectedData.add(subf); selectedSubfiles.add(subf); Set<VertexInfo> vis = lineLinkedToVertices.get(subf); if (vis == null) return; for (VertexInfo vertexInfo : vis) { selectedVertices.add(vertexInfo.getVertex()); GData g = vertexInfo.getLinkedData(); selectedData.add(g); switch (g.type()) { case 2: selectedLines.add((GData2) g); break; case 3: selectedTriangles.add((GData3) g); break; case 4: selectedQuads.add((GData4) g); break; case 5: selectedCondlines.add((GData5) g); break; default: break; } } } public synchronized void selectSubfiles(Composite3D c3d, Event event) { selectedVerticesForSubfile.clear(); selectedLinesForSubfile.clear(); selectedTrianglesForSubfile.clear(); selectedQuadsForSubfile.clear(); selectedCondlinesForSubfile.clear(); Set<GData1> backupSubfiles = new HashSet<>(selectedSubfiles); if (!(c3d.getKeys().isCtrlPressed() || (Cocoa.IS_COCOA && c3d.getKeys().isCmdPressed()))) { clearSelection2(); backupSubfiles.clear(); } backupSelection(); clearSelection(); { final Vector4f selectionWidth = new Vector4f(c3d.getSelectionWidth()); final Vector4f selectionHeight = new Vector4f(c3d.getSelectionHeight()); selectFaces2(c3d, event, selectionWidth, selectionHeight); selectLines2(c3d, selectionWidth, selectionHeight); } // Determine which subfiles were selected selectedData.addAll(selectedLinesForSubfile); selectedData.addAll(selectedTrianglesForSubfile); selectedData.addAll(selectedQuadsForSubfile); selectedData.addAll(selectedCondlinesForSubfile); selectedVerticesForSubfile.clear(); selectedLinesForSubfile.clear(); selectedTrianglesForSubfile.clear(); selectedQuadsForSubfile.clear(); selectedCondlinesForSubfile.clear(); if (NLogger.debugging) { NLogger.debug(getClass(), "Selected data:"); //$NON-NLS-1$ for (GData g : selectedData) { NLogger.debug(getClass(), g.toString()); } } NLogger.debug(getClass(), "Subfiles in selection:"); //$NON-NLS-1$ Set<GData1> subs = new HashSet<>(); for (GData g : selectedData) { GData1 s = g.parent.firstRef; if (!View.DUMMY_REFERENCE.equals(s)) { subs.add(s); } } for (GData g : subs) { NLogger.debug(getClass(), g.toString()); } selectedData.clear(); NLogger.debug(getClass(), "Subfiles in selection, to add/remove:"); //$NON-NLS-1$ Set<GData1> subsToAdd = new HashSet<>(); Set<GData1> subsToRemove = new HashSet<>(); if (c3d.getKeys().isCtrlPressed()) { for (GData1 subf : backupSubfiles) { if (subs.contains(subf)) { subsToRemove.add(subf); } else { subsToAdd.add(subf); } } for (GData1 subf : subs) { if (!subsToRemove.contains(subf)) { subsToAdd.add(subf); } } } else { subsToAdd.addAll(subs); } restoreSelection(); NLogger.debug(getClass(), "Subfiles in selection (REMOVE)"); //$NON-NLS-1$ for (GData1 g : subsToRemove) { NLogger.debug(getClass(), g.toString()); removeSubfileFromSelection(g); } NLogger.debug(getClass(), "Subfiles in selection (ADD)"); //$NON-NLS-1$ for (GData1 g : subsToAdd) { NLogger.debug(getClass(), g.toString()); addSubfileToSelection(g); } } public Vector4f getSelectionCenter() { final Set<Vertex> objectVertices = Collections.newSetFromMap(new ThreadsafeSortedMap<>()); objectVertices.addAll(selectedVertices); // 1. Object Based Selection for (GData2 line : selectedLines) { Vertex[] verts = lines.get(line); if (verts == null) continue; objectVertices.addAll(Arrays.asList(verts)); } for (GData3 triangle : selectedTriangles) { Vertex[] verts = triangles.get(triangle); if (verts == null) continue; objectVertices.addAll(Arrays.asList(verts)); } for (GData4 quad : selectedQuads) { Vertex[] verts = quads.get(quad); if (verts == null) continue; objectVertices.addAll(Arrays.asList(verts)); } for (GData5 condline : selectedCondlines) { Vertex[] verts = condlines.get(condline); if (verts == null) continue; objectVertices.addAll(Arrays.asList(verts)); } // 2. Subfile Based Selection if (!selectedSubfiles.isEmpty()) { for (GData1 subf : selectedSubfiles) { Set<VertexInfo> vis = lineLinkedToVertices.get(subf); if (vis == null) continue; for (VertexInfo vertexInfo : vis) { objectVertices.add(vertexInfo.getVertex()); } } } if (!objectVertices.isEmpty()) { float x = 0f; float y = 0f; float z = 0f; for (Vertex vertex : objectVertices) { x = x + vertex.x; y = y + vertex.y; z = z + vertex.z; } float count = objectVertices.size(); return new Vector4f(x / count, y / count, z / count, 1f); } else { return new Vector4f(0f, 0f, 0f, 1f); } } public int[] toggleTEXMAP() { return toggleHelper("0 !: "); //$NON-NLS-1$ } public int[] toggleComment() { return toggleHelper("0 // "); //$NON-NLS-1$ } private int[] toggleHelper(final String token) { int[] offsetCorrection = new int[]{0, 0}; boolean firstToken = true; final String token2 = token.substring(0, 4); final GColour col16 = LDConfig.getColour16(); HashBiMap<Integer, GData> dpl = linkedDatFile.getDrawPerLineNoClone(); for (GData g : selectedData) { final GData b = g.getBefore(); final GData n = g.getNext(); final String oldStr = g.toString(); final String lineToParse; if (oldStr.startsWith(token)) { lineToParse = oldStr.substring(5); offsetCorrection[0] -= 5; if (firstToken) { firstToken = false; offsetCorrection[1] = -5; } } else if (oldStr.startsWith(token2)) { lineToParse = oldStr.substring(4); offsetCorrection[0] -= 4; if (firstToken) { firstToken = false; offsetCorrection[1] = -4; } } else { lineToParse = token + oldStr; offsetCorrection[0] += 5; if (firstToken) { firstToken = false; offsetCorrection[1] = 5; } } Integer line = dpl.getKey(g); if (remove(g)) { linkedDatFile.setDrawChainTail(b); } Set<String> alreadyParsed = new HashSet<>(); alreadyParsed.add(linkedDatFile.getShortName()); GData pasted; if (StringHelper.isNotBlank(lineToParse)) { List<ParsingResult> result = DatParser.parseLine(lineToParse, -1, 0, col16.getR(), col16.getG(), col16.getB(), 1.0f, View.DUMMY_REFERENCE, View.ID, View.ACCURATE_ID, linkedDatFile, false, alreadyParsed); pasted = result.get(0).getGraphicalData(); if (pasted == null) pasted = new GData0(lineToParse, View.DUMMY_REFERENCE); } else { pasted = new GData0(lineToParse, View.DUMMY_REFERENCE); } if (token2.equals(pasted.toString())) { pasted = new GData0(lineToParse, View.DUMMY_REFERENCE); } b.setNext(pasted); pasted.setNext(n); dpl.put(line, pasted); linkedDatFile.setDrawChainTail(dpl.getValue(dpl.size())); } return offsetCorrection; } }
package mockit; import java.io.*; import java.util.*; import java.util.concurrent.*; import static org.junit.Assert.*; import org.junit.*; public final class DynamicPartialMockingTest { static class Collaborator { protected final int value; Collaborator() { value = -1; } Collaborator(int value) { this.value = value; } final int getValue() { return value; } @SuppressWarnings({"UnusedDeclaration"}) final boolean simpleOperation(int a, String b, Date c) { return true; } @SuppressWarnings({"UnusedDeclaration"}) static void doSomething(boolean b, String s) { throw new IllegalStateException(); } boolean methodWhichCallsAnotherInTheSameClass() { return simpleOperation(1, "internal", null); } String overridableMethod() { return "base"; } } interface Dependency { boolean doSomething(); List<?> doSomethingElse(int n); } @Test public void dynamicallyMockAClass() { new Expectations(Collaborator.class) { { new Collaborator().getValue(); result = 123; } }; // Mocked: Collaborator collaborator = new Collaborator(); assertEquals(0, collaborator.value); assertEquals(123, collaborator.getValue()); // Not mocked: assertTrue(collaborator.simpleOperation(1, "b", null)); assertEquals(45, new Collaborator(45).value); } @Test public void dynamicallyMockJREClass() throws Exception { new Expectations(ByteArrayOutputStream.class) { { new ByteArrayOutputStream().size(); result = 123; } }; // Mocked: ByteArrayOutputStream collaborator = new ByteArrayOutputStream(); assertNull(Deencapsulation.getField(collaborator, "buf")); assertEquals(123, collaborator.size()); // Not mocked: ByteArrayOutputStream buf = new ByteArrayOutputStream(200); buf.write(65); assertEquals("A", buf.toString("UTF-8")); } @Test public void dynamicallyMockAMockedClass(@Mocked final Collaborator mock) { assertEquals(0, mock.value); new Expectations(mock) { { mock.getValue(); result = 123; } }; // Mocked: assertEquals(123, mock.getValue()); // Not mocked: Collaborator collaborator = new Collaborator(); assertEquals(-1, collaborator.value); assertTrue(collaborator.simpleOperation(1, "b", null)); assertEquals(45, new Collaborator(45).value); } @Test public void dynamicallyMockAnInstance() { final Collaborator collaborator = new Collaborator(); new Expectations(collaborator) { { collaborator.getValue(); result = 123; } }; // Mocked: assertEquals(123, collaborator.getValue()); // Not mocked: assertTrue(collaborator.simpleOperation(1, "b", null)); assertEquals(45, new Collaborator(45).value); assertEquals(-1, new Collaborator().value); } @Test(expected = AssertionError.class) public void expectTwoInvocationsOnStrictDynamicMockButReplayOnce() { final Collaborator collaborator = new Collaborator(); new Expectations(collaborator) { { collaborator.getValue(); times = 2; } }; assertEquals(0, collaborator.getValue()); } @Test public void expectOneInvocationOnStrictDynamicMockButReplayTwice() { final Collaborator collaborator = new Collaborator(1); new Expectations(collaborator) { { collaborator.methodWhichCallsAnotherInTheSameClass(); result = false; } }; // Mocked: assertFalse(collaborator.methodWhichCallsAnotherInTheSameClass()); // No longer mocked, since it's strict: assertTrue(collaborator.methodWhichCallsAnotherInTheSameClass()); } @Test public void expectTwoInvocationsOnStrictDynamicMockButReplayMoreTimes() { final Collaborator collaborator = new Collaborator(1); new Expectations(collaborator) { { collaborator.getValue(); times = 2; } }; // Mocked: assertEquals(0, collaborator.getValue()); assertEquals(0, collaborator.getValue()); // No longer mocked, since it's strict and all expected invocations were already replayed: assertEquals(1, collaborator.getValue()); } @Test(expected = AssertionError.class) public void expectTwoInvocationsOnNonStrictDynamicMockButReplayOnce() { final Collaborator collaborator = new Collaborator(); new NonStrictExpectations(collaborator) { { collaborator.getValue(); times = 2; } }; assertEquals(0, collaborator.getValue()); } @Test(expected = AssertionError.class) public void expectOneInvocationOnNonStrictDynamicMockButReplayTwice() { final Collaborator collaborator = new Collaborator(1); new NonStrictExpectations(collaborator) { { collaborator.getValue(); times = 1; } }; // Mocked: assertEquals(0, collaborator.getValue()); // Still mocked because it's non-strict: assertEquals(0, collaborator.getValue()); } @Test public void dynamicallyMockAnInstanceWithNonStrictExpectations() { final Collaborator collaborator = new Collaborator(2); new NonStrictExpectations(collaborator) { { collaborator.simpleOperation(1, "", null); result = false; Collaborator.doSomething(anyBoolean, "test"); } }; // Mocked: assertFalse(collaborator.simpleOperation(1, "", null)); Collaborator.doSomething(true, "test"); // Not mocked: assertEquals(2, collaborator.getValue()); assertEquals(45, new Collaborator(45).value); assertEquals(-1, new Collaborator().value); try { Collaborator.doSomething(false, null); fail(); } catch (IllegalStateException ignore) {} new Verifications() { { Collaborator.doSomething(anyBoolean, "test"); collaborator.getValue(); times = 1; new Collaborator(45); } }; } @Test public void mockMethodInSameClass() { final Collaborator collaborator = new Collaborator(); new NonStrictExpectations(collaborator) { { collaborator.simpleOperation(1, anyString, null); result = false; } }; assertFalse(collaborator.methodWhichCallsAnotherInTheSameClass()); assertTrue(collaborator.simpleOperation(2, "", null)); assertFalse(collaborator.simpleOperation(1, "", null)); } static final class SubCollaborator extends Collaborator { SubCollaborator() { this(1); } SubCollaborator(int value) { super(value); } @Override String overridableMethod() { return super.overridableMethod() + " overridden"; } String format() { return String.valueOf(value); } } @Test(expected = IllegalStateException.class) public void dynamicallyMockASubCollaboratorInstance() { final SubCollaborator collaborator = new SubCollaborator(); new NonStrictExpectations(collaborator) { { collaborator.getValue(); result = 5; new SubCollaborator().format(); result = "test"; } }; // Mocked: assertEquals(5, collaborator.getValue()); assertEquals("test", collaborator.format()); // Not mocked: assertTrue(collaborator.simpleOperation(0, null, null)); Collaborator.doSomething(true, null); } @Test public void dynamicallyMockOnlyTheSubclass() { final SubCollaborator collaborator = new SubCollaborator(); new NonStrictExpectations(SubCollaborator.class) { { collaborator.getValue(); collaborator.format(); result = "test"; } }; // Mocked: assertEquals("test", collaborator.format()); // Not mocked: assertEquals(1, collaborator.getValue()); assertTrue(collaborator.simpleOperation(0, null, null)); // Mocked sub-constructor/not mocked base constructor: assertEquals(-1, new SubCollaborator().value); new VerificationsInOrder() { { collaborator.format(); new SubCollaborator(); } }; } @Test public void mockTheBaseMethodWhileExercisingTheOverride() { final Collaborator collaborator = new Collaborator(); new Expectations(Collaborator.class) { { collaborator.overridableMethod(); result = ""; collaborator.overridableMethod(); result = "mocked"; } }; assertEquals("", collaborator.overridableMethod()); assertEquals("mocked overridden", new SubCollaborator().overridableMethod()); } @Test public void dynamicallyMockAnAnonymousClassInstanceThroughTheImplementedInterface() { final Collaborator collaborator = new Collaborator(); final Dependency dependency = new Dependency() { public boolean doSomething() { return false; } public List<?> doSomethingElse(int n) { return null; } }; new NonStrictExpectations(collaborator, dependency) { { collaborator.getValue(); result = 5; dependency.doSomething(); result = true; } }; // Mocked: assertEquals(5, collaborator.getValue()); assertTrue(dependency.doSomething()); // Not mocked: assertTrue(collaborator.simpleOperation(0, null, null)); assertNull(dependency.doSomethingElse(3)); new FullVerifications() { { dependency.doSomething(); collaborator.getValue(); dependency.doSomethingElse(anyInt); collaborator.simpleOperation(0, null, null); } }; } @Test public void dynamicallyMockInstanceOfJREClass() { final List<String> list = new LinkedList<String>(); @SuppressWarnings({"UseOfObsoleteCollectionType"}) List<String> anotherList = new Vector<String>(); new NonStrictExpectations(list, anotherList) { { list.get(1); result = "an item"; list.size(); result = 2; } }; // Use mocked methods: assertEquals(2, list.size()); assertEquals("an item", list.get(1)); // Use unmocked methods: assertTrue(list.add("another")); assertEquals("another", list.remove(0)); anotherList.add("one"); assertEquals("one", anotherList.get(0)); assertEquals(1, anotherList.size()); } public interface AnotherInterface {} @Test public void attemptToUseDynamicMockingForInvalidTypes(AnotherInterface mockedInterface) { assertInvalidTypeForDynamicMocking(Dependency.class); assertInvalidTypeForDynamicMocking(Test.class); assertInvalidTypeForDynamicMocking(int[].class); assertInvalidTypeForDynamicMocking(new String[1]); assertInvalidTypeForDynamicMocking(char.class); assertInvalidTypeForDynamicMocking(123); assertInvalidTypeForDynamicMocking(Boolean.class); assertInvalidTypeForDynamicMocking(true); assertInvalidTypeForDynamicMocking(2.5); assertInvalidTypeForDynamicMocking(Mockit.newEmptyProxy(Dependency.class)); assertInvalidTypeForDynamicMocking(mockedInterface); } private void assertInvalidTypeForDynamicMocking(Object classOrObject) { try { new Expectations(classOrObject) {}; fail(); } catch (IllegalArgumentException ignore) {} } @Test public void dynamicPartialMockingWithExactArgumentMatching() { final Collaborator collaborator = new Collaborator(); new NonStrictExpectations(collaborator) {{ collaborator.simpleOperation(1, "s", null); result = false; }}; assertFalse(collaborator.simpleOperation(1, "s", null)); assertTrue(collaborator.simpleOperation(2, "s", null)); assertTrue(collaborator.simpleOperation(1, "S", null)); assertTrue(collaborator.simpleOperation(1, "s", new Date())); assertTrue(collaborator.simpleOperation(1, null, new Date())); assertFalse(collaborator.simpleOperation(1, "s", null)); new FullVerifications() { { collaborator.simpleOperation(anyInt, null, null); } }; } @Test public void dynamicPartialMockingWithFlexibleArgumentMatching(final Collaborator mock) { new NonStrictExpectations(mock) {{ mock.simpleOperation(anyInt, withPrefix("s"), null); result = false; }}; Collaborator collaborator = new Collaborator(); assertFalse(collaborator.simpleOperation(1, "sSs", null)); assertTrue(collaborator.simpleOperation(2, " s", null)); assertTrue(collaborator.simpleOperation(1, "S", null)); assertFalse(collaborator.simpleOperation(-1, "s", new Date())); assertTrue(collaborator.simpleOperation(1, null, null)); assertFalse(collaborator.simpleOperation(0, "string", null)); } @Test public void dynamicPartialMockingWithOnInstanceMatching() { final Collaborator mock = new Collaborator(); new NonStrictExpectations(mock) {{ onInstance(mock).getValue(); result = 3; }}; assertEquals(3, mock.getValue()); assertEquals(4, new Collaborator(4).getValue()); new FullVerificationsInOrder() { { onInstance(mock).getValue(); mock.getValue(); } }; } @Test public void methodWithNoRecordedExpectationCalledTwiceDuringReplay() { final Collaborator collaborator = new Collaborator(123); new NonStrictExpectations(collaborator) {}; assertEquals(123, collaborator.getValue()); assertEquals(123, collaborator.getValue()); new FullVerifications() { { collaborator.getValue(); times = 2; } }; } static final class TaskWithConsoleInput { boolean finished; void doIt() { int input = '\0'; while (input != 'A') { try { input = System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } if (input == 'Z') { finished = true; break; } } } } private boolean runTaskWithTimeout(long timeoutInMillis) throws InterruptedException, ExecutionException { final TaskWithConsoleInput task = new TaskWithConsoleInput(); Runnable asynchronousTask = new Runnable() { public void run() { task.doIt(); } }; ExecutorService executor = Executors.newSingleThreadExecutor(); while (!task.finished) { Future<?> worker = executor.submit(asynchronousTask); try { worker.get(timeoutInMillis, TimeUnit.MILLISECONDS); } catch (TimeoutException ignore) { executor.shutdownNow(); return false; } } return true; } @Test public void taskWithConsoleInputTerminatingNormally() throws Exception { new Expectations(System.in) { { System.in.read(); returns((int) 'A', (int) 'x', (int) 'Z'); } }; assertTrue(runTaskWithTimeout(5000)); } @Test public void taskWithConsoleInputTerminatingOnTimeout() throws Exception { new Expectations(System.in) { { System.in.read(); result = new Delegate() { void takeTooLong() throws InterruptedException { Thread.sleep(5000); } }; } }; assertFalse("no timeout", runTaskWithTimeout(10)); } static class ClassWithStaticInitializer { static boolean initialized = true; static int doSomething() { return initialized ? 1 : -1; } } @Test public void doNotStubOutStaticInitializersWhenDynamicallyMockingAClass() { new Expectations(ClassWithStaticInitializer.class) { { ClassWithStaticInitializer.doSomething(); result = 2; } }; assertEquals(2, ClassWithStaticInitializer.doSomething()); assertTrue(ClassWithStaticInitializer.initialized); } static final class ClassWithNative { int doSomething() { return nativeMethod(); } private native int nativeMethod(); } @Test(expected = UnsatisfiedLinkError.class) public void attemptToPartiallyMockNativeMethod() { final ClassWithNative mock = new ClassWithNative(); new Expectations(mock) {{ // The native method is ignored when using dynamic mocking, so this actually tries to execute the real method, // failing since there is no native implementation. mock.nativeMethod(); }}; } @Test // with FileIO compiled with "target 1.1", this produced a VerifyError public void mockClassCompiledForJava11() throws Exception { final FileIO f = new FileIO(); new Expectations(f) {{ f.writeToFile("test"); }}; f.writeToFile("test"); } }
package org.objectweb.proactive.core.component; import org.objectweb.fractal.api.Component; import org.objectweb.fractal.api.NoSuchInterfaceException; import org.objectweb.fractal.api.Type; import org.objectweb.fractal.api.factory.Factory; import org.objectweb.fractal.api.factory.GenericFactory; import org.objectweb.fractal.api.factory.InstantiationException; import org.objectweb.fractal.api.type.ComponentType; import org.objectweb.fractal.api.type.InterfaceType; import org.objectweb.fractal.api.type.TypeFactory; import org.objectweb.proactive.ActiveObjectCreationException; import org.objectweb.proactive.ProActive; import org.objectweb.proactive.core.ProActiveRuntimeException; import org.objectweb.proactive.core.body.ProActiveMetaObjectFactory; import org.objectweb.proactive.core.component.controller.ComponentParametersController; import org.objectweb.proactive.core.component.representative.ProActiveComponentRepresentative; import org.objectweb.proactive.core.component.representative.ProActiveComponentRepresentativeFactory; import org.objectweb.proactive.core.component.type.Composite; import org.objectweb.proactive.core.component.type.ParallelComposite; import org.objectweb.proactive.core.component.type.ProActiveTypeFactory; import org.objectweb.proactive.core.group.Group; import org.objectweb.proactive.core.group.ProActiveComponentGroup; import org.objectweb.proactive.core.group.ProActiveGroup; import org.objectweb.proactive.core.mop.Proxy; import org.objectweb.proactive.core.mop.StubObject; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.node.NodeException; import org.objectweb.proactive.core.util.ProActiveLogger; import java.util.Hashtable; import java.util.Map; /** * This class is used for creating components. * It acts as :<br> * 1. a bootstrap component<br> * 2. a GenericFactory for instantiating new components * 3. a utility class providing static methods to create collective interfaces and retreive references to ComponentParametersController<br> */ public class Fractive implements GenericFactory, Component, Factory { private static Fractive instance = null; private TypeFactory typeFactory = (TypeFactory) ProActiveTypeFactory.instance(); private Type type = null; /** * no-arg constructor (used by Fractal to get a bootstrap component) * */ public Fractive() { } private static Fractive instance() { if (instance == null) { instance = new Fractive(); } return instance; } /** * Returns the {@link org.objectweb.fractal.api.control.ContentController} interface of the given component. * * @param component a component. * @return the {@link org.objectweb.fractal.api.control.ContentController} interface of the given component. * @throws NoSuchInterfaceException if there is no such interface. */ public static ComponentParametersController getComponentParametersController( final Component component) throws NoSuchInterfaceException { return (ComponentParametersController) component.getFcInterface(Constants.COMPONENT_PARAMETERS_CONTROLLER); } /** * Returns a generated interface reference, whose impl field is a group * It is able to handle multiple bindings */ public static ProActiveInterface createCollectiveClientInterface( String itfName, String itfSignature) throws ProActiveRuntimeException { try { InterfaceType itf_type = ProActiveTypeFactory.instance() .createFcItfType(itfName, itfSignature, TypeFactory.CLIENT, TypeFactory.MANDATORY, TypeFactory.COLLECTION); ProActiveInterface itf_ref_group = ProActiveComponentGroup.newComponentInterfaceGroup(itf_type); return itf_ref_group; } catch (Exception e) { throw new ProActiveRuntimeException("Impossible to create a collective client interface ", e); } } private static Component newFcInstance(ContentDescription contentDesc, ComponentParameters componentParameters) throws InstantiationException { //MetaObjectFactory factory = null; try { // instantiate the component metaobject factory with parameters of the component if (contentDesc.getFactory() == null) { // first create a hashtable with the parameters Hashtable factory_params = new Hashtable(1); factory_params.put(ProActiveMetaObjectFactory.COMPONENT_PARAMETERS_KEY, componentParameters); contentDesc.setFactory(new ProActiveMetaObjectFactory( factory_params)); // factory = ProActiveComponentMetaObjectFactory.newInstance(componentParameters); } Object ao = null; if (!contentDesc.isLocalizedOnAVirtualNode()) { // case 1. Node ao = ProActive.newActive(contentDesc.getClassName(), contentDesc.getConstructorParameters(), contentDesc.getNode(), contentDesc.getActivity(), contentDesc.getFactory()); } else { // case 2. Virtual Node contentDesc.getVirtualNode().activate(); if (contentDesc.getVirtualNode().getNodes().length == 0) { throw new InstantiationException( "Cannot create component on virtual node as no node is associated with this virtual node"); } Node[] nodes = contentDesc.getVirtualNode().getNodes(); if ((nodes.length > 1) && !contentDesc.uniqueInstance()) { // cyclic node + 1 instance per node //Component components = (Component) ProActiveGroup.newGroup(Component.class.getName()); Component components = ProActiveComponentGroup.newComponentRepresentativeGroup(componentParameters.getComponentType()); Group group_of_components = ProActiveGroup.getGroup(components); Proxy proxy = null; if (componentParameters.getHierarchicalType().equals(Constants.PRIMITIVE)) { // task = instantiate a component with a different name // on each of the node mapped to the given virtual node String original_component_name = componentParameters.getName(); contentDesc.getVirtualNode().activate(); for (int i = 0; i < nodes.length; i++) { // change the name of each component (add a suffix) String new_name = original_component_name + Constants.CYCLIC_NODE_SUFFIX + i; componentParameters.setName(new_name); // change location of each component contentDesc.setNode(nodes[i]); group_of_components.add(Fractive.newFcInstance( contentDesc, componentParameters)); } return components; } else { ao = ProActive.newActive(contentDesc.getClassName(), contentDesc.getConstructorParameters(), contentDesc.getVirtualNode().getNode(), contentDesc.getActivity(), contentDesc.getFactory()); } } else { // this is the case where contentDesc.getVirtualNode().getNodeCount() == 1) { // or when virtual node is multiple but only 1 component should be instantiated on the virtual node // create the component on the first node retreived from the virtual node ao = ProActive.newActive(contentDesc.getClassName(), contentDesc.getConstructorParameters(), contentDesc.getVirtualNode().getNode(), contentDesc.getActivity(), contentDesc.getFactory()); } } // Find the proxy org.objectweb.proactive.core.mop.Proxy myProxy = ((StubObject) ao).getProxy(); if (myProxy == null) { throw new ProActiveRuntimeException( "Cannot find a Proxy on the stub object: " + ao); } ProActiveComponentRepresentative representative = ProActiveComponentRepresentativeFactory.instance() .createComponentRepresentative(componentParameters.getComponentType(), myProxy); representative.setStubOnBaseObject((StubObject) ao); return representative; } catch (ActiveObjectCreationException e) { throw new InstantiationException(e.getMessage()); } catch (NodeException e) { throw new InstantiationException(e.getMessage()); } catch (ClassNotFoundException e) { throw new InstantiationException(e.getMessage()); } catch (java.lang.InstantiationException e) { e.printStackTrace(); throw new InstantiationException(e.getMessage()); } } private Component newFcInstance(Type type, ControllerDescription controllerDesc, ContentDescription contentDesc) throws InstantiationException { if (contentDesc == null) { // either a parallel or a composite component, no activitiy/factory/node specified if (Constants.COMPOSITE.equals(controllerDesc.getHierarchicalType())) { contentDesc = new ContentDescription(Composite.class.getName()); } else if (Constants.PARALLEL.equals( controllerDesc.getHierarchicalType())) { contentDesc = new ContentDescription(ParallelComposite.class.getName()); } else { throw new InstantiationException( "Content can be null only if the hierarchical type of the component is composite or parallel"); } } ComponentParameters component_params = new ComponentParameters((ComponentType) type, controllerDesc); return Fractive.newFcInstance(contentDesc, component_params); } /** * see {@link org.objectweb.fractal.api.factory.GenericFactory#newFcInstance(org.objectweb.fractal.api.Type, java.lang.Object, java.lang.Object)} */ public Component newFcInstance(Type arg0, Object arg1, Object arg2) throws InstantiationException { try { return newFcInstance(arg0, (ControllerDescription) arg1, (ContentDescription) arg2); } catch (ClassCastException e) { if ((arg0 == null) && (arg1 == null) && (arg2 instanceof Map)) { // for compatibility with the new org.objectweb.fractal.util.Fractal class return this; } if ((arg1 instanceof ControllerDescription) && ((arg2 instanceof String) || (arg2 == null))) { // for the ADL, when only type and ControllerDescription are given return newFcInstance(arg0, arg1, (arg2 == null) ? null : new ContentDescription( (String) arg2)); } // code compatibility with Julia if ("composite".equals(arg1) && (arg2 == null)) { return newFcInstance(arg0, new ControllerDescription(null, Constants.COMPOSITE), null); } if ("primitive".equals(arg1) && (arg2 instanceof String)) { return newFcInstance(arg0, new ControllerDescription(null, Constants.PRIMITIVE), new ContentDescription((String) arg2)); } if ("parallel".equals(arg1) && (arg2 == null)) { return newFcInstance(arg0, new ControllerDescription(null, Constants.PARALLEL), null); } // any other case throw new InstantiationException( "With this implementation, parameters must be of respective types : " + Type.class.getName() + ',' + ControllerDescription.class.getName() + ',' + ContentDescription.class.getName()); } } /** * see {@link org.objectweb.fractal.api.Component#getFcInterface(java.lang.String)} */ public Object getFcInterface(String itfName) throws NoSuchInterfaceException { if ("generic-factory".equals(itfName)) { return this; } else if ("type-factory".equals(itfName)) { return typeFactory; } else { throw new NoSuchInterfaceException(itfName); } } /** * see {@link org.objectweb.fractal.api.Component#getFcInterfaces()} */ public Object[] getFcInterfaces() { return null; } /** * see {@link org.objectweb.fractal.api.Component#getFcType()} */ public Type getFcType() { if (type == null) { try { return type = typeFactory.createFcType(new InterfaceType[] { typeFactory.createFcItfType("generic-factory", GenericFactory.class.getName(), false, false, false), typeFactory.createFcItfType("type-factory", TypeFactory.class.getName(), false, false, false) }); } catch (InstantiationException e) { ProActiveLogger.getLogger("components").error(e.getMessage()); return null; } } else { return type; } } /** * see {@link org.objectweb.fractal.api.factory.Factory#getFcContentDesc()} */ public Object getFcContentDesc() { return null; } /** * see {@link org.objectweb.fractal.api.factory.Factory#getFcControllerDesc()} */ public Object getFcControllerDesc() { return null; } /** * see {@link org.objectweb.fractal.api.factory.Factory#getFcInstanceType()} */ public Type getFcInstanceType() { return null; } /** * see {@link org.objectweb.fractal.api.factory.Factory#newFcInstance()} */ public Component newFcInstance() throws InstantiationException { return this; } }
package net.i2p.heartbeat; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; import net.i2p.data.DataFormatException; import net.i2p.data.Destination; import net.i2p.util.Log; /** * Define the configuration for testing against one particular peer as a client */ public class ClientConfig { private static final Log _log = new Log(ClientConfig.class); private Destination _peer; private Destination _us; private String _statFile; private int _statDuration; private int _statFrequency; private int _sendFrequency; private int _sendSize; private int _numHops; private String _comment; private int _averagePeriods[]; /** * @see ClientConfig#load * @see ClientConfig#store */ public static final String PROP_PREFIX = "peer."; /** * @see ClientConfig#load * @see ClientConfig#store */ public static final String PROP_PEER = ".peer"; /** * @see ClientConfig#load * @see ClientConfig#store */ public static final String PROP_STATFILE = ".statFile"; /** * @see ClientConfig#load * @see ClientConfig#store */ public static final String PROP_STATDURATION = ".statDuration"; /** * @see ClientConfig#load * @see ClientConfig#store */ public static final String PROP_STATFREQUENCY = ".statFrequency"; /** * @see ClientConfig#load * @see ClientConfig#store */ public static final String PROP_SENDFREQUENCY = ".sendFrequency"; /** * @see ClientConfig#load * @see ClientConfig#store */ public static final String PROP_SENDSIZE = ".sendSize"; /** * @see ClientConfig#load * @see ClientConfig#store */ public static final String PROP_COMMENT = ".comment"; /** * @see ClientConfig#load * @see ClientConfig#store */ public static final String PROP_AVERAGEPERIODS = ".averagePeriods"; /** * Default constructor... */ public ClientConfig() { this(null, null, null, -1, -1, -1, -1, 0, null, null); } /** * @param peer who we will test against * @param us who we are * @param statFile the file to save stats to * @param duration how many minutes to keep events for * @param statFreq how often to write out stats * @param sendFreq how often to send pings * @param sendSize how large the pings should be * @param numHops how many hops is the current Heartbeat app using * @param comment describe this test * @param averagePeriods list of minutes to summarize over */ public ClientConfig(Destination peer, Destination us, String statFile, int duration, int statFreq, int sendFreq, int sendSize, int numHops, String comment, int averagePeriods[]) { _peer = peer; _us = us; _statFile = statFile; _statDuration = duration; _statFrequency = statFreq; _sendFrequency = sendFreq; _sendSize = sendSize; _numHops = numHops; _comment = comment; _averagePeriods = averagePeriods; } /** * Retrieves the peer to test against * * @return the Destination (peer) */ public Destination getPeer() { return _peer; } /** * Sets the peer to test against * * @param peer the Destination (peer) */ public void setPeer(Destination peer) { _peer = peer; } /** * Retrieves who we are when we test * * @return the Destination (us) */ public Destination getUs() { return _us; } /** * Sets who we are when we test * * @param us the Destination (us) */ public void setUs(Destination us) { _us = us; } /** * Retrieves the location to write the current stats to * * @return the name of the file */ public String getStatFile() { return _statFile; } /** * Sets the name of the location we write the current stats to * * @param statFile the name of the file */ public void setStatFile(String statFile) { _statFile = statFile; } /** * Retrieves how many minutes of statistics should be maintained within the * window for this client * * @return the number of minutes */ public int getStatDuration() { return _statDuration; } /** * Sets how many minutes of statistics should be maintained within the * window for this client * * @param durationMinutes the number of minutes */ public void setStatDuration(int durationMinutes) { _statDuration = durationMinutes; } /** * Retrieves how frequently the stats are written out (in seconds) * * @return the frequency in seconds */ public int getStatFrequency() { return _statFrequency; } /** * Sets how frequently the stats are written out (in seconds) * * @param freqSeconds the frequency in seconds */ public void setStatFrequency(int freqSeconds) { _statFrequency = freqSeconds; } /** * Retrieves how frequenty we send messages to the peer (in seconds) * * @return the frequency in seconds */ public int getSendFrequency() { return _sendFrequency; } /** * Sets how frequenty we send messages to the peer (in seconds) * * @param freqSeconds the frequency in seconds */ public void setSendFrequency(int freqSeconds) { _sendFrequency = freqSeconds; } /** * Retrieves how many bytes the ping messages should be (min values ~700, * max ~32KB) * * @return the size in bytes */ public int getSendSize() { return _sendSize; } /** * Sets how many bytes the ping messages should be (min values ~700, max * ~32KB) * * @param numBytes the size in bytes */ public void setSendSize(int numBytes) { _sendSize = numBytes; } /** * Retrieves the brief, 1 line description of the test. Useful comments are * along the lines of "The peer is located on a fast router and connection * with 2 hop tunnels". * * @return the brief comment */ public String getComment() { return _comment; } /** * Sets a brief, 1 line description (comment) of the test. * * @param comment the brief comment */ public void setComment(String comment) { _comment = comment; } /** * Retrieves the periods that the client's tests should be averaged over. * * @return list of periods (in minutes) that the data should be averaged * over, or null */ public int[] getAveragePeriods() { return _averagePeriods; } /** * Sets the periods that the client's tests should be averaged over. * * @param periods the list of periods (in minutes) that the data should be * averaged over, or null */ public void setAveragePeriods(int periods[]) { _averagePeriods = periods; } /** * Retrieves how many hops this test engine is configured to use for its * outbound and inbound tunnels * * @return the number of hops */ public int getNumHops() { return _numHops; } /** * Sets how many hops this test engine is configured to use for its outbound * and inbound tunnels * * @param numHops the number of hops */ public void setNumHops(int numHops) { _numHops = numHops; } /** * Load the client config from the properties specified, deriving the * current config entry from the peer number. * * @param clientConfig the properties to load from * @param peerNum the number associated with the peer * @return true if it was loaded correctly, false if there were errors */ public boolean load(Properties clientConfig, int peerNum) { if ((clientConfig == null) || (peerNum < 0)) return false; String peerVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_PEER); String statFileVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_STATFILE); String statDurationVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_STATDURATION); String statFrequencyVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_STATFREQUENCY); String sendFrequencyVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_SENDFREQUENCY); String sendSizeVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_SENDSIZE); String commentVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_COMMENT); String periodsVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_AVERAGEPERIODS); if ((peerVal == null) || (statFileVal == null) || (statDurationVal == null) || (statFrequencyVal == null) || (sendFrequencyVal == null) || (sendSizeVal == null)) { if (_log.shouldLog(Log.DEBUG)) { _log.debug("Peer number " + peerNum + " does not exist"); } return false; } try { int duration = getInt(statDurationVal); int statFreq = getInt(statFrequencyVal); int sendFreq = getInt(sendFrequencyVal); int sendSize = getInt(sendSizeVal); if ((duration <= 0) || (statFreq <= 0) || (sendFreq <= 0) || (sendSize <= 0)) { if (_log.shouldLog(Log.WARN)) { _log.warn("Invalid client config: duration [" + statDurationVal + "] stat frequency [" + statFrequencyVal + "] send frequency [" + sendFrequencyVal + "] send size [" + sendSizeVal + "]"); } return false; } statFileVal = statFileVal.trim(); if (statFileVal.length() <= 0) { if (_log.shouldLog(Log.WARN)) { _log.warn("Stat file is blank for peer " + peerNum); } return false; } Destination d = new Destination(); d.fromBase64(peerVal); if (commentVal == null) { commentVal = ""; } commentVal = commentVal.trim(); commentVal = commentVal.replace('\n', '_'); List periods = new ArrayList(4); if (periodsVal != null) { StringTokenizer tok = new StringTokenizer(periodsVal); while (tok.hasMoreTokens()) { String periodVal = tok.nextToken(); int minutes = getInt(periodVal); if (minutes > 0) { periods.add(new Integer(minutes)); } } } int avgPeriods[] = new int[periods.size()]; for (int i = 0; i < periods.size(); i++) { avgPeriods[i] = ((Integer) periods.get(i)).intValue(); } _comment = commentVal; _statDuration = duration; _statFrequency = statFreq; _sendFrequency = sendFreq; _sendSize = sendSize; _statFile = statFileVal; _peer = d; _averagePeriods = avgPeriods; return true; } catch (DataFormatException dfe) { _log.error("Peer destination for " + peerNum + " was invalid: " + peerVal); return false; } } /** * Store the client config to the properties specified, deriving the current * config entry from the peer number. * * @param clientConfig the properties to store to * @param peerNum the number associated with the peer * @return true if it was stored correctly, false if there were errors */ public boolean store(Properties clientConfig, int peerNum) { if ((_peer == null) || (_sendFrequency <= 0) || (_sendSize <= 0) || (_statDuration <= 0) || (_statFrequency <= 0) || (_statFile == null)) { return false; } String comment = _comment; if (comment == null) { comment = ""; } comment = comment.trim(); comment = comment.replace('\n', '_'); StringBuffer buf = new StringBuffer(32); if (_averagePeriods != null) { for (int i = 0; i < _averagePeriods.length; i++) { buf.append(_averagePeriods[i]).append(' '); } } clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_PEER, _peer.toBase64()); clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_STATFILE, _statFile); clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_STATDURATION, _statDuration + ""); clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_STATFREQUENCY, _statFrequency + ""); clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_SENDFREQUENCY, _sendFrequency + ""); clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_SENDSIZE, _sendSize + ""); clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_COMMENT, comment); clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_AVERAGEPERIODS, buf.toString()); return true; } private static final int getInt(String val) { if (val == null) return -1; try { int i = Integer.parseInt(val); return i; } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.DEBUG)) { _log.debug("Value [" + val + "] is not a valid integer"); } return -1; } } }
package org.plantuml.idea.toolwindow; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.LowMemoryWatcher; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.ToolWindow; import com.intellij.ui.components.JBScrollPane; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.plantuml.idea.action.NextPageAction; import org.plantuml.idea.action.SelectPageAction; import org.plantuml.idea.lang.settings.PlantUmlSettings; import org.plantuml.idea.rendering.*; import org.plantuml.idea.toolwindow.listener.PlantUmlAncestorListener; import org.plantuml.idea.util.UIUtils; import javax.swing.*; import javax.swing.event.AncestorListener; import java.awt.*; import java.awt.event.*; import java.io.File; import java.util.concurrent.atomic.AtomicInteger; /** * @author Eugene Steinberg */ public class PlantUmlToolWindow extends JPanel implements Disposable { private static Logger logger = Logger.getInstance(PlantUmlToolWindow.class); private ToolWindow toolWindow; private JPanel imagesPanel; private JScrollPane scrollPane; private int zoom = 100; private int selectedPage = -1; private RenderCache renderCache; private AncestorListener plantUmlAncestorListener; private final LazyApplicationPoolExecutor lazyExecutor; private Project project; private AtomicInteger sequence = new AtomicInteger(); public boolean renderUrlLinks; public ExecutionStatusPanel executionStatusPanel; private SelectedPagePersistentStateComponent selectedPagePersistentStateComponent; private FileEditorManager fileEditorManager; private FileDocumentManager fileDocumentManager; private int lastValidVerticalScrollValue; private int lastValidHorizontalScrollValue; public PlantUmlToolWindow(Project project, final ToolWindow toolWindow) { super(new BorderLayout()); this.project = project; this.toolWindow = toolWindow; PlantUmlSettings settings = PlantUmlSettings.getInstance();// Make sure settings are loaded and applied before we start rendering. renderCache = new RenderCache(settings.getCacheSizeAsInt()); selectedPagePersistentStateComponent = ServiceManager.getService(SelectedPagePersistentStateComponent.class); plantUmlAncestorListener = new PlantUmlAncestorListener(this, project); fileEditorManager = FileEditorManager.getInstance(project); fileDocumentManager = FileDocumentManager.getInstance(); setupUI(); lazyExecutor = new LazyApplicationPoolExecutor(settings.getRenderDelayAsInt(), executionStatusPanel); LowMemoryWatcher.register(new Runnable() { @Override public void run() { renderCache.clear(); if (renderCache.getDisplayedItem() != null && !toolWindow.isVisible()) { renderCache.setDisplayedItem(null); imagesPanel.removeAll(); imagesPanel.add(new JLabel("Low memory detected, cache and images cleared. Go to PlantUML plugin settings and set lower cache size, or increase IDE heap size (-Xmx).")); imagesPanel.revalidate(); imagesPanel.repaint(); } } }, this); //must be last this.toolWindow.getComponent().addAncestorListener(plantUmlAncestorListener); } private void setupUI() { DefaultActionGroup newGroup = getActionGroup(); final ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, newGroup, true); actionToolbar.setTargetComponent(this); add(actionToolbar.getComponent(), BorderLayout.PAGE_START); imagesPanel = new JPanel(); imagesPanel.setLayout(new BoxLayout(imagesPanel, BoxLayout.Y_AXIS)); scrollPane = new JBScrollPane(imagesPanel); scrollPane.getVerticalScrollBar().setUnitIncrement(20); scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent adjustmentEvent) { if (!adjustmentEvent.getValueIsAdjusting()) { RenderCacheItem displayedItem = getDisplayedItem(); if (displayedItem != null && !displayedItem.getRenderResult().hasError()) { lastValidVerticalScrollValue = adjustmentEvent.getValue(); } } } }); scrollPane.getHorizontalScrollBar().addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent adjustmentEvent) { if (!adjustmentEvent.getValueIsAdjusting()) { RenderCacheItem displayedItem = getDisplayedItem(); if (displayedItem != null && !displayedItem.getRenderResult().hasError()) { lastValidHorizontalScrollValue = adjustmentEvent.getValue(); } } } }); imagesPanel.add(new Usage("Usage:\n")); add(scrollPane, BorderLayout.CENTER); addScrollBarListeners(imagesPanel); } @NotNull private DefaultActionGroup getActionGroup() { DefaultActionGroup group = (DefaultActionGroup) ActionManager.getInstance().getAction("PlantUML.Toolbar"); DefaultActionGroup newGroup = new DefaultActionGroup(); AnAction[] childActionsOrStubs = group.getChildActionsOrStubs(); for (int i = 0; i < childActionsOrStubs.length; i++) { AnAction stub = childActionsOrStubs[i]; newGroup.add(stub); if (stub instanceof ActionStub) { if (((ActionStub) stub).getClassName().equals(NextPageAction.class.getName())) { newGroup.add(new SelectPageAction(this)); } } } executionStatusPanel = new ExecutionStatusPanel(); newGroup.add(executionStatusPanel); return newGroup; } private void addScrollBarListeners(JComponent panel) { panel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { if (e.isControlDown()) { setZoom(Math.max(getZoom() - e.getWheelRotation() * 10, 1)); } else { e.setSource(scrollPane); scrollPane.dispatchEvent(e); } } }); panel.addMouseMotionListener(new MouseMotionListener() { private int x, y; @Override public void mouseDragged(MouseEvent e) { JScrollBar h = scrollPane.getHorizontalScrollBar(); JScrollBar v = scrollPane.getVerticalScrollBar(); int dx = x - e.getXOnScreen(); int dy = y - e.getYOnScreen(); h.setValue(h.getValue() + dx); v.setValue(v.getValue() + dy); x = e.getXOnScreen(); y = e.getYOnScreen(); } @Override public void mouseMoved(MouseEvent e) { x = e.getXOnScreen(); y = e.getYOnScreen(); } }); } @Override public void dispose() { logger.debug("dispose"); toolWindow.getComponent().removeAncestorListener(plantUmlAncestorListener); } public void renderLater(final LazyApplicationPoolExecutor.Delay delay, final RenderCommand.Reason reason) { logger.debug("renderLater ", project.getName(), " ", delay); ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { if (isProjectValid(project)) { final String source = UIUtils.getSelectedSourceWithCaret(fileEditorManager); if ("".equals(source)) { //is included file or some crap? logger.debug("empty source"); VirtualFile selectedFile = UIUtils.getSelectedFile(fileEditorManager, fileDocumentManager); RenderCacheItem last = renderCache.getDisplayedItem(); //todo check all items for included file? // if (last != null && reason == RenderCommand.Reason.FILE_SWITCHED) { // selectedPage = selectedPagePersistentStateComponent.getPage(last.getSourceFilePath()); // logger.debug("file switched, setting selected page ",selectedPage); if (last != null && reason == RenderCommand.Reason.REFRESH) { logger.debug("empty source, executing command, reason=", reason); lazyExecutor.execute(getCommand(RenderCommand.Reason.REFRESH, last.getSourceFilePath(), last.getSource(), last.getBaseDir(), selectedPage, zoom, null, delay)); } if (last != null && reason == RenderCommand.Reason.SOURCE_PAGE_ZOOM) { logger.debug("empty source, executing command, reason=", reason); lazyExecutor.execute(getCommand(RenderCommand.Reason.SOURCE_PAGE_ZOOM, last.getSourceFilePath(), last.getSource(), last.getBaseDir(), selectedPage, zoom, null, delay)); } if (last != null && last.isIncludedFile(selectedFile)) { logger.debug("include file selected"); if (last.isIncludedFileChanged(selectedFile, fileDocumentManager)) { logger.debug("includes changed, executing command"); lazyExecutor.execute(getCommand(RenderCommand.Reason.INCLUDES, last.getSourceFilePath(), last.getSource(), last.getBaseDir(), selectedPage, zoom, last, delay)); } else if (last.renderRequired(selectedPage, zoom, fileEditorManager, fileDocumentManager)) { logger.debug("render required"); lazyExecutor.execute(getCommand(RenderCommand.Reason.SOURCE_PAGE_ZOOM, last.getSourceFilePath(), last.getSource(), last.getBaseDir(), selectedPage, zoom, last, delay)); } else { logger.debug("include file, not changed"); } } else if (last != null && !renderCache.isDisplayed(last, selectedPage)) { logger.debug("empty source, not include file, displaying cached item ", last); displayExistingDiagram(last); } else { logger.debug("nothing needed"); } return; } String sourceFilePath = UIUtils.getSelectedFile(fileEditorManager, fileDocumentManager).getPath(); selectedPage = selectedPagePersistentStateComponent.getPage(sourceFilePath); logger.debug("setting selected page from storage ", selectedPage); if (reason == RenderCommand.Reason.REFRESH) { logger.debug("executing command, reason=", reason); final File selectedDir = UIUtils.getSelectedDir(fileEditorManager, fileDocumentManager); lazyExecutor.execute(getCommand(RenderCommand.Reason.REFRESH, sourceFilePath, source, selectedDir, selectedPage, zoom, null, delay)); return; } RenderCacheItem cachedItem = renderCache.getCachedItem(sourceFilePath, source, selectedPage, zoom, fileEditorManager, fileDocumentManager); if (cachedItem == null || cachedItem.renderRequired(source, selectedPage, fileEditorManager, fileDocumentManager)) { logger.debug("render required"); final File selectedDir = UIUtils.getSelectedDir(fileEditorManager, fileDocumentManager); lazyExecutor.execute(getCommand(RenderCommand.Reason.SOURCE_PAGE_ZOOM, sourceFilePath, source, selectedDir, selectedPage, zoom, cachedItem, delay)); } else if (!renderCache.isDisplayed(cachedItem, selectedPage)) { logger.debug("render not required, displaying cached item ", cachedItem); displayExistingDiagram(cachedItem); } else { logger.debug("render not required, item already displayed ", cachedItem); if (reason != RenderCommand.Reason.CARET) { cachedItem.setVersion(sequence.incrementAndGet()); lazyExecutor.cancel(); executionStatusPanel.updateNow(cachedItem.getVersion(), ExecutionStatusPanel.State.DONE, "cached"); } } } } }); } public void displayExistingDiagram(RenderCacheItem last) { last.setVersion(sequence.incrementAndGet()); last.setRequestedPage(selectedPage); executionStatusPanel.updateNow(last.getVersion(), ExecutionStatusPanel.State.DONE, "cached"); displayDiagram(last); } @NotNull protected RenderCommand getCommand(RenderCommand.Reason reason, String selectedFile, final String source, @Nullable final File baseDir, final int page, final int zoom, RenderCacheItem cachedItem, LazyApplicationPoolExecutor.Delay delay) { logger.debug("#getCommand selectedFile='", selectedFile, "', baseDir=", baseDir, ", page=", page, ", zoom=", zoom); int version = sequence.incrementAndGet(); return new MyRenderCommand(reason, selectedFile, source, baseDir, page, zoom, cachedItem, version, delay, renderUrlLinks, executionStatusPanel); } private class MyRenderCommand extends RenderCommand { public MyRenderCommand(Reason reason, String selectedFile, String source, File baseDir, int page, int zoom, RenderCacheItem cachedItem, int version, LazyApplicationPoolExecutor.Delay delay, boolean renderUrlLinks, ExecutionStatusPanel label) { super(reason, selectedFile, source, baseDir, page, zoom, cachedItem, version, renderUrlLinks, delay, label); } @Override public void postRenderOnEDT(RenderCacheItem newItem, long total, RenderResult result) { if (reason == Reason.REFRESH) { if (cachedItem != null) { renderCache.removeFromCache(cachedItem); } } if (!newItem.getRenderResult().hasError()) { renderCache.addToCache(newItem); } logger.debug("displaying item ", newItem); if (displayDiagram(newItem)) { executionStatusPanel.updateNow(newItem.getVersion(), ExecutionStatusPanel.State.DONE, total, result); } } } public boolean displayDiagram(RenderCacheItem cacheItem) { if (renderCache.isOlderRequest(cacheItem)) { //ctrl+z with cached image vs older request in progress logger.debug("skipping displaying older result", cacheItem); return false; } //maybe track position per file? RenderCacheItem displayedItem = renderCache.getDisplayedItem(); boolean restoreScrollPosition = displayedItem != null && displayedItem.getRenderResult().hasError() && renderCache.isSameFile(cacheItem); //must be before revalidate int lastValidVerticalScrollValue = this.lastValidVerticalScrollValue; int lastValidHorizontalScrollValue = this.lastValidHorizontalScrollValue; renderCache.setDisplayedItem(cacheItem); ImageItem[] imagesWithData = cacheItem.getImageItems(); RenderResult imageResult = cacheItem.getRenderResult(); int requestedPage = cacheItem.getRequestedPage(); if (requestedPage >= imageResult.getPages()) { logger.debug("requestedPage >= imageResult.getPages()", requestedPage, ">=", imageResult.getPages()); requestedPage = -1; if (!imageResult.hasError()) { logger.debug("toolWindow.page=", requestedPage, " (previously page=", selectedPage, ")"); selectedPage = requestedPage; } } imagesPanel.removeAll(); if (requestedPage == -1) { logger.debug("displaying images ", requestedPage); for (int i = 0; i < imagesWithData.length; i++) { displayImage(cacheItem, i, imagesWithData[i]); } } else { logger.debug("displaying image ", requestedPage); displayImage(cacheItem, requestedPage, imagesWithData[requestedPage]); } imagesPanel.revalidate(); imagesPanel.repaint(); //would be nice without a new event :( if (restoreScrollPosition) { //hope concurrency wont be an issue SwingUtilities.invokeLater(new Runnable() { public void run() { scrollPane.getVerticalScrollBar().setValue(lastValidVerticalScrollValue); scrollPane.getHorizontalScrollBar().setValue(lastValidHorizontalScrollValue); } }); } return true; } public void displayImage(RenderCacheItem cacheItem, int pageNumber, ImageItem imageWithData) { if (imageWithData == null) { throw new RuntimeException("trying to display null image. selectedPage=" + selectedPage + ", nullPage=" + pageNumber + ", cacheItem=" + cacheItem); } PlantUmlImageLabel label = new PlantUmlImageLabel(imageWithData, pageNumber, cacheItem.getRenderRequest()); addScrollBarListeners(label); if (pageNumber != 0 && imagesPanel.getComponentCount() > 0) { imagesPanel.add(separator()); } imagesPanel.add(label); } public void applyNewSettings(PlantUmlSettings plantUmlSettings) { lazyExecutor.setDelay(plantUmlSettings.getRenderDelayAsInt()); renderCache.setMaxCacheSize(plantUmlSettings.getCacheSizeAsInt()); renderUrlLinks = plantUmlSettings.isRenderUrlLinks(); } private JSeparator separator() { JSeparator separator = new JSeparator(SwingConstants.HORIZONTAL); Dimension size = new Dimension(separator.getPreferredSize().width, 10); separator.setVisible(true); separator.setMaximumSize(size); separator.setPreferredSize(size); return separator; } public int getZoom() { return zoom; } public void setZoom(int zoom) { this.zoom = zoom; renderLater(LazyApplicationPoolExecutor.Delay.POST_DELAY, RenderCommand.Reason.SOURCE_PAGE_ZOOM); } public void setSelectedPage(int selectedPage) { if (selectedPage >= -1 && selectedPage < getNumPages()) { logger.debug("page ", selectedPage, " selected"); this.selectedPage = selectedPage; selectedPagePersistentStateComponent.setPage(selectedPage, renderCache.getDisplayedItem()); renderLater(LazyApplicationPoolExecutor.Delay.POST_DELAY, RenderCommand.Reason.SOURCE_PAGE_ZOOM); } } public void nextPage() { setSelectedPage(this.selectedPage + 1); } public void prevPage() { setSelectedPage(this.selectedPage - 1); } public int getNumPages() { int pages = -1; RenderCacheItem last = renderCache.getDisplayedItem(); if (last != null) { RenderResult imageResult = last.getRenderResult(); if (imageResult != null) { pages = imageResult.getPages(); } } return pages; } public int getSelectedPage() { return selectedPage; } public RenderCacheItem getDisplayedItem() { return renderCache.getDisplayedItem(); } private boolean isProjectValid(Project project) { return project != null && !project.isDisposed(); } public JPanel getImagesPanel() { return imagesPanel; } }
package org.usfirst.frc2832.Robot_2016; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.ByteBuffer; import java.util.ArrayDeque; import java.util.Deque; import com.ni.vision.NIVision; import com.ni.vision.NIVision.FlipAxis; import com.ni.vision.NIVision.Image; import com.ni.vision.NIVision.RawData; import com.ni.vision.VisionException; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.vision.USBCamera; /* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ // replicates CameraServer.cpp in java lib public class CameraServer2832 { private static final int kPort = 1180; private static final byte[] kMagicNumber = {0x01, 0x00, 0x00, 0x00}; private static final int kSize640x480 = 0; private static final int kSize320x240 = 1; private static final int kSize160x120 = 2; private static final int kHardwareCompression = -1; private static final String kDefaultCameraName = "cam1"; private static final int kMaxImageSize = 200000; private boolean flipped; private static CameraServer2832 server; public static CameraServer2832 getInstance() { if (server == null) { server = new CameraServer2832(); } return server; } private Thread serverThread; private int m_quality; private boolean m_autoCaptureStarted; private boolean m_hwClient = true; private USBCamera m_camera[]; private int selectedCamera = 0; private CameraData m_imageData; private Deque<ByteBuffer> m_imageDataPool; private long lastSwitch; private class CameraData { RawData data; int start; public CameraData(RawData d, int s) { data = d; start = s; } } private CameraServer2832() { m_quality = 50; m_camera = null; m_imageData = null; m_imageDataPool = new ArrayDeque<>(3); for (int i = 0; i < 3; i++) { m_imageDataPool.addLast(ByteBuffer.allocateDirect(kMaxImageSize)); } serverThread = new Thread(new Runnable() { public void run() { try { serve(); } catch (IOException e) { // do stuff here } catch (InterruptedException e) { // do stuff here } } }); serverThread.setName("CameraServer Send Thread"); serverThread.start(); } private synchronized void setImageData(RawData data, int start) { if (m_imageData != null && m_imageData.data != null) { m_imageData.data.free(); if (m_imageData.data.getBuffer() != null){ m_imageDataPool.addLast(m_imageData.data.getBuffer()); } m_imageData = null; } m_imageData = new CameraData(data, start); notifyAll(); } /** * Manually change the image that is served by the MJPEG stream. This can be * called to pass custom annotated images to the dashboard. Note that, for * 640x480 video, this method could take between 40 and 50 milliseconds to * complete. * * This shouldn't be called if {@link #startAutomaticCapture} is called. * * @param image The IMAQ image to show on the dashboard */ public void flip(){ flipped = !flipped; } public void setImage(Image image) { // handle multi-threadedness /* Flatten the IMAQ image to a JPEG */ if(flipped){ Image flippedImage = null; NIVision.imaqFlip(flippedImage, image, FlipAxis.HORIZONTAL_AXIS); image = flippedImage; } RawData data = NIVision.imaqFlatten(image, NIVision.FlattenType.FLATTEN_IMAGE, NIVision.CompressionType.COMPRESSION_JPEG, 10 * m_quality); ByteBuffer buffer = data.getBuffer(); boolean hwClient; synchronized (this) { hwClient = m_hwClient; } /* Find the start of the JPEG data */ int index = 0; if (hwClient) { while (index < buffer.limit() - 1) { if ((buffer.get(index) & 0xff) == 0xFF && (buffer.get(index + 1) & 0xff) == 0xD8) break; index++; } } if (buffer.limit() - index - 1 <= 2) { throw new VisionException("data size of flattened image is less than 2. Try another camera! "); } setImageData(data, index); } /** * Start automatically capturing images to send to the dashboard. You should * call this method to just see a camera feed on the dashboard without doing * any vision processing on the roboRIO. {@link #setImage} shouldn't be called * after this is called. This overload calles * {@link #startAutomaticCapture(String)} with the default camera name */ public void startAutomaticCapture() { startAutomaticCapture(USBCamera.kDefaultCameraName); } /** * Start automatically capturing images to send to the dashboard. * * You should call this method to just see a camera feed on the dashboard * without doing any vision processing on the roboRIO. {@link #setImage} * shouldn't be called after this is called. * * @param cameraName The name of the camera interface (e.g. "cam1") */ public void startAutomaticCapture(String cameraName) { try { USBCamera camera = new USBCamera(cameraName); camera.openCamera(); startAutomaticCapture(camera); } catch (VisionException ex) { DriverStation.reportError( "Error when starting the camera: " + cameraName + " " + ex.getMessage(), true); } } public synchronized void startAutomaticCapture(USBCamera... camera) { if (m_autoCaptureStarted) return; m_autoCaptureStarted = true; m_camera = camera; m_camera[selectedCamera].startCapture(); Thread captureThread = new Thread(new Runnable() { @Override public void run() { capture(); } }); captureThread.setName("Camera Capture Thread"); captureThread.start(); } protected void capture() { Image frame = NIVision.imaqCreateImage(NIVision.ImageType.IMAGE_RGB, 0); while (true) { boolean hwClient; ByteBuffer dataBuffer = null; synchronized (this) { hwClient = m_hwClient; if (hwClient) { dataBuffer = m_imageDataPool.removeLast(); } } try { if (hwClient && dataBuffer != null) { // Reset the image buffer limit dataBuffer.limit(dataBuffer.capacity() - 1); m_camera[selectedCamera].getImageData(dataBuffer); setImageData(new RawData(dataBuffer), 0); } else { m_camera[selectedCamera].getImage(frame); setImage(frame); } } catch (VisionException ex) { DriverStation.reportError("Error when getting image from the camera: " + ex.getMessage(), true); if (dataBuffer != null) { synchronized (this) { m_imageDataPool.addLast(dataBuffer); Timer.delay(.1); } } } } } public void setSelectedCamera(int id) { if (lastSwitch + 2500 > System.currentTimeMillis()) return; if (selectedCamera != id && id >= 0 && id < m_camera.length) { try { m_camera[selectedCamera].stopCapture(); m_camera[id].startCapture(); selectedCamera = id; } catch (VisionException e) { DriverStation.reportError("A camera was unplugged.", true); } lastSwitch = System.currentTimeMillis(); } } /** * check if auto capture is started * */ public synchronized boolean isAutoCaptureStarted() { return m_autoCaptureStarted; } /** * Sets the size of the image to use. Use the public kSize constants to set * the correct mode, or set it directory on a camera and call the appropriate * autoCapture method *$ * @param size The size to use */ public synchronized void setSize(int size, int camID) { if (m_camera[camID] == null) return; switch (size) { case kSize640x480: m_camera[camID].setSize(640, 480); break; case kSize320x240: m_camera[camID].setSize(320, 240); break; case kSize160x120: m_camera[camID].setSize(160, 120); break; } } /** * Set the quality of the compressed image sent to the dashboard * * @param quality The quality of the JPEG image, from 0 to 100 */ public synchronized void setQuality(int quality) { m_quality = quality > 100 ? 100 : quality < 0 ? 0 : quality; } /** * Get the quality of the compressed image sent to the dashboard * * @return The quality, from 0 to 100 */ public synchronized int getQuality() { return m_quality; } /** * Run the M-JPEG server. * * This function listens for a connection from the dashboard in a background * thread, then sends back the M-JPEG stream. * * @throws IOException if the Socket connection fails * @throws InterruptedException if the sleep is interrupted */ protected void serve() throws IOException, InterruptedException { ServerSocket socket = new ServerSocket(); socket.setReuseAddress(true); InetSocketAddress address = new InetSocketAddress(kPort); socket.bind(address); while (true) { try { Socket s = socket.accept(); DataInputStream is = new DataInputStream(s.getInputStream()); DataOutputStream os = new DataOutputStream(s.getOutputStream()); int fps = is.readInt(); int compression = is.readInt(); int size = is.readInt(); if (compression != kHardwareCompression) { DriverStation.reportError("Choose \"USB Camera HW\" on the dashboard", false); s.close(); continue; } // Wait for the camera synchronized (this) { System.out.println("Camera not yet ready, awaiting image"); if (m_camera[selectedCamera] == null) wait(); m_hwClient = compression == kHardwareCompression; if (!m_hwClient) setQuality(100 - compression); else if (m_camera[selectedCamera] != null) m_camera[selectedCamera].setFPS(fps); setSize(size, selectedCamera); } long period = (long) (1000 / (1.0 * fps)); while (true) { long t0 = System.currentTimeMillis(); CameraData imageData = null; synchronized (this) { wait(); imageData = m_imageData; m_imageData = null; } if (imageData == null) continue; // Set the buffer position to the start of the data, // and then create a new wrapper for the data at // exactly that position imageData.data.getBuffer().position(imageData.start); byte[] imageArray = new byte[imageData.data.getBuffer().remaining()]; imageData.data.getBuffer().get(imageArray, 0, imageData.data.getBuffer().remaining()); // write numbers try { os.write(kMagicNumber); os.writeInt(imageArray.length); os.write(imageArray); os.flush(); long dt = System.currentTimeMillis() - t0; if (dt < period) { Thread.sleep(period - dt); } } catch (IOException | UnsupportedOperationException ex) { DriverStation.reportError(ex.getMessage(), true); break; } finally { imageData.data.free(); if (imageData.data.getBuffer() != null) { synchronized (this) { m_imageDataPool.addLast(imageData.data.getBuffer()); } } } } } catch (IOException ex) { DriverStation.reportError(ex.getMessage(), true); continue; } } } }
package org.jgroups.tests; import org.jgroups.Global; import org.jgroups.JChannel; import org.jgroups.blocks.ReplicatedHashMap; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Test methods for ReplicatedHashMap * @author Bela Ban */ @Test(groups={Global.STACK_DEPENDENT,Global.EAP_EXCLUDED},singleThreaded=true) public class ReplicatedHashMapTest extends ChannelTestBase { private ReplicatedHashMap<String,String> map1; private ReplicatedHashMap<String,String> map2; private ConcurrentHashMap<String,String> wrap=new ConcurrentHashMap<>(); @BeforeClass protected void setUp() throws Exception { //channel_conf = "tcp.xml"; JChannel c1=createChannel(true, 2); this.map1=new ReplicatedHashMap<>(c1); map1.setBlockingUpdates(true); c1.connect("ReplicatedHashMapTest"); this.map1.start(5000); JChannel c2=createChannel(c1); this.map2=new ReplicatedHashMap<>(wrap, c2); map2.setBlockingUpdates(true); c2.connect("ReplicatedHashMapTest"); this.map2.start(5000); } @AfterMethod protected void clean() { map1.clear(); map2.clear(); } @AfterClass protected void tearDown() throws Exception { this.map1.stop(); this.map2.stop(); } public void testEqualsEtc() { map1.put("key1", "value1"); assertEquals(this.map1, this.map2); Assert.assertEquals(this.map1.hashCode(), this.map2.hashCode()); Assert.assertEquals(this.map1.toString(), this.map2.toString()); assertEquals(this.wrap, this.map1); } public void testSize() { Assert.assertEquals(0, this.map1.size()); Assert.assertEquals(this.map2.size(), this.map1.size()); this.map1.put("key1", "value1"); Assert.assertEquals(1, this.map1.size()); Assert.assertEquals(this.map2.size(), this.map1.size()); this.map2.put("key2", "value2"); Assert.assertEquals(2, this.map1.size()); Assert.assertEquals(this.map2.size(), this.map1.size()); } public void testIsEmpty() { assertTrue(this.map1.isEmpty()); assertTrue(this.map2.isEmpty()); this.map1.put("key", "value"); assertFalse(this.map1.isEmpty()); assertFalse(this.map2.isEmpty()); } public void testContainsKey() { assertFalse(this.map1.containsKey("key1")); assertFalse(this.map2.containsKey("key1")); this.map1.put("key1", "value"); assertTrue(this.map1.containsKey("key1")); assertTrue(this.map2.containsKey("key1")); this.map2.put("key2", "value"); assertTrue(this.map1.containsKey("key2")); assertTrue(this.map2.containsKey("key2")); } public void testContainsValue() { assertFalse(this.map1.containsValue("value1")); assertFalse(this.map2.containsValue("value1")); this.map1.put("key1", "value1"); assertTrue(this.map1.containsValue("value1")); assertTrue(this.map2.containsValue("value1")); this.map2.put("key2", "value2"); assertTrue(this.map1.containsValue("value2")); assertTrue(this.map2.containsValue("value2")); } public void testPutAndGet() { assert this.map1.get("key1") == null; assert this.map2.get("key1") == null; this.map1.put("key1", "value1"); assertNotNull(this.map1.get("key1")); assertNotNull(this.map2.get("key1")); this.map2.put("key2", "value2"); assertNotNull(this.map1.get("key2")); assertNotNull(this.map2.get("key2")); } public void testPutIfAbsent() { String retval=map1.putIfAbsent("name", "Bela"); assert retval == null; retval=map1.putIfAbsent("name", "Michelle"); assertNotNull(retval); Assert.assertEquals("Bela", retval); Assert.assertEquals("Bela", map1.get("name")); Assert.assertEquals("Bela", map2.get("name")); } public void testRemove() { assert this.map1.get("key1") == null; assert this.map2.get("key1") == null; this.map1.put("key1", "value1"); this.map2.put("key2", "value2"); assertNotNull(this.map1.get("key1")); assertNotNull(this.map2.get("key1")); assertNotNull(this.map1.get("key2")); assertNotNull(this.map2.get("key2")); this.map1.remove("key1"); assert this.map1.get("key1") == null; assert this.map2.get("key1") == null; assertNotNull(this.map1.get("key2")); assertNotNull(this.map2.get("key2")); this.map2.remove("key2"); assert this.map1.get("key2") == null; assert this.map2.get("key2") == null; } public void testRemove2() { map1.put("name", "Bela"); map1.put("id", "322649"); System.out.println("map1: " + map1); boolean removed=map1.remove("id", "322000"); assertFalse(removed); assertTrue(map1.containsKey("id")); removed=map1.remove("id", "322649"); System.out.println("map1: " + map1); assertTrue(removed); assertFalse(map1.containsKey("id")); Assert.assertEquals(1, map2.size()); } public void testReplace() { map1.put("name", "Bela"); map1.put("id", "322649"); System.out.println("map1: " + map1); String val=map1.replace("id2", "322000"); Assert.assertEquals(2, map1.size()); assert map1.get("id2") == null; System.out.println("map1: " + map1); assert val == null; val=map1.replace("id", "322000"); System.out.println("map1: " + map1); assertNotNull(val); Assert.assertEquals("322649", val); Assert.assertEquals("322000", map1.get("id")); Assert.assertEquals("322000", map2.get("id")); } public void testReplace2() { map1.put("name", "Bela"); map1.put("id", "322649"); System.out.println("map1: " + map1); boolean replaced=map1.replace("id", "322000", "1"); assertFalse(replaced); Assert.assertEquals("322649", map1.get("id")); replaced=map1.replace("id", "322649", "1"); assertTrue(replaced); Assert.assertEquals("1", map1.get("id")); } public void testPutAll() { Map<String,String> all1=new HashMap<>(); all1.put("key1", "value1"); all1.put("key2", "value2"); Map<String,String> all2=new HashMap<>(); all2.put("key3", "value3"); all2.put("key4", "value4"); this.map1.putAll(all1); Assert.assertEquals(2, this.map1.size()); Assert.assertEquals(2, this.map2.size()); this.map2.putAll(all2); Assert.assertEquals(4, this.map1.size()); Assert.assertEquals(4, this.map2.size()); assertTrue(this.map1.containsKey("key1")); assertTrue(this.map1.containsKey("key2")); assertTrue(this.map1.containsKey("key3")); assertTrue(this.map1.containsKey("key4")); assertTrue(this.map2.containsKey("key1")); assertTrue(this.map2.containsKey("key2")); assertTrue(this.map2.containsKey("key3")); assertTrue(this.map2.containsKey("key4")); } public void testClear() { assertTrue(this.map1.isEmpty()); assertTrue(this.map2.isEmpty()); this.map1.put("key", "value"); assertFalse(this.map1.isEmpty()); assertFalse(this.map2.isEmpty()); this.map1.clear(); assertTrue(this.map1.isEmpty()); assertTrue(this.map2.isEmpty()); this.map2.put("key", "value"); assertFalse(this.map1.isEmpty()); assertFalse(this.map2.isEmpty()); this.map2.clear(); assertTrue(this.map1.isEmpty()); assertTrue(this.map2.isEmpty()); } public void testKeySet() { Map<String,String> all1=new HashMap<>(); all1.put("key1", "value1"); all1.put("key2", "value2"); Map<String,String> all2=new HashMap<>(); all2.put("key3", "value3"); all2.put("key4", "value4"); this.map1.putAll(all1); assertEquals(all1.keySet(), this.map1.keySet()); assertEquals(all1.keySet(), this.map2.keySet()); this.map2.putAll(all2); all1.putAll(all2); assertEquals(all1.keySet(), this.map1.keySet()); assertEquals(all1.keySet(), this.map2.keySet()); } public void testKeySet_mutate() { Map<String,String> all1=new HashMap<>(); all1.put("key1", "value1"); all1.put("key2", "value2"); Map<String,String> all2=new HashMap<>(); all2.put("key3", "value3"); all2.put("key4", "value4"); this.map1.putAll(all1); assertEquals(all1.keySet(), this.map1.keySet()); assertEquals(all1.keySet(), this.map2.keySet()); this.map2.putAll(all2); this.map1.keySet().retainAll(all1.keySet()); assertEquals(all1.keySet(), this.map1.keySet()); assertEquals(all1.keySet(), this.map2.keySet()); } public void testValues() { Map<String,String> all1=new HashMap<>(); all1.put("key1", "value1"); all1.put("key2", "value2"); Map<String,String> all2=new HashMap<>(); all2.put("key3", "value3"); all2.put("key4", "value4"); this.map1.putAll(all1); assertTrue(this.map1.values().containsAll(all1.values())); assertTrue(this.map2.values().containsAll(all1.values())); this.map2.putAll(all2); all1.putAll(all2); assertTrue(this.map1.values().containsAll(all1.values())); assertTrue(this.map2.values().containsAll(all1.values())); } public void testValuesClear() { Map<String,String> all1=new HashMap<>(); all1.put("key1", "value1"); all1.put("key2", "value2"); this.map1.putAll(all1); assertTrue(this.map1.values().containsAll(all1.values())); assertTrue(this.map2.values().containsAll(all1.values())); this.map2.values().clear(); assertTrue(map2.isEmpty()); assertTrue(this.map1.isEmpty()); } }
public class BinaryHeap { int[] h; int size; public BinaryHeap(int n) { h = new int[n]; } // build heap in O(n) public BinaryHeap(int[] keys) { h = keys.clone(); size = keys.length; for (int pos = size / 2 - 1; pos >= 0; pos moveDown(pos); } } public void add(int node) { h[size++] = node; moveUp(h[size - 1]); } public int remove() { int removed = h[0]; h[0] = h[--size]; moveDown(0); return removed; } void moveUp(int pos) { while (pos > 0) { int parent = (pos - 1) / 2; if (h[pos] >= h[parent]) { break; } swap(h, pos, parent); pos = parent; } } void moveDown(int pos) { while (pos < size / 2) { int child = 2 * pos + 1; if (child + 1 < size && h[child] > h[child + 1]) { ++child; } if (h[pos] <= h[child]) { break; } swap(h, pos, child); pos = child; } } static void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; } // Usage example public static void main(String[] args) { BinaryHeap heap = new BinaryHeap(10); heap.add(2); heap.add(5); heap.add(1); // print elements in sorted order while (heap.size > 0) { int x = heap.remove(); System.out.println(x); } } }
package io.spine.protobuf; import com.google.common.base.Charsets; import com.google.common.testing.NullPointerTester; import com.google.protobuf.Any; import com.google.protobuf.BoolValue; import com.google.protobuf.ByteString; import com.google.protobuf.BytesValue; import com.google.protobuf.DoubleValue; import com.google.protobuf.EnumValue; import com.google.protobuf.FloatValue; import com.google.protobuf.Int32Value; import com.google.protobuf.Int64Value; import com.google.protobuf.Message; import com.google.protobuf.StringValue; import com.google.protobuf.UInt32Value; import com.google.protobuf.UInt64Value; import io.spine.test.protobuf.TaskStatus; import io.spine.testing.UtilityClassTest; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import static io.spine.base.Identifier.newUuid; import static io.spine.protobuf.TypeConverter.toMessage; import static io.spine.test.protobuf.TaskStatus.EXECUTING; import static io.spine.test.protobuf.TaskStatus.FAILED; import static io.spine.test.protobuf.TaskStatus.SUCCESS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @DisplayName("TypeConverter utility class should") class TypeConverterTest extends UtilityClassTest<TypeConverter> { TypeConverterTest() { super(TypeConverter.class); } @Override protected void configure(NullPointerTester tester) { super.configure(tester); tester.setDefault(Any.class, Any.getDefaultInstance()); } @Nested @DisplayName("map") class Map { @Test @DisplayName("arbitrary message to itself") void map_arbitrary_message_to_itself() { Message message = StringValue.of(newUuid()); checkMapping(message, message); } @Test @DisplayName("Int32Value to int") void map_Int32Value_to_int() { int rawValue = 42; Message value = Int32Value.of(rawValue); checkMapping(rawValue, value); } @Test @DisplayName("Int64Value to int") void map_Int64Value_to_long() { long rawValue = 42; Message value = Int64Value.of(rawValue); checkMapping(rawValue, value); } @Test @DisplayName("FloatValue to float") void map_FloatValue_to_float() { float rawValue = 42.0f; Message value = FloatValue.of(rawValue); checkMapping(rawValue, value); } @Test @DisplayName("DoubleValue to double") void map_DoubleValue_to_double() { double rawValue = 42.0; Message value = DoubleValue.of(rawValue); checkMapping(rawValue, value); } @Test @DisplayName("BoolValue to boolean") void map_BoolValue_to_boolean() { boolean rawValue = true; Message value = BoolValue.of(rawValue); checkMapping(rawValue, value); } @Test @DisplayName("StringValue to String") void map_StringValue_to_String() { String rawValue = "Hello"; Message value = StringValue.of(rawValue); checkMapping(rawValue, value); } @Test @DisplayName("BytesValue to ByteString") void map_BytesValue_to_ByteString() { ByteString rawValue = ByteString.copyFrom("Hello!", Charsets.UTF_8); Message value = BytesValue.of(rawValue); checkMapping(rawValue, value); } @Test @DisplayName("UInt32 to int") void map_uint32_to_int() { int value = 42; UInt32Value wrapped = UInt32Value.of(value); Any packed = AnyPacker.pack(wrapped); int mapped = TypeConverter.toObject(packed, Integer.class); assertEquals(value, mapped); } @Test @DisplayName("UInt64 to int") void map_uint64_to_long() { long value = 42L; UInt64Value wrapped = UInt64Value.of(value); Any packed = AnyPacker.pack(wrapped); long mapped = TypeConverter.toObject(packed, Long.class); assertEquals(value, mapped); } private void checkMapping(Object javaObject, Message protoObject) { Any wrapped = AnyPacker.pack(protoObject); Object mappedJavaObject = TypeConverter.toObject(wrapped, javaObject.getClass()); assertEquals(javaObject, mappedJavaObject); Any restoredWrapped = TypeConverter.toAny(mappedJavaObject); Message restored = AnyPacker.unpack(restoredWrapped); assertEquals(protoObject, restored); } } @Nested @DisplayName("convert `EnumValue` to `Enum`") class ConvertEnumValueToEnum { @Test @DisplayName("if a `EnumValue` has the enum constant name specified") void ifHasName() { EnumValue value = EnumValue.newBuilder() .setName(SUCCESS.name()) .build(); checkConverts(value, SUCCESS); } @Test @DisplayName("if a `EnumValue` has the enum constant number specified") void ifHasNumber() { EnumValue value = EnumValue.newBuilder() .setNumber(EXECUTING.getNumber()) .build(); checkConverts(value, EXECUTING); } @Test @DisplayName("using the constant name if both the name and the number are specified") void preferringConversionWithName() { // Set the different name and number just for the sake of test. EnumValue value = EnumValue.newBuilder() .setName(SUCCESS.name()) .setNumber(FAILED.getNumber()) .build(); checkConverts(value, SUCCESS); } private void checkConverts(EnumValue enumValue, Enum<?> expected) { Any wrapped = AnyPacker.pack(enumValue); Object mappedJavaObject = TypeConverter.toObject(wrapped, expected.getDeclaringClass()); assertEquals(expected, mappedJavaObject); } } @SuppressWarnings("CheckReturnValue") // The method is called to throw exception. @Test @DisplayName("throw an `IAE` when the `EnumValue` with an unknown number is specified") void throwOnInvalidNumber() { int unknownValue = 156; EnumValue value = EnumValue.newBuilder() .setNumber(unknownValue) .build(); Any wrapped = AnyPacker.pack(value); assertThrows(IllegalArgumentException.class, () -> TypeConverter.toObject(wrapped, TaskStatus.class)); } @SuppressWarnings("CheckReturnValue") // The method is called to throw exception. @Test @Disabled // TODO:2019-12-13:dmytro.kuzmin:WIP Add a fix for this. @DisplayName("throw an `IAE` when converting a non-`EnumValue` object to a `Enum`") void throwOnRawValuesForEnum() { Int32Value enumNumber = Int32Value .newBuilder() .setValue(SUCCESS.getNumber()) .build(); Any packed = AnyPacker.pack(enumNumber); assertThrows(IllegalArgumentException.class, () -> TypeConverter.toObject(packed, TaskStatus.class)); } @Test @DisplayName("convert `Enum` to `EnumValue`") void convertEnumToEnumValue() { Any restoredWrapped = TypeConverter.toAny(SUCCESS); Message restored = AnyPacker.unpack(restoredWrapped); EnumValue expected = EnumValue .newBuilder() .setName(SUCCESS.name()) .setNumber(SUCCESS.getNumber()) .build(); assertEquals(expected, restored); } @Nested @DisplayName("convert") class Convert { @Test @DisplayName("a value to a particular message") void valueToParticularMessage() { String stringValue = "a string value"; StringValue convertedValue = toMessage(stringValue, StringValue.class); assertEquals(stringValue, convertedValue.getValue()); } } }
/** * Searching substring in a string. * * @author Vadim Mironov (multik6292@mail.ru/mironov6292@gmail.ru) * @version $Id$ * @since 0.1 */ package ru.job4j.testtask; /** * Class for searcheing substring in a string. */ public class SubStringClass { /** * Method for searcheing substring in a string. * @param origin - string for searcheing substring * @param sub - substring * @return boolean - is origin contains substring */ public boolean contains(String origin, String sub) { char[] originArray = origin.toCharArray(); char[] subArray = sub.toCharArray(); label: for (int i = 0; i < originArray.length - subArray.length; i++) { if (originArray[i] == subArray[0]) { boolean isContains = true; for (int j = i + 1, t = 1; t < subArray.length; j++, t++) { if (originArray[j] != subArray[t]) { isContains = false; } } if (isContains) { return true; } } } return false; } }
package ru.nivanov; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.TreeSet; class SortUser { /** * Sorting users by age. * @param users .. * @return sorted list by users age. */ Set<User> sort(List<User> users) { TreeSet<User> sortedUsersByAge = new TreeSet<>(); sortedUsersByAge.addAll(users); return sortedUsersByAge; } /** * Sorting by hash code. * @param users .. * @return sorted list. */ List<User> sortHash(List<User> users) { users.sort((userOne, userTwo) -> Integer.valueOf(userOne.hashCode()).compareTo(userTwo.hashCode())); return users; } /** * Sorting by name length. * @param users .. * @return sorted list. */ List<User> sortLength(List<User> users) { users.sort(new Comparator<User>() { @Override public int compare(User userOne, User userTwo) { return Integer.valueOf(userOne.getName().length()).compareTo(userTwo.getName().length()); } }); return users; } }
package com.github.sviperll.text; import java.util.function.Function; /** * Can be used as layout. * <p> * <tt>{@code Layout&lt;Html&gt; }</tt> is supposed to generate * html output. * * @param <T> marks given renderable with it's format * * @author Victor Nazarov &lt;asviraspossible@gmail.com&gt; */ public class Layout<T> implements Layoutable<T> { @SuppressWarnings({"rawtypes", "unchecked"}) private static final Layout CHROMELESS = new Layout(new ChromelessLayoutable()); @SuppressWarnings("unchecked") public static <T> Layout<T> chromeless() { return CHROMELESS; } public static <T> Layout<T> of(Layoutable<T> layoutable) { if (layoutable instanceof Layout) return (Layout<T>)layoutable; else return new Layout<T>(layoutable); } public static <T> Layout<T> of(Function<Appendable, Renderer> header, Function<Appendable, Renderer> footer) { return new Layout<T>(new FunctionLayoutable<T>(header, footer)); } private final Layoutable<T> layoutable; private Layout(Layoutable<T> layoutable) { this.layoutable = layoutable; } @Override public Renderer createHeaderRenderer(Appendable appendable) { return layoutable.createHeaderRenderer(appendable); } @Override public Renderer createFooterRenderer(Appendable appendable) { return layoutable.createFooterRenderer(appendable); } public Layout<T> enclose(Layoutable<T> thatLayoutable) { return new Layout<T>(new EnclosedLayoutable<T>(this.layoutable, thatLayoutable)); } private static class FunctionLayoutable<T> implements Layoutable<T> { private final Function<Appendable, Renderer> header; private final Function<Appendable, Renderer> footer; FunctionLayoutable(Function<Appendable, Renderer> header, Function<Appendable, Renderer> footer) { this.header = header; this.footer = footer; } @Override public Renderer createHeaderRenderer(Appendable appendable) { return header.apply(appendable); } @Override public Renderer createFooterRenderer(Appendable appendable) { return footer.apply(appendable); } } private static class ChromelessLayoutable<T> implements Layoutable<T> { @Override public Renderer createHeaderRenderer(Appendable appendable) { return Renderer.blank(); } @Override public Renderer createFooterRenderer(Appendable appendable) { return Renderer.blank(); } } private static class EnclosedLayoutable<T> implements Layoutable<T> { private final Layoutable<T> enclosing; private final Layoutable<T> enclosed; EnclosedLayoutable(Layoutable<T> enclosing, Layoutable<T> enclosed) { this.enclosing = enclosing; this.enclosed = enclosed; } @Override public Renderer createHeaderRenderer(Appendable appendable) { return enclosing.createHeaderRenderer(appendable).andThen(enclosed.createHeaderRenderer(appendable)); } @Override public Renderer createFooterRenderer(Appendable appendable) { return enclosed.createHeaderRenderer(appendable).andThen(enclosing.createHeaderRenderer(appendable)); } } }
package mondrian.test; import mondrian.olap.Result; import mondrian.olap.Util; import junit.framework.Assert; /** * <code>ParentChildHierarchyTest</code> tests parent-child hierarchies. * * @author jhyde * @since Mar 6, 2003 * @version $Id$ **/ public class ParentChildHierarchyTest extends FoodMartTestCase { public ParentChildHierarchyTest(String name) { super(name); } public void testAll() { runQueryCheckResult( "select {[Measures].[Org Salary], [Measures].[Count]} on columns," + nl + " {[Employees]} on rows" + nl + "from [HR]", "Axis #0:" + nl + "{}" + nl + "Axis #1:" + nl + "{[Measures].[Org Salary]}" + nl + "{[Measures].[Count]}" + nl + "Axis #2:" + nl + "{[Employees].[All Employees]}" + nl + "Row #0: $39,431.67" + nl + "Row #0: 7,392" + nl); } public void testChildrenOfAll() { runQueryCheckResult( "select {[Measures].[Org Salary], [Measures].[Count]} on columns," + nl + " {[Employees].children} on rows" + nl + "from [HR]", "Axis #0:" + nl + "{}" + nl + "Axis #1:" + nl + "{[Measures].[Org Salary]}" + nl + "{[Measures].[Count]}" + nl + "Axis #2:" + nl + "{[Employees].[All Employees].[Sheri Nowmer]}" + nl + "Row #0: $39,431.67" + nl + "Row #0: 7,392" + nl); } public void testLeaf() { // Juanita Sharp has no reports runQueryCheckResult( "select {[Measures].[Org Salary], [Measures].[Count]} on columns," + nl + " {[Employees].[All Employees].[Sheri Nowmer].[Rebecca Kanagaki].[Juanita Sharp]} on rows" + nl + "from [HR]", "Axis #0:" + nl + "{}" + nl + "Axis #1:" + nl + "{[Measures].[Org Salary]}" + nl + "{[Measures].[Count]}" + nl + "Axis #2:" + nl + "{[Employees].[All Employees].[Sheri Nowmer].[Rebecca Kanagaki].[Juanita Sharp]}" + nl + "Row #0: $72.36" + nl + "Row #0: 12" + nl); } public void testOneAboveLeaf() { // Rebecca Kanagaki has 2 direct reports, and they have no reports runQueryCheckResult( "select {[Measures].[Org Salary], [Measures].[Count]} on columns," + nl + " {[Employees].[All Employees].[Sheri Nowmer].[Rebecca Kanagaki]} on rows" + nl + "from [HR]", "Axis #0:" + nl + "{}" + nl + "Axis #1:" + nl + "{[Measures].[Org Salary]}" + nl + "{[Measures].[Count]}" + nl + "Axis #2:" + nl + "{[Employees].[All Employees].[Sheri Nowmer].[Rebecca Kanagaki]}" + nl + "Row #0: $234.36" + nl + "Row #0: 24" + nl); } public void _testFoo() { runQueryCheckResult( "WITH SET [NonEmptyEmployees] AS 'FILTER(DESCENDANTS([Employees].[All Employees], 10, LEAVES)," + nl + " NOT ISEMPTY( [Measures].[Employee Salary]) )'" + nl + "SELECT { [Measures].[Employee Salary], [Measures].[Number of Employees] } ON COLUMNS," + nl + " BOTTOMCOUNT([NonEmptyEmployees], 10, [Measures].[Employee Salary]) ON ROWS" + nl + "FROM HR" + nl + "WHERE ([Pay Type].[All Pay Type].[Hourly])", ""); } public void _testBar() { runQueryCheckResult( "with set [Leaves] as 'Descendants([Employees].[All Employees], 15, LEAVES )'" + nl + " set [Parents] as 'Generate( [Leaves], {[Employees].CurrentMember.Parent} )'" + nl + " set [FirstParents] as 'Filter( [Parents], " + nl + "Count( Descendants( [Employees].CurrentMember, 2 )) = 0 )'" + nl + "select {[Measures].[Number of Employees]} on Columns," + nl + " TopCount( [FirstParents], 10, [Measures].[Number of Employees]) on Rows" + nl + "from HR", ""); } // todo: test DimensionUsage which joins to a level which is not in the // same table as the lowest level. /** * The recursion cyclicity check kicks in when the recursion depth reachs * the number of dimensions in the cube. So create a cube with fewer * dimensions (3) than the depth of the emp dimension (6). */ public void testHierarchyFalseCycle() { // On the regular HR cube, this has always worked. runQueryCheckResult( "SELECT {[Employees].[All Employees].Children} on columns," + nl + " {[Measures].[Org Salary]} on rows" + nl + "FROM [HR]", "Axis #0:" + nl + "{}" + nl + "Axis #1:" + nl + "{[Employees].[All Employees].[Sheri Nowmer]}" + nl + "Axis #2:" + nl + "{[Measures].[Org Salary]}" + nl + "Row #0: $39,431.67" + nl); getConnection().getSchema().createCube( "<Cube name='HR-fewer-dims'>" + nl + " <Table name='salary'/>" + nl + " <Dimension name='Department' foreignKey='department_id'>" + nl + " <Hierarchy hasAll='true' primaryKey='department_id'>" + nl + " <Table name='department'/>" + nl + " <Level name='Department Description' uniqueMembers='true' column='department_id'/>" + nl + " </Hierarchy>" + nl + " </Dimension>" + nl + " <Dimension name='Employees' foreignKey='employee_id'>" + nl + " <Hierarchy hasAll='true' allMemberName='All Employees' primaryKey='employee_id'>" + nl + " <Table name='employee'/>" + nl + " <Level name='Employee Id' type='Numeric' uniqueMembers='true' column='employee_id' parentColumn='supervisor_id' nameColumn='full_name' nullParentValue='0'>" + nl + " <Property name='Marital Status' column='marital_status'/>" + nl + " <Property name='Position Title' column='position_title'/>" + nl + " <Property name='Gender' column='gender'/>" + nl + " <Property name='Salary' column='salary'/>" + nl + " <Property name='Education Level' column='education_level'/>" + nl + " <Property name='Management Role' column='management_role'/>" + nl + " </Level>" + nl + " </Hierarchy>" + nl + " </Dimension>" + nl + " <Measure name='Org Salary' column='salary_paid' aggregator='sum' formatString='Currency' />" + nl + " <Measure name='Count' column='employee_id' aggregator='count' formatString=' "</Cube>"); // On a cube with fewer dimensions, this gave a false failure. runQueryCheckResult( "SELECT {[Employees].[All Employees].Children} on columns," + nl + " {[Measures].[Org Salary]} on rows" + nl + "FROM [HR-fewer-dims]", "Axis #0:" + nl + "{}" + nl + "Axis #1:" + nl + "{[Employees].[All Employees].[Sheri Nowmer]}" + nl + "Axis #2:" + nl + "{[Measures].[Org Salary]}" + nl + "Row #0: $271,552.44" + nl); } public void testGenuineCycle() { Result result = runQuery("with member [Measures].[Foo] as " + nl + " '([Measures].[Foo], OpeningPeriod([Time].[Month]))'" + nl + "select" + nl + " {[Measures].[Unit Sales], [Measures].[Foo]} on Columns," + nl + " { [Time].[1997].[Q2]} on rows" + nl + "from [Sales]"); String resultString = toString(result); // The precise moment when the cycle is detected depends upon the state // of the cache, so this test can throw various errors. Here are come // examples: // Axis // Axis // {[Measures].[Unit Sales]} // {[Measures].[Foo]} // Axis // {[Time].[1997].[Q2]} // Row #0: 62,610 // Row #0: #ERR: mondrian.olap.fun.MondrianEvaluationException: Infinite loop while evaluating calculated member '[Measures].[Foo]'; context stack is {([Time].[1997].[Q2].[4]), ([Time].[1997].[Q2].[4]), ([Time].[1997].[Q2].[4]), ([Time].[1997].[Q2].[4]), ([Time].[1997].[Q2].[4]), ([Time].[1997].[Q2].[4]), ([Time].[1997].[Q2].[4]), ([Time].[1997].[Q2].[4]), ([Time].[1997].[Q2].[4]), ([Time].[1997].[Q2].[4]), ([Time].[1997].[Q2].[4]), ([Time].[1997].[Q2])} // Axis // Axis // {[Measures].[Unit Sales]} // {[Measures].[Foo]} // Axis // {[Time].[1997].[Q2]} // Row #0: (null) // Row #0: #ERR: mondrian.olap.fun.MondrianEvaluationException: Infinite loop while evaluating calculated member '[Measures].[Foo]'; context stack is {([Store].[All Stores].[Mexico], [Time].[1997].[Q2].[4]), ([Store].[All Stores].[Mexico], [Time].[1997].[Q2].[4]), ([Store].[All Stores].[Mexico], [Time].[1997].[Q2].[4]), ([Store].[All Stores].[Mexico], [Time].[1997].[Q2].[4]), ([Store].[All Stores].[Mexico], [Time].[1997].[Q2].[4]), ([Store].[All Stores].[Mexico], [Time].[1997].[Q2].[4]), ([Store].[All Stores].[Mexico], [Time].[1997].[Q2].[4]), ([Store].[All Stores].[Mexico], [Time].[1997].[Q2].[4]), ([Store].[All Stores].[Mexico], [Time].[1997].[Q2].[4]), ([Store].[All Stores].[Mexico], [Time].[1997].[Q2].[4]), ([Store].[All Stores].[Mexico], [Time].[1997].[Q2].[4]), ([Store].[All Stores].[Mexico], [Time].[1997].[Q2].[4]), ([Store].[All Stores].[Mexico], [Time].[1997].[Q2].[4]), ([Store].[All Stores].[Mexico], [Time].[1997].[Q2])}" // So encapsulate the error string as a pattern. final String expectedPattern = "(?s).*Row #0: #ERR: mondrian.olap.fun.MondrianEvaluationException.*: Infinite loop while evaluating calculated member \\'\\[Measures\\].\\[Foo\\]\\'; context stack is.*"; if (!resultString.matches(expectedPattern)) { System.out.println(resultString); Assert.assertEquals(expectedPattern, resultString); } } } // End ParentChildHierarchyTest.java
package ch.sportchef.business.configuration.boundary; import ch.sportchef.business.configuration.entity.Configuration; import javax.inject.Named; import javax.validation.constraints.NotNull; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Properties; import java.util.logging.Logger; @Named public class ConfigurationManager { private static final Logger LOGGER = Logger.getLogger(ConfigurationManager.class.getName()); private static final String DEFAULT_CONFIGURATION_FILE = "cfg_default.properties"; //NON-NLS private static final String CUSTOM_CONFIGURATION_FILE = "cfg_custom.properties"; //NON-NLS @SuppressWarnings("InstanceVariableOfConcreteClass") private final Configuration configuration; public ConfigurationManager() { final Properties properties = new Properties(); // load default configuration first loadProperties("default", DEFAULT_CONFIGURATION_FILE) //NON-NLS .forEach(properties::put); // load custom configuration loadProperties("custom", CUSTOM_CONFIGURATION_FILE) //NON-NLS .forEach(properties::put); configuration = new Configuration(properties); } private static Map<Object, Object> loadProperties(@NotNull final String type, @NotNull final String fileName) { final Properties properties = new Properties(); try (final InputStream stream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(fileName)) { properties.load(stream); } catch (final IOException e) { LOGGER.severe(String.format( "Could not load %s configuration from file '%s'!", //NON-NLS type, fileName)); } return properties; } @SuppressWarnings("MethodReturnOfConcreteClass") public final Configuration getConfiguration() { return configuration; } @Override public final String toString() { //noinspection MagicCharacter return "ConfigurationManager{" + //NON-NLS "configuration=" + configuration + //NON-NLS '}'; } }
package com.github.jrrdev.mantisbtsync.core.common.auth; import java.io.File; import java.io.IOException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ResourceLoaderAware; import org.springframework.core.io.ResourceLoader; import com.github.jrrdev.mantisbtsync.core.common.auth.beans.AuthSequenceBean; import com.github.jrrdev.mantisbtsync.core.common.auth.beans.HttpGetBean; import com.github.jrrdev.mantisbtsync.core.common.auth.beans.HttpPostBean; import com.github.jrrdev.mantisbtsync.core.common.auth.beans.HttpRequestBean; import com.github.jrrdev.mantisbtsync.core.common.auth.request.AbstractAuthHttpRequest; import com.github.jrrdev.mantisbtsync.core.common.auth.request.AuthHttpGet; import com.github.jrrdev.mantisbtsync.core.common.auth.request.AuthHttpPost; /** * Class used to build an {@link PortalAuthManager} from * the definition of a sequence of requests contains in a * XML file. * * @author jrrdev * */ public class PortalAuthBuilder implements ResourceLoaderAware { private static Logger LOGGER = LoggerFactory.getLogger(PortalAuthBuilder.class); /** * Spring resource loader. */ private ResourceLoader resourceLoader; /** * Private constructor. */ public PortalAuthBuilder() { } /** * Build the portal authentication manager from an XML file * describing the sequence of requests to be sent. * * @param filepath * File path of the XML file. The file is loaded through Spring resource loader, so * the file path can contain definition like "classpath:" * @return the portal authentication manager * @throws JAXBException * If an error occurs during the XML unmarshalling * @throws IOException * if the resource cannot be resolved as absolute file path, i.e. if the resource is * not available in a file system */ public PortalAuthManager buildAuthManager(final String filepath) throws JAXBException, IOException { final PortalAuthManager mgr = new PortalAuthManager(); if (filepath != null && !filepath.isEmpty()) { if (LOGGER.isInfoEnabled()) { LOGGER.info("Loading portal authentication configuration from file : " + filepath); } final File file = resourceLoader.getResource(filepath).getFile(); if (file.exists() && file.isFile() && file.canRead()) { final JAXBContext jaxbContext = JAXBContext.newInstance(AuthSequenceBean.class); final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); final AuthSequenceBean sequence = (AuthSequenceBean) jaxbUnmarshaller.unmarshal(file); if (sequence != null) { mgr.setFirstRequest(buildRequest(sequence.getFirstRequest())); } if (LOGGER.isInfoEnabled()) { LOGGER.info("Portal authentication configuration loaded"); } } else { if (LOGGER.isErrorEnabled()) { LOGGER.error("Portal authentication configuration loading failed, file may not exists or can't be read"); throw new IOException("Portal authentication configuration loading failed, file may not exists or can't be read : " + filepath); } } } else if (LOGGER.isInfoEnabled()) { LOGGER.info("No portal authentication configuration file specified"); } return mgr; } /** * Build an implementation of the request described by the bean * and make a recursive call to be build the next request in the sequence. * * @param reqBean * Bean containing the description of the request * @return An implementation of the request */ private AbstractAuthHttpRequest buildRequest(final HttpRequestBean reqBean) { AbstractAuthHttpRequest req = null; if (reqBean != null) { if (reqBean.getRequestType() instanceof HttpGetBean) { final AuthHttpGet reqImp = new AuthHttpGet(); reqImp.setUri(reqBean.getUri()); req = reqImp; } else if (reqBean.getRequestType() instanceof HttpPostBean) { final HttpPostBean postBean = (HttpPostBean) reqBean.getRequestType(); final AuthHttpPost reqImp = new AuthHttpPost(); reqImp.setUri(reqBean.getUri()); reqImp.setParameters(postBean.getParameters()); reqImp.setFormAction(postBean.getFormAction()); req = reqImp; } if (req != null) { req.setNextRequest(buildRequest(reqBean.getNextRequest())); } } return req; } /** * {@inheritDoc} * @see org.springframework.context.ResourceLoaderAware#setResourceLoader(org.springframework.core.io.ResourceLoader) */ @Override public void setResourceLoader(final ResourceLoader pResourceLoader) { resourceLoader = pResourceLoader; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.mdrsolutions.util.sanitize.annotation.impl; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import static com.mdrsolutions.util.sanitize.annotation.impl.ParserTypes.HTML_EVENT_LISTENERS; import static com.mdrsolutions.util.sanitize.annotation.impl.ParserTypes.HTML_TAGS_ATTRIBUTES; import static com.mdrsolutions.util.sanitize.annotation.impl.ParserTypes.JS_DOCUMENT_GET_ELEMENT_CALLS; import static com.mdrsolutions.util.sanitize.annotation.impl.ParserTypes.SCRIPT_TAGS; import static com.mdrsolutions.util.sanitize.annotation.impl.ParserTypes.TAG_OPEN_CLOSERS; import org.apache.commons.lang3.StringUtils; /** * * @author michael.rodgers1 */ public class AbstractParserType implements ParserTypes { public static enum METHOD_TYPE { SETTER, GETTER; } public static String replaceHtmlJavascript(String charString) { if (null != charString) { charString = stripScriptTags(charString); charString = stripHtmlTags(charString); charString = stripElementEventListeners(charString); charString = stripDocumentGetElementCalls(charString); charString = stripTagOpenClose(charString); charString = stripNonAsciUnicode(charString); charString = charString.replaceAll("\\Qalert(\\E", ""); //escape the html syntax //charString = StringEscapeUtils.escapeHtml4(charString); //escape the javascript syntax //charString = StringEscapeUtils.escapeEcmaScript(charString); charString = StringUtils.stripAccents(charString); } return charString; } private static String stripTagOpenClose(String charString) { if (null != charString) { for (String pattern : TAG_OPEN_CLOSERS) { charString = replaceULAll(charString, pattern, ""); } } return charString; } private static String stripScriptTags(String charString) { if (null != charString) { for (String pattern : SCRIPT_TAGS) { charString = replaceULAll(charString, pattern, ""); } } return charString; } private static String stripHtmlTags(String charString) { if (null != charString) { for (String pattern : HTML_TAGS_ATTRIBUTES) { charString = replaceULAll(charString, pattern, ""); } } return charString; } private static String stripElementEventListeners(String charString) { if (null != charString) { for (String pattern : HTML_EVENT_LISTENERS) { charString = replaceULAll(charString, pattern, ""); } } return charString; } private static String stripDocumentGetElementCalls(String charString) { if (null != charString) { for (String pattern : JS_DOCUMENT_GET_ELEMENT_CALLS) { charString = replaceULAll(charString, pattern, ""); } } return charString; } private static String wrapp(String charString) { //if (charString.contains("<") || charString.contains(">")) { // return "(?i)" + charString + "([^>]+)(.+?)"; //} else { // return "\\b(" + charString + ")\\W"; return charString; } private static String replaceULAll(String charString, String pattern, String replaceWith) { if (null != charString) { charString = charString.replaceAll(wrapp(pattern), replaceWith); if (!pattern.contains("(?i")) { charString = charString.replaceAll(wrapp(pattern.toLowerCase()), replaceWith); charString = charString.replaceAll(wrapp(pattern.toUpperCase()), replaceWith); } } return charString; } private static String stripNonAsciUnicode(String charString) { Set<String> keySet = getUnicodeMap().keySet(); for (String key : keySet) { Pattern p = Pattern.compile("[" + key + "]"); charString = charString.replaceAll(p.pattern(), getUnicodeMap().get(key)); } return charString; } private static Map<String, String> getUnicodeMap() { Map<String, String> unicodeMap = new HashMap<String, String>(100); unicodeMap.put("•", "*"); unicodeMap.put("", "*"); unicodeMap.put("", "*"); unicodeMap.put("", "*"); unicodeMap.put("", "*"); unicodeMap.put("«", "\""); unicodeMap.put("­", "-"); unicodeMap.put("´", "'"); unicodeMap.put("»", "\""); unicodeMap.put("÷", "/"); unicodeMap.put("ǀ", "|"); unicodeMap.put("ǃ", "!"); unicodeMap.put("ʹ", "'"); unicodeMap.put("ʺ", "\""); unicodeMap.put("ʼ", "'"); unicodeMap.put("’", "'"); unicodeMap.put("˄", "^"); unicodeMap.put("ˆ", "^"); unicodeMap.put("ˈ", "'"); unicodeMap.put("ˋ", "`"); unicodeMap.put("ˍ", "_"); unicodeMap.put("˜", "~"); unicodeMap.put("։", ":"); unicodeMap.put("٪", "%"); unicodeMap.put("٭", "*"); unicodeMap.put("‐", "-"); unicodeMap.put("‑", "-"); unicodeMap.put("‒", "-"); unicodeMap.put("–", "-"); unicodeMap.put("—", "-"); unicodeMap.put("―", " unicodeMap.put("‗", "_"); unicodeMap.put("‘", "'"); unicodeMap.put("’", "'"); unicodeMap.put("‚", ","); unicodeMap.put("‛", "'"); unicodeMap.put("“", "\""); unicodeMap.put("”", "\""); unicodeMap.put("„", "\""); unicodeMap.put("‟", "\""); unicodeMap.put("′", "'"); unicodeMap.put("″", "\""); unicodeMap.put("‸", "^"); unicodeMap.put("‹", "<"); unicodeMap.put("›", ">"); unicodeMap.put("‽", "?"); unicodeMap.put("⁄", "/"); unicodeMap.put("⁎", "*"); unicodeMap.put("⁒", "%"); unicodeMap.put("⁓", "~"); unicodeMap.put("⁠", ""); unicodeMap.put("−", "-"); unicodeMap.put("∕", "/"); unicodeMap.put("∖", "\""); unicodeMap.put("∗", "*"); unicodeMap.put("∣", "|"); unicodeMap.put("∶", ":"); unicodeMap.put("∼", "~"); unicodeMap.put("≤", "<="); unicodeMap.put("≥", ">="); unicodeMap.put("≦", "<="); unicodeMap.put("≧", ">="); unicodeMap.put("⌃", "^"); unicodeMap.put("〈", "<"); unicodeMap.put("〉", ">"); unicodeMap.put("", " unicodeMap.put("", "*"); unicodeMap.put("", "|"); unicodeMap.put("", "!"); unicodeMap.put("", "["); unicodeMap.put("", "<"); unicodeMap.put("", ">"); unicodeMap.put("", "{"); unicodeMap.put("", "}"); unicodeMap.put("", "\""); unicodeMap.put("", "<"); unicodeMap.put("", ">"); unicodeMap.put("", "]"); unicodeMap.put("", "~"); unicodeMap.put("", "\""); unicodeMap.put("", "\""); return unicodeMap; } public AbstractParserType() { } }
package com.netease.xmpp.master.event.client; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.apache.log4j.Logger; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelPipelineException; import com.netease.xmpp.master.common.ConfigConst; import com.netease.xmpp.master.common.HeartBeatWorker; import com.netease.xmpp.master.event.EventContext; import com.netease.xmpp.master.event.EventDispatcher; import com.netease.xmpp.master.event.EventHandler; import com.netease.xmpp.master.event.EventType; import com.netease.xmpp.master.event.UnrecognizedEvent; public class ServerConnectionEventHandler implements EventHandler { private static Logger logger = Logger.getLogger(ServerConnectionEventHandler.class); private ClientBootstrap bootstrap = null; private HeartBeatWorker worker = null; private AtomicBoolean isDone = new AtomicBoolean(false); protected AtomicLong timeoutTime = new AtomicLong(-1); protected Channel serverChannel = null; private Thread timeoutChecker = null; private EventDispatcher eventDispatcher = null; public ServerConnectionEventHandler(ClientBootstrap bootstrap, EventDispatcher dispatcher) { this.bootstrap = bootstrap; this.eventDispatcher = dispatcher; timeoutChecker = new Thread(new Runnable() { @Override public void run() { while (true) { synchronized (timeoutTime) { if (timeoutTime.get() > 0) { if (timeoutTime.get() <= System.currentTimeMillis()) { logger.debug("SERVER_HEARTBEAT_TIMOUT"); eventDispatcher.dispatchEvent(null, null, EventType.CLIENT_SERVER_HEARTBEAT_TIMOUT); } } } try { Thread.sleep(ConfigConst.HEARTBEAT_INTERVAL * 1000); } catch (InterruptedException e) { // Do nothing } } } }); timeoutChecker.start(); } @Override public void handle(EventContext ctx) throws IOException { EventType event = ctx.getEvent(); Channel channel = ctx.getChannel(); long timeoutValue = System.currentTimeMillis() + ConfigConst.HEARTBEAT_TIMEOUT * 1000; switch (event) { case CLIENT_SERVER_CONNECTED: serverChannel = channel; startHeartBeat(); synchronizedSet(timeoutTime, timeoutValue); break; case CLIENT_SERVER_HEARTBEAT_TIMOUT: synchronizedSet(timeoutTime, -1); serverChannel.close().awaitUninterruptibly(); break; case CLIENT_SERVER_DISCONNECTED: reconnect(); break; case CLIENT_SERVER_HEARTBEAT: synchronizedSet(timeoutTime, timeoutValue); break; default: throw new UnrecognizedEvent(event.toString()); } } protected void synchronizedSet(AtomicLong timeoutTime, long value) { synchronized (timeoutTime) { timeoutTime.set(value); } } protected void startHeartBeat() { worker = new HeartBeatWorker(serverChannel); worker.start(); } private synchronized void reconnect() { if (worker != null) { worker.stop(); } while (true) { logger.info("START RECONNECTING......"); isDone.set(false); try { ChannelFuture f = bootstrap.connect(); f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { isDone.set(true); } } }); Thread.sleep(10 * 1000); if (isDone.get()) { logger.info("SERVER CONNECTED"); break; } } catch (ChannelPipelineException e) { // Do nothing } catch (InterruptedException e) { // Do nothing } } } }
package com.solofeed.tchernocraft.container.containers; import com.solofeed.tchernocraft.container.ContainerHelper; import com.solofeed.tchernocraft.container.Coord2D; import com.solofeed.tchernocraft.container.TchernocraftAbstractContainer; import com.solofeed.tchernocraft.tileentity.tileentities.TestBlockTileEntity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.ItemStackHandler; public class TestBlockContainer extends TchernocraftAbstractContainer { private static final int ROWS = 3; private static final int COLUMNS = 3; private static final Coord2D SELF_INVENTORY_COORDS = new Coord2D(61,18); private TestBlockTileEntity tileEntity; public TestBlockContainer(IInventory playerInv, TestBlockTileEntity tileEntity) { this.tileEntity = tileEntity; itemHandler = tileEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null); itemHandler = new ItemStackHandler(ROWS * COLUMNS); // generate test block inventory slots ContainerHelper.create(SELF_INVENTORY_COORDS, ROWS, COLUMNS, itemHandler).forEach(this::addSlotToContainer); // generates default player inventory slots generateDefaultSlots(playerInv); } @Override public boolean canInteractWith(EntityPlayer playerIn) { return true; } }
package de.fernunihagen.dna.jkn.scalephant.storage.sstable; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.fernunihagen.dna.jkn.scalephant.ScalephantConfiguration; import de.fernunihagen.dna.jkn.scalephant.ScalephantService; import de.fernunihagen.dna.jkn.scalephant.storage.Memtable; import de.fernunihagen.dna.jkn.scalephant.storage.Storage; import de.fernunihagen.dna.jkn.scalephant.storage.StorageManagerException; import de.fernunihagen.dna.jkn.scalephant.storage.entity.BoundingBox; import de.fernunihagen.dna.jkn.scalephant.storage.entity.DeletedTuple; import de.fernunihagen.dna.jkn.scalephant.storage.entity.SSTableName; import de.fernunihagen.dna.jkn.scalephant.storage.entity.Tuple; import de.fernunihagen.dna.jkn.scalephant.storage.sstable.compact.SSTableCompactorThread; import de.fernunihagen.dna.jkn.scalephant.storage.sstable.reader.SSTableFacade; import de.fernunihagen.dna.jkn.scalephant.storage.sstable.reader.SSTableKeyIndexReader; import de.fernunihagen.dna.jkn.scalephant.storage.sstable.reader.SSTableReader; import de.fernunihagen.dna.jkn.scalephant.util.State; import de.fernunihagen.dna.jkn.scalephant.util.Stoppable; public class SSTableManager implements ScalephantService, Storage { /** * The name of the table */ protected final SSTableName name; /** * The Storage configuration */ protected final ScalephantConfiguration storageConfiguration; /** * The number of the table */ protected AtomicInteger tableNumber; /** * The reader for existing SSTables */ protected final List<SSTableFacade> sstableFacades; /** * The unflushed memtables */ protected List<Memtable> unflushedMemtables; /** * Ready flag for flush thread */ protected volatile boolean ready; /** * The corresponding storage manager state */ protected State storageState; /** * The running threads */ protected final Set<Thread> runningThreads; /** * The stoppable tasks */ protected final Set<Stoppable> stoppableTasks; /** * The timeout for a thread join (10 seconds) */ protected long THREAD_WAIT_TIMEOUT = TimeUnit.SECONDS.toMillis(10); /** * The logger */ private final static Logger logger = LoggerFactory.getLogger(SSTableManager.class); public SSTableManager(final State storageState, final SSTableName name, final ScalephantConfiguration storageConfiguration) { super(); this.storageConfiguration = storageConfiguration; this.storageState = storageState; this.name = name; this.tableNumber = new AtomicInteger(); this.ready = false; this.unflushedMemtables = new CopyOnWriteArrayList<Memtable>(); this.sstableFacades = new CopyOnWriteArrayList<SSTableFacade>(); this.runningThreads = new HashSet<Thread>(); this.stoppableTasks = new HashSet<Stoppable>(); } /** * Init the instance * */ @Override public void init() { if(ready == true) { logger.warn("SSTable manager is active and init() is called"); return; } logger.info("Init a new instance for the table: " + getName()); unflushedMemtables.clear(); sstableFacades.clear(); runningThreads.clear(); createSSTableDirIfNeeded(); try { scanForExistingTables(); } catch (StorageManagerException e) { logger.error("Unable to init the instance: " + getName(), e); return; } tableNumber.set(getLastSequencenumberFromReader()); // Set to ready before the threads are started ready = true; startMemtableFlushThread(); startCompactThread(); startCheckpointThread(); } /** * Start the checkpoint thread if needed */ protected void startCheckpointThread() { if(storageConfiguration.getStorageCheckpointInterval() > 0) { final int maxUncheckpointedSeconds = storageConfiguration.getStorageCheckpointInterval(); final SSTableCheckpointThread ssTableCheckpointThread = new SSTableCheckpointThread(maxUncheckpointedSeconds); final Thread checkpointThread = new Thread(ssTableCheckpointThread); checkpointThread.start(); runningThreads.add(checkpointThread); stoppableTasks.add(ssTableCheckpointThread); } else { logger.info("NOT starting the checkpoint thread for: " + getName()); } } /** * Start the compact thread if needed */ protected void startCompactThread() { if(storageConfiguration.isStorageRunCompactThread()) { final Thread compactThread = new Thread(new SSTableCompactorThread(this)); compactThread.setName("Compact thread for: " + getName()); compactThread.start(); runningThreads.add(compactThread); } else { logger.info("NOT starting the sstable compact thread for: " + getName()); } } /** * Start the memtable flush thread if needed */ protected void startMemtableFlushThread() { if(storageConfiguration.isStorageRunMemtableFlushThread()) { final SSTableFlushThread ssTableFlushThread = new SSTableFlushThread(this); final Thread flushThread = new Thread(ssTableFlushThread); flushThread.setName("Memtable flush thread for: " + getName()); flushThread.start(); runningThreads.add(flushThread); stoppableTasks.add(ssTableFlushThread); } else { logger.info("NOT starting the memtable flush thread for:" + getName()); } } /** * Shutdown the instance */ @Override public void shutdown() { logger.info("Shuting down the instance for table: " + getName()); // Set ready to false. The threads will shutdown after completing // the running tasks ready = false; stopThreads(); // Close all sstables for(final SSTableFacade facade : sstableFacades) { facade.shutdown(); } sstableFacades.clear(); } /** * Shutdown all running service threads */ public void stopThreads() { // Stop the running tasks for(final Stoppable stoppable : stoppableTasks) { stoppable.stop(); } // Stop the corresponsing threads for(final Thread thread : runningThreads) { logger.info("Interrupt and join thread: " + thread.getName()); thread.interrupt(); try { thread.join(THREAD_WAIT_TIMEOUT); } catch (InterruptedException e) { logger.warn("Got exception while waiting on thread join: " + thread.getName(), e); } } } /** * Is the shutdown complete? * * @return */ public boolean isShutdownComplete() { for(final Thread thread : runningThreads) { if(thread.isAlive()) { return false; } } return true; } /** * Ensure that the directory for the given table exists * */ protected void createSSTableDirIfNeeded() { final File rootDir = new File(storageConfiguration.getDataDirectory()); final File directoryHandle = new File(SSTableHelper.getSSTableDir(storageConfiguration.getDataDirectory(), name.getFullname())); if(rootDir.exists() && ! directoryHandle.exists()) { logger.info("Create a new dir for table: " + getName()); directoryHandle.mkdir(); } } /** * Scan the database directory for all existing SSTables and * create reader objects * @throws StorageManagerException * */ protected void scanForExistingTables() throws StorageManagerException { logger.info("Scan for existing SSTables: " + getName()); final File directoryHandle = new File(SSTableHelper.getSSTableDir(storageConfiguration.getDataDirectory(), name.getFullname())); checkSSTableDir(directoryHandle); final File[] entries = directoryHandle.listFiles(); for(final File file : entries) { final String filename = file.getName(); if(isFileNameSSTable(filename)) { logger.info("Found sstable: " + filename); try { final int sequenceNumber = SSTableHelper.extractSequenceFromFilename(name, filename); final SSTableFacade facade = new SSTableFacade(storageConfiguration.getDataDirectory(), name, sequenceNumber); facade.init(); sstableFacades.add(facade); } catch(StorageManagerException e) { logger.warn("Unable to parse sequence number, ignoring file: " + filename, e); } } } } /** * Get the highest sequence number, based on the reader * instances * * @return the sequence number */ protected int getLastSequencenumberFromReader() { int number = 0; for(final SSTableFacade facade : sstableFacades) { final int sequenceNumber = facade.getTablebumber(); if(sequenceNumber >= number) { number = sequenceNumber + 1; } } return number; } /** * Ensure that the storage directory does exist * * @param directoryHandle * @throws StorageManagerException */ public void checkSSTableDir(final File directoryHandle) throws StorageManagerException { if(! directoryHandle.isDirectory()) { final String message = "Storage directory is not an directory: " + directoryHandle; storageState.setReady(false); logger.error(message); throw new StorageManagerException(message); } } /** * Delete all existing SSTables in the given directory * * @return Directory was deleted or not * @throws StorageManagerException */ public boolean deleteExistingTables() throws StorageManagerException { logger.info("Delete all existing SSTables for relation: " + getName()); final File directoryHandle = new File(SSTableHelper.getSSTableDir(storageConfiguration.getDataDirectory(), name.getFullname())); // Does the directory exist? if(! directoryHandle.isDirectory()) { return true; } final File[] entries = directoryHandle.listFiles(); for(final File file : entries) { final String filename = file.getName(); if(isFileNameSSTable(filename)) { logger.info("Deleting file: " + file); file.delete(); } else if(isFileNameSSTableIndex(filename)) { logger.info("Deleting index file: " + file); file.delete(); } else if(isFileNameSSTableMetadata(filename)) { logger.info("Deleting meta file: " + file); file.delete(); } } // Delete the directory if empty if(directoryHandle.listFiles().length != 0) { logger.info("SStable directory is not empty, skip directory delete"); return false; } else { directoryHandle.delete(); return true; } } /** * Belongs the given filename to a SSTable? * * @param filename * @return */ protected boolean isFileNameSSTable(final String filename) { return filename.startsWith(SSTableConst.SST_FILE_PREFIX) && filename.endsWith(SSTableConst.SST_FILE_SUFFIX); } /** * Belongs the given filename to a SSTable index? * * @param filename * @return */ protected boolean isFileNameSSTableIndex(final String filename) { return filename.startsWith(SSTableConst.SST_FILE_PREFIX) && filename.endsWith(SSTableConst.SST_INDEX_SUFFIX); } /** * Belongs the given filename to a SSTable meta file? * @param filename * @return */ protected boolean isFileNameSSTableMetadata(final String filename) { return filename.startsWith(SSTableConst.SST_FILE_PREFIX) && filename.endsWith(SSTableConst.SST_META_SUFFIX); } /** * Schedule a memtable for flush * * @param memtable * @throws StorageManagerException */ public void flushMemtable(final Memtable memtable) throws StorageManagerException { // Empty memtables don't need to be flushed to disk if(memtable.isEmpty()) { return; } synchronized (unflushedMemtables) { unflushedMemtables.add(memtable); unflushedMemtables.notifyAll(); } } /** * Search for the most recent version of the tuple * @param key * @return The tuple or null * @throws StorageManagerException */ public Tuple get(final String key) throws StorageManagerException { // Read unflushed memtables first Tuple tuple = getTupleFromMemtable(key); boolean readComplete = false; while(! readComplete) { readComplete = true; // Read data from the persistent SSTables for(final SSTableFacade facade : sstableFacades) { boolean canBeUsed = facade.acquire(); if(! canBeUsed ) { readComplete = false; break; } final SSTableKeyIndexReader indexReader = facade.getSsTableKeyIndexReader(); final SSTableReader reader = facade.getSsTableReader(); final int position = indexReader.getPositionForTuple(key); // Found a tuple if(position != -1) { final Tuple tableTuple = reader.getTupleAtPosition(position); if(tuple == null) { tuple = tableTuple; } else if(tableTuple.getTimestamp() > tuple.getTimestamp()) { tuple = tableTuple; } } facade.release(); } } if(tuple instanceof DeletedTuple) { return null; } return tuple; } /** * Get all tuples that are inside of the bounding box * @param boundingBox * @return * @throws StorageManagerException */ public Collection<Tuple> getTuplesInside(final BoundingBox boundingBox) throws StorageManagerException { final List<Tuple> resultList = new ArrayList<Tuple>(); // Read unflushed memtables first for(final Memtable unflushedMemtable : unflushedMemtables) { try { final Collection<Tuple> memtableResult = unflushedMemtable.getTuplesInside(boundingBox); resultList.addAll(memtableResult); } catch (StorageManagerException e) { logger.warn("Got an exception while scanning unflushed memtable: ", e); } } // Scan the sstables boolean readComplete = false; final List<Tuple> storedTuples = new ArrayList<Tuple>(); while(! readComplete) { readComplete = true; storedTuples.clear(); // Read data from the persistent SSTables for(final SSTableFacade facade : sstableFacades) { boolean canBeUsed = facade.acquire(); if(! canBeUsed ) { readComplete = false; break; } final SSTableKeyIndexReader indexReader = facade.getSsTableKeyIndexReader(); for (final Tuple tuple : indexReader) { if(tuple.getBoundingBox().overlaps(boundingBox)) { storedTuples.add(tuple); } } facade.release(); } } resultList.addAll(storedTuples); return resultList; } @Override public Collection<Tuple> getTuplesAfterTime(final long timestamp) throws StorageManagerException { final List<Tuple> resultList = new ArrayList<Tuple>(); // Read unflushed memtables first for(final Memtable unflushedMemtable : unflushedMemtables) { try { final Collection<Tuple> memtableResult = unflushedMemtable.getTuplesAfterTime(timestamp); resultList.addAll(memtableResult); } catch (StorageManagerException e) { logger.warn("Got an exception while scanning unflushed memtable: ", e); } } // Scan the sstables boolean readComplete = false; final List<Tuple> storedTuples = new ArrayList<Tuple>(); while(! readComplete) { readComplete = true; storedTuples.clear(); // Read data from the persistent SSTables for(final SSTableFacade facade : sstableFacades) { boolean canBeUsed = facade.acquire(); if(! canBeUsed ) { readComplete = false; break; } // Scan only tables that contain newer tuples if(facade.getSsTableMetadata().getNewestTuple() > timestamp) { final SSTableKeyIndexReader indexReader = facade.getSsTableKeyIndexReader(); for (final Tuple tuple : indexReader) { if(tuple.getTimestamp() > timestamp) { storedTuples.add(tuple); } } } facade.release(); } } resultList.addAll(storedTuples); return resultList; } /** * Get the tuple from the unflushed memtables * @param key * @return */ protected Tuple getTupleFromMemtable(final String key) { Tuple result = null; for(final Memtable unflushedMemtable : unflushedMemtables) { final Tuple tuple = unflushedMemtable.get(key); if(tuple != null) { if(result == null) { result = tuple; continue; } // Get the most recent version of the tuple if(tuple.compareTo(result) < 0) { result = tuple; continue; } } } return result; } /** * Get and increase the table number * @return */ public int increaseTableNumber() { return tableNumber.getAndIncrement(); } /** * Is the instance ready? * @return */ public boolean isReady() { return ready; } /** * Set ready flag * @param ready */ public void setReady(final boolean ready) { this.ready = ready; } /** * Get the sstable name for this instance * @return */ public SSTableName getName() { return name; } /** * Returns the configuration * @return */ public ScalephantConfiguration getStorageConfiguration() { return storageConfiguration; } /** * Get the name of this service */ @Override public String getServicename() { return "SSTable manager"; } /** * Get the sstable facades * @return */ public List<SSTableFacade> getSstableFacades() { return sstableFacades; } /** * Get the unflushed memtables * @return */ public List<Memtable> getUnflushedMemtables() { return unflushedMemtables; } // These methods are required by the interface @Override public void put(final Tuple tuple) throws StorageManagerException { throw new UnsupportedOperationException("SSTables are read only"); } @Override public void delete(final String key) throws StorageManagerException { throw new UnsupportedOperationException("SSTables are read only"); } @Override public void clear() throws StorageManagerException { throw new UnsupportedOperationException("SSTables are read only"); } }
package de.uni_potsdam.hpi.bpt.bp2014.jcore.eventhandling; import com.google.gson.Gson; import com.google.gson.JsonObject; import de.uni_potsdam.hpi.bpt.bp2014.database.DbCaseStart; import de.uni_potsdam.hpi.bpt.bp2014.database.controlnodes.events.DbEventMapping; import de.uni_potsdam.hpi.bpt.bp2014.database.history.DbLogEntry; import de.uni_potsdam.hpi.bpt.bp2014.jcore.*; import de.uni_potsdam.hpi.bpt.bp2014.jcore.controlnodes.AbstractEvent; import de.uni_potsdam.hpi.bpt.bp2014.jcore.controlnodes.EventFactory; import de.uni_potsdam.hpi.bpt.bp2014.jcore.controlnodes.TimerEventInstance; import de.uni_potsdam.hpi.bpt.bp2014.jcore.data.DataAttributeInstance; import de.uni_potsdam.hpi.bpt.bp2014.jcore.executionbehaviors.TimeEventJob; import de.uni_potsdam.hpi.bpt.bp2014.settings.PropertyLoader; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.log4j.Logger; import org.glassfish.jersey.client.ClientProperties; import org.json.JSONArray; import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; import javax.ws.rs.*; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.*; import java.util.stream.Collectors; import static org.quartz.JobBuilder.newJob; import static org.quartz.TriggerBuilder.newTrigger; /** * The event dispatcher class is responsible for manage registrations from Events to RestQueries. */ @Path("eventdispatcher/") public final class EventDispatcher { private static final String REST_PATH = PropertyLoader.getProperty("unicorn.path.query.rest"); private static final String REST_DEPLOY_URL = PropertyLoader.getProperty("unicorn.url") + PropertyLoader.getProperty("unicorn.path.deploy"); private static final String SELF_DEPLOY_URL = PropertyLoader.getProperty("chimera.url") + PropertyLoader.getProperty("chimera.path.deploy"); private static final String SELF_PATH_NODES = "%s/api/eventdispatcher/scenario/%d/instance/%d/events/%s"; private static final String SELF_PATH_CASESTART = "%s/api/eventdispatcher/casestart/%s"; private static Logger logger = Logger.getLogger(EventDispatcher.class); @POST @Consumes(MediaType.APPLICATION_JSON) @Path("scenario/{scenarioId}/instance/{instanceId}/events/{requestKey}") public static Response receiveEvent( @PathParam("scenarioId") int scenarioId, @PathParam("instanceId") int scenarioInstanceId, @PathParam("requestKey") String requestId, String eventJson) { AbstractEvent event = findEvent(requestId, scenarioId, scenarioInstanceId); if (eventJson.isEmpty()) { event.terminate(); } else { event.terminate(eventJson); } unregisterEvent(event); return Response.accepted("Event received.").build(); } @POST @Consumes(MediaType.APPLICATION_JSON) @Path("casestart/{requestKey}") public static Response startCase(@PathParam("requestKey") String requestKey, String eventJson) { int scenarioId = new DbCaseStart().getScenarioId(requestKey); int scenarioInstanceId = ExecutionService.startNewScenarioInstanceStatic(scenarioId); ScenarioInstance instance = new ScenarioInstance(scenarioId, scenarioInstanceId); String queryId = new DbCaseStart().getQueryId(requestKey); CaseStarter caseStarter = new CaseStarter(scenarioId, queryId); try { caseStarter.startInstance(eventJson, instance); } catch (IllegalStateException e) { logger.error("Could not start case from query", e); return Response.status(Response.Status.NOT_FOUND) .type(MediaType.APPLICATION_JSON) .entity(e.getMessage()) .build(); } return Response.ok("Event received.").build(); } public static AbstractEvent findEvent(String requestId, int scenarioId, int instanceId) { ScenarioInstance scenarioInstance = new ScenarioInstance(scenarioId, instanceId); return getEvent(scenarioInstance, requestId); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("scenario/{scenarioId}/instance/{instanceId}/events") public static Response getRegisteredEvents( @PathParam("instanceId") int scenarioInstanceId, @PathParam("scenarioId") int scenarioId) { ScenarioInstance scenarioInstance = new ScenarioInstance(scenarioId, scenarioInstanceId); List<Integer> fragmentIds = scenarioInstance.getFragmentInstances().stream() .map(FragmentInstance::getFragmentId) .collect(Collectors.toList()); DbEventMapping eventMapping = new DbEventMapping(); List<String> requestKeys = fragmentIds.stream() .map(eventMapping::getRequestKeysForFragment).flatMap(Collection::stream) .collect(Collectors.toList()); JSONArray jsonArray = new JSONArray(requestKeys); return Response.ok().type(MediaType.APPLICATION_JSON).entity(jsonArray.toString()).build(); } public static void unregisterEvent(AbstractEvent event) { if (isExclusiveEvent(event)) { discardAllAlternatives(event); } else { unregisterEvent(event.getControlNodeId(), event.getFragmentInstanceId()); } } private static void discardAllAlternatives(AbstractEvent event) { DbEventMapping mapping = new DbEventMapping(); int fragmentInstanceId = event.getFragmentInstanceId(); List<Integer> alternativeEventNodes = mapping.getAlternativeEventsIds(event); alternativeEventNodes.forEach(x -> unregisterEvent(x, fragmentInstanceId)); } public static void registerCaseStartEvent(String eventQuery, int scenarioId, String id) { final String requestId = UUID.randomUUID().toString().replaceAll("\\-", ""); String notificationPath = String.format( SELF_PATH_CASESTART, SELF_DEPLOY_URL, requestId); String notificationRuleId = sendQueryToEventService( eventQuery, requestId, notificationPath); new DbCaseStart().insertCaseStartMapping(requestId, scenarioId, notificationRuleId, id); } public static void registerTimerEvent(TimerEventInstance event, int fragmentInstanceId, int scenarioInstanceId, int scenarioId) { String mappingKey = registerEvent(event, fragmentInstanceId, scenarioInstanceId, scenarioId); Date terminationDate = event.getTerminationDate(); assert (terminationDate.after(new Date())); SchedulerFactory sf = new StdSchedulerFactory(); try { Scheduler sched = sf.getScheduler(); JobDetail job = createJob(mappingKey, scenarioInstanceId, scenarioId); SimpleTrigger trigger = (SimpleTrigger) newTrigger() .startAt(terminationDate) .build(); sched.start(); sched.scheduleJob(job, trigger); } catch (SchedulerException e) { logger.error(e.getMessage(), e); } } private static JobDetail createJob(String mappingKey, int scenarioInstanceId, int scenarioId) { JobDetail timeEventJob = newJob(TimeEventJob.class) .withIdentity("1") .build(); timeEventJob.getJobDataMap().put("mappingKey", mappingKey); timeEventJob.getJobDataMap().put("scenarioInstanceId", scenarioInstanceId); timeEventJob.getJobDataMap().put("scenarioId", scenarioId); return timeEventJob; } private static boolean isExclusiveEvent(AbstractEvent event) { DbEventMapping mapping = new DbEventMapping(); return mapping.isAlternativeEvent(event); } private static AbstractEvent getEvent(ScenarioInstance instance, String requestId) { DbEventMapping eventMapping = new DbEventMapping(); EventFactory factory = new EventFactory(instance); int eventControlNodeId = eventMapping.getEventControlNodeId(requestId); int fragmentInstanceId = eventMapping.getFragmentInstanceId(requestId); AbstractEvent event = factory.getEventForControlNodeId(eventControlNodeId, fragmentInstanceId); new DbLogEntry().logEvent(event.getControlNodeInstanceId(), instance.getScenarioInstanceId(), "received"); return event; } public static String registerEvent( AbstractEvent event, int fragmentInstanceId, int scenarioInstanceId, int scenarioId) { final String requestId = UUID.randomUUID().toString().replaceAll("\\-", ""); String query = insertAttributesIntoQueryString( event.getQueryString(), scenarioInstanceId, scenarioId); String notificationRuleId = sendQueryToEventService( query, requestId, scenarioInstanceId, scenarioId); DbEventMapping mapping = new DbEventMapping(); mapping.saveMappingToDatabase( fragmentInstanceId, requestId, event.getControlNodeId(), notificationRuleId); new DbLogEntry().logEvent(event.getControlNodeInstanceId(), scenarioInstanceId, "registered"); return requestId; } public static String insertAttributesIntoQueryString( String queryString, int scenarioInstanceId, int scenarioId) { if (queryString.contains(" ScenarioInstance scenario = new ScenarioInstance(scenarioId, scenarioInstanceId); for (DataAttributeInstance attribute : scenario .getDataManager().getDataAttributeInstances()) { String dataattributePath = String.format(" attribute.getDataObject().getName(), attribute.getName()); queryString = queryString.replace(dataattributePath, attribute.getValue().toString()); } } return queryString; } public static void registerExclusiveEvents(List<AbstractEvent> events) { DbEventMapping mapping = new DbEventMapping(); mapping.saveAlternativeEvents(events); } private static String sendQueryToEventService(String rawQuery, String requestId, int scenarioInstanceId, int scenarioId) { String notificationPath = String.format(SELF_PATH_NODES, SELF_DEPLOY_URL, scenarioId, scenarioInstanceId, requestId); return sendQueryToEventService(rawQuery, requestId, notificationPath); } private static String sendQueryToEventService( String rawQuery, String requestId, String notificationPath) { // since some symbols (mainly < and >) are escaped in the fragment xml, we need to unescape them. String query = StringEscapeUtils.unescapeHtml4(rawQuery); logger.debug("Sending EventQuery to Unicorn: " + query + " " + requestId); JsonObject queryRequest = new JsonObject(); queryRequest.addProperty("queryString", query); queryRequest.addProperty("notificationPath", notificationPath); Gson gson = new Gson(); Client client = ClientBuilder.newClient(); client.property(ClientProperties.CONNECT_TIMEOUT, 1000); client.property(ClientProperties.READ_TIMEOUT, 1000); WebTarget target = client.target(REST_DEPLOY_URL).path(REST_PATH); try { Response response = target.request() .post(Entity.json(gson.toJson(queryRequest))); if (response.getStatus() != 200) { // throw new RuntimeException("Query could not be registered"); logger.warn("Could not register Query \"" + query + "\""); return "-1"; } else { // return the UUID of the Notification Rule // so that it can be removed later return response.readEntity(String.class); } } catch (ProcessingException e) { logger.warn("Could not register Query \"" + query+ "\""); return "-1"; } } public static void unregisterEvent(int eventControlNodeId, int fragmentInstanceId) { DbEventMapping eventMapping = new DbEventMapping(); String notificationRuleId = eventMapping.getNotificationRuleId(eventControlNodeId); unregisterNotificationRule(notificationRuleId); eventMapping.removeEventMapping(fragmentInstanceId, eventControlNodeId); } private static void unregisterNotificationRule(String notificationRuleId) { Client client = ClientBuilder.newClient(); client.property(ClientProperties.CONNECT_TIMEOUT, 1000); client.property(ClientProperties.READ_TIMEOUT, 1000); try { WebTarget target = client.target(REST_DEPLOY_URL).path(REST_PATH + "/" + notificationRuleId); Response response = target.request().delete(); if(response.getStatus() != 200) { logger.debug("Could not unregister Query"); } } catch (ProcessingException e) { logger.debug("Could not unregister Query"); } } }