List of usage examples for java.util LinkedList add
public boolean add(E e)
From source file:net.dv8tion.jda.core.MessageHistory.java
public RestAction<List<Message>> retrieveFuture(int amount) { if (amount > 100 || amount < 0) throw new IllegalArgumentException( "Message retrieval limit is between 1 and 100 messages. No more, no less. Limit provided: " + amount);//from w ww . j a v a2 s. co m if (history.isEmpty()) throw new IllegalStateException( "No messageId is stored to use as the marker between the future and past." + "Either use MessageHistory(MessageChannel, String) or make a call to retrievePast(int) first."); Route.CompiledRoute route = Route.Messages.GET_MESSAGE_HISTORY_AFTER.compile(channel.getId(), Integer.toString(amount), history.firstKey()); return new RestAction<List<Message>>(api, route, null) { @Override protected void handleResponse(Response response, Request request) { if (!response.isOk()) request.onFailure(response); EntityBuilder builder = EntityBuilder.get(api); LinkedList<Message> msgs = new LinkedList<>(); JSONArray historyJson = response.getArray(); for (int i = 0; i < historyJson.length(); i++) msgs.add(builder.createMessage(historyJson.getJSONObject(i))); for (Iterator<Message> it = msgs.descendingIterator(); it.hasNext();) { Message m = it.next(); history.put(0, m.getId(), m); } request.onSuccess(msgs); } }; }
From source file:com.asakusafw.runtime.directio.DirectDataSourceRepository.java
/** * Returns all {@link DirectDataSource}s registered in this repository. * @return all {@link DirectDataSource}s * @throws IOException if failed to initialize data sources * @throws InterruptedException if interrupted *///from w ww . j av a 2s . c o m public Collection<String> getContainerPaths() throws IOException, InterruptedException { Collection<String> results = new ArrayList<>(); LinkedList<Node> work = new LinkedList<>(); work.add(root); while (work.isEmpty() == false) { Node node = work.removeFirst(); if (node.hasContent()) { results.add(node.path.getPathString()); } work.addAll(node.children.values()); } return results; }
From source file:com.kse.bigdata.file.SequenceSampler.java
public LinkedList<Sequence> getRandomSample() { System.out.println("Sampling Start..."); System.out.println("Sample Size is " + SAMPLE_SIZE); try {//from w ww . j a v a2 s . com FileSystem fs = FileSystem.get(new Configuration()); BufferedReader fileReader = new BufferedReader(new InputStreamReader(fs.open(sampleFile))); LinkedList<Double> deque = new LinkedList<Double>(); String line; int[] sampleIndexes = getRandomSampleIndexArray(); int counter = -1; while ((line = fileReader.readLine()) != null) { counter++; deque.add(extractValidInformation(line)); if (deque.size() == Sequence.SIZE_OF_SEQUENCE) { for (int sampleIndex : sampleIndexes) if (sampleIndex == counter) randomSamples.add(new Sequence(deque)); deque.removeFirst(); } if (randomSamples.size() == SAMPLE_SIZE) return randomSamples; } } catch (IOException e) { e.printStackTrace(); } return this.randomSamples; }
From source file:com.quartercode.classmod.extra.def.DefaultFunctionInvocation.java
/** * Creates a new default function invocation for the given {@link Function}. * The required data is taken from the given {@link Function} object. * This constructor also takes the available {@link FunctionExecutor}s and sorts them so they * /*from w w w.ja v a 2 s . c om*/ * @param source The {@link Function} the default function invocation is used by. */ public DefaultFunctionInvocation(Function<R> source) { this.source = source; // Specify the list type for using this as a queue later on // We need a list here for sorting the executors LinkedList<FunctionExecutorContext<R>> executors = new LinkedList<FunctionExecutorContext<R>>(); for (FunctionExecutorContext<R> executor : source.getExecutors()) { if (isExecutorInvocable(executor)) { executors.add(executor); } } Collections.sort(executors, new Comparator<FunctionExecutorContext<R>>() { @Override public int compare(FunctionExecutorContext<R> o1, FunctionExecutorContext<R> o2) { return ((Integer) o2.getValue(Prioritized.class, "value")) .compareTo((Integer) o1.getValue(Prioritized.class, "value")); } }); remainingExecutors = executors; }
From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.DatapropRetryController.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) { if (!isAuthorizedToDisplayPage(request, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) { return;/* ww w . j av a 2 s . co m*/ } //create an EditProcessObject for this and put it in the session EditProcessObject epo = super.createEpo(request); epo.setBeanClass(DataProperty.class); VitroRequest vreq = new VitroRequest(request); WebappDaoFactory wadf = ModelAccess.on(getServletContext()).getWebappDaoFactory(); DatatypeDao dDao = wadf.getDatatypeDao(); DataPropertyDao dpDao = wadf.getDataPropertyDao(); epo.setDataAccessObject(dpDao); OntologyDao ontDao = wadf.getOntologyDao(); DataProperty objectForEditing = null; String action = null; if (epo.getAction() == null) { action = "insert"; epo.setAction("insert"); } else { action = epo.getAction(); } if (epo.getUseRecycledBean()) { objectForEditing = (DataProperty) epo.getNewBean(); } else { String uri = request.getParameter("uri"); if (uri != null) { try { objectForEditing = dpDao.getDataPropertyByURI(uri); epo.setOriginalBean(objectForEditing); action = "update"; epo.setAction("update"); } catch (NullPointerException e) { log.error("Need to implement 'record not found' error message."); } } else { action = "insert"; epo.setAction("insert"); objectForEditing = new DataProperty(); epo.setOriginalBean(objectForEditing); } } //put this in the parent class? //make a simple mask for the class's id Object[] simpleMaskPair = new Object[2]; simpleMaskPair[0] = "URI"; simpleMaskPair[1] = objectForEditing.getURI(); epo.getSimpleMask().add(simpleMaskPair); //set any validators LinkedList lnList = new LinkedList(); lnList.add(new XMLNameValidator()); epo.getValidatorMap().put("LocalName", lnList); LinkedList vlist = new LinkedList(); vlist.add(new IntValidator(0, 99)); epo.getValidatorMap().put("StatusId", vlist); //set the getMethod so we can retrieve a new bean after we've inserted it try { Class[] args = new Class[1]; args[0] = String.class; epo.setGetMethod(dpDao.getClass().getDeclaredMethod("getDataPropertyByURI", args)); } catch (NoSuchMethodException e) { log.error("DatapropRetryController could not find the getDataPropertyByURI method in the facade"); } //make a postinsert pageforwarder that will send us to a new class's fetch screen epo.setPostInsertPageForwarder(new DataPropertyInsertPageForwarder()); //make a postdelete pageforwarder that will send us to the list of properties epo.setPostDeletePageForwarder(new UrlForwarder("listDatatypeProperties")); //set up any listeners List changeListenerList = new ArrayList(); changeListenerList.add(new PropertyRestrictionListener()); epo.setChangeListenerList(changeListenerList); FormObject foo = new FormObject(); foo.setErrorMap(epo.getErrMsgMap()); // retain error messages from previous time through the form epo.setFormObject(foo); FormUtils.populateFormFromBean(objectForEditing, action, foo); //for now, this is also making the value hash - need to separate this out HashMap optionMap = new HashMap(); List namespaceList = FormUtils.makeOptionListFromBeans(ontDao.getAllOntologies(), "URI", "Name", ((objectForEditing.getNamespace() == null) ? "" : objectForEditing.getNamespace()), null, (objectForEditing.getNamespace() != null)); namespaceList.add(0, new Option(vreq.getUnfilteredWebappDaoFactory().getDefaultNamespace(), "default")); optionMap.put("Namespace", namespaceList); List<Option> domainOptionList = FormUtils.makeVClassOptionList(vreq.getUnfilteredWebappDaoFactory(), objectForEditing.getDomainClassURI()); if (objectForEditing.getDomainClassURI() != null) { VClass domain = vreq.getWebappDaoFactory().getVClassDao() .getVClassByURI(objectForEditing.getDomainClassURI()); if (domain != null && domain.isAnonymous()) { domainOptionList.add(0, new Option(domain.getURI(), domain.getName(), true)); } } domainOptionList.add(0, new Option("", "(none specified)")); optionMap.put("DomainClassURI", domainOptionList); List datatypeOptionList = FormUtils.makeOptionListFromBeans(dDao.getAllDatatypes(), "Uri", "Name", objectForEditing.getRangeDatatypeURI(), null); datatypeOptionList.add(0, new Option("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral", "XML literal (allows XHTML markup)")); datatypeOptionList.add(0, new Option(null, "untyped (use if language tags desired)")); optionMap.put("RangeDatatypeURI", datatypeOptionList); List groupOptList = FormUtils.makeOptionListFromBeans( vreq.getUnfilteredWebappDaoFactory().getPropertyGroupDao().getPublicGroups(true), "URI", "Name", ((objectForEditing.getGroupURI() == null) ? "" : objectForEditing.getGroupURI()), null, (objectForEditing.getGroupURI() != null)); HashMap<String, Option> hashMap = new HashMap<String, Option>(); groupOptList = getSortedList(hashMap, groupOptList, vreq); groupOptList.add(0, new Option("", "none")); optionMap.put("GroupURI", groupOptList); optionMap.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri", RoleLevelOptionsSetup.getDisplayOptionsList(objectForEditing)); optionMap.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri", RoleLevelOptionsSetup.getUpdateOptionsList(objectForEditing)); optionMap.put("HiddenFromPublishBelowRoleLevelUsingRoleUri", RoleLevelOptionsSetup.getPublishOptionsList(objectForEditing)); foo.setOptionLists(optionMap); request.setAttribute("functional", objectForEditing.getFunctional()); //checkboxes are pretty annoying : we don't know if someone *unchecked* a box, so we have to default to false on updates. if (objectForEditing.getURI() != null) { objectForEditing.setFunctional(false); } foo.setErrorMap(epo.getErrMsgMap()); RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP); request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp"); request.setAttribute("colspan", "4"); request.setAttribute("scripts", "/templates/edit/formBasic.js"); request.setAttribute("formJsp", "/templates/edit/specific/dataprop_retry.jsp"); request.setAttribute("title", "Data Property Editing Form"); request.setAttribute("_action", action); request.setAttribute("unqualifiedClassName", "DatatypeProperty"); setRequestAttributes(request, epo); try { rd.forward(request, response); } catch (Exception e) { log.error("DatatypeRetryController could not forward to view."); log.error(e.getMessage()); log.error(e.getStackTrace()); } }
From source file:edu.csun.ecs.cs.multitouchj.application.whiteboard.ui.InteractiveCanvas.java
protected void addPreviousPoints(List<ObjectObserverEvent> objectObserverEvents) { synchronized (previousPoints) { for (ObjectObserverEvent ooe : objectObserverEvents) { LinkedList<Point> points = previousPoints.get(ooe.getId()); if (points == null) { points = new LinkedList<Point>(); }//from www . j a v a2 s . c om points.add(new Point(ooe.getX(), ooe.getY())); previousPoints.put(ooe.getId(), points); previousTimes.put(ooe.getId(), ooe.getTime()); } } }
From source file:com.pinterest.secor.common.ZookeeperConnector.java
public List<Integer> getCommittedOffsetPartitions(String topic) throws Exception { ZooKeeper zookeeper = mZookeeperClient.get(); String topicPath = getCommittedOffsetTopicPath(topic); List<String> partitions = zookeeper.getChildren(topicPath, false); LinkedList<Integer> result = new LinkedList<Integer>(); for (String partitionPath : partitions) { String[] elements = partitionPath.split("/"); String partition = elements[elements.length - 1]; result.add(Integer.valueOf(partition)); }/*from w w w .j a v a 2 s .c om*/ return result; }
From source file:com.handcraftedbits.bamboo.plugin.go.task.test.GoTestTaskType.java
@NotNull @Override//from w w w . ja v a2 s . c o m public TaskResult execute(@NotNull final TaskContext taskContext) throws TaskException { final GoTestTaskConfiguration configuration = new GoTestTaskConfiguration(getTaskHelper(), taskContext); int i = 0; final File outputDirectory = new File(taskContext.getWorkingDirectory(), configuration.getLogOutputPath()); final List<GoArgumentList> packagesWithArguments = configuration .getPackagesWithArguments(GoTestTaskConfiguration.flagsToExclude); final ProcessHelper processHelper = getTaskHelper().createProcessHelper(taskContext); if (outputDirectory.exists()) { try { FileUtils.forceDelete(outputDirectory); } catch (final IOException e) { taskContext.getBuildLogger().addErrorLogEntry(getTaskHelper().getText( "task.test.error.directory." + "results.delete", outputDirectory.getAbsolutePath())); return TaskResultBuilder.newBuilder(taskContext).failedWithError().build(); } } if (!outputDirectory.mkdirs()) { taskContext.getBuildLogger().addErrorLogEntry(getTaskHelper() .getText("task.test.error.directory." + "results.create", outputDirectory.getAbsolutePath())); return TaskResultBuilder.newBuilder(taskContext).failedWithError().build(); } for (final GoArgumentList packageWithArguments : packagesWithArguments) { final LinkedList<String> commandLine = new LinkedList<>(); final FileOutputHandler fileOutputHandler = new FileOutputHandler( new File(outputDirectory, "goTestOutput" + (i++) + ".log")); final ExternalProcess process; commandLine.add(configuration.getGoExecutable()); commandLine.add("test"); commandLine.add("-v"); commandLine.addAll(packageWithArguments.getItems()); if (configuration.shouldLogOutputToBuild()) { process = processHelper.executeProcess(commandLine, configuration.getSourcePath(), configuration.getEnvironmentVariables(), new CompositeOutputHandler(taskContext.getBuildLogger(), processHelper.createStandardOutputHandler(), fileOutputHandler), new CompositeOutputHandler(taskContext.getBuildLogger(), processHelper.createStandardErrorHandler(), fileOutputHandler)); } else { process = processHelper.executeProcess(commandLine, configuration.getSourcePath(), configuration.getEnvironmentVariables(), fileOutputHandler, fileOutputHandler); } if (process.getHandler().getExitCode() != 0) { return TaskResultBuilder.newBuilder(taskContext).checkReturnCode(process, 0).build(); } } return TaskResultBuilder.newBuilder(taskContext).success().build(); }
From source file:com.kpb.other.AcmeCorpPhysicalNamingStrategy.java
private LinkedList<String> splitAndReplace(String name) { LinkedList<String> result = new LinkedList<String>(); for (String part : StringUtils.splitByCharacterTypeCamelCase(name)) { if (part == null || part.trim().isEmpty()) { // skip null and space continue; }//ww w.j ava 2s. c om part = applyAbbreviationReplacement(part); result.add(part.toLowerCase(Locale.ROOT)); } return result; }
From source file:com.samanamp.algorithms.RandomSelectionAlgorithm.java
public void runAlgoAndSimulation(int maxCost, int maxTime, int runs) { this.maxCost = maxCost; this.maxTime = maxTime; this.runs = runs; Random randomGen = new Random(); randomGen.setSeed(System.currentTimeMillis()); Node[] nodes = graph.vertexSet().toArray(new Node[graph.vertexSet().size()]); LinkedList<Node> selectedNodes = new LinkedList<Node>(); Node tmpNode;//from w w w .ja v a2s .c o m int arraySize = nodes.length; for (int currentCost = 0; currentCost < maxCost;) { tmpNode = nodes[((int) (randomGen.nextFloat() * arraySize))]; if (tmpNode.cost + currentCost <= maxCost) { selectedNodes.add(tmpNode); currentCost += tmpNode.cost; } } System.out.println("#nodes selected: " + selectedNodes.size()); runSimulation(selectedNodes); }