List of usage examples for java.util ArrayList remove
public boolean remove(Object o)
From source file:com.peter.mavenrunner.MavenRunnerTopComponent.java
private void editGoalMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editGoalMenuItemActionPerformed TreePath path = projectTree.getSelectionPath(); if (path == null) { return;/*from w w w. j av a 2 s.c o m*/ } MyTreeNode node = (MyTreeNode) ((MyTreeNode) path.getLastPathComponent()); if (node.type.equals("goal")) { MavenGoalDialog dialog = new MavenGoalDialog(null, true); dialog.setTitle("Edit goals"); dialog.setLocationRelativeTo(addGoalMenuItem); dialog.nameTextField.setText(node.name); dialog.goalsTextField.setText(node.goals); dialog.profileTextField.setText(node.profile); dialog.propertiesTextArea.setText(StringUtils.join(node.properties, "\n")); dialog.skipTestsCheckBox.setSelected(node.skipTests); dialog.setVisible(true); if (!dialog.isCancel) { String name = dialog.nameTextField.getText(); if (name.trim().equals("")) { return; } String key = node.projectInformation.getDisplayName(); ArrayList<PersistData> list = data.get(key); if (list == null) { list = new ArrayList<PersistData>(); data.put(key, list); } int index = 0; Iterator<PersistData> i = list.iterator(); while (i.hasNext()) { PersistData p = i.next(); if (p.name.equals(node.name)) { break; } index++; } String goals = dialog.goalsTextField.getText(); String profile = dialog.profileTextField.getText(); List<String> properties = Arrays.asList(dialog.propertiesTextArea.getText().split("\n")); boolean skipTests = dialog.skipTestsCheckBox.isSelected(); log("index=" + index); list.remove(index); list.add(index, new PersistData(node.type, node.projectInformation.getDisplayName(), name, goals, profile, properties, skipTests)); node.name = name; node.goals = goals; node.profile = profile; node.properties = properties; node.skipTests = skipTests; projectTree.updateUI(); NbPreferences.forModule(this.getClass()).put("data", toString(data)); } } }
From source file:edu.isi.wings.catalog.component.api.impl.kb.ComponentReasoningKB.java
/** * <b>Query 4.2</b><br/> * This function is supposed to <b>SET</b> the DataSet Metrics, or Parameter * Values for the Variables that are passed in via the input/output maps as * part of details.<br/>/*from www . j a v a2s. c o m*/ * Variables will already be bound to dataObjects, so the function will have * to do something like the following : * * <pre> * If Variable.isParameterVariable() Variable.setParameterValue(value) * If Variable.isDataVariable() Variable.getDataObjectBinding().setDataMetrics(xml) * </pre> * * @param details * A ComponentDetails Object which contains: * <ul> * <li>component, * <li>maps of component input arguments to template variables, * <li>maps of component output arguments to template variables, * <li>template variable descriptions (dods) - list of triples * </ul> * @return List of extra template variable descriptions (will mostly be * empty in Q4.2 though) */ public ArrayList<ComponentPacket> findOutputDataPredictedDescriptions(ComponentPacket details) { ArrayList<ComponentPacket> list = new ArrayList<ComponentPacket>(); HashMap<String, KBObject> omap = this.objPropMap; HashMap<String, KBObject> dmap = this.dataPropMap; // If the component has no rules, then simplify !! // Extract info from details object ComponentVariable c = details.getComponent(); HashMap<String, Variable> sRoleMap = details.getStringRoleMaps(); HashMap<String, Boolean> noParamBindings = new HashMap<String, Boolean>(); ArrayList<KBTriple> redbox = details.getRequirements(); Component comp = this.getCachedComponent(c.getBinding().getID()); if (comp == null) { logger.debug(c.getBinding().getID() + " is not a valid component"); details.addExplanations(c.getBinding().getID() + " is not a valid component"); details.setInvalidFlag(true); list.add(details); return list; } c.setRequirements(comp.getComponentRequirement()); boolean typesOk = true; // Set default parameter values (if not already set) // - Also recheck type compatibility ArrayList<String> inputRoles = new ArrayList<String>(); for (ComponentRole role : comp.getInputs()) { inputRoles.add(role.getRoleName()); Variable v = sRoleMap.get(role.getRoleName()); if (role.isParam()) { if (v.getBinding() == null) { v.setBinding(new ValueBinding(role.getParamDefaultalue())); noParamBindings.put(v.getID(), true); } else if (v.getBinding().getValue() == null) { v.getBinding().setValue(role.getParamDefaultalue()); noParamBindings.put(v.getID(), true); } } else { ArrayList<String> varclassids = new ArrayList<String>(); ArrayList<Metric> vartypes = v.getBinding().getMetrics().getMetrics().get(KBUtils.RDF + "type"); if (vartypes != null) { for (Metric m : vartypes) { varclassids.add(m.getValueAsString()); } // Check type compatibility of roles if (!checkTypeCompatibility(varclassids, role.getID())) { details.addExplanations("INFO " + comp + " is not selectable because " + role.getID() + " is not type compatible with variable binding: " + v.getBinding()); typesOk = false; break; } } } } details.setInputRoles(inputRoles); if (!typesOk) { details.setInvalidFlag(true); list.add(details); return list; } if (!comp.hasRules()) { // No rules. Just set default parameter values (if not already set) list.add(details); return list; } // Create a new temporary KB store to run rules on KBAPI tkb = this.ontologyFactory.getKB(OntSpec.PLAIN); KBObject compobj = this.kb.getIndividual(comp.getID()); // Add component to the temporary KB store (add all its classes // explicitly) KBObject tcomp = this.copyObjectIntoKB(comp.getID(), compobj, tkb, this.pcdomns, null, false); // Keep a map of variable object to variable name HashMap<Variable, String> variableNameMap = new HashMap<Variable, String>(); for (String rolestr : sRoleMap.keySet()) { Variable var = sRoleMap.get(rolestr); // Map template variable to a temporary variable for running rules // - Reason is that the same variable may be used in multiple roles // and we want to distinguish them String variableName = var.getID() + "_" + rolestr; variableNameMap.put(var, variableName); } // Add the information from redbox to the temporary KB store // Cache varid to varobj HashMap<String, KBObject> varIDObjMap = new HashMap<String, KBObject>(); for (Variable var : sRoleMap.values()) { KBObject varobj = tkb.getResource(variableNameMap.get(var)); varIDObjMap.put(var.getID(), varobj); } // Add information from redbox for (KBTriple t : redbox) { KBObject subj = varIDObjMap.get(t.getSubject().getID()); KBObject obj = varIDObjMap.get(t.getObject().getID()); if (subj == null) subj = t.getSubject(); if (obj == null) obj = t.getObject(); tkb.addTriple(subj, t.getPredicate(), obj); } // Get a mapping of ArgID's to arg for the Component // Also note which roles are inputs HashMap<String, ComponentRole> argMaps = new HashMap<String, ComponentRole>(); HashMap<String, Boolean> sInputRoles = new HashMap<String, Boolean>(); for (ComponentRole role : comp.getInputs()) { argMaps.put(role.getRoleName(), role); sInputRoles.put(role.getRoleName(), true); } for (ComponentRole role : comp.getOutputs()) { argMaps.put(role.getRoleName(), role); } // Convert metrics to Property assertions in the Temporary KB for (String rolestr : sRoleMap.keySet()) { Variable var = sRoleMap.get(rolestr); ComponentRole arg = argMaps.get(rolestr); if (arg == null) { details.addExplanations("ERROR Component catalog cannot recognize role id " + rolestr); continue; } String variableName = variableNameMap.get(var); // Get a KBObject for the temporary variable KBObject varobj = tkb.getResource(variableName); if (var.isDataVariable()) { // If the variable is a data variable (& is bound) if (var.getBinding() != null) { // Convert Metrics to PC properties in order to run rules Metrics metrics = var.getBinding().getMetrics(); HashMap<String, ArrayList<Metric>> propValMap = metrics.getMetrics(); for (String propid : propValMap.keySet()) { for (Metric tmp : propValMap.get(propid)) { Object val = tmp.getValue(); String valstring = tmp.getValueAsString(); int type = tmp.getType(); String dtype = tmp.getDatatype(); KBObject metricProp = this.kb.getProperty(propid); if (metricProp != null) { //System.out.println(var.getName()+": " + propid + " = " +valstring); if (type == Metric.URI) { // Object Property KBObject valobj = this.kb.getResource(valstring); if (valobj == null) { // TODO: Log and explain (make a utility // function) details.addExplanations( "ERROR Cannot Recognize Metrics Value " + valstring); continue; } // Copy over the object class into kb as well // (except where the object itself is a class) if (!metricProp.getID().equals(KBUtils.RDF + "type")) { valobj = this.copyObjectIntoKB(valobj.getID(), valobj, tkb, null, null, true); // Remove any existing values first for (KBTriple t : tkb.genericTripleQuery(varobj, metricProp, null)) tkb.removeTriple(t); } // Add a Triple for the metric property value tkb.addTriple(varobj, metricProp, valobj); } else if (type == Metric.LITERAL && val != null) { // Literal value KBObject tobj = dtype != null ? tkb.createXSDLiteral(valstring, dtype) : tkb.createLiteral(val); if (tobj != null) { // Remove any existing values first for (KBTriple t : tkb.genericTripleQuery(varobj, metricProp, null)) tkb.removeTriple(t); // Add a Triple for the metric propertyvalue tkb.addTriple(varobj, metricProp, tobj); } else { details.addExplanations("ERROR Cannot Convert Metrics Value " + valstring); continue; } } } else { // TODO: Log and explain (make a utility function) details.addExplanations( "ERROR No Such Metrics Property Known to Component Catalog : " + propid); continue; } } } // Create other standard PC properties on variable // - hasDimensionSizes // - hasBindingID if (var.getBinding().isSet()) { String dimensionSizes = ""; ArrayList<Binding> vbs = new ArrayList<Binding>(); vbs.add(var.getBinding()); while (!vbs.isEmpty()) { Binding vb = vbs.remove(0); if (vb.isSet()) { for (WingsSet vs : vb) { vbs.add((Binding) vs); } if (!dimensionSizes.equals("")) dimensionSizes += ","; dimensionSizes += vb.getSize(); } } tkb.setPropertyValue(varobj, dmap.get("hasDimensionSizes"), tkb.createLiteral(dimensionSizes)); } if (var.getBinding().getID() != null) tkb.addTriple(varobj, dmap.get("hasBindingID"), tkb.createLiteral(var.getBinding().getName())); else tkb.addTriple(varobj, dmap.get("hasBindingID"), tkb.createLiteral("")); // end if (var.getDataBinding() != null) } // end if (var.isDataVariable()) } else if (var.isParameterVariable()) { // If the Variable/Argument is a Parameter ValueBinding parambinding = (ValueBinding) var.getBinding(); if (parambinding != null && parambinding.getValue() != null) { // If the template has any value specified, use that instead //arg_value = tkb.createLiteral(var.getBinding().getValue()); KBObject arg_value = tkb.createXSDLiteral(parambinding.getValueAsString(), parambinding.getDatatype()); tkb.setPropertyValue(varobj, dmap.get("hasValue"), arg_value); } if (dmap.containsKey("hasBindingID")) // Set the hasBindingID term tkb.addTriple(varobj, dmap.get("hasBindingID"), tkb.createLiteral("Param" + arg.getName())); } // Copy argument classes from Catalog as classes for the temporary // variable in the temporary kb store KBObject argobj = kb.getIndividual(arg.getID()); this.copyObjectClassesIntoKB(varobj.getID(), argobj, tkb, null, null, true); // Set the temporary variable's argumentID so rules can get/set // triples based on the argument tkb.addTriple(varobj, dmap.get("hasArgumentID"), tkb.createLiteral(rolestr)); // Set hasInput or hasOutput for the temporary Variable if (sInputRoles.containsKey(rolestr)) { tkb.addTriple(tcomp, omap.get("hasInput"), varobj); } else { tkb.addTriple(tcomp, omap.get("hasOutput"), varobj); } // end of for (String rolestr : sRoleMap.keySet()) } // Add all metrics and datametrics properties to temporary store tkb.addTriples(metricTriples); // Set current output variable metrics to do a diff with later for (String rolestr : sRoleMap.keySet()) { Variable var = sRoleMap.get(rolestr); if (var.isDataVariable() && !sInputRoles.containsKey(rolestr)) { Metrics metrics = new Metrics(); KBObject varobj = tkb.getResource(variableNameMap.get(var)); // Create Metrics from PC Properties for (KBObject metricProp : metricProps) { KBObject val = tkb.getPropertyValue(varobj, metricProp); if (val == null) continue; // Add value if (val.isLiteral()) metrics.addMetric(metricProp.getID(), new Metric(Metric.LITERAL, val.getValue(), val.getDataType())); else metrics.addMetric(metricProp.getID(), new Metric(Metric.URI, val.getID())); } var.getBinding().setMetrics(metrics); } } KBRuleList rules = this.getCachedComponentRules(comp); if (rules.getRules().size() > 0) { // Redirect Standard output to a byte stream ByteArrayOutputStream bost = new ByteArrayOutputStream(); PrintStream oldout = System.out; System.setOut(new PrintStream(bost, true)); // *** Run propagation rules on the temporary ontmodel *** tkb.setRulePrefixes(this.rulePrefixes); tkb.applyRules(rules); //tkb.applyRulesFromString(allrules); // Add printouts from rules as explanations if (!bost.toString().equals("")) { for (String exp : bost.toString().split("\\n")) { details.addExplanations(exp); } } // Reset the Standard output System.setOut(oldout); } // Check if the rules marked this component as invalid for // the current component details packet KBObject invalidProp = this.dataPropMap.get("isInvalid"); KBObject isInvalid = tkb.getPropertyValue(tcomp, invalidProp); if (isInvalid != null && (Boolean) isInvalid.getValue()) { details.addExplanations("INFO " + tcomp + " is not valid for its inputs"); logger.debug(tcomp + " is not valid for its inputs"); details.setInvalidFlag(true); list.add(details); return list; } // Check component dependencies // If set, overwrite the component dependencies with these ComponentRequirement req = this.getComponentRequirements(tcomp, tkb); if (req != null) { if (req.getMemoryGB() != 0) c.getRequirements().setMemoryGB(req.getMemoryGB()); if (req.getStorageGB() != 0) c.getRequirements().setStorageGB(req.getStorageGB()); } // Set values of variables by looking at values set by rules // in temporary kb store // - Only set if there isn't already a binding value for the variable for (Variable var : sRoleMap.values()) { if (var.isParameterVariable() && (noParamBindings.containsKey(var.getID()) || var.getBinding() == null || var.getBinding().getValue() == null)) { KBObject varobj = tkb.getResource(variableNameMap.get(var)); KBObject origvarobj = tkb.getResource(var.getID()); KBObject val = tkb.getPropertyValue(varobj, dmap.get("hasValue")); if (val != null && val.getValue() != null) { tkb.addTriple(origvarobj, tkb.getResource(this.wflowns + "hasParameterValue"), val); var.setBinding(new ValueBinding(val.getValue(), val.getDataType())); } } } // To create the output Variable metrics, we go through the metrics // property of the output data variables and get their metrics property // values for (String rolestr : sRoleMap.keySet()) { Variable var = sRoleMap.get(rolestr); if (var.isDataVariable() && !sInputRoles.containsKey(rolestr)) { Metrics curmetrics = var.getBinding().getMetrics(); Metrics metrics = new Metrics(); KBObject varobj = tkb.getResource(variableNameMap.get(var)); // Create Metrics from PC Properties for (KBObject metricProp : metricProps) { ArrayList<KBObject> vals = tkb.getPropertyValues(varobj, metricProp); if (vals == null) continue; for (KBObject val : vals) { if (vals.size() > 1) { if (!curmetrics.getMetrics().containsKey(metricProp.getID())) continue; // If multiple values present, ignore value that is equal to current value for (Metric mval : curmetrics.getMetrics().get(metricProp.getID())) { if (!val.isLiteral() && val.getID().equals(mval.getValue())) continue; else if (val.isLiteral() && val.getValue().equals(mval.getValue())) continue; } } // Add value if (val.isLiteral()) metrics.addMetric(metricProp.getID(), new Metric(Metric.LITERAL, val.getValue(), val.getDataType())); else metrics.addMetric(metricProp.getID(), new Metric(Metric.URI, val.getID())); } } ArrayList<KBObject> clses = this.getAllClassesOfInstance(tkb, varobj.getID()); for (KBObject cls : clses) metrics.addMetric(KBUtils.RDF + "type", new Metric(Metric.URI, cls.getID())); // Set metrics for the Binding if (var.getBinding() != null) var.getBinding().setMetrics(metrics); // -- Dealing with Collections -- // User other Properties for creating output binding collections // and setting the collection item metrics as well // PC Properties used: // - hasDimensionSizes // - hasDimensionIndexProperties int dim = 0; final int maxdims = 10; // not more than 10 dimensions int[] dimSizes = new int[maxdims]; String[] dimIndexProps = new String[maxdims]; KBObject dimSizesObj = tkb.getPropertyValue(varobj, dmap.get("hasDimensionSizes")); KBObject dimIndexPropsObj = tkb.getPropertyValue(varobj, dmap.get("hasDimensionIndexProperties")); // Parse dimension sizes string (can be given as a comma-separated list) // Example 2,3 // - This will create a 2x3 matrix if (dimSizesObj != null && dimSizesObj.getValue() != null) { if (dimSizesObj.getValue().getClass().getName().equals("java.lang.Integer")) { dimSizes[0] = (Integer) dimSizesObj.getValue(); dim = 1; } else { String dimSizesStr = (String) dimSizesObj.getValue(); for (String dimSize : dimSizesStr.split(",")) { try { int size = Integer.parseInt(dimSize); dimSizes[dim] = size; dim++; } catch (Exception e) { } } } } // Parse dimension index string (can be given as a comma // separated list) // Example hasXIndex, hasYIndex // - This will set each output item's // - first dimension index using property hasXIndex // - second dimension index using property hasYIndex // Example output: // - output // - output0 (hasXIndex 0) // - output00 (hasXIndex 0, hasYIndex 0) // - output01 (hasXIndex 0, hasYIndex 1) // - output0 (hasXIndex 1) // - output10 (hasXIndex 1, hasYIndex 0) // - output11 (hasXIndex 1, hasYIndex 1) if (dimIndexPropsObj != null && dimIndexPropsObj.getValue() != null) { int xdim = 0; String dimIndexPropsStr = (String) dimIndexPropsObj.getValue(); for (String dimIndexProp : dimIndexPropsStr.split(",")) { try { dimIndexProps[xdim] = dimIndexProp; xdim++; } catch (Exception e) { } } } // If the output is a collection // dim = 1 is a List // dim = 2 is a Matrix // dim = 3 is a Cube // .. and so on if (dim > 0) { int[] dimCounters = new int[dim]; dimCounters[0] = 1; for (int k = 1; k < dim; k++) { int perms = 1; for (int l = k - 1; l >= 0; l--) perms *= dimSizes[l]; dimCounters[k] = dimCounters[k - 1] + perms; } Binding b = var.getBinding(); ArrayList<Binding> vbs = new ArrayList<Binding>(); vbs.add(b); int counter = 0; while (!vbs.isEmpty()) { Binding vb = vbs.remove(0); if (vb.getMetrics() == null) continue; int vdim = 0; for (vdim = 0; vdim < dim; vdim++) { if (counter < dimCounters[vdim]) break; } if (vdim < dim) { for (int i = 0; i < dimSizes[vdim]; i++) { Binding cvb = new Binding(b.getNamespace() + UuidGen.generateAUuid("" + i)); // Copy over metrics from parent variable binding Metrics tmpMetrics = new Metrics(vb.getMetrics()); // Add dimension index (if property set) String prop = dimIndexProps[vdim]; if (prop != null && !prop.equals("")) { Metric nm = new Metric(Metric.LITERAL, i, KBUtils.XSD + "integer"); tmpMetrics.addMetric(this.dcdomns + prop, nm); } cvb.setMetrics(tmpMetrics); vb.add(cvb); vbs.add(cvb); } } counter++; } } // end if(dim > 0) } } // FIXME: Handle multiple configurations list.add(details); return list; }
From source file:com.krawler.spring.crm.accountModule.crmAccountDAOImpl.java
public KwlReturnObject getCrmAccountCustomData(HashMap<String, Object> requestParams) throws ServiceException { List ll = null;//from www . ja v a 2s .c o m int dl = 0; try { ArrayList filter_names = new ArrayList(); ArrayList filter_params = new ArrayList(); if (requestParams.containsKey("filter_names")) { filter_names = new ArrayList((List<String>) requestParams.get("filter_names")); } if (requestParams.containsKey("filter_values")) { filter_params = new ArrayList((List<String>) requestParams.get("filter_values")); } String Hql = "from CrmAccountCustomData "; String filterQuery = StringUtil.filterQuery(filter_names, "where"); int ind = filterQuery.indexOf("("); if (ind > -1) { int index = Integer.valueOf(filterQuery.substring(ind + 1, ind + 2)); filterQuery = filterQuery.replaceAll("(" + index + ")", filter_params.get(index).toString()); filter_params.remove(index); } Hql += filterQuery; ll = executeQueryPaging(Hql, filter_params.toArray(), new Integer[] { 0, 1 }); dl = ll.size(); } catch (Exception e) { e.printStackTrace(); throw ServiceException.FAILURE("crmAccountDAOImpl.getCrmAccountCustomData : " + e.getMessage(), e); } return new KwlReturnObject(true, KWLErrorMsgs.S01, "", ll, dl); }
From source file:com.ntua.cosmos.hackathonplanneraas.Planner.java
/** * // w w w . j av a 2 s .c o m * @param params * @param thr * @return */ public boolean compareProbParams(ArrayList<String> params, double thr) { //query for all problem ATTRIBUTES of each problem in localstore. System.out.println("***************************************"); System.out.println( "At this point we are checking if a similar problem " + "structure is present in the Case Base."); System.out.println("***************************************\n\n"); StoredPaths pan = new StoredPaths(); boolean isworthchecking = false; double similarity; ArrayList<ArrayList<String>> contents = new ArrayList<>(); ArrayList<String> tempparam = new ArrayList<>(); ArrayList<String> namelist = new ArrayList<>(); String tempname = ""; for (int i = 0; i < params.size(); i++) { String tempName = params.get(i); if (tempName.equals("ttl")) { params.remove(i); } } //Begin the initialisation process. OntModelSpec s = new OntModelSpec(OntModelSpec.OWL_DL_MEM); OntDocumentManager dm = OntDocumentManager.getInstance(); dm.setFileManager(FileManager.get()); s.setDocumentManager(dm); OntModel m = ModelFactory.createOntologyModel(s, null); InputStream in = FileManager.get().open(StoredPaths.casebasepath); if (in == null) { throw new IllegalArgumentException("File: " + StoredPaths.casebasepath + " not found"); } // read the file m.read(in, null); //begin building query string. String queryString = pan.prefixrdf + pan.prefixowl + pan.prefixxsd + pan.prefixrdfs + pan.prefixCasePath; queryString += "\nSELECT distinct ?prob ?param WHERE { ?prob ?param ?value . ?prob base:hasCaseType \"problem\"^^xsd:string . filter isLiteral(?value) . ?param a owl:DatatypeProperty . filter not exists{ { filter regex(str(?value), \"problem\" )} union {?prob ?param true} union {?prob ?param false} } }"; System.out.println("***************************************"); System.out.println("Query String used: "); System.out.println(queryString); System.out.println("***************************************\n\n"); try { Query query = QueryFactory.create(queryString); QueryExecution qe = QueryExecutionFactory.create(query, m); ResultSet results = qe.execSelect(); int i = 0; for (; results.hasNext();) { QuerySolution soln = results.nextSolution(); // Access variables: soln.get("x"); Resource res; Resource res2; res = soln.getResource("prob");// Get a result variable by name. if (!res.getURI().equalsIgnoreCase(tempname)) { tempname = res.getURI(); namelist.add(res.getURI()); i++; if (!tempparam.isEmpty()) contents.add(new ArrayList<>(tempparam)); tempparam.clear(); } res2 = soln.getResource("param"); tempparam.add(res2.getURI().substring(res2.getURI().indexOf('#') + 1)); } qe.close(); contents.add(new ArrayList<>(tempparam)); } catch (NumberFormatException e) { System.out.println("Query not valid."); } m.close(); ArrayList<String> union = new ArrayList<>(); ArrayList<String> intersection = new ArrayList<>(); int i = 0; for (ArrayList<String> content : contents) { intersection.addAll(params); intersection.retainAll(content); union.addAll(content); similarity = intersection.size() / union.size(); if (similarity >= thr) { isworthchecking = true; System.out.println("The Case is worth checking because of this " + similarity + " metric " + "in problem identified as " + namelist.get(i) + "."); } i++; intersection.clear(); union.clear(); } return isworthchecking; }
From source file:com.datatorrent.stram.plan.physical.PhysicalPlan.java
void removePTOperator(PTOperator oper) { LOG.debug("Removing operator " + oper); // per partition merge operators if (!oper.upstreamMerge.isEmpty()) { for (PTOperator unifier : oper.upstreamMerge.values()) { removePTOperator(unifier);/*ww w . j a va 2s.co m*/ } } // remove inputs from downstream operators for (PTOutput out : oper.outputs) { for (PTInput sinkIn : out.sinks) { if (sinkIn.source.source == oper) { ArrayList<PTInput> cowInputs = Lists.newArrayList(sinkIn.target.inputs); cowInputs.remove(sinkIn); sinkIn.target.inputs = cowInputs; } } } // remove from upstream operators for (PTInput in : oper.inputs) { in.source.sinks.remove(in); } for (HostOperatorSet s : oper.groupings.values()) { s.getOperatorSet().remove(oper); } // remove checkpoint states try { synchronized (oper.checkpoints) { for (Checkpoint checkpoint : oper.checkpoints) { oper.operatorMeta.getValue(OperatorContext.STORAGE_AGENT).delete(oper.id, checkpoint.windowId); } } } catch (IOException e) { LOG.warn("Failed to remove state for " + oper, e); } List<PTOperator> cowList = Lists.newArrayList(oper.container.operators); cowList.remove(oper); oper.container.operators = cowList; this.deployOpers.remove(oper); this.undeployOpers.add(oper); this.allOperators.remove(oper.id); this.ctx.recordEventAsync(new StramEvent.RemoveOperatorEvent(oper.getName(), oper.getId())); }
From source file:de.bayern.gdi.processor.AtomDownloadJob.java
@Override protected void download() throws JobExecutionException { Document ds = getDocument(figureoutDatasource()); HashMap<String, String> vars = new HashMap<>(); vars.put("VARIATION", this.variation); NodeList nl = (NodeList) XML.xpath(ds, XPATH_LINKS, XPathConstants.NODESET, NAMESPACE_CONTEXT, vars); ArrayList<DLFile> files = new ArrayList<>(nl.getLength()); String format = "%0" + places(nl.getLength()) + "d.%s"; for (int i = 0, j = 0, n = nl.getLength(); i < n; i++) { Element link = (Element) nl.item(i); String href = link.getAttribute("href"); if (href.isEmpty()) { continue; }//from w w w. j a va2 s. c o m URL dataURL = toURL(href); String fileName; // Service call? if (dataURL.getQuery() != null) { String type = link.getAttribute("type"); String ext = mimetypeToExt(type); fileName = String.format(format, j, ext); j++; } else { // Direct download. // XXX: Do more to prevent directory traversals? fileName = new File(dataURL.getPath()).getName().replaceAll("\\.+", "."); if (fileName.isEmpty()) { String type = link.getAttribute("type"); String ext = mimetypeToExt(type); fileName = String.format(format, j, ext); j++; } } File file = new File(this.workingDir, fileName); files.add(new DLFile(file, dataURL)); } int failed = 0; int numFiles = files.size(); for (;;) { for (int i = 0; i < files.size();) { DLFile file = files.get(i); if (downloadFile(file)) { files.remove(i); } else { if (++file.tries < MAX_TRIES) { i++; } else { failed++; files.remove(i); } } broadcastMessage( I18n.format("atom.downloaded.files", numFiles - failed - files.size(), files.size())); } if (files.isEmpty()) { break; } try { Thread.sleep(FAIL_SLEEP); } catch (InterruptedException ie) { break; } } log.log(Level.INFO, "Bytes downloaded: " + this.totalCount); if (failed > 0) { throw new JobExecutionException(I18n.format("atom.downloaded.failed", numFiles - failed, failed)); } broadcastMessage(I18n.format("atom.downloaded.success", numFiles)); }
From source file:fr.natoine.PortletAnnotation.PortletCreateAnnotation.java
private void doUnColorSelection(ActionRequest request, ActionResponse response) { ArrayList<HighlightSelectionHTML> _colored_selections = (ArrayList<HighlightSelectionHTML>) request .getPortletSession().getAttribute("colored_selections"); if (_colored_selections == null) _colored_selections = new ArrayList<HighlightSelectionHTML>(); String _selection_id = request.getParameter("to_uncolor"); //rcuprer la slection ArrayList _selections = (ArrayList) request.getPortletSession().getAttribute("selections"); HighlightSelectionHTML _selection_to_color = null; for (Object _selection : _selections) { if (_selection instanceof HighlightSelectionHTML) { if (((HighlightSelectionHTML) _selection).getId().compareTo(_selection_id) == 0) { _selection_to_color = (HighlightSelectionHTML) _selection; break; }/*from www. j a va2 s . c o m*/ } } if (_selection_to_color != null) { //envoyer la slection en event au Browser sendEvent("todelete", _selection_to_color, response); //enlever la slection la liste des colors _colored_selections.remove(_selection_to_color); request.getPortletSession().setAttribute("colored_selections", _colored_selections); } }
From source file:it.cnr.icar.eric.client.ui.swing.RegistryObjectsTable.java
/** * DOCUMENT ME!/*w ww. ja va2 s . c om*/ */ @SuppressWarnings("unchecked") protected void removeAction() { RegistryBrowser.setWaitCursor(); int[] selectedIndices = getSelectedRows(); if (selectedIndices.length >= 1) { try { ArrayList<?> selectedObjects = getSelectedRegistryObjects(); ArrayList<Key> removeKeys = new ArrayList<Key>(); int size = selectedObjects.size(); for (int i = size - 1; i >= 0; i--) { RegistryObject obj = (RegistryObject) selectedObjects.get(i); Key key = obj.getKey(); removeKeys.add(key); } // Confirm the remove boolean confirmRemoves = true; // I18N: Do not localize next statement. String confirmRemovesStr = ProviderProperties.getInstance() .getProperty("jaxr-ebxml.registryBrowser.confirmRemoves", "true"); if (confirmRemovesStr.equalsIgnoreCase("false") || confirmRemovesStr.toLowerCase().equals("off")) { confirmRemoves = false; } if (confirmRemoves) { int option = JOptionPane.showConfirmDialog(null, resourceBundle.getString("dialog.confirmRemove.text"), resourceBundle.getString("dialog.confirmRemove.title"), JOptionPane.YES_NO_OPTION); if (option == JOptionPane.NO_OPTION) { RegistryBrowser.setDefaultCursor(); return; } } // cancels the cell editor, if any removeEditor(); JAXRClient client = RegistryBrowser.getInstance().getClient(); BusinessLifeCycleManager lcm = client.getBusinessLifeCycleManager(); BulkResponse resp = lcm.deleteObjects(removeKeys); client.checkBulkResponse(resp); if (resp.getStatus() == JAXRResponse.STATUS_SUCCESS) { //Remove from UI model @SuppressWarnings("rawtypes") ArrayList objects = (ArrayList) ((tableModel.getRegistryObjects()).clone()); size = selectedIndices.length; for (int i = size - 1; i >= 0; i--) { RegistryObject ro = (RegistryObject) dataModel.getValueAt(selectedIndices[i], -1); objects.remove(ro); } tableModel.setRegistryObjects(objects); } } catch (JAXRException e) { RegistryBrowser.displayError(e); } } else { RegistryBrowser.displayError(resourceBundle.getString("error.removeAction")); } RegistryBrowser.setDefaultCursor(); }
From source file:ai.susi.server.UserRoles.java
public void loadUserRolesFromObject() throws IllegalArgumentException { defaultRoles = new HashMap<>(); roles = new HashMap<>(); try {//from w w w .j a v a 2s. c o m ArrayList<String> queue = new ArrayList<>(); // get all user roles based on BaseUserRole. Add all other into a queue. for (String name : json.keySet()) { Log.getLog().debug("searching for key " + name); JSONObject obj = json.getJSONObject(name); if (hasMandatoryFields(obj)) { Log.getLog().debug(name + " has mandatory fields"); Log.getLog().debug("parent value is: " + obj.getString("parent")); BaseUserRole bur; try { bur = BaseUserRole.valueOf(obj.getString("parent")); } catch (IllegalArgumentException e) { queue.add(name); Log.getLog().debug("no bur, adding to queue"); continue; } Log.getLog().debug("successfully created bur from parent"); UserRole userRole = new UserRole(name, bur, null, obj); roles.put(name, userRole); } } // recursively add boolean changed = true; while (changed) { changed = false; for (String key : queue) { JSONObject obj = json.getJSONObject(key); if (roles.containsKey(obj.getString("parent"))) { UserRole parent = roles.get(obj.getString("parent")); UserRole userRole = new UserRole(key, parent.getBaseUserRole(), parent, obj); roles.put(key, userRole); queue.remove(key); changed = true; } } } Log.getLog().debug("available roles: " + roles.keySet().toString()); // get default roles JSONObject defaults = json.getJSONObject("defaults"); for (BaseUserRole bur : BaseUserRole.values()) { if (defaults.has(bur.name()) && roles.containsKey(defaults.getString(bur.name()))) { Log.getLog().debug("found default role for " + bur.name() + ": " + roles.get(defaults.getString(bur.name())).getDisplayName()); setDefaultUserRole(bur, roles.get(defaults.getString(bur.name()))); } else { Log.getLog().info("could not find default role for " + bur.name() + ", creating default role"); createDefaultUserRole(bur); } } } catch (Exception e) { defaultRoles = null; roles = null; throw new IllegalArgumentException("Could not load user roles from file: ", e); } }
From source file:edu.umd.ks.cm.util.siscm.dao.impl.SisCmDaoImpl.java
private String getNaturalLanguageForStatement(String booleanExpression, List<ReqComponentReference> reqComponentList) throws Exception { HashMap reqComponentMap = new HashMap(); LinkedHashMap<Integer, Integer> parPositionMap = new LinkedHashMap<Integer, Integer>(); ArrayList<Integer> parLeftList = new ArrayList<Integer>(); for (ReqComponentReference reqComponent : reqComponentList) { String translation = this.reqComponentTranslator.translate(reqComponent.getReqComponent(), "KUALI.RULE.CATALOG", "en"); if (translation != null && translation.length() > 0 && translation.substring(translation.length() - 1).equals(".")) translation = translation.substring(0, translation.length() - 1); reqComponentMap.put(reqComponent.getBooleanId(), translation); }//from www .j ava2 s. c o m BooleanFunction booleanFunction = new BooleanFunction(booleanExpression); List<String> funcSymbs = booleanFunction.getSymbols(); for (int i = 0; i < funcSymbs.size(); i++) { if (funcSymbs.get(i).equals("(")) { parLeftList.add(i); } int parLeftLast = parLeftList.size() - 1; if (funcSymbs.get(i).equals(")")) { parPositionMap.put(parLeftList.get(parLeftLast), i); parLeftList.remove(parLeftLast); } } // For the expression (A + B + (C * D)) want to remove outer () if (parPositionMap.containsKey(0) && parPositionMap.get(0) == funcSymbs.size() - 1) { parPositionMap.remove(0); funcSymbs.set(0, "null"); funcSymbs.set(funcSymbs.size() - 1, "null"); } if (!parPositionMap.isEmpty()) { for (Integer key : parPositionMap.keySet()) { StringBuffer funcSymb = new StringBuffer(""); int pos = 0; String expr = ""; for (int i = key + 1; i < parPositionMap.get(key); i++) { String funcSymbAdd = funcSymbs.get(i); if (!funcSymbAdd.equals("+") && !funcSymbAdd.equals("*") && !funcSymbAdd.equals("null")) { expr = (String) reqComponentMap.get(funcSymbAdd); if (pos == 0 && !funcSymbAdd.substring(0, 1).equals("V") && expr.length() > 2 && expr.substring(0, 1).equals("(") && expr.substring(expr.length() - 1).equals(")")) { expr = expr.substring(1, expr.length() - 1); } pos = 1; //convert the first character of 'expr' to lower case, if necessary if (expr.length() > 0) { char ch0 = expr.charAt(0); if (ch0 <= 'Z' && ch0 >= 'A') { if (expr.length() > 1) { char ch1 = expr.charAt(1); if (ch1 >= 'a' && ch1 <= 'z') { expr = expr.substring(0, 1).toLowerCase() + expr.substring(1); } } else { expr = expr.toLowerCase(); } } } funcSymb.append(expr); } else if (funcSymbAdd.equals("+")) { funcSymb.append("; or "); } else if (funcSymbAdd.equals("*")) { funcSymb.append("; and "); } } // for int i String id = "V" + Integer.toString(key); funcSymb.insert(0, "("); funcSymb.append(")"); reqComponentMap.put(id, funcSymb.toString()); funcSymbs.set(key, id); for (int i = key + 1; i < parPositionMap.get(key) + 1; i++) funcSymbs.set(i, "null"); } } List<String> funcSymbsNew = new ArrayList<String>(); for (int i = 0; i < funcSymbs.size(); i++) { if (!funcSymbs.get(i).equals("null")) funcSymbsNew.add(funcSymbs.get(i)); } String nl = ""; if (funcSymbsNew.size() == 1) { nl = (String) reqComponentMap.get(funcSymbsNew.get(0)); if (nl.substring(0, 1).equals("(") && nl.substring(nl.length() - 1).equals(")")) nl = nl.substring(1, nl.length() - 1); } else { int pos = 0; String expr = ""; for (int i = 0; i < funcSymbsNew.size(); i++) { if (!funcSymbsNew.get(i).equals("*") && !funcSymbsNew.get(i).equals("+")) { expr = (String) reqComponentMap.get(funcSymbsNew.get(i)); if (pos == 0) { if (expr.length() > 2 && expr.substring(0, 1).equals("(") && expr.substring(expr.length() - 1).equals(")")) expr = expr.substring(1, expr.length() - 1); pos = 1; } else { if (funcSymbsNew.get(i).substring(0, 1).equals("V") && expr.length() > 2 && expr.substring(0, 1).equals("(") && expr.substring(expr.length() - 1).equals(")")) expr = expr.substring(1, expr.length() - 1); } nl = nl + expr; } else if (funcSymbsNew.get(i).equals("+")) { if ((i > 0 && funcSymbsNew.get(i - 1).substring(0, 1).equals("V")) || (i < (funcSymbsNew.size() - 1) && funcSymbsNew.get(i + 1).substring(0, 1).equals("V"))) nl = nl + ". Or "; else nl = nl + "; or "; } else if (funcSymbsNew.get(i).equals("*")) { if ((i > 0 && funcSymbsNew.get(i - 1).substring(0, 1).equals("V")) || (i < (funcSymbsNew.size() - 1) && funcSymbsNew.get(i + 1).substring(0, 1).equals("V"))) nl = nl + ". And "; else nl = nl + "; and "; } } } //TODO: Fix Capitalization nl = nl.substring(0, 1).toUpperCase() + nl.substring(1); return nl.trim(); }