List of usage examples for java.util ArrayList iterator
public Iterator<E> iterator()
From source file:be.cytomine.client.Cytomine.java
public static String join(ArrayList s, String delimiter) { if (s.size() == 0) return ""; StringBuffer buffer = new StringBuffer(); Iterator iterator = s.iterator(); while (iterator.hasNext()) { buffer.append(iterator.next());/* w ww. j a v a 2 s.c om*/ if (iterator.hasNext()) { buffer.append(delimiter); } } return buffer.toString(); }
From source file:com.collabnet.ccf.core.eis.connection.ConnectionPool.java
private synchronized void runScavengerCodeInLocalThread() { // first find out whether we have to run this code at this time again long currentTime = System.currentTimeMillis(); if (currentTime - scavengerLastRun > scavengerInterval) { try {//from w w w. j ava2s . com scavengerLastRun = currentTime; Set<String> keys = connectionPool.keySet(); for (String key : keys) { ArrayList<ConnectionInfo> connectionInfos = connectionPool.get(key); synchronized (connectionInfos) { Iterator<ConnectionInfo> it = connectionInfos.iterator(); while (it.hasNext()) { ConnectionInfo info = it.next(); if (info.isFreeFor(maxIdleTime) || (!factory.isAlive(info.getConnection()))) { try { factory.closeConnection(info.getConnection()); } catch (ConnectionException e) { log.warn("Could not close one of the pooled connections for " + key, e); } it.remove(); reversePoolMap.remove(info.getConnection()); } } } } } catch (Exception e) { log.error("An unexpected exception occured while cleaning up the connection pool.", e); } } }
From source file:com.redhat.rhn.domain.server.NetworkInterface.java
/** * @return Returns first most global ipv6 address *///from w ww . j av a2 s .c om public String getGlobalIpv6Addr() { ArrayList<String> addrs = getGlobalIpv6Addresses(); if (addrs == null) { addrs = findServerNetAddress6ByScope("site"); } if (addrs == null) { addrs = findServerNetAddress6ByScope("link"); } if (addrs == null) { addrs = findServerNetAddress6ByScope("host"); } return ((addrs != null && addrs.iterator().hasNext()) ? addrs.iterator().next() : "::1"); }
From source file:com.xpn.xwiki.plugin.chronopolys.FolderManager.java
public ArrayList<Object> getProjectContainerProjects(String uid, XWikiContext context) throws XWikiException { ArrayList<Object> list = null; String key = context.getDatabase() + ":" + context.getLocalUser() + ":" + uid + ":childs"; initFoldersCache(context);//from ww w. j a v a 2 s . c o m synchronized (key) { try { // retreive projects list from cache list = (ArrayList<Object>) foldersCache.getFromCache(key); } catch (XWikiCacheNeedsRefreshException e) { // update the folders list cache foldersCache.cancelUpdate(key); list = new ArrayList<Object>(); // recursively call this method passing childs UID's ArrayList<Object> childs = getProjectContainerChilds(uid, context); Iterator it = childs.iterator(); while (it.hasNext()) { Object obj = (Object) it.next(); String objUid = (String) obj.display("uid", "view"); ArrayList<Object> subList = getProjectContainerProjects(objUid, context); if (subList != null) { list.addAll(subList); } } // retreive projects with this container as parent List allProjects = plugin.getProjectManager().getProjects(context); it = allProjects.iterator(); while (it.hasNext()) { Object currentProject = (Object) it.next(); if (uid.equals(currentProject.display("container", "view"))) { list.add(currentProject); } } foldersCache.putInCache(key, list); } } return list; }
From source file:it.cyberdyne.dss.beans.PlaceTableBean.java
public void updateMatrix(List<String> list) { System.out.println("UpdateMatrix"); this.distanceList = (ArrayList<Distance>) getDistanceListFromDB(); ArrayList<String> row0 = new ArrayList<>(Arrays.asList(list.get(0).split(";"))); ArrayList<Integer> indices = new ArrayList<>(); Iterator<String> it = row0.iterator(); int c = 0;/* w ww . j ava 2 s . co m*/ while (it.hasNext()) { String currentLabel = it.next(); int index = searchInPlaceList(currentLabel, placeList); if (index >= 0) { indices.add(index); } } //System.out.println("ListSize:"+list.size()+" IndicesSize:"+indices.size()); ManagePlaces manager = new ManagePlaces(loginBean.getLoggedId()); int rowNumber = 0; for (int i = 0; i < indices.size(); i++) { rowNumber++; String currentRow = list.get(rowNumber); List<String> rows = new ArrayList<>(Arrays.asList(currentRow.split(";"))); for (int j = 0; j < indices.size(); j++) { int id1 = manager.getPlaceId(row0.get(i)); int id2 = manager.getPlaceId(row0.get(j)); int s = searchInDistanceList(id1, id2); if (s != -1) { //System.out.println("Distance Found!"); } else { addDistance(id1, id2, Double.parseDouble(rows.get(j))); } } } //System.out.println(" ************ Current List: **********"); //System.out.println("DistanceList size:"+distanceList.size()); //printCurrentDistanceMatrix(); SessionFactory s = HibernateUtil.getSessionFactory(); for (Distance distance : distanceList) { int id; if (distance.getId() != null) id = distance.getId(); else id = -1; if (id < 0) { Session session = s.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.save(distance); tx.commit(); } catch (HibernateException e) { if (tx != null) { tx.rollback(); } } finally { session.close(); } } } }
From source file:ambit.data.qmrf.QMRFConverter.java
public String listNodeAttributes(Document doc, String name_node, String ref_name, String catalog_name, String[] attributes, boolean line) throws Exception { ArrayList node_list = findNodeIDRef(name_node, ref_name, catalog_name, doc); int r = 1;// w ww .ja v a2 s . c om boolean printnumbers = (node_list.size() > 1) && line; StringBuffer b = new StringBuffer(); boolean printnewline = false; for (Iterator it = node_list.iterator(); it.hasNext();) { if (printnewline) { b.append('\n'); if (!line) b.append('\n'); } Node node = (Node) it.next(); if (printnumbers) { b.append('['); b.append(r); b.append(']'); } printnewline = false; for (int i = 0; i < attributes.length; i++) try { String value = findAttributeValue(attributes[i], node).trim(); if (value.length() > 0) { b.append(value); if (line) b.append(' '); else b.append('\n'); printnewline = true; } } catch (Exception x) { System.out.println(attributes[i] + x.getMessage()); //x.printStackTrace(); } r++; } return b.toString(); }
From source file:it.cyberdyne.dss.beans.PlaceTableBean.java
public void updateTimeMatrix(List<String> list) { System.out.println("UpdateTimeMatrix"); this.timeList = (ArrayList<TravelTime>) getTimeListFromDB(); this.placeList = (ArrayList<Place>) getPlaceListFromDB(); ArrayList<String> row0 = new ArrayList<>(Arrays.asList(list.get(0).split(";"))); ArrayList<Integer> indices = new ArrayList<>(); Iterator<String> it = row0.iterator(); int c = 0;/*w ww . j a v a 2 s . c o m*/ while (it.hasNext()) { String currentLabel = it.next(); int index = searchInPlaceList(currentLabel, placeList); if (index >= 0) { indices.add(index); } } //System.out.println("ListSize:"+list.size()+" IndicesSize:"+indices.size()); ManagePlaces manager = new ManagePlaces(loginBean.getLoggedId()); int rowNumber = 0; for (int i = 0; i < indices.size(); i++) { rowNumber++; String currentRow = list.get(rowNumber); List<String> rows = new ArrayList<>(Arrays.asList(currentRow.split(";"))); for (int j = 0; j < indices.size(); j++) { int id1 = manager.getPlaceId(row0.get(i)); int id2 = manager.getPlaceId(row0.get(j)); int s = searchInTimeList(id1, id2); if (s != -1) { //System.out.println("Distance Found!"); } else { addTime(id1, id2, Double.parseDouble(rows.get(j))); } } } //System.out.println(" ************ Current List: **********"); //System.out.println("DistanceList size:"+distanceList.size()); //printCurrentDistanceMatrix(); SessionFactory s = HibernateUtil.getSessionFactory(); for (TravelTime time : timeList) { int id; if (time.getId() != null) id = time.getId(); else id = -1; if (id < 0) { Session session = s.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.save(time); tx.commit(); } catch (HibernateException e) { if (tx != null) { tx.rollback(); } } finally { session.close(); } } } }
From source file:Hash.Hash.java
private static byte[] getPointers(ArrayList<ifdField> imageLocationFields, File file, boolean endian) throws IOException { /* RawImageDigest Tag 50972 (C71C.H)/*from ww w . j a v a 2 s.c om*/ Type BYTE Count 16 Value See below Default Optional Usage IFD 0 Description This tag is an MD5 digest of the raw image data. All pixels in the image are processed in rowscan order. Each pixel is zero padded to 16 or 32 bits deep (16-bit for data less than or equal to 16 bits deep, 32-bit otherwise). The data for each pixel is processed in little-endian byte order */ long imageLength; long imageWidth; long pieceOffsets = 0; long pieceOffsetsCount = 0; int pieceOffsetsLength = 0; long pieceLength; long pieceWidth = 1; long pieceByteCounts = 0; long pieceByteCountsCount = 0; int pieceByteLength = 0; Iterator<ifdField> iterator = imageLocationFields.iterator(); while (iterator.hasNext()) { ifdField field = iterator.next(); switch (field.tag) { case 256: imageWidth = field.offset; break; case 257: imageLength = field.offset; break; case 273: case 324: pieceOffsets = field.offset; pieceOffsetsCount = field.count; pieceOffsetsLength = field.getTypeLength(); break; case 322: pieceWidth = field.offset; break; case 278: case 323: pieceLength = field.offset; break; case 279: case 325: pieceByteCounts = field.offset; pieceByteCountsCount = field.count; pieceByteLength = field.getTypeLength(); break; } } if (pieceByteCountsCount != pieceOffsetsCount) return null; try (RandomAccessFile fileRand = new RandomAccessFile(file.getAbsolutePath(), "r")) { MessageDigest md5Digest = null; try { md5Digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { return null; } if (pieceOffsetsCount == 1) { System.out.println(file.getName() + " bytes readed: " + pieceByteCounts + " File size " + file.length() + " % " + (100 * pieceByteCounts / file.length())); fileRand.seek(pieceOffsets); long readed = 0; int bufferSize = 4096; while (readed + bufferSize < pieceByteCounts) { byte chunk[] = new byte[bufferSize]; int read = fileRand.read(chunk); if (read == -1) return null; readed += read; md5Digest.update(chunk); } int residue = (int) (pieceByteCounts - readed); byte chunk[] = new byte[residue]; int read = fileRand.read(chunk); if (read == -1) return null; md5Digest.update(chunk); } else { long totalread = 0; for (int j = 0; j < pieceOffsetsCount; j++) { fileRand.seek(pieceByteCounts + j * pieceByteLength); long actualPieceBytes = 0; for (int i = 0; i < pieceByteLength; i++) { long c = fileRand.read(); if (endian) { c = (long) (c * Math.pow(256, i)); } else { c = (long) (c * Math.pow(256, pieceByteLength - i)); } actualPieceBytes += c; } // System.out.println("Count [" + j + "] =" + actualPieceBytes); fileRand.seek(pieceOffsets + j * pieceOffsetsLength); long actualPieceOffset = 0; for (int i = 0; i < pieceOffsetsLength; i++) { long c = fileRand.read(); if (endian) { c = (long) (c * Math.pow(256, i)); } else { c = (long) (c * Math.pow(256, pieceOffsetsLength - i)); } actualPieceOffset += c; } totalread += actualPieceBytes; // System.out.println("Offset [" + j + "] =" + actualPieceOffset); fileRand.seek(actualPieceOffset); long readed = 0; int bufferSize = 4096; while (readed + bufferSize < actualPieceBytes) { byte chunk[] = new byte[bufferSize]; int read = fileRand.read(chunk); if (read == -1) return null; readed += read; md5Digest.update(chunk); } int residue = (int) (actualPieceBytes - readed); byte chunk[] = new byte[residue]; int read = fileRand.read(chunk); if (read == -1) return null; md5Digest.update(chunk); } System.out.println(file.getName() + " bytes readed: " + totalread + " File size " + file.length() + " % " + (100 * totalread / file.length())); } return md5Digest.digest(); } }
From source file:de.suse.swamp.modules.actions.WorkflowActions.java
/** * Is called when a task ok comes in.//from w ww . j av a 2s. c o m */ public void doTaskok(RunData data, Context context) throws Exception { Logger.LOG("doTaskok() from webapp."); SWAMPUser user = ((SWAMPTurbineUser) data.getUser()).getSWAMPUser(); WorkflowAPI wfapi = new WorkflowAPI(); TaskAPI taskapi = new TaskAPI(); ResultList history = new ResultList(); if (data.getParameters().containsKey("taskid")) { // get the task we're working on int taskId = data.getParameters().getInt("taskid"); WorkflowTask task = taskapi.doGetTask(taskId, user.getUserName()); String taskType = null; ArrayList validationErrors = new ArrayList(); // Check for availability of that Task: if (task != null && task.getState() == WorkflowTask.ACTIVE) { // get the action type of the task taskType = task.getActionType(); // fill in the result for different if (taskType.equals("manualtask")) { ManualtaskResult result = (ManualtaskResult) task.getResult(); result.setDone(true); } else if (taskType.equals("decision")) { int answer = -1; // get the answer given if (data.getParameters().containsKey("answer")) { answer = data.getParameters().getInt("answer"); Logger.DEBUG("Answer #" + answer); // if no answer selected, log error } else { Logger.ERROR("in doTaskok: no answer on question given."); } // put selection into result DecisionResult result = (DecisionResult) task.getResult(); result.setSelection(answer); } else if (taskType.equals("dataedit")) { DataeditResult result = (DataeditResult) task.getResult(); context.put("result", result); DataeditActionTemplate action = (DataeditActionTemplate) task.getActionTemplate(); HashMap actionFields = action.getAllFields(task.getWorkflowId()); Workflow wf = wfapi.getWorkflow(task.getWorkflowId(), user.getUserName()); // put all values in the result object for (Iterator iter = actionFields.keySet().iterator(); iter.hasNext();) { ArrayList setField = (ArrayList) actionFields.get(iter.next()); for (Iterator it = setField.iterator(); it.hasNext();) { Field f = (Field) it.next(); String fieldpath = f.getPath(); String field = "field_" + fieldpath; if (data.getParameters().containsKey(field)) { // binary data need extra storage if (f.getDatatype().equals("fileref")) { FileItem value = data.getParameters().getFileItem(field); Logger.DEBUG("Value for key (file)" + field + ": " + value); // need to store the file now Databit dbit = wf.getDatabit(fieldpath); if (DatapackActions.storeFile(dbit, true, value, user.getUserName())) { String fileName = value.getName(); // fix for browsers setting complete path as name: if (fileName.indexOf("\\") >= 0) fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); if (fileName.indexOf("/") >= 0) fileName = fileName.substring(fileName.lastIndexOf("/") + 1); result.setValue(fieldpath, fileName); } } else if (f.getDatatype().equalsIgnoreCase("multienum")) { SWAMPHashSet values = new SWAMPHashSet(data.getParameters().getStrings(field)); result.setValue(fieldpath, values.toString(", ")); } else if (f.getDatatype().equalsIgnoreCase("patchdocumd")) { String value = data.getParameters().get(field); Logger.DEBUG("Value for key " + field + ": " + value); result.setValue(fieldpath, value); } else { String value = StringEscapeUtils.unescapeHtml(data.getParameters().get(field)); Logger.DEBUG("Value for key " + field + ": " + value); result.setValue(fieldpath, value); } } else if (data.getParameters().containsKey("boolean_" + fieldpath)) { result.setValue(fieldpath, "false"); } else if (!f.isMandatory()) { // don't complain about missing, non-mandatory fields } else { Logger.ERROR("Mandatory field " + fieldpath + " not set."); } } } } // validate task result validationErrors = task.validate(); // if everything is ok, try to finish the task if (validationErrors.size() == 0) { try { taskapi.finishTask(task, user.getUserName(), history); } catch (Exception e) { e.printStackTrace(); validationErrors.add(e.getMessage()); } } if (validationErrors.size() == 0) { Logger.LOG("Webapp: Done with working on task with id " + task.getId()); WorkflowTask wftask = task; Workflow wf = wfapi.getWorkflow(wftask.getWorkflowId(), user.getUserName()); context.put("statusheader", "Success"); context.put("statusmessage", "Task \"" + task.getReplacedDescription() + "\" done in workflow " + wf.getName() + "."); context.put("statusclass", "success"); context.put("icon", "ok"); context.put("history", history); context.put("workflow", wf); // add general Workflow Help SWAMPScreen.addHelplink(wf.getTemplate(), context, user.getUserName()); ArrayList helps = new ArrayList(); if (context.get("helps") != null) { helps = (ArrayList) context.get("helps"); } // add helplinks if there are new Tasks: if (wf.getActiveTasks().size() > 0) { List activeTasks = wf.getActiveTasks(); for (Iterator it = activeTasks.iterator(); it.hasNext();) { WorkflowTask helptask = (WorkflowTask) it.next(); String helpConext = helptask.getActionTemplate().getHelpContext(); if (helpConext != null && !helpConext.equals("")) { ContextHelp help = new DocumentationAPI().getContextHelp(helpConext, user.getUserName()); if (help != null && !helps.contains(help)) { helps.add(help); } } } context.put("helps", helps); } if (user.getPerm("taskpage", "results").equals("workflow")) { Logger.DEBUG("Doing redirect to workflow page after task for " + user.getUserName()); setTemplate(data, "DisplayWorkflow.vm"); } else if (user.getPerm("taskpage", "results").equals("previous")) { CircularFifoBuffer pageBuffer = (CircularFifoBuffer) data.getUser().getTemp("pageBuffer", new CircularFifoBuffer(2)); SWAMPHashMap params = (SWAMPHashMap) pageBuffer.get(); if (params != null && params.containsKey("template")) { Logger.DEBUG("Redirect to previous page (" + params.get("template") + ") for " + user.getUserName()); data.getParameters().clear(); for (Iterator it = params.keySet().iterator(); it.hasNext();) { String key = (String) it.next(); data.getParameters().add(key, (String) params.get(key)); } setTemplate(data, (String) params.get("template")); } else { Logger.WARN("Desired redirect not possible, no pageBuffer"); } } // if there were errors during validation, log the error } else { // go back to the Task-Page context.put("taskerror", "true"); setTemplate(data, "DisplayTask.vm"); Iterator errIter = validationErrors.iterator(); String message = "", error; while (errIter.hasNext()) { error = (String) errIter.next(); message = message + "<br />" + error; Logger.ERROR(error); } message = message + "<p />Please correct the above mistake!"; context.put("statusclass", "error"); context.put("statusheader", "Error validating task"); context.put("statusmessage", message); context.put("icon", "error"); // fix page buffer CircularFifoBuffer pageBuffer = (CircularFifoBuffer) data.getUser().getTemp("pageBuffer", new CircularFifoBuffer(2)); pageBuffer.add(pageBuffer.get()); } // end validation } else { // illegal task requested, redirect setTemplate(data, "DisplayTask.vm"); } } else { Logger.ERROR("in doTaskok: no task id."); } //end taskid }
From source file:com.nubits.nubot.trading.wrappers.AltsTradeWrapper.java
@Override public ApiResponse getOrderDetail(String orderID) { ApiResponse apiResponse = new ApiResponse(); ApiResponse getAllOrders = getActiveOrders(); if (getAllOrders.isPositive()) { ArrayList<Order> orders = (ArrayList) getAllOrders.getResponseObject(); for (Iterator<Order> order = orders.iterator(); order.hasNext();) { Order thisOrder = order.next(); if (thisOrder.getId().equals(orderID)) { apiResponse.setResponseObject(thisOrder); }/*from www.ja va2s . c om*/ } } else { apiResponse = getAllOrders; } return apiResponse; }