List of usage examples for java.util ArrayList iterator
public Iterator<E> iterator()
From source file:com.amalto.core.plugin.base.xslt.XSLTTransformerPluginBean.java
/** * Process the mappings after xsl transformation * /*from w w w . j a v a2 s.c o m*/ * @param xrefElement * @return the processed Element */ private Element processMappings(Element xrefElement) throws XtentisException { try { String xrefcluster = xrefElement.getAttribute("xrefCluster"); //$NON-NLS-1$ String xrefIn = xrefElement.getAttribute("xrefIn"); //$NON-NLS-1$ String xrefOut = xrefElement.getAttribute("xrefOut"); //$NON-NLS-1$ String xrefIgnore = xrefElement.getAttribute("xrefIgnore"); //$NON-NLS-1$ String xrefDefault = xrefElement.getAttribute("xrefDefault"); //$NON-NLS-1$ Logger.getLogger(XSLTTransformerPluginBean.class) .debug("\n xrefIgnore=" + xrefIgnore + "\n xrefDefault=" + xrefDefault); //$NON-NLS-1$ //$NON-NLS-2$ // parse xrefbein dockey1:xrefkey1,dockey2:xrefkey2 String[] mappings = xrefIn.split(","); //$NON-NLS-1$ HashMap<String, String> itemvals = new HashMap<String, String>(); for (int j = 0; j < mappings.length; j++) { String[] relations = mappings[j].split("="); //$NON-NLS-1$ String docpath = relations[0]; String xrefpath = relations[1]; String itemval = ""; //$NON-NLS-1$ try { if (docpath.startsWith("[")) // hardcoded value //$NON-NLS-1$ itemval = docpath.substring(1, docpath.length() - 1); else itemval = Util.getFirstTextNode(xrefElement, docpath); } catch (Exception x) { throw new XtentisException( "Value for business element '" + xrefElement.getNodeName() + '/' + docpath //$NON-NLS-1$ + "' cannot be found!"); //$NON-NLS-1$ } if (itemval == null) itemval = ""; //$NON-NLS-1$ String content = stripeOuterBracket(itemval); if (content.split(",").length >= mappings.length) //$NON-NLS-1$ itemvals.put(xrefpath, content.split(",")[j]); //$NON-NLS-1$ else itemvals.put(xrefpath, ""); //$NON-NLS-1$ } WhereAnd wAnd = new WhereAnd(); Collection<Map.Entry<String, String>> c = itemvals.entrySet(); int i = 0; for (Iterator<Map.Entry<String, String>> iter = c.iterator(); iter.hasNext();) { i++; Map.Entry<String, String> entry = iter.next(); wAnd.add(new WhereCondition(entry.getKey(), WhereCondition.EQUALS, entry.getValue(), WhereCondition.PRE_NONE, false)); } ArrayList<String> resList = Util.getItemCtrl2Local().xPathsSearch(new DataClusterPOJOPK(xrefcluster), null, new ArrayList<String>(Arrays.asList(new String[] { xrefOut })), wAnd, -1, // spell 0, // start 1, // limit false); String val = ""; //$NON-NLS-1$ if ((resList == null) || (resList.size() == 0)) { if (xrefIgnore.equals("true") || xrefIgnore.equals("1")) { //$NON-NLS-1$ //$NON-NLS-2$ if (xrefDefault != null) val = xrefDefault; else val = ""; //$NON-NLS-1$ } else { String ks = ""; //$NON-NLS-1$ c = itemvals.entrySet(); for (Iterator<Map.Entry<String, String>> iter = c.iterator(); iter.hasNext();) { Map.Entry<String, String> entry = iter.next(); ks += " " + entry.getKey() + "=\"" + entry.getValue() + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } throw new XtentisException("Foreign keys values not found for: " + ks); //$NON-NLS-1$ } } else { // read result Pattern p = Pattern.compile("<.*?>(.*?)</.*>", Pattern.DOTALL); //$NON-NLS-1$ Matcher m = p.matcher(resList.iterator().next()); if (m.matches()) val = StringEscapeUtils.unescapeXml(m.group(1)); else { Pattern p2 = Pattern.compile("<.*?/>", Pattern.DOTALL); //$NON-NLS-1$ Matcher m2 = p2.matcher(resList.iterator().next()); if (!m2.matches() && !(xrefIgnore.equals("true") || xrefIgnore.equals("1"))) { //$NON-NLS-1$ //$NON-NLS-2$ throw new XtentisException("Result values were not understood for crossref element"); //$NON-NLS-1$ } } } NodeList l = xrefElement.getChildNodes(); for (int j = 0; j < l.getLength(); j++) { switch (l.item(j).getNodeType()) { case Node.TEXT_NODE: l.item(j).setNodeValue(val); break; case Node.ELEMENT_NODE: xrefElement.removeChild(l.item(j)); break; default: } } xrefElement.removeAttribute("xrefCluster"); //$NON-NLS-1$ xrefElement.removeAttribute("xrefIgnore"); //$NON-NLS-1$ xrefElement.removeAttribute("xrefDefault"); //$NON-NLS-1$ xrefElement.removeAttribute("xrefIn"); //$NON-NLS-1$ xrefElement.removeAttribute("xrefOut"); //$NON-NLS-1$ return xrefElement; } catch (Exception e) { String err = "Unable to process the mappings for the element '" + xrefElement.getLocalName() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ LOG.error(err, e); throw new XtentisException(err); } }
From source file:org.mwc.debrief.sensorfusion.views.DataSupport.java
/** * Deletes all blocks of sensor data that are more than 45 degrees from an * secondary track./* ww w .ja va 2s. c om*/ * * @return */ public static ArrayList<SensorWrapper> trimToSensorNearSubjectTracks(final TrackWrapper primary, final WatchableList[] secondaries) { ArrayList<SensorWrapper> toRemove = new ArrayList<SensorWrapper>(); ArrayList<SensorWrapper> toKeep = new ArrayList<SensorWrapper>(); if (primary == null || secondaries == null) return toRemove; Enumeration<Editable> sensors = primary.getSensors().elements(); while (sensors.hasMoreElements()) { SensorWrapper sensor = (SensorWrapper) sensors.nextElement(); // ok, remember this one toRemove.add(sensor); final Enumeration<Editable> contacts = sensor.elements(); // loop though the individual sensor contact objects while (sensor != null && (contacts.hasMoreElements())) { final SensorContactWrapper contact = (SensorContactWrapper) contacts.nextElement(); // check this sensor contact has a bearing if (!contact.getHasBearing()) { // hey, no bearing - we aren't sufficiently able to decide if // it can be ditched. toKeep.add(sensor); sensor = null; } else { final HiResDate contactTime = contact.getDTG(); // loop through each secondary track for (int i = 0; i < secondaries.length; i++) { final WatchableList thisS = secondaries[i]; final Watchable[] secondaryFixes = thisS.getNearestTo(contactTime); final Watchable[] primaryFixes = primary.getNearestTo(contactTime); double bearing = 0; if (secondaryFixes != null && secondaryFixes.length > 0) { if (primaryFixes != null && primaryFixes.length > 0) { WorldLocation wl1 = secondaryFixes[0].getLocation(); WorldLocation wl2 = primaryFixes[0].getLocation(); bearing = wl1.bearingFrom(wl2); } } double bearingDelta = contact.getBearing() - Math.toDegrees(bearing); if (Math.abs(bearingDelta) < THRESHOLD_FOR_IRRELEVANT_DATA) { // ok, this sensor is relevant toKeep.add(sensor); // now clear the sensor, as a marker to move on to the next // sensor sensor = null; } } } } // end loop through sensor contacts } // ok, we've built up a list of sensors to keep. We now need to get rid of // the other ones Iterator<SensorWrapper> keepers = toKeep.iterator(); while (keepers.hasNext()) { SensorWrapper keepMe = (SensorWrapper) keepers.next(); toRemove.remove(keepMe); } return toRemove; }
From source file:cobweb.Cobweb.java
/** * Delete all selected nodes/*from w w w . ja v a 2 s. c o m*/ */ public void deleteSelectedNodes() { ArrayList<Node> removeNode = new ArrayList<Node>(); for (int i = 0; i < particleSys.numberOfSelectedNodes(); ++i) removeNode.add(particleSys.getSelectedNode(i)); for (Iterator<Node> partIt = removeNode.iterator(); partIt.hasNext();) deleteNode(partIt.next()); }
From source file:main.MainClass.java
private String SupportToReportsSyncer(String mode) { loggerObj.log(Level.INFO, "Inside SupportToReportsSyncer method"); String masterConfigFile = "./conf/SupportToReportsSyncer/masterconfig.props"; ArrayList<String> fileLocation = FileOperations.getFilesLocForSupToRepSync(masterConfigFile); if (fileLocation == null || fileLocation.size() == 0) { loggerObj.log(Level.INFO, "Cannot get conf file Locations from master config file " + masterConfigFile); return null; }/*from www .j a v a 2 s. com*/ loggerObj.log(Level.INFO, "The conf files obtained from master config file is " + fileLocation.toString()); for (Iterator indiFileItr = fileLocation.iterator(); indiFileItr.hasNext();) { String indiFileLoc = (String) indiFileItr.next(); JSONObject supportToreportsDetails = initializeSupportToReportsDetails(indiFileLoc); if (supportToreportsDetails == null) { System.out.println("The config file is empty or does not contain proper data"); return "JSON OBJECT READ FROM FILE IS NULL"; } try { loggerObj.log(Level.INFO, "Received supportToreports details json object after parsing the file is " + supportToreportsDetails.toJSONString()); JSONObject supDetails = (JSONObject) supportToreportsDetails.get("supDetails"); JSONObject repDetails = (JSONObject) supportToreportsDetails.get("repDetails"); loggerObj.log(Level.INFO, "Going to parse Config file to get support details and query support data from support.zoho.com"); System.out.println( "Going to parse Config file to get support details and query support data from support.zoho.com"); String folderToWriteResponse = "./fromServer/SupportToReportsSyncer"; String[] responseString = getSupportDataWithConfigDetails(supDetails, mode, folderToWriteResponse, false, "SupportToReportSyncer"); if (responseString == null) { System.out .println("The config file does not contain essential support configuration data data"); loggerObj.log(Level.SEVERE, "The config file does not contain essential support configuration data data"); return "REPORT DETAILS IN JSON OBJECT READ FROM FILE IS NULL"; } //https://support.zoho.com/api/json/requests/getrecords?authtoken=8ecc8d0229b00b83d4c398b19a4282bc&portal=memdmissuemgr&department=MDM%20Issue%20Mgr&selectfields=requests(Ticket%20Id,Created%20At,Module,Functionality,Immediate%20priority,Status,Issue%20Source,Issue%20Type,Priority,OS%20Platform,Customer%20Email,Request%20Tag,Ticket%20Owner,Modified%20Time,Modified%20By,Ticket%20Closed%20Time,Old%20Issue%20ID,To%20Address,Email,Subject,Developer%20Comments,Customer%20Description)// String folderToReadFrom = responseString[0]; int numOfSupFiles = Integer.parseInt(responseString[1]); loggerObj.log(Level.INFO, "Response String received from Support api/Internal files is: folderToReadFrom" + folderToReadFrom + " Number of files is " + numOfSupFiles); System.out.println("support data is fetched from support.zoho.com"); //This is used to write the ResponseJSONArray to file system so that it can be used for future parsing loggerObj.log(Level.INFO, "Going to parse the data from supportToReport config file to get ExtraColumns data"); System.out.println( "Going to parse the data from supportToReport config file to get ExtraColumns data"); JSONObject extraColumnsJSONObj = getExtraColumnsForReports(repDetails); loggerObj.log(Level.INFO, "Going to parse the data from supportToReport config file to get column names that need change in reports"); JSONObject SupToRepHdrChgJSONObj = getSupToRepNameChngeCol(repDetails); loggerObj.log(Level.INFO, "Going to parse the data from supportToReport config file to change column names that need change in reports"); JSONObject SupToRepHdrObj = getFinalSupToRepColName(SupToRepHdrChgJSONObj, extraColumnsJSONObj, supDetails); loggerObj.log(Level.INFO, "Going to parse the data downloaded from support to change to a format to upload tp reports"); Integer reportsFileNum = 1; String currTime = getCurrTimeInDD_MM_YY_HH_MM_SS(); String folderToWriteParsedResponse = "./parsed_output/SupportToReportsSyncer/" + currTime; boolean createFolderToWriteResponse = new File(folderToWriteParsedResponse).mkdirs(); if (!createFolderToWriteResponse) { loggerObj.log(Level.INFO, "Cannot create a folder" + folderToWriteParsedResponse + " to write response"); return null; } JSONOperations parserObj = new JSONOperations(); for (int i = 1; i <= numOfSupFiles; i++) { String fileToReadFrom = folderToReadFrom + i + ".json"; JSONObject responseFromSup = (JSONObject) FileOperations.readFromJSONFile(fileToReadFrom); JSONArray issueMgrJSONArray = parserObj.SupJOToReportsJA(responseFromSup, extraColumnsJSONObj, SupToRepHdrChgJSONObj, "row"); if (issueMgrJSONArray == null) { loggerObj.log(Level.INFO, "Processed JSON from zoho support to delver to reports is null while reading file " + fileToReadFrom); System.out.println("Processed JSON from zoho support to delver to reports is null"); return "PROCESSED JSON FOR REPORTS IS NULL"; } String fileToWriteParsedResponse = folderToWriteParsedResponse + "/ParsedJSON_" + reportsFileNum + ".json"; loggerObj.log(Level.INFO, "Processed JSON from zoho support. GOing to write it to a file to import to zoho reports" + fileToWriteParsedResponse); boolean isFileWriteSuccess = FileOperations.writeObjectToFile(issueMgrJSONArray, fileToWriteParsedResponse); //System.out.println("Processed JSON from zoho support. GOing to write it to a file to import to zoho reports"); if (!isFileWriteSuccess) { loggerObj.log(Level.INFO, "Error occurred while writing Processed JSON from zoho support to delver to reports to the file located in" + fileToWriteParsedResponse); return "ERROR IN WRITING PROCESSED JSON TO FILE " + fileToWriteParsedResponse; } loggerObj.log(Level.INFO, "Processed JSON from zoho support is writtrn to a file to import to zoho reports" + fileToWriteParsedResponse); reportsFileNum++; } //Need to have invalid jsonarray check also// JSONArray repConnectionParams = getRepDetailsFromConfigFile(repDetails); //Handling null check if any required field is not present; if (repConnectionParams.size() == 1) { JSONObject errorJSON = (JSONObject) repConnectionParams.get(0); ArrayList<String> nullFields = (ArrayList<String>) errorJSON.get("nullFields"); loggerObj.log(Level.INFO, "The following fields required to make connection to reports is not present" + nullFields.toString()); System.out.println("The following fields required to make connection to reports is not present" + nullFields.toString()); return null; } // Handling error case to check if the Matching columns are not present in Reports column if (repDetails.get("ZOHO_MATCHING_COLUMNS") != null) { String[] matchingColumns = repDetails.get("ZOHO_MATCHING_COLUMNS").toString().split(","); boolean isPresent = false; ArrayList<String> matchingColNotInRepColn = null; for (String i : matchingColumns) { Set<String> repColns = SupToRepHdrObj.keySet(); for (Iterator it = repColns.iterator(); it.hasNext();) { String repColnHdr = it.next().toString(); if (repColnHdr.equals(i)) { isPresent = true; } } if (isPresent != true) { if (matchingColNotInRepColn == null) { matchingColNotInRepColn = new ArrayList<>(); } matchingColNotInRepColn.add(i); } isPresent = false; } if (matchingColNotInRepColn != null) { loggerObj.log(Level.INFO, "The following fields are present in Matching columns but not in Report columns" + matchingColNotInRepColn.toString()); System.out.println( "The following fields required to make connection to reports is not present" + matchingColNotInRepColn.toString()); return null; } } else { if (repDetails.get("ZOHO_IMPORT_TYPE").equals("UPDATEADD")) { loggerObj.log(Level.SEVERE, "Please provide the matching columns as it is mandatory for UPDATEADD import type in config file."); System.out.println( "Please provide the matching columns as it is mandatory for UPDATEADD import type in config file."); return null; } } JSONObject urlParams = (JSONObject) repConnectionParams.get(0); JSONObject postParams = (JSONObject) repConnectionParams.get(1); repConnectionParams = null; loggerObj.log(Level.INFO, "urlParams is " + urlParams.toJSONString()); loggerObj.log(Level.INFO, "postParams is " + postParams.toJSONString()); loggerObj.log(Level.INFO, "Going to bulk import the json file in the folder " + folderToWriteParsedResponse + " to the reports"); System.out.println("Going to bulk import in to the reports:"); for (int i = 1; i <= reportsFileNum - 1; i++) { String fileToUploadToReports = folderToWriteParsedResponse + "/ParsedJSON_" + i + ".json"; loggerObj.log(Level.INFO, "Going to upload " + fileToUploadToReports + "to reports"); postParams.put("jsonFileName", fileToUploadToReports); ZohoReportsAPIManager reportsClient = new ZohoReportsAPIManager(); boolean isSuccessfullImport = false; try { isSuccessfullImport = reportsClient.postBulkJSONImport(urlParams, postParams); } catch (IOException ex) { loggerObj.log(Level.INFO, "Problem in bulk importing the json file " + fileToUploadToReports + " to the reports"); System.out.println("Problem in bulk importing the json file to the reports"); } if (isSuccessfullImport) { loggerObj.log(Level.INFO, "Successfully bulk imported the json file " + fileToUploadToReports + " to the reports"); System.out.println("Successfully bulk imported the json file " + fileToUploadToReports + " to the reports"); } else { loggerObj.log(Level.INFO, "Probelem in bulk importing the json file " + fileToUploadToReports + " to the reports"); System.out.println("Probelem in bulk importing the json file " + fileToUploadToReports + " to the reports"); } } } catch (Exception e) { loggerObj.log(Level.SEVERE, "Some problem in Syncing support with reports. Exception is"); loggerObj.log(Level.SEVERE, e.getMessage(), e); System.out.println("Exception is " + e.toString()); return null; } } return null; }
From source file:net.cellcloud.talk.TalkService.java
/** ? Session *//*from w ww . j a v a2s. co m*/ protected void processUnidentifiedSessions(long time) { if (null == this.unidentifiedSessions || this.unidentifiedSessions.isEmpty()) { return; } // Session ArrayList<Session> sessionList = null; Iterator<Map.Entry<Long, Certificate>> iter = this.unidentifiedSessions.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<Long, Certificate> e = iter.next(); Certificate cert = e.getValue(); if (false == cert.checked) { cert.checked = true; deliverChecking(cert.session, cert.plaintext, cert.key); } else { // 20 if (time - cert.time > 20000) { if (null == sessionList) { sessionList = new ArrayList<Session>(); } sessionList.add(cert.session); } } } if (null != sessionList) { // Session Iterator<Session> siter = sessionList.iterator(); while (siter.hasNext()) { Session session = siter.next(); StringBuilder log = new StringBuilder(); log.append("Talk service session timeout: "); log.append(session.getAddress().getAddress().getHostAddress()); log.append(":"); log.append(session.getAddress().getPort()); Logger.i(TalkService.class, log.toString()); log = null; // this.unidentifiedSessions.remove(session.getId()); if (session instanceof HttpSession) { // HTTP Session this.httpSessionManager.unmanage((HttpSession) session); } else if (session instanceof WebSocketSession) { // WebSocket Session this.webSocketManager.close((WebSocketSession) session); } else { // ??? Session this.acceptor.close(session); } } sessionList.clear(); sessionList = null; } }
From source file:edu.cornell.mannlib.vitro.webapp.reasoner.SimpleReasoner.java
/** * Find the most specific types (classes) of an individual and * infer them for the individual with the mostSpecificType * annotation.// ww w . j av a 2 s . com */ protected void setMostSpecificTypes(Resource individual, Model inferenceModel, HashSet<String> unknownTypes) { tboxModel.enterCriticalSection(Lock.READ); aboxModel.enterCriticalSection(Lock.READ); inferenceModel.enterCriticalSection(Lock.READ); HashSet<String> typeURIs = new HashSet<String>(); try { OntModel unionModel = VitroModelFactory.createOntologyModel(); unionModel.addSubModel(aboxModel); unionModel.addSubModel(inferenceModel); List<OntClass> types = new ArrayList<OntClass>(); StmtIterator stmtIter = unionModel.listStatements(individual, RDF.type, (RDFNode) null); while (stmtIter.hasNext()) { Statement stmt = stmtIter.next(); if (!stmt.getObject().isResource()) { log.warn("The object of this rdf:type assertion is expected to be a resource: " + stmtString(stmt)); continue; } OntClass ontClass = null; if ((stmt.getObject().asResource()).getURI() != null) { ontClass = tboxModel.getOntClass(stmt.getObject().asResource().getURI()); } else { log.debug("The object of this rdf:type assertion has a null URI: " + stmtString(stmt)); continue; } if (ontClass == null) { if (!(stmt.getObject().asResource().getNameSpace()).equals(OWL.NS)) { if (!unknownTypes.contains(stmt.getObject().asResource().getURI())) { unknownTypes.add(stmt.getObject().asResource().getURI()); log.debug( "Didn't find the target class (the object of an asserted or inferred rdf:type statement) in the TBox: " + (stmt.getObject().asResource()).getURI() + ". No mostSpecificType computation will be done based on " + (stmt.getObject().asResource()).getURI() + " type statements."); } } continue; } if (ontClass.isAnon()) continue; types.add(ontClass); } List<OntClass> types2 = new ArrayList<OntClass>(); types2.addAll(types); Iterator<OntClass> typeIter = types.iterator(); while (typeIter.hasNext()) { OntClass type = typeIter.next(); boolean add = true; Iterator<OntClass> typeIter2 = types2.iterator(); while (typeIter2.hasNext()) { OntClass type2 = typeIter2.next(); if (type.equals(type2)) { continue; } if (type.hasSubClass(type2, false) && !type2.hasSubClass(type, false)) { add = false; break; } } if (add) { typeURIs.add(type.getURI()); ArrayList<Resource> equivalentClasses = new ArrayList<Resource>(); Iterator<Statement> iter = tboxModel.listStatements((Resource) null, OWL.equivalentClass, type); while (iter.hasNext()) { Statement stmt = iter.next(); Resource res = stmt.getSubject(); if ((res == null) || res.isAnon() || equivalentClasses.contains(res)) { continue; } equivalentClasses.add(res); } Iterator<Resource> eIter = equivalentClasses.iterator(); while (eIter.hasNext()) { Resource equivClass = eIter.next(); if (equivClass.isAnon()) continue; typeURIs.add(equivClass.getURI()); } } } } finally { inferenceModel.leaveCriticalSection(); aboxModel.leaveCriticalSection(); tboxModel.leaveCriticalSection(); } setMostSpecificTypes(individual, typeURIs, inferenceModel); return; }
From source file:cobweb.Cobweb.java
/** * Initial method that get called when the applet is loaded. Sets some * constants, initializes the particle system, the control elements and the * handle to the javascript object, if available. Then it calls the parser * to read the given XGMML-data./* ww w . ja v a 2 s . com*/ */ public void setup() { if (getParameter("edgeLength") != null) edgeLength = Float.valueOf(getParameter("edgeLength")); else edgeLength = 150; if (getParameter("scaleFactor") != null) scaleFactor = Float.valueOf(getParameter("scaleFactor")); else scaleFactor = 1; if (getParameter("edgeStrength") != null) edgeStrength = Float.valueOf(getParameter("edgeStrength")); else edgeStrength = 0.04f; if (getParameter("repulsionStrength") != null) repulsionStrength = Float.valueOf(getParameter("repulsionStrength")); else repulsionStrength = 4000; size(Integer.valueOf(getParameter("width")), Integer.valueOf(getParameter("height"))); smooth(); strokeWeight(2); ellipseMode(CENTER); rectMode(CENTER); imageMode(CENTER); textAlign(CENTER, CENTER); frameRate(30); particleSys = new ParticleSystem(0.2f); createControlElements(); // any font in ttf format can be used to draw the node-names. Just // rename it to "font.ttf" and include it in the jar-file font = createFont("font.ttf", 14, true); textFont(font); try { window = JSObject.getWindow(this); } catch (Exception e) { println("window element not available"); } String serverAddress = getCodeBase().toString(); if (serverAddress.substring(0, 4).equals("file")) serverAddress = "http://localhost/cobweb_website/applet/"; callJavascriptFunctionStatusMessage("parsing network data", true); String network = null; if (getParameter("networkXGMML") != null) { network = getParameter("networkXGMML"); networkType = "xgmml"; } else if (getParameter("fileXGMML") != null) { String lines[] = loadStrings(serverAddress + getParameter("fileXGMML")); StringBuffer stringBuf = new StringBuffer(); for (int i = 0; i < lines.length; i++) stringBuf.append(lines[i]); network = stringBuf.toString(); networkType = "xgmml"; } else if (getParameter("networkGraphML") != null) { network = getParameter("networkGraphML"); networkType = "graphml"; } else if (getParameter("fileGraphML") != null) { String lines[] = loadStrings(serverAddress + getParameter("fileGraphML")); StringBuffer stringBuf = new StringBuffer(); for (int i = 0; i < lines.length; i++) stringBuf.append(lines[i]); network = stringBuf.toString(); networkType = "graphml"; } else if (getParameter("networkSIF") != null) { network = getParameter("networkSIF"); // newlines and tabs are not preserved in html PARAM-tags, so they // have to be encoded by <br> and <tab> network = network.replace("<br>", "\n"); network = network.replace("<tab>", "\t"); networkType = "sif"; } else if (getParameter("fileSIF") != null) { String lines[] = loadStrings(serverAddress + getParameter("fileSIF")); StringBuffer stringBuf = new StringBuffer(); for (int i = 0; i < lines.length; i++) stringBuf.append(lines[i] + "\n"); network = stringBuf.toString(); networkType = "sif"; } if (networkType != null) { if (networkType.equals("xgmml")) { XGMMLParser parser = new XGMMLParser(this, network); parser.parseParameters(particleSys, serverAddress); parser.parseNodes(particleSys, width, height); parser.parseEdges(particleSys, edgeLength); params = parser.getParameters(); } else if (networkType.equals("graphml")) { GraphMLParser parser = new GraphMLParser(this, network); parser.parseParameters(particleSys, serverAddress); parser.parseNodes(particleSys, width, height); parser.parseEdges(particleSys, edgeLength); params = parser.getParameters(); } else if (networkType.equals("sif")) { SIFParser parser = new SIFParser(this, network); parser.parseParameters(particleSys, serverAddress); parser.parseNetwork(particleSys, width, height, edgeLength); params = parser.getParameters(); } else System.out.println("unknown network type: " + networkType); } else System.out.println("no network type defined"); // if no edges are present in the starting network, neighbours for all // nodes are loaded if (particleSys.numberOfEdges() == 0) { ArrayList<Node> n = new ArrayList<Node>(); for (int i = 0; i < particleSys.numberOfNodes(); i++) n.add(particleSys.getNode(i)); for (Iterator<Node> nIt = n.iterator(); nIt.hasNext();) loadNeighbourhood(nIt.next()); } callJavascriptFunctionStatusMessage("computing node positions", true); for (int i = 0; i < 2000; i++) particleSys.tick(); fitNetworkInWindow(); callJavascriptFunctionStatusMessage("applet loaded"); callJavascriptFunctionClearSidebar(); }
From source file:edu.harvard.i2b2.ontology.dao.ConceptDao.java
private String parseMatchString(String match, DBInfoType dbInfo) { String whereClause = null;/* w ww .j a v a 2 s . c o m*/ String[] terms = match.split(" "); ArrayList<String> goodWords = new ArrayList<String>(); String word = getStopWords(); for (int i = 0; i < terms.length; i++) { if (word.contains(terms[i])) ; else { goodWords.add(terms[i]); } } if (goodWords.isEmpty()) return null; Iterator it = goodWords.iterator(); while (it.hasNext()) { if (whereClause == null) whereClause = " where upper(c_name) like " + "'%" + ((String) it.next()).toUpperCase() + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : ""); //{ESCAPE '?'}"; else whereClause = whereClause + " AND upper(c_name) like " + "'% " + ((String) it.next()).toUpperCase() + "%' " + (!dbInfo.getDb_serverType().toUpperCase().equals("POSTGRESQL") ? "{ESCAPE '?'}" : ""); //{ESCAPE '?'}"; } return whereClause; }
From source file:com.chinamobile.bcbsp.bspcontroller.JobInProgress.java
/** * Predict the worker's burden in future,whether the staff need to migrate. * @param sm/*from w w w. jav a 2 s . c o m*/ * migrate staff to tell. * @return if the staff need migrate true, not false. */ private boolean shouldMigrate(StaffMigrate sm) { LOG.info("Predict the worker's burden in future"); StaffInProgress sip = getStaff(sm.getStaffID()); // Check current staffs on the samework ArrayList<StaffStatus> onSameWorkerStaffs = this.controller .checkStaff(sip.getWorkerManagerStatus().getWorkerManagerName()); LOG.info("sameWorkerStaffs is "); for (int i = 0; i < onSameWorkerStaffs.size(); i++) { LOG.info(onSameWorkerStaffs.get(i).getStaffId()); } int willIdleStaffSlot = 0; double tolerance = 1 / 5; Iterator<StaffStatus> it = onSameWorkerStaffs.iterator(); // Compute willIdleStaffSlot while (it.hasNext()) { StaffStatus ss = it.next(); if (ss.getJobId().equals(this.jobId)) { continue; } // Staff in different job long time = ss.getRunTime(); if (time != 0) { if (time * (this.controller.getJob(ss.getJobId()).getJob().getNumSuperStep() - ss.getSuperstepCount()) < (job.getNumBspStaff() - sm.getCurrentSuperStep()) * sm.getStaffRunTime() * tolerance) { willIdleStaffSlot++; } } } LOG.info("worker has max Staff count is " + sip.getWorkerManagerStatus().getMaxStaffsCount()); LOG.info("current staff occupy staff slot is " + this.controller.checkStaff(sip.getWorkerManagerStatus().getWorkerManagerName()).size()); LOG.info("willIdleStaffSlot is " + willIdleStaffSlot); if (willIdleStaffSlot + sip.getWorkerManagerStatus().getMaxStaffsCount() - this.controller.checkStaff(sip.getWorkerManagerStatus().getWorkerManagerName()).size() >= sip .getWorkerManagerStatus().getMaxStaffsCount() / 2) { return false; } else { return true; } }
From source file:com.konakart.bl.modules.ordertotal.BaseOrderTotalModule.java
/** * This is a helper method for the discount modules. Many promotions may be relevant for an * order. This method receives all of the relative promotions (in the form of Order Total * objects) in a list as an input parameter. It sums all of the cumulative promotions into a * single Order Total object and then compares all of the order totals that it has, in order to * select the one that provides the largest discount. * /*from w ww . j a va 2s . co m*/ * @param order * @param orderTotalsList * @return An OrderTotal object * @throws Exception */ protected OrderTotal getDiscountOrderTotalFromList(Order order, List<OrderTotal> orderTotalsList) throws Exception { if (orderTotalsList == null || order == null) { return null; } if (orderTotalsList.size() == 1) { // Simple case with just one applicable order total OrderTotal localOt = orderTotalsList.get(0); if (localOt == null || localOt.getValue() == null) { return null; } // Add colon to title localOt.setTitle(localOt.getTitle() + ":"); // Subtract the discount from the total of the order order.setTotalIncTax(order.getTotalIncTax().subtract(localOt.getValue())); // Reduce the tax of the order if (localOt.getTax() != null) { order.setTax(order.getTax().subtract(localOt.getTax())); order.setTotalIncTax(order.getTotalIncTax().subtract(localOt.getTax())); } // Set the promotion id used in the order setPromotionIds(order, Integer.toString(localOt.getPromotions()[0].getId())); // Set the coupon id if applicable if (localOt.getPromotions()[0].getCoupon() != null) { setCouponIds(order, Integer.toString(localOt.getPromotions()[0].getCoupon().getId())); } return localOt; } else if (orderTotalsList.size() > 1) { // Create one order total object for any cumulative promotions and then select the order // total object offering the biggest discount OrderTotal cumulativeOT = null; ArrayList<OrderTotal> cumulativeList = new ArrayList<OrderTotal>(); // For cumulative promotions we attach all of the promotions to the OrderTotal in an // array ArrayList<PromotionIf> promotionList = new ArrayList<PromotionIf>(); for (Iterator<OrderTotal> iter = orderTotalsList.iterator(); iter.hasNext();) { OrderTotal localOt = iter.next(); if (localOt == null || localOt.getValue() == null) { iter.remove(); continue; } if (localOt.getPromotions()[0].isCumulative()) { cumulativeList.add(localOt); if (cumulativeOT == null) { cumulativeOT = localOt.getClone(); } else { // Add the discounts BigDecimal newDiscount = cumulativeOT.getValue().add(localOt.getValue()); cumulativeOT.setValue(newDiscount); cumulativeOT.setText("-" + getCurrMgr().formatPrice(newDiscount, order.getCurrencyCode())); // Merge titles cumulativeOT.setTitle(cumulativeOT.getTitle() + "+" + localOt.getTitle()); // Add tax if (cumulativeOT.getTax() != null && localOt.getTax() != null) { cumulativeOT.setTax(cumulativeOT.getTax().add(localOt.getTax())); } else if (cumulativeOT.getTax() == null && localOt.getTax() != null) { cumulativeOT.setTax(localOt.getTax()); } } // Add the participating promotions to a list promotionList.add(localOt.getPromotions()[0]); // Remove from list if it is cumulative since it is substituted by cumulativeOT iter.remove(); } } // Add the cumulative OrderTotal to the list if it isn't null if (cumulativeOT != null) { // Create a promotions array and add it to the cumulativeOt PromotionIf[] promotionArray = new Promotion[promotionList.size()]; int i = 0; for (Iterator<PromotionIf> iter = promotionList.iterator(); iter.hasNext();) { PromotionIf prom = iter.next(); promotionArray[i++] = prom; } cumulativeOT.setPromotions(promotionArray); cumulativeOT.setOrderTotals(cumulativeList.toArray(new OrderTotal[0])); orderTotalsList.add(cumulativeOT); } // Select biggest order total object OrderTotal selectedOT = orderTotalsList.get(0); for (Iterator<OrderTotal> iter = orderTotalsList.iterator(); iter.hasNext();) { OrderTotal localOt = iter.next(); if (localOt.getValue().compareTo(selectedOT.getValue()) > 0) { selectedOT = localOt; } } // Add colon to title selectedOT.setTitle(selectedOT.getTitle() + ":"); // Subtract the discount of the selected OrderTotal from the total of the order order.setTotalIncTax(order.getTotalIncTax().subtract(selectedOT.getValue())); // Reduce the tax of the order if (selectedOT.getTax() != null) { order.setTax(order.getTax().subtract(selectedOT.getTax())); order.setTotalIncTax(order.getTotalIncTax().subtract(selectedOT.getTax())); } // If the order total consists of more than one promotion and / or more than one valid // coupon, the promotion and coupon ids are saved in the order as comma separated lists. // We need to save these with the order since once the order has been approved we may // need to write into the database to update the number of times a coupon has been used // or the number of times a promotion has been used by a particular customer etc. StringBuffer promotionIds = new StringBuffer(); StringBuffer couponIds = new StringBuffer(); for (int i = 0; i < selectedOT.getPromotions().length; i++) { PromotionIf prom = selectedOT.getPromotions()[i]; CouponIf coupon = prom.getCoupon(); if (promotionIds.length() > 0) { promotionIds.append(","); } promotionIds.append(prom.getId()); if (coupon != null) { if (couponIds.length() > 0) { couponIds.append(","); } couponIds.append(coupon.getId()); } } // Set the promotion ids used in the order setPromotionIds(order, promotionIds.toString()); // Set the coupon ids if applicable if (couponIds.length() > 0) { setCouponIds(order, couponIds.toString()); } return selectedOT; } return null; }