List of usage examples for java.util TreeSet isEmpty
public boolean isEmpty()
From source file:edu.duke.cabig.c3pr.domain.StudySubject.java
@Transient public StudyVersion getFirstConsentedStudyVersion() { TreeSet uniqueStudyVersions = new TreeSet(); List<StudySubjectConsentVersion> allStudySubjectConsentVersions = getAllConsents(); for (StudySubjectConsentVersion studySubjectConsentVersion : allStudySubjectConsentVersions) { uniqueStudyVersions.add(studySubjectConsentVersion.getConsent().getStudyVersion()); }/* w w w .ja va2 s .c o m*/ return uniqueStudyVersions.isEmpty() ? null : (StudyVersion) uniqueStudyVersions.first(); }
From source file:edu.duke.cabig.c3pr.domain.StudySubject.java
@Transient public StudyVersion getLastConsentedStudyVersion() { TreeSet uniqueStudyVersions = new TreeSet(); List<StudySubjectConsentVersion> allStudySubjectConsentVersions = getAllConsents(); for (StudySubjectConsentVersion studySubjectConsentVersion : allStudySubjectConsentVersions) { uniqueStudyVersions.add(studySubjectConsentVersion.getConsent().getStudyVersion()); }//from ww w . j a v a2 s . c om return uniqueStudyVersions.isEmpty() ? null : (StudyVersion) uniqueStudyVersions.last(); }
From source file:net.sourceforge.fenixedu.domain.StudentCurricularPlan.java
final public Enrolment getLatestDissertationEnrolment() { final TreeSet<Enrolment> result = new TreeSet<Enrolment>(Enrolment.COMPARATOR_BY_EXECUTION_PERIOD_AND_ID); result.addAll(getDissertationEnrolments()); return result.isEmpty() ? null : result.last(); }
From source file:org.jahia.services.importexport.ImportExportBaseService.java
private void exportNodesWithBinaries(JCRNodeWrapper rootNode, Set<JCRNodeWrapper> nodes, ZipOutputStream zout, Set<String> typesToIgnore, Set<String> externalReferences, Map<String, Object> params, boolean logProgress) throws SAXException, IOException, RepositoryException, TransformerException { TreeSet<JCRNodeWrapper> liveSortedNodes = new TreeSet<JCRNodeWrapper>(new Comparator<JCRNodeWrapper>() { @Override/*from w ww.j av a2 s. co m*/ public int compare(JCRNodeWrapper o1, JCRNodeWrapper o2) { return o1.getPath().compareTo(o2.getPath()); } }); // final String xsl = (String) params.get(XSL_PATH); if (params.containsKey(INCLUDE_LIVE_EXPORT)) { final JCRSessionWrapper liveSession = jcrStoreService.getSessionFactory().getCurrentUserSession("live"); JCRNodeWrapper liveRootNode = null; try { liveRootNode = liveSession.getNodeByIdentifier(rootNode.getIdentifier()); } catch (RepositoryException e) { } if (liveRootNode != null) { for (JCRNodeWrapper node : nodes) { try { liveSortedNodes.add(liveSession.getNodeByIdentifier(node.getIdentifier())); } catch (ItemNotFoundException e) { } } if (!liveSortedNodes.isEmpty()) { zout.putNextEntry(new ZipEntry(LIVE_REPOSITORY_XML)); logger.info("Exporting live workspace for nodes {} ...", nodes); exportNodes(liveRootNode, liveSortedNodes, zout, typesToIgnore, externalReferences, params, logProgress); zout.closeEntry(); exportNodesBinary(liveRootNode, liveSortedNodes, zout, typesToIgnore, "/live-content"); logger.info("Live workspace exported for nodes {}", nodes); } } } TreeSet<JCRNodeWrapper> sortedNodes = new TreeSet<JCRNodeWrapper>(new Comparator<JCRNodeWrapper>() { @Override public int compare(JCRNodeWrapper o1, JCRNodeWrapper o2) { return o1.getPath().compareTo(o2.getPath()); } }); sortedNodes.addAll(nodes); for (JCRNodeWrapper liveSortedNode : liveSortedNodes) { try { sortedNodes.add(rootNode.getSession().getNodeByIdentifier(liveSortedNode.getIdentifier())); } catch (ItemNotFoundException e) { // Node does not exist in default do nothing } } zout.putNextEntry(new ZipEntry(REPOSITORY_XML)); logger.info("Exporting default workspace for nodes {} ...", nodes); exportNodes(rootNode, sortedNodes, zout, typesToIgnore, externalReferences, params, logProgress); zout.closeEntry(); exportNodesBinary(rootNode, sortedNodes, zout, typesToIgnore, "/content"); logger.info("Default workspace exported for nodes {}", nodes); }
From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java
/** * add an element to the XForms document: the bind + the control * (only the control if "withBind" is false) */// w w w .j a v a2 s.com private void addElement(Document xForm, Element modelSection, Element formSection, XSElementDeclaration elementDecl, XSTypeDefinition controlType, String pathToRoot) { if (controlType == null) { // TODO!!! Figure out why this happens... for now just warn... // seems to happen when there is an element of type IDREFS LOGGER.warn("WARNING!!! controlType is null for " + elementDecl + ", " + elementDecl.getName()); return; } switch (controlType.getTypeCategory()) { case XSTypeDefinition.SIMPLE_TYPE: { addSimpleType(xForm, modelSection, formSection, (XSSimpleTypeDefinition) controlType, elementDecl, pathToRoot); break; } case XSTypeDefinition.COMPLEX_TYPE: { if (controlType.getName() != null && controlType.getName().equals("anyType")) { addAnyType(xForm, modelSection, formSection, (XSComplexTypeDefinition) controlType, elementDecl, pathToRoot); break; } else { // find the types which are compatible(derived from) the parent type. // // This is used if we encounter a XML Schema that permits the xsi:type // attribute to specify subtypes for the element. // // For example, the <address> element may be typed to permit any of // the following scenarios: // <address xsi:type="USAddress"> // </address> // <address xsi:type="CanadianAddress"> // </address> // <address xsi:type="InternationalAddress"> // </address> // // What we want to do is generate an XForm' switch element with cases // representing any valid non-abstract subtype. // // <xforms:select1 xforms:bind="xsi_type_13" // <xforms:label>Address</xforms:label> // <xforms:choices> // <xforms:item> // <xforms:label>US Address Type</xforms:label> // <xforms:value>USAddressType</xforms:value> // <xforms:action ev:event="xforms-select"> // <xforms:toggle xforms:case="USAddressType-case"/> // </xforms:action> // </xforms:item> // <xforms:item> // <xforms:label>Canadian Address Type</xforms:label> // <xforms:value>CanadianAddressType</xforms:value> // <xforms:action ev:event="xforms-select"> // <xforms:toggle xforms:case="CanadianAddressType-case"/> // </xforms:action> // </xforms:item> // <xforms:item> // <xforms:label>International Address Type</xforms:label> // <xforms:value>InternationalAddressType</xforms:value> // <xforms:action ev:event="xforms-select"> // <xforms:toggle xforms:case="InternationalAddressType-case"/> // </xforms:action> // </xforms:item> // // </xforms:choices> // <xforms:select1> // <xforms:trigger> // <xforms:label>validate Address type</xforms:label> // <xforms:action> // <xforms:dispatch id="dispatcher" xforms:name="xforms-activate" xforms:target="select1_0"/> // </xforms:action> //</xforms:trigger> // // <xforms:switch id="address_xsi_type_switch"> // <xforms:case id="USAddressType-case" selected="false"> // <!-- US Address Type sub-elements here--> // </xforms:case> // <xforms:case id="CanadianAddressType-case" selected="false"> // <!-- US Address Type sub-elements here--> // </xforms:case> // ... // </xforms:switch> // // + change bindings to add: // - a bind for the "@xsi:type" attribute // - for each possible element that can be added through the use of an inheritance, add a "relevant" attribute: // ex: xforms:relevant="../@xsi:type='USAddress'" // look for compatible types // String typeName = controlType.getName(); boolean relative = true; if (typeName != null) { TreeSet compatibleTypes = (TreeSet) typeTree.get(controlType.getName()); //TreeSet compatibleTypes = (TreeSet) typeTree.get(controlType); if (compatibleTypes != null) { relative = false; if (LOGGER.isDebugEnabled()) { LOGGER.debug("compatible types for " + typeName + ":"); Iterator it1 = compatibleTypes.iterator(); while (it1.hasNext()) { //String name = (String) it1.next(); XSTypeDefinition compType = (XSTypeDefinition) it1.next(); LOGGER.debug(" compatible type name=" + compType.getName()); } } Element control = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "select1"); String select1_id = this.setXFormsId(control); Element choices = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "choices"); this.setXFormsId(choices); //get possible values Vector enumValues = new Vector(); //add the type (if not abstract) if (!((XSComplexTypeDefinition) controlType).getAbstract()) enumValues.add(controlType); //enumValues.add(typeName); //add compatible types Iterator it = compatibleTypes.iterator(); while (it.hasNext()) { enumValues.add(it.next()); } if (enumValues.size() > 1) { String caption = createCaption(elementDecl.getName() + " Type"); Element controlCaption = (Element) control .appendChild(xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "label")); this.setXFormsId(controlCaption); controlCaption.appendChild(xForm.createTextNode(caption)); // multiple compatible types for this element exist // in the schema - allow the user to choose from // between compatible non-abstract types Element bindElement = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "bind"); String bindId = this.setXFormsId(bindElement); bindElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "nodeset", pathToRoot + "/@xsi:type"); modelSection.appendChild(bindElement); control.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "bind", bindId); //add the "element" bind, in addition Element bindElement2 = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "bind"); String bindId2 = this.setXFormsId(bindElement2); bindElement2.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "nodeset", pathToRoot); modelSection.appendChild(bindElement2); if (enumValues.size() < Long.parseLong(getProperty(SELECTONE_LONG_LIST_SIZE_PROP))) { control.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "appearance", getProperty(SELECTONE_UI_CONTROL_SHORT_PROP)); } else { control.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "appearance", getProperty(SELECTONE_UI_CONTROL_LONG_PROP)); // add the "Please select..." instruction item for the combobox // and set the isValid attribute on the bind element to check for the "Please select..." // item to indicate that is not a valid value // String pleaseSelect = "[Select1 " + caption + "]"; Element item = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "item"); this.setXFormsId(item); choices.appendChild(item); Element captionElement = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "label"); this.setXFormsId(captionElement); item.appendChild(captionElement); captionElement.appendChild(xForm.createTextNode(pleaseSelect)); Element value = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "value"); this.setXFormsId(value); item.appendChild(value); value.appendChild(xForm.createTextNode(pleaseSelect)); // not(purchaseOrder/state = '[Choose State]') //String isValidExpr = "not(" + bindElement.getAttributeNS(XFORMS_NS, "nodeset") + " = '" + pleaseSelect + "')"; // ->no, not(. = '[Choose State]') String isValidExpr = "not( . = '" + pleaseSelect + "')"; //check if there was a constraint String constraint = bindElement.getAttributeNS(XFORMS_NS, "constraint"); if ((constraint != null) && !constraint.equals("")) { constraint = constraint + " && " + isValidExpr; } else { constraint = isValidExpr; } bindElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "constraint", constraint); } Element choicesControlWrapper = _wrapper.createControlsWrapper(choices); control.appendChild(choicesControlWrapper); Element controlWrapper = _wrapper.createControlsWrapper(control); formSection.appendChild(controlWrapper); ///////////////// /////////////// // add content to select1 HashMap case_types = new HashMap(); addChoicesForSelectSwitchControl(xForm, choices, enumValues, case_types); ///////////////// //add a trigger for this control (is there a way to not need it ?) Element trigger = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "trigger"); formSection.appendChild(trigger); this.setXFormsId(trigger); Element label_trigger = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "label"); this.setXFormsId(label_trigger); trigger.appendChild(label_trigger); String trigger_caption = createCaption("validate choice"); label_trigger.appendChild(xForm.createTextNode(trigger_caption)); Element action_trigger = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "action"); this.setXFormsId(action_trigger); trigger.appendChild(action_trigger); Element dispatch_trigger = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "dispatch"); this.setXFormsId(dispatch_trigger); action_trigger.appendChild(dispatch_trigger); dispatch_trigger.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "name", "DOMActivate"); dispatch_trigger.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "target", select1_id); ///////////////// //add switch Element switchElement = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "switch"); this.setXFormsId(switchElement); Element switchControlWrapper = _wrapper.createControlsWrapper(switchElement); formSection.appendChild(switchControlWrapper); //formSection.appendChild(switchElement); /////////////// add this type ////////////// Element firstCaseElement = (Element) case_types.get(controlType.getName()); switchElement.appendChild(firstCaseElement); addComplexType(xForm, modelSection, firstCaseElement, (XSComplexTypeDefinition) controlType, elementDecl, pathToRoot, true, false); /////////////// add sub types ////////////// it = compatibleTypes.iterator(); // add each compatible type within // a case statement while (it.hasNext()) { /*String compatibleTypeName = (String) it.next(); //WARNING: order of parameters inversed from the doc for 2.6.0 !!! XSTypeDefinition type =getSchema().getTypeDefinition( compatibleTypeName, targetNamespace);*/ XSTypeDefinition type = (XSTypeDefinition) it.next(); String compatibleTypeName = type.getName(); if (LOGGER.isDebugEnabled()) { if (type == null) LOGGER.debug(">>>addElement: compatible type is null!! type=" + compatibleTypeName + ", targetNamespace=" + targetNamespace); else LOGGER.debug(" >>>addElement: adding compatible type " + type.getName()); } if (type != null && type.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { //Element caseElement = (Element) xForm.createElementNS(XFORMS_NS,getXFormsNSPrefix() + "case"); //caseElement.setAttributeNS(XFORMS_NS,getXFormsNSPrefix() + "id",bindId + "_" + type.getName() +"_case"); //String case_id=this.setXFormsId(caseElement); Element caseElement = (Element) case_types.get(type.getName()); switchElement.appendChild(caseElement); addComplexType(xForm, modelSection, caseElement, (XSComplexTypeDefinition) type, elementDecl, pathToRoot, true, true); ////// // modify bind to add a "relevant" attribute that checks the value of @xsi:type // if (LOGGER.isDebugEnabled()) DOMUtil.prettyPrintDOM(bindElement2); NodeList binds = bindElement2.getElementsByTagNameNS(XFORMS_NS, "bind"); Element thisBind = null; int nb_binds = binds.getLength(); int i = 0; while (i < nb_binds && thisBind == null) { Element subBind = (Element) binds.item(i); String name = subBind.getAttributeNS(XFORMS_NS, "nodeset"); if (LOGGER.isDebugEnabled()) LOGGER.debug("Testing sub-bind with nodeset " + name); if (this.isElementDeclaredIn(name, (XSComplexTypeDefinition) type, false) || this.isAttributeDeclaredIn(name, (XSComplexTypeDefinition) type, false)) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Element/Attribute " + name + " declared in type " + type.getName() + ": adding relevant attribute"); //test sub types of this type TreeSet subCompatibleTypes = (TreeSet) typeTree.get(type.getName()); //TreeSet subCompatibleTypes = (TreeSet) typeTree.get(type); String newRelevant = null; if (subCompatibleTypes == null || subCompatibleTypes.isEmpty()) { //just add ../@xsi:type='type' newRelevant = "../@xsi:type='" + type.getName() + "'"; } else { //add ../@xsi:type='type' or ../@xsi:type='otherType' or ... newRelevant = "../@xsi:type='" + type.getName() + "'"; Iterator it_ct = subCompatibleTypes.iterator(); while (it_ct.hasNext()) { //String otherTypeName = (String) it_ct.next(); XSTypeDefinition otherType = (XSTypeDefinition) it_ct.next(); String otherTypeName = otherType.getName(); newRelevant = newRelevant + " or ../@xsi:type='" + otherTypeName + "'"; } } //change relevant attribute String relevant = subBind.getAttributeNS(XFORMS_NS, "relevant"); if (relevant != null && !relevant.equals("")) { newRelevant = "(" + relevant + ") and " + newRelevant; } if (newRelevant != null && !newRelevant.equals("")) subBind.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "relevant", newRelevant); } i++; } } } /*if (LOGGER.isDebugEnabled()) { LOGGER.debug( "###addElement for derived type: bind created:"); DOMUtil.prettyPrintDOM(bindElement2); }*/ // we're done // break; } else if (enumValues.size() == 1) { // only one compatible type, set the controlType value // and fall through // //controlType = getSchema().getComplexType((String)enumValues.get(0)); controlType = getSchema().getTypeDefinition((String) enumValues.get(0), targetNamespace); } } else if (LOGGER.isDebugEnabled()) LOGGER.debug("No compatible type found for " + typeName); //name not null but no compatibleType? relative = true; } if (relative) //create the bind in case it is a repeat { if (LOGGER.isDebugEnabled()) LOGGER.debug(">>>Adding empty bind for " + typeName); // create the <xforms:bind> element and add it to the model. Element bindElement = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "bind"); String bindId = this.setXFormsId(bindElement); bindElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "nodeset", pathToRoot); modelSection.appendChild(bindElement); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug("addElement: bind is not relative for " + elementDecl.getName()); } //addComplexType(xForm,modelSection, formSection,(ComplexType)controlType,elementDecl,pathToRoot, relative); addComplexType(xForm, modelSection, formSection, (XSComplexTypeDefinition) controlType, elementDecl, pathToRoot, true, false); break; } } default: // TODO: add wildcard support LOGGER.warn("\nWARNING!!! - Unsupported type [" + elementDecl.getType() + "] for node [" + controlType.getName() + "]"); } }
From source file:com.datatorrent.stram.StreamingContainerManager.java
/** * Compute checkpoints required for a given operator instance to be recovered. * This is done by looking at checkpoints available for downstream dependencies first, * and then selecting the most recent available checkpoint that is smaller than downstream. * * @param operator Operator instance for which to find recovery checkpoint * @param ctx Context into which to collect traversal info */// w w w . j a va 2s .c o m public void updateRecoveryCheckpoints(PTOperator operator, UpdateCheckpointsContext ctx) { if (operator.getRecoveryCheckpoint().windowId < ctx.committedWindowId.longValue()) { ctx.committedWindowId.setValue(operator.getRecoveryCheckpoint().windowId); } if (operator.getState() == PTOperator.State.ACTIVE && (ctx.currentTms - operator.stats.lastWindowIdChangeTms) > operator.stats.windowProcessingTimeoutMillis) { // if the checkpoint is ahead, then it is not blocked but waiting for activation (state-less recovery, at-most-once) if (ctx.committedWindowId.longValue() >= operator.getRecoveryCheckpoint().windowId) { LOG.debug("Marking operator {} blocked committed window {}, recovery window {}", operator, Codec.getStringWindowId(ctx.committedWindowId.longValue()), Codec.getStringWindowId(operator.getRecoveryCheckpoint().windowId)); ctx.blocked.add(operator); } } // the most recent checkpoint eligible for recovery based on downstream state Checkpoint maxCheckpoint = Checkpoint.INITIAL_CHECKPOINT; Set<OperatorMeta> checkpointGroup = ctx.checkpointGroups.get(operator.getOperatorMeta()); if (checkpointGroup == null) { checkpointGroup = Collections.singleton(operator.getOperatorMeta()); } // find intersection of checkpoints that group can collectively move to TreeSet<Checkpoint> commonCheckpoints = new TreeSet<>(new Checkpoint.CheckpointComparator()); synchronized (operator.checkpoints) { commonCheckpoints.addAll(operator.checkpoints); } Set<PTOperator> groupOpers = new HashSet<>(checkpointGroup.size()); boolean pendingDeploy = operator.getState() == PTOperator.State.PENDING_DEPLOY; if (checkpointGroup.size() > 1) { for (OperatorMeta om : checkpointGroup) { Collection<PTOperator> operators = plan.getAllOperators(om); for (PTOperator groupOper : operators) { synchronized (groupOper.checkpoints) { commonCheckpoints.retainAll(groupOper.checkpoints); } // visit all downstream operators of the group ctx.visited.add(groupOper); groupOpers.add(groupOper); pendingDeploy |= operator.getState() == PTOperator.State.PENDING_DEPLOY; } } // highest common checkpoint if (!commonCheckpoints.isEmpty()) { maxCheckpoint = commonCheckpoints.last(); } } else { // without logical grouping, treat partitions as independent // this is especially important for parallel partitioning ctx.visited.add(operator); groupOpers.add(operator); maxCheckpoint = operator.getRecentCheckpoint(); if (ctx.recovery && maxCheckpoint.windowId == Stateless.WINDOW_ID && operator.isOperatorStateLess()) { long currentWindowId = WindowGenerator.getWindowId(ctx.currentTms, this.vars.windowStartMillis, this.getLogicalPlan().getValue(LogicalPlan.STREAMING_WINDOW_SIZE_MILLIS)); maxCheckpoint = new Checkpoint(currentWindowId, 0, 0); } } // DFS downstream operators for (PTOperator groupOper : groupOpers) { for (PTOperator.PTOutput out : groupOper.getOutputs()) { for (PTOperator.PTInput sink : out.sinks) { PTOperator sinkOperator = sink.target; if (groupOpers.contains(sinkOperator)) { continue; // downstream operator within group } if (!ctx.visited.contains(sinkOperator)) { // downstream traversal updateRecoveryCheckpoints(sinkOperator, ctx); } // recovery window id cannot move backwards // when dynamically adding new operators if (sinkOperator.getRecoveryCheckpoint().windowId >= operator .getRecoveryCheckpoint().windowId) { maxCheckpoint = Checkpoint.min(maxCheckpoint, sinkOperator.getRecoveryCheckpoint()); } if (ctx.blocked.contains(sinkOperator)) { if (sinkOperator.stats.getCurrentWindowId() == operator.stats.getCurrentWindowId()) { // downstream operator is blocked by this operator ctx.blocked.remove(sinkOperator); } } } } } // find the common checkpoint that is <= downstream recovery checkpoint if (!commonCheckpoints.contains(maxCheckpoint)) { if (!commonCheckpoints.isEmpty()) { maxCheckpoint = Objects.firstNonNull(commonCheckpoints.floor(maxCheckpoint), maxCheckpoint); } } for (PTOperator groupOper : groupOpers) { // checkpoint frozen during deployment if (!pendingDeploy || ctx.recovery) { // remove previous checkpoints Checkpoint c1 = Checkpoint.INITIAL_CHECKPOINT; LinkedList<Checkpoint> checkpoints = groupOper.checkpoints; synchronized (checkpoints) { if (!checkpoints.isEmpty() && (checkpoints.getFirst()).windowId <= maxCheckpoint.windowId) { c1 = checkpoints.getFirst(); Checkpoint c2; while (checkpoints.size() > 1 && ((c2 = checkpoints.get(1)).windowId) <= maxCheckpoint.windowId) { checkpoints.removeFirst(); //LOG.debug("Checkpoint to delete: operator={} windowId={}", operator.getName(), c1); this.purgeCheckpoints.add(new Pair<PTOperator, Long>(groupOper, c1.windowId)); c1 = c2; } } else { if (ctx.recovery && checkpoints.isEmpty() && groupOper.isOperatorStateLess()) { LOG.debug("Adding checkpoint for stateless operator {} {}", groupOper, Codec.getStringWindowId(maxCheckpoint.windowId)); c1 = groupOper.addCheckpoint(maxCheckpoint.windowId, this.vars.windowStartMillis); } } } //LOG.debug("Operator {} checkpoints: commit {} recent {}", new Object[] {operator.getName(), c1, operator.checkpoints}); groupOper.setRecoveryCheckpoint(c1); } else { LOG.debug("Skipping checkpoint update {} during {}", groupOper, groupOper.getState()); } } }
From source file:org.gvsig.framework.web.service.impl.OGCInfoServiceImpl.java
public WMSInfo getCapabilitiesFromWMS(String urlServerWMS, TreeSet<String> listCrs, String format, boolean isCalledByWizard) throws ServerGeoException { WMSInfo wmsInfo = new WMSInfo(); // put url on object WMSInfo wmsInfo.setServiceUrl(urlServerWMS); // Create hashmap to add the layers getted to the WMSInfo object Map<String, org.gvsig.framework.web.ogc.WMSLayer> layersMap = new HashMap<String, org.gvsig.framework.web.ogc.WMSLayer>(); // Create conexion with server WMS try {/*from w ww . j av a 2s . c o m*/ WMSClient wms = new WMSClient(urlServerWMS); wms.connect(null); // set server information WMSServiceInformation serviceInfo = wms.getServiceInformation(); wmsInfo.setServiceAbstract(serviceInfo.abstr); wmsInfo.setServiceName(serviceInfo.name); wmsInfo.setServiceTitle(serviceInfo.title); // set id of the request wmsinfo (service name + calendar) int hashCode = (serviceInfo.name + Calendar.getInstance()).hashCode(); wmsInfo.setId(hashCode); // get and set version String version = wms.getVersion(); wmsInfo.setVersion(version); // get and set formats Vector formatVector = wms.getFormats(); TreeSet<String> formatSet = new TreeSet<String>(); formatSet.addAll(formatVector); wmsInfo.setFormatsSupported(formatSet); if (StringUtils.isEmpty(format)) { format = getFirstFormatSupported(formatSet); wmsInfo.setFormatSelected(format); } // check format if (isCalledByWizard || (!isCalledByWizard && formatVector.contains(format))) { wmsInfo.setFormatSelected(format); // get root layer WMSLayer rootLayer = wms.getRootLayer(); // get crs (srs) (belong to layer) Vector crsVector = rootLayer.getAllSrs(); // get and set all common crs supported TreeSet<String> crsTreeSet = new TreeSet<String>(); crsTreeSet.addAll(crsVector); wmsInfo.setCrsSupported(crsTreeSet); // Create tree with layer values List<TreeNode> tree = new ArrayList<TreeNode>(); // Create root node ArrayList<WMSLayer> children = rootLayer.getChildren(); TreeNode rootNode = new TreeNode("rootLayer_" + rootLayer.getName()); rootNode.setTitle(rootLayer.getTitle()); if (children.isEmpty()) { rootNode.setFolder(false); } else { rootNode.setFolder(true); rootNode.setExpanded(true); generateWMSChildrenNodes(children, tree, listCrs, rootNode, layersMap, wmsInfo); } // Set childrenLayers paramrootLayer.getChildren() wmsInfo.setChildrenCount(children.size()); // Only register the tree if it has a layer with crs defined if (rootNode.hasChildren()) { tree.add(rootNode); wmsInfo.setLayersTree(tree); } TreeSet<String> selCrs = new TreeSet<String>(); if (listCrs.isEmpty()) { selCrs.addAll(wmsInfo.getCrsSupported()); } else { selCrs.addAll(CollectionUtils.intersection(listCrs, wmsInfo.getCrsSupported())); } wmsInfo.setCrsSelected(selCrs); // Add map that contains info of all layers wmsInfo.setLayers(layersMap); } } catch (Exception exc) { // Show exception in log and create ServerGeoException which is // captured on controller and puts message to ajax response logger.error("Exception on getCapabilitiesFromWMS", exc); throw new ServerGeoException(); } return wmsInfo; }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
private ArrayList<String> getActiveLogfilesFromCheckpointTable(TreeSet<Filename> candidates) { assert (candidates != null && !candidates.isEmpty()); ArrayList<String> activeFrontier = this.getIndexedLogfiles(getCTable()); Filename minLogfilename = null;//from ww w. j a v a 2 s .co m for (String active : activeFrontier) { Filename curFilename = new Filename(new File(active)); if (minLogfilename == null) minLogfilename = curFilename; if (curFilename.compareTo(minLogfilename) < 0) minLogfilename = curFilename; } assert (minLogfilename != null) : this + " found no minLogfile while trying to garbage collect candidates " + candidates + "; activeFrontier=" + activeFrontier; ArrayList<String> activeLogfiles = new ArrayList<String>(); for (Filename candidate : candidates) if (minLogfilename.compareTo(candidate) <= 0) activeLogfiles.add(candidate.file.toString()); log.log(Level.INFO, "{0} found min_logfile={1}; returning activeLogFiles={2}", new Object[] { this, minLogfilename, activeLogfiles }); return activeLogfiles; }
From source file:net.sourceforge.fenixedu.domain.student.Registration.java
public PrecedentDegreeInformation getLatestPrecedentDegreeInformation() { TreeSet<PrecedentDegreeInformation> degreeInformations = new TreeSet<PrecedentDegreeInformation>( Collections.reverseOrder(PrecedentDegreeInformation.COMPARATOR_BY_EXECUTION_YEAR)); ExecutionYear currentExecutionYear = ExecutionYear.readCurrentExecutionYear(); for (PrecedentDegreeInformation pdi : getPrecedentDegreesInformationsSet()) { if (!pdi.getExecutionYear().isAfter(currentExecutionYear)) { degreeInformations.add(pdi); }//w ww .j ava 2 s . co m } if (degreeInformations.isEmpty()) { return null; } return degreeInformations.iterator().next(); }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
private @Nonnull Version getVersion() throws CloudException, InternalException { Cache<Version> cache = Cache.getInstance(provider, "vCloudVersions", Version.class, CacheLevel.CLOUD, new TimePeriod<Day>(1, TimePeriod.DAY)); ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new CloudException("No context was defined for this request"); }/*w ww . j av a2 s. c o m*/ { Iterable<Version> versions = cache.get(ctx); Iterator<Version> it = (versions == null ? null : versions.iterator()); if (it != null && it.hasNext()) { return it.next(); } } // TODO: how does vCHS do version discovery? if (ctx.getCloud().getEndpoint().startsWith("https://vchs")) { // This is a complete hack that needs to be changed to reflect vCHS version discovery Version version = new Version(); version.loginUrl = ctx.getCloud().getEndpoint() + "/api/vchs/sessions"; version.version = "5.6"; cache.put(ctx, Collections.singletonList(version)); return version; } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [GET (" + (new Date()) + ")] -> " + ctx.getCloud().getEndpoint() + " >--------------------------------------------------------------------------------------"); } try { final String[] preferred = provider.getVersionPreference(); HttpClient client = getClient(false); HttpGet method = new HttpGet(ctx.getCloud().getEndpoint() + "/api/versions"); if (wire.isDebugEnabled()) { wire.debug(method.getRequestLine().toString()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; StatusLine status; try { APITrace.trace(provider, "GET versions"); response = client.execute(method); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } status = response.getStatusLine(); } catch (IOException e) { throw new CloudException(e); } if (status.getStatusCode() == HttpServletResponse.SC_OK) { HttpEntity entity = response.getEntity(); String body; try { body = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(body); wire.debug(""); } } catch (IOException e) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } try { ByteArrayInputStream bas = new ByteArrayInputStream(body.getBytes()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(bas); bas.close(); NodeList versions = doc.getElementsByTagName("VersionInfo"); TreeSet<Version> set = new TreeSet<Version>(new Comparator<Version>() { public int compare(Version version1, Version version2) { if (version1.equals(version2)) { return 0; } if (preferred != null) { for (String v : preferred) { if (v.equals(version1.version)) { return -1; } else if (v.equals(version2.version)) { return 1; } } } for (String v : VERSIONS) { if (v.equals(version1.version)) { return -1; } else if (v.equals(version2.version)) { return 1; } } return -version1.version.compareTo(version2.version); } }); for (int i = 0; i < versions.getLength(); i++) { Node versionInfo = versions.item(i); NodeList vattrs = versionInfo.getChildNodes(); String version = null; String url = null; for (int j = 0; j < vattrs.getLength(); j++) { Node attr = vattrs.item(j); if (attr.getNodeName().equalsIgnoreCase("Version") && attr.hasChildNodes()) { version = attr.getFirstChild().getNodeValue().trim(); } else if (attr.getNodeName().equalsIgnoreCase("LoginUrl") && attr.hasChildNodes()) { url = attr.getFirstChild().getNodeValue().trim(); } } if (version == null || url == null || !isSupported(version)) { continue; } Version v = new Version(); v.version = version; v.loginUrl = url; set.add(v); } if (set.isEmpty()) { throw new CloudException("Unable to identify a supported version"); } Version v = set.iterator().next(); cache.put(ctx, set); return v; } catch (IOException e) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } catch (ParserConfigurationException e) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } catch (SAXException e) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } } else { logger.error("Expected OK for GET request, got " + status.getStatusCode()); String xml = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } vCloudException.Data data = null; if (xml != null && !xml.equals("")) { Document doc = parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList errors = doc.getElementsByTagName(nsString + "Error"); if (errors.getLength() > 0) { data = vCloudException.parseException(status.getStatusCode(), errors.item(0)); } } if (data == null) { throw new vCloudException(CloudErrorType.GENERAL, status.getStatusCode(), response.getStatusLine().getReasonPhrase(), "No further information"); } logger.error("[" + status.getStatusCode() + " : " + data.title + "] " + data.description); throw new vCloudException(data); } } finally { if (wire.isDebugEnabled()) { wire.debug("<<< [GET (" + (new Date()) + ")] -> " + ctx.getEndpoint() + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } }