List of usage examples for java.util ArrayList remove
public boolean remove(Object o)
From source file:co.carlosandresjimenez.gotit.backend.controller.GotItSvc.java
@RequestMapping(value = ANSWER_PATH, method = RequestMethod.POST) public @ResponseBody int saveAnswers(@RequestBody ArrayList<Answer> answers, HttpServletRequest request) { if (answers == null || answers.isEmpty()) { return RESPONSE_STATUS_NOT_SAVED; }/* ww w . j a v a2 s . c om*/ Checkin checkin; String email = (String) request.getAttribute("email"); if (email == null || email.isEmpty()) { return RESPONSE_STATUS_AUTH_REQUIRED; } int lastAnswerPosition = answers.size() - 1; Answer lastAnswer = answers.get(lastAnswerPosition); try { checkin = checkinRepository.save( new Checkin(null, email, Utility.getDatetime(), Boolean.parseBoolean(lastAnswer.getValue()))); } catch (JDOException e) { e.printStackTrace(); return RESPONSE_STATUS_NOT_SAVED; } answers.remove(lastAnswerPosition); for (Answer answer : answers) { answer.setCheckinId(checkin.getCheckinId()); } ArrayList<Answer> result; try { result = (ArrayList<Answer>) answerRepository.save(answers); } catch (JDOException e) { e.printStackTrace(); return RESPONSE_STATUS_NOT_SAVED; } if (result == null || result.isEmpty()) { return RESPONSE_STATUS_NOT_SAVED; } if (result.size() != answers.size()) { return RESPONSE_STATUS_NOT_SAVED; } return RESPONSE_STATUS_OK; }
From source file:com.twinsoft.convertigo.engine.ContextManager.java
public void remove(Context context) { if (context == null) { // Silently ignore Engine.logContextManager.warn("The context cannot be removed because it does not exist any more!"); return;/*from w w w . j ava 2 s .com*/ } // To prevent from deadlock, we must synchronize on the context itself (see #3048) // to avoid another request thread to try to use the context simultaneously. // This lock must occur BEFORE acquiring lock the the contexts table. synchronized (context) { String contextID = context.contextID; Engine.logContextManager.info("Removing context " + contextID); synchronized (contexts) { contexts.remove(contextID); } context.isDestroying = true; if ((context.requestedObject != null) && (context.requestedObject.runningThread != null)) { Engine.logContextManager.debug("Stopping requestable thread for context " + contextID); //context.requestedObject.runningThread.bContinue = false; context.abortRequestable(); } // Trying to execute the end transaction (only in the engine mode) if ((Engine.isEngineMode()) && (context.getConnector() != null)) { // Execute the end transaction String endTransactionName = "n/a"; try { endTransactionName = context.getConnector().getEndTransactionName(); if ((endTransactionName != null) && (!endTransactionName.equals(""))) { Engine.logContextManager .debug("Trying to execute the end transaction: \"" + endTransactionName + "\""); context.transactionName = endTransactionName; DefaultRequester defaultRequester = new DefaultRequester(); // #4910 - prevent loop for destroying context renew context.isDestroying = false; defaultRequester.processRequest(context); Engine.logContextManager.debug("End transaction successfull"); } } catch (Throwable e) { Engine.logContextManager.error("Unable to execute the end transaction; " + "context: " + context.contextID + ", " + "project: " + context.projectName + ", " + "connector: " + context.connectorName + ", " + "end transaction: " + endTransactionName, e); } finally { context.isDestroying = true; } // Unlocks device if any // WARNING: removing the device pool MUST BE DONE AFTER the end transaction!!! String connectorQName = context.getConnector().getQName(); DevicePool devicePool = getDevicePool(connectorQName); if (devicePool != null) { long contextNum = (Long.valueOf(Integer.toString(context.contextNum, 10))).longValue(); Engine.logContextManager.trace("DevicePool for '" + connectorQName + "' exist: unlocking device for context number " + contextNum + "."); devicePool.unlockDevice(contextNum); } } if (Engine.isEngineMode()) { for (final Connector connector : context.getOpenedConnectors()) { Engine.logContextManager.trace("Releasing " + connector.getName() + " connector (" + connector.getClass().getName() + ") for context id " + context.contextID); Thread th = new Thread(new Runnable() { public void run() { connector.release(); } }); th.setDaemon(true); th.start(); } } context.clearConnectors(); // Set TwsCachedXPathAPI to null context.cleanXpathApi(); Engine.theApp.sessionManager.removeSession(contextID); String projectName = (String) context.projectName; /* Fix: #1754 - Slower transaction execution with many session */ // HTTP session maintain its own context list in order to // improve context removal on session unbound process // See also #4198 which fix a regression String sessionID = context.httpSession != null ? context.httpSession.getId() : context.contextID.substring(0, context.contextID.indexOf("_")); HttpSession httpSession = HttpSessionListener.getHttpSession(sessionID); if (httpSession != null) { synchronized (httpSession) { try { ArrayList<Context> contextList = GenericUtils.cast(httpSession.getAttribute("contexts")); if ((contextList != null) && contextList.contains(context)) { contextList.remove(context); Engine.logContextManager.debug("(ContextManager) context " + contextID + " has been removed from http session's context list"); } httpSession.setAttribute("contexts", contextList); } catch (Exception e) { // Ignore: HTTP session may have already been invalidated } } } Engine.logContextManager.debug("Context " + contextID + " has been removed"); Engine.logContext.debug("[" + contextID + "] Context removed, project: " + projectName); Engine.logContextManager.info("Current in-use contexts: " + contexts.size()); Engine.logUsageMonitor.info("[Contexts] Current in-use contexts: " + contexts.size()); } }
From source file:edu.isi.wings.catalog.component.api.impl.kb.ComponentReasoningKB.java
private void setInvocationArguments(ComponentInvocation invocation, KBObject arg, Variable var, boolean isInput) { HashMap<String, KBObject> dmap = this.dataPropMap; KBObject defaultValue = this.kb.getPropertyValue(arg, dmap.get("hasValue")); KBObject prefixobj = this.kb.getPropertyValue(arg, dmap.get("hasArgumentName")); String prefix = (String) prefixobj.getValue(); ArrayList<Binding> bindings = new ArrayList<Binding>(); bindings.add(var.getBinding()); while (!bindings.isEmpty()) { Binding b = bindings.remove(0); // System.out.println(var.getName() + ":" + b); if (b.isSet()) { for (WingsSet s : b) { bindings.add((Binding) s); }/*from w ww . j a va2 s. c o m*/ } else { if (var.isDataVariable()) { invocation.addArgument(prefix, b, var.getID(), isInput); } else if (var.isParameterVariable()) { if (var.getBinding() != null) { invocation.addArgument(prefix, ((ValueBinding) var.getBinding()).getValueAsString(), var.getID(), isInput); } else if (defaultValue != null && defaultValue.getValue() != null) { invocation.addArgument(prefix, defaultValue.getValueAsString(), var.getID(), isInput); } } } } }
From source file:net.sourceforge.mipa.predicatedetection.lattice.WindowedLatticeChecker.java
private void grow(AbstractLatticeIDNode node, int id) { ArrayList<AbstractLatticeIDNode> set = new ArrayList<AbstractLatticeIDNode>(); set.add(node);//w w w . j a v a 2 s . c om while (!set.isEmpty()) { AbstractLatticeIDNode newNode = set.remove(0); String ID = StringUtils.join(newNode.getID(), ' '); if (mappedLattice.get(ID) == null) { mappedLattice.put(ID, newNode); if (DEBUG) { long time_t = (new Date()).getTime(); outConstruction.println("[In]" + ID); outConstruction.flush(); wastedTime += (new Date()).getTime() - time_t; } ArrayList<AbstractLatticeIDNode> prec = prec(newNode, id); ArrayList<AbstractLatticeIDNode> sub = sub(newNode, id); if (prec.size() == 0) { minCGS = newNode; } if (sub.size() == 0) { maxCGS = newNode; } for (int i = 0; i < prec.size(); i++) { String ind = StringUtils.join(prec.get(i).getID(), ' '); if (mappedLattice.get(ind) == null) { if (!set.contains(prec.get(i))) { set.add(prec.get(i)); } } } for (int i = 0; i < sub.size(); i++) { String ind = StringUtils.join(sub.get(i).getID(), ' '); if (mappedLattice.get(ind) == null) { if (!set.contains(sub.get(i))) { set.add(sub.get(i)); } } } } } }
From source file:com.chinamobile.bcbsp.comm.DiskManager.java
/** * Save messages of every partition on disk. * @param msgList/*from ww w. ja v a 2 s .c o m*/ * @param superStep * @param srcPartitionDstBucket * @throws IOException e */ public void processMessagesSave(ArrayList<IMessage> msgList, int superStep, int srcPartitionDstBucket) throws IOException { int count = msgList.size(); int bucket = PartitionRule.getBucket(srcPartitionDstBucket); int srcPartition = PartitionRule.getPartition(srcPartitionDstBucket); String fileName = "srcPartition-" + srcPartition + "_" + "counter" + "-" + counter[srcPartitionDstBucket]++ + "_" + "count" + "-" + count; String tmpPath = DiskManager.workerDir + "/" + "superstep-" + superStep + "/" + "bucket-" + bucket; File tmpFile = new File(tmpPath); if (!tmpFile.exists()) { tmpFile.mkdirs(); } String url = new File(tmpFile, fileName).toString(); // SpillingDiskOutputBuffer writeBuffer = new SpillingDiskOutputBuffer(url); FileOutputStream fot = new FileOutputStream(new File(url)); BufferedOutputStream bos = new BufferedOutputStream(fot, MetaDataOfMessage.MESSAGE_IO_BYYES); DataOutputStream dos = new DataOutputStream(bos); for (int i = 0; i < count; i++) { msgList.remove(0).write(dos); } dos.close(); }
From source file:FastArrayList.java
/** * Remove the element at the specified position in the list, and shift * any subsequent elements down one position. * * @param index Index of the element to be removed * * @exception IndexOutOfBoundsException if the index is out of range *//*from w w w .j a v a 2s. c om*/ public Object remove(int index) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); Object result = temp.remove(index); list = temp; return (result); } } else { synchronized (list) { return (list.remove(index)); } } }
From source file:FastArrayList.java
/** * Remove the first occurrence of the specified element from the list, * and shift any subsequent elements down one position. * * @param element Element to be removed//w w w . j ava 2 s. c o m */ public boolean remove(Object element) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); boolean result = temp.remove(element); list = temp; return (result); } } else { synchronized (list) { return (list.remove(element)); } } }
From source file:hotbeans.support.FileSystemHotBeanModuleRepository.java
/** * Checks for module updates.//from w ww . j a va 2s . c o m */ protected void checkForModuleUpdates() { Log logger = this.getLog(); if (logger.isDebugEnabled()) logger.debug("Checking for updated modules in path '" + this.moduleRepositoryDirectory + "'."); synchronized (super.getLock()) { RepositoryFileLock fileLock = null; try { fileLock = this.obtainRepositoryFileLockNoRetries(true); // Obtain lock without retries since this method // will be executed again in the // near future... File[] moduleDirectories = this.moduleRepositoryDirectory.listFiles(); ArrayList activeModuleNames = new ArrayList(Arrays.asList(super.getHotBeanModuleNames())); if (moduleDirectories != null) { String moduleName; for (int i = 0; i < moduleDirectories.length; i++) { if (moduleDirectories[i].isDirectory()) { moduleName = moduleDirectories[i].getName(); if (moduleName != null) { activeModuleNames.remove(moduleName); this.checkModuleDirectory(moduleName, moduleDirectories[i]); } } } } // Check for deleted modules... Iterator deletedModulesIterator = activeModuleNames.iterator(); // HotBeanModule module; HotBeanModuleType moduleType; while (deletedModulesIterator.hasNext()) { moduleType = super.getHotBeanModuleType((String) deletedModulesIterator.next()); if (moduleType != null) moduleType.setRemoveType(true); // Set remove flag of type } } catch (Exception e) { logger.error("Error checking for updated modules - " + e + "!", e); // TODO: Handle/log exception } finally { this.releaseRepositoryFileLock(fileLock); fileLock = null; } } }
From source file:br.unicamp.cst.learning.QLearning.java
/** * Selects the best action for this state with probability "e", * and a random one with probability (1-e) * If a given state has no record of one or more actions, it will consider them as valued 0. * @param state//from w w w . ja v a 2 s . com * @param e * @return selectedAction */ public String getAction(String state) {//TODO should improve this. It should consider all non explored actions as being equally 0 for all purposes // System.out.println("Inside get action"); String selectedAction = null; if (r.nextDouble() <= e) { //TODO Use boltzmann distribution here? // if(ql.getAction(stringState)!=null){ // action=ql.getAction(stringState);// //----- if (this.Q.get(state) != null) { ArrayList<String> actionsLeft = new ArrayList<String>(); actionsLeft.addAll(this.actionsList); HashMap<String, Double> actionsQ = this.Q.get(state); double bestQval = -Double.POSITIVE_INFINITY; Iterator<Entry<String, Double>> it = actionsQ.entrySet().iterator(); while (it.hasNext()) { Entry<String, Double> pairs = it.next(); double qVal = pairs.getValue(); String qAct = pairs.getKey(); if (qVal > bestQval) { bestQval = qVal; selectedAction = qAct; } actionsLeft.remove(qAct); } if ((bestQval < 0) && (actionsLeft.size() > 0)) { //this means we should randomly choose from the other actions; selectedAction = selectRandomAction(actionsLeft); } if (showDebugMessages) { System.out.println("Selected the best available action."); } } else { // System.out.println("Inside else null"); // selectedAction=null; selectedAction = selectRandomAction(actionsList); if (showDebugMessages) { System.out.println("Selected a random action because there was no available suggestion."); } } // }else{ // action=selectRandomAction(); // } } else { if (showDebugMessages) { System.out.println("Naturally selected a random action."); } selectedAction = selectRandomAction(actionsList); } return selectedAction; }
From source file:net.sf.xmm.moviemanager.gui.DialogIMDbMultiAdd.java
/** * Takes all the media files in a Files object and generated a string * listing all the files categorized by parent directory. *//* w w w. java 2 s. c om*/ void setFileLocationContent() { if (multiAddFile != null && multiAddFile.getFile() != null) { int height = 0; ArrayList<Files> files = multiAddFile.getFiles(); String str = ""; while (files.size() > 0) { String parent = files.get(0).getParent(); if (str.length() > 0) str += SysUtil.getLineSeparator(); // Show directory of the file(s) str += parent + SysUtil.getDirSeparator(); height++; int fileNumber = 1; for (int i = 0; i < files.size(); i++) { // Find all files in the current parent if (files.get(i).getParent().equals(parent)) { height++; str += SysUtil.getLineSeparator() + String.format(" %-3d - %s", fileNumber++, files.get(i).getName()); files.remove(i); i--; } } } fileLocation.setText(str); fileLocation.setRows(height); } }