List of usage examples for java.util LinkedList forEach
default void forEach(Consumer<? super T> action)
From source file:net.dv8tion.jda.core.MessageHistory.java
public static RestAction<MessageHistory> getHistoryAround(MessageChannel channel, final String markerMessageId, int limit) { if (markerMessageId == null) throw new IllegalArgumentException("Provided markedMessageId cannot be null!"); if (limit > 100 || limit < 1) throw new IllegalArgumentException( "Provided limit was out of bounds. Minimum: 1, Max: 100. Provided: " + limit); Route.CompiledRoute route = Route.Messages.GET_MESSAGE_HISTORY_AROUND.compile(channel.getId(), Integer.toString(limit), markerMessageId); return new RestAction<MessageHistory>(channel.getJDA(), route, null) { @Override//ww w. j ava2s. c o m protected void handleResponse(Response response, Request request) { if (!response.isOk()) request.onFailure(response); MessageHistory mHistory = new MessageHistory(channel); mHistory.markerId = markerMessageId; 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))); msgs.forEach(msg -> mHistory.history.put(msg.getId(), msg)); request.onSuccess(mHistory); } }; }
From source file:se.trixon.pacoma.ui.PagePanel.java
private void init() { mDropTarget = new DropTarget() { @Override/*from ww w .j ava 2s .c o m*/ public synchronized void drop(DropTargetDropEvent evt) { try { evt.acceptDrop(DnDConstants.ACTION_COPY); LinkedList<File> droppedFiles = new LinkedList<>( (List<File>) evt.getTransferable().getTransferData(DataFlavor.javaFileListFlavor)); List<File> invalidFiles = new LinkedList<>(); droppedFiles.forEach((droppedFile) -> { if (droppedFile.isFile() && FilenameUtils.isExtension(droppedFile.getName().toLowerCase(Locale.getDefault()), new String[] { "jpg", "jpeg", "png" })) { //all ok } else { invalidFiles.add(droppedFile); } }); invalidFiles.forEach((invalidFile) -> { droppedFiles.remove(invalidFile); System.out.println("remomve invalid file: " + invalidFile.getAbsolutePath()); }); droppedFiles.forEach((droppedFile) -> { System.out.println("accept: " + droppedFile.getAbsolutePath()); }); mCollage.addFiles(droppedFiles); } catch (UnsupportedFlavorException | IOException ex) { System.err.println(ex.getMessage()); } } }; setDropTarget(mDropTarget); }
From source file:net.dv8tion.jda.core.MessageHistory.java
public synchronized RestAction<List<Message>> retrievePast(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 www . j av a2s . co m*/ Route.CompiledRoute route; if (history.isEmpty()) route = Route.Messages.GET_MESSAGE_HISTORY.compile(channel.getId(), Integer.toString(amount)); else route = Route.Messages.GET_MESSAGE_HISTORY_BEFORE.compile(channel.getId(), Integer.toString(amount), history.lastKey()); 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))); if (history.isEmpty()) msgs.forEach(msg -> history.put(msg.getId(), msg)); request.onSuccess(msgs); } }; }
From source file:de.elggconnect.elggconnectclient.webservice.StatusUser.java
/** * handle the StatusUser JSON Response and store it into the StatusManager * <p>/* ww w . j av a 2 s.c o m*/ * Remove the old Data and fill it with new one * * @param result */ private void handleStatusUserResponse(JSONArray result) { LinkedList<JSONObject> statusUserObjectList = new LinkedList<>(); //Save JSON Objects from result array for (Object aResult : result) { JSONObject object = (JSONObject) aResult; statusUserObjectList.add((JSONObject) object.get("object")); } //Clear StatusUserObjects StatusUserManager.getInstance().getStatusUserObjects().clear(); //save all UserStatus objects statusUserObjectList.forEach(this::saveStatusUserObject); }
From source file:net.dv8tion.jda.core.entities.MessageHistory.java
/** * Retrieves messages from Discord that were sent before the oldest sent message in MessageHistory's history cache * ({@link #getRetrievedHistory()})./*from w w w.j a v a2s . c om*/ * <br>Can only retrieve a <b>maximum</b> of {@code 100} messages at a time. * <br>This method has 2 modes of operation: initial retrieval and additional retrieval. * <ul> * <li><b>Initial Retrieval</b> * <br>This mode is what is used when no {@link net.dv8tion.jda.core.entities.Message Messages} have been retrieved * yet ({@link #getRetrievedHistory()}'s size is 0). Initial retrieval starts from the most recent message sent * to the channel and retrieves backwards from there. So, if 50 messages are retrieved during this mode, the * most recent 50 messages will be retrieved.</li> * * <li><b>Additional Retrieval</b> * <br>This mode is used once some {@link net.dv8tion.jda.core.entities.Message Messages} have already been retrieved * from Discord and are stored in MessageHistory's history ({@link #getRetrievedHistory()}). When retrieving * messages in this mode, MessageHistory will retrieve previous messages starting from the oldest message * stored in MessageHistory. * <br>E.g: If you initially retrieved 10 messages, the next call to this method to retrieve 10 messages would * retrieve the <i>next</i> 10 messages, starting from the oldest message of the 10 previously retrieved messages.</li> * </ul> * <p> * Possible {@link net.dv8tion.jda.core.requests.ErrorResponse ErrorResponses} include: * <ul> * <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#UNKNOWN_MESSAGE UNKNOWN_MESSAGE} * <br>Can occur if retrieving in Additional Mode and the Message being used as the marker for the last retrieved * Message was deleted. Currently, to fix this, you need to create a new * {@link net.dv8tion.jda.core.entities.MessageHistory MessageHistory} instance.</li> * * <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS} * <br>Can occur if the request for history retrieval was executed <i>after</i> JDA lost access to the Channel, * typically due to the account being removed from the {@link net.dv8tion.jda.core.entities.Guild Guild} or * {@link net.dv8tion.jda.client.entities.Group Group}.</li> * * <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS} * <br>Can occur if the request for history retrieval was executed <i>after</i> JDA lost the * {@link net.dv8tion.jda.core.Permission#MESSAGE_HISTORY} permission.</li> * * <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#UNKNOWN_CHANNEL UNKNOWN_CHANNEL} * <br>The send request was attempted after the channel was deleted.</li> * </ul> * * @param amount * The amount of {@link net.dv8tion.jda.core.entities.Message Messages} to retrieve. * * @throws java.lang.IllegalArgumentException * The the {@code amount} is less than {@code 1} or greater than {@code 100}. * * @return {@link net.dv8tion.jda.core.requests.RestAction RestAction} - * Type: {@link java.util.List List}{@literal <}{@link net.dv8tion.jda.core.entities.Message Message}{@literal >} * <br>Retrieved Messages are placed in a List and provided in order of most recent to oldest with most recent * starting at index 0. If the list is empty, there were no more messages left to retrieve. */ @CheckReturnValue public RestAction<List<Message>> retrievePast(int amount) { if (amount > 100 || amount < 1) throw new IllegalArgumentException( "Message retrieval limit is between 1 and 100 messages. No more, no less. Limit provided: " + amount); Route.CompiledRoute route = Route.Messages.GET_MESSAGE_HISTORY.compile(channel.getId()) .withQueryParams("limit", Integer.toString(amount)); if (!history.isEmpty()) route = route.withQueryParams("before", String.valueOf(history.lastKey())); return new RestAction<List<Message>>(getJDA(), route) { @Override protected void handleResponse(Response response, Request<List<Message>> request) { if (!response.isOk()) { request.onFailure(response); return; } EntityBuilder builder = api.getEntityBuilder(); ; LinkedList<Message> msgs = new LinkedList<>(); JSONArray historyJson = response.getArray(); for (int i = 0; i < historyJson.length(); i++) msgs.add(builder.createMessage(historyJson.getJSONObject(i))); msgs.forEach(msg -> history.put(msg.getIdLong(), msg)); request.onSuccess(msgs); } }; }
From source file:org.netbeans.modeler.specification.model.document.property.ElementPropertySet.java
public void executeProperties() { for (Entry<String, LinkedList<SheetProperty>> entry : preOrderedPropeties.entrySet()) { LinkedList<SheetProperty> propertyList = entry.getValue(); //Prepare hashmap container Map<String, PropertyLinkedList<SheetProperty>> filterContainerMap = new LinkedHashMap<>(); propertyList.forEach(p -> { if (filterContainerMap.get(p.getProperty().getName()) == null) { PropertyLinkedList<SheetProperty> propertyLinkedList = new PropertyLinkedList<>(); propertyLinkedList.addFirst(p); filterContainerMap.put(p.getProperty().getName(), propertyLinkedList); } else { filterContainerMap.get(p.getProperty().getName()).addLast(p); }//from www. java2 s . co m }); propertyList.forEach(p -> { if (p.getProperty() instanceof ModelerSheetProperty) { ModelerSheetProperty msp = (ModelerSheetProperty) p.getProperty(); if (msp.getAfter() != null) { PropertyLinkedList<SheetProperty> linklistA = filterContainerMap.get(msp.getAfter()); PropertyLinkedList<SheetProperty> linklistB = filterContainerMap .get(p.getProperty().getName()); if (linklistA == null) { System.out.println("Invalid after type : " + msp.getAfter()); } if (linklistA != null && linklistA != linklistB) { linklistA.addLast(linklistB.getHead()); } } if (msp.getBefore() != null) { PropertyLinkedList<SheetProperty> linklistB = filterContainerMap .get(p.getProperty().getName()); PropertyLinkedList<SheetProperty> linklistA = filterContainerMap.get(msp.getBefore()); if (linklistA == null) { System.out.println("Invalid before type : " + msp.getBefore()); } if (linklistA != null && linklistA != linklistB) { linklistB.addLast(linklistA.getHead()); } } } }); for (Entry<String, PropertyLinkedList<SheetProperty>> filterEntry : filterContainerMap.entrySet()) { PropertyLinkedList<SheetProperty> propertyLinkedList = filterEntry.getValue(); if (propertyLinkedList.getHead().prev == null) { PropertyLinkedList<SheetProperty>.Node node = propertyLinkedList.getHead(); while (node != null) { putProperty(entry.getKey(), node.element.getProperty(), node.element.isReplace()); node = node.next; } } } } preOrderedPropeties.clear(); }
From source file:se.trixon.pacoma.ui.MainFrame.java
private void initListeners() { mActionManager.addAppListener(new ActionManager.AppListener() { @Override/*from ww w. j ava2 s . c om*/ public void onCancel(ActionEvent actionEvent) { } @Override public void onMenu(ActionEvent actionEvent) { if (actionEvent.getSource() != menuButton) { menuButtonMousePressed(null); } } @Override public void onOptions(ActionEvent actionEvent) { showOptions(); } @Override public void onQuit(ActionEvent actionEvent) { quit(); } @Override public void onRedo(ActionEvent actionEvent) { mCollage.nextHistory(); updateToolButtons(); } @Override public void onStart(ActionEvent actionEvent) { } @Override public void onUndo(ActionEvent actionEvent) { mCollage.prevHistory(); updateToolButtons(); } }); mActionManager.addProfileListener(new ActionManager.ProfileListener() { @Override public void onAdd(ActionEvent actionEvent) { addImages(); } @Override public void onClear(ActionEvent actionEvent) { mCollage.clearFiles(); } @Override public void onClose(ActionEvent actionEvent) { setTitle("pacoma"); mActionManager.setEnabledDocumentActions(false); canvasPanel.close(); } @Override public void onEdit(ActionEvent actionEvent) { editCollage(mCollage); } @Override public void onRegenerate(ActionEvent actionEvent) { //TODO } @Override public void onNew(ActionEvent actionEvent) { editCollage(null); if (mCollage != null && mCollage.getName() != null) { setTitle(mCollage); canvasPanel.open(mCollage); mActionManager.getAction(ActionManager.CLEAR).setEnabled(false); mActionManager.getAction(ActionManager.REGENERATE).setEnabled(false); } } @Override public void onOpen(ActionEvent actionEvent) { initFileDialog(mCollageFileNameExtensionFilter); if (SimpleDialog.openFile()) { try { open(SimpleDialog.getPath()); } catch (IOException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } } } @Override public void onSave(ActionEvent actionEvent) { save(); } @Override public void onSaveAs(ActionEvent actionEvent) { saveAs(); } }); mCollagePropertyChangeListener = () -> { if (mCollage != null) { setTitle(mCollage); mActionManager.getAction(ActionManager.SAVE).setEnabled(true); mActionManager.getAction(ActionManager.CLEAR).setEnabled(mCollage.hasImages()); mActionManager.getAction(ActionManager.REGENERATE).setEnabled(mCollage.hasImages()); } }; mDropTarget = new DropTarget() { @Override public synchronized void drop(DropTargetDropEvent evt) { try { evt.acceptDrop(DnDConstants.ACTION_COPY); LinkedList<File> droppedFiles = new LinkedList<>( (List<File>) evt.getTransferable().getTransferData(DataFlavor.javaFileListFlavor)); List<File> invalidFiles = new LinkedList<>(); droppedFiles.forEach((droppedFile) -> { if (droppedFile.isFile() && FilenameUtils.isExtension( droppedFile.getName().toLowerCase(Locale.getDefault()), Collage.FILE_EXT)) { //all ok } else { invalidFiles.add(droppedFile); } }); invalidFiles.forEach((invalidFile) -> { droppedFiles.remove(invalidFile); }); switch (droppedFiles.size()) { case 0: Message.error(MainFrame.this, Dict.Dialog.TITLE_IO_ERROR.toString(), "Not a valid collage file."); break; case 1: open(droppedFiles.getFirst()); break; default: Message.error(MainFrame.this, Dict.Dialog.TITLE_IO_ERROR.toString(), "Too many files dropped."); break; } } catch (UnsupportedFlavorException | IOException ex) { System.err.println(ex.getMessage()); } } }; canvasPanel.setDropTarget(mDropTarget); }
From source file:com.ikanow.aleph2.graph.titan.services.SimpleGraphMergeService.java
@Override public void onObjectBatch(Stream<Tuple2<Long, IBatchRecord>> batch, Optional<Integer> batch_size, Optional<JsonNode> grouping_key) { // (some horrible mutable state to keep this simple) final LinkedList<Tuple2<Long, IBatchRecord>> mutable_user_elements = new LinkedList<>(); final Optional<Validation<BasicMessageBean, JsonNode>> output = batch.filter(t2 -> { if (!t2._2().injected() && mutable_user_elements.isEmpty()) { // (save one element per label in case there are no injected elements) mutable_user_elements.add(t2); }/* ww w . j a v a2s. co m*/ return t2._2().injected(); }).filter(t2 -> { final ObjectNode o = (ObjectNode) t2._2().getJson(); return Optional.ofNullable(o.get(GraphAnnotationBean.type)).filter(j -> (null != j) && j.isTextual()) .map(j -> j.asText()).map(type -> { if (GraphAnnotationBean.ElementType.edge.toString().equals(type)) { // Return the first matching edge: return true; } else if (GraphAnnotationBean.ElementType.vertex.toString().equals(type)) { // Return the first matching vertex: return true; } else return false; }).orElse(false); }).findFirst().<Validation<BasicMessageBean, JsonNode>>map( element -> _context.get().emitImmutableObject(_context.get().getNextUnusedId(), element._2().getJson(), Optional.empty(), Optional.empty(), Optional.empty())); if (!output.isPresent()) { // If didn't find any matching elements, then stick the first one we did find in there mutable_user_elements.forEach(t2 -> _context.get().emitImmutableObject(t2._1(), t2._2().getJson(), Optional.empty(), Optional.empty(), Optional.empty())); } }
From source file:canreg.client.gui.analysis.TableBuilderInternalFrame.java
private void refreshTableTypeList() { FilenameFilter filter = (File dir, String name1) -> (name1.endsWith(".conf")); LinkedList<String> children = new LinkedList<>(); // get directories of .confs File[] dirs = { new File(Globals.TABLES_CONF_PATH), new File(Globals.USER_TABLES_CONF_PATH) }; for (File dir : dirs) { if (dir.exists()) { for (String fileName : dir.list(filter)) { children.add(dir.getAbsolutePath() + Globals.FILE_SEPARATOR + fileName); }//ww w . ja v a2 s . c om } } // LinkedList<TableBuilderListElement> tableTypeLinkedList = new LinkedList<TableBuilderListElement>(); DefaultListModel listModel = new DefaultListModel(); //open one by one using configreader //make list children.forEach((configFileName) -> { // Get filename of file or directory try { String[] tempArray; FileReader fileReader = new FileReader(configFileName); LinkedList<ConfigFields> configFields = ConfigFieldsReader.readFile(fileReader); TableBuilderListElement etle = new TableBuilderListElement(); etle.setConfigFileName(configFileName); etle.setConfigFields(configFields); tempArray = ConfigFieldsReader.findConfig("table_label", configFields); if (tempArray != null && tempArray.length > 0) { etle.setName(tempArray[0]); // System.out.println(tempArray[0]); } tempArray = ConfigFieldsReader.findConfig("table_description", configFields); if (tempArray != null && tempArray.length > 0) { etle.setDescription(tempArray[0]); // System.out.println(tempArray[0]); } tempArray = ConfigFieldsReader.findConfig("table_engine", configFields); if (tempArray != null && tempArray.length > 0) { etle.setEngineName(tempArray[0]); // System.out.println(tempArray[0]); } String[] engineParameters = ConfigFieldsReader.findConfig("engine_parameters", configFields); etle.setEngineParameters(engineParameters); tempArray = ConfigFieldsReader.findConfig("preview_image", configFields); if (tempArray != null && tempArray.length > 0) { etle.setPreviewImageFilename(tempArray[0]); // System.out.println(tempArray[0]); } // tableTypeLinkedList.add(etle); listModel.addElement(etle); } catch (FileNotFoundException ex) { Logger.getLogger(TableBuilderInternalFrame.class.getName()).log(Level.SEVERE, null, ex); } }); tableTypeList.setModel(listModel); }
From source file:net.dv8tion.jda.core.entities.MessageChannel.java
/** * Uses the provided {@code id} of a message as a marker and retrieves messages around * the marker. The {@code limit} determines the amount of message retrieved near the marker. Discord will * attempt to evenly split the limit between before and after the marker, however in the case that the marker is set * near the beginning or near the end of the channel's history the amount of messages on each side of the marker may * be different, and their total count may not equal the provided {@code limit}. * * <p><b>Examples:</b> * <br>Retrieve 100 messages from the middle of history. {@literal >}100 message exist in history and the marker is {@literal >}50 messages * from the edge of history./* w w w.ja va 2s . co m*/ * <br>{@code getHistoryAround(messageId, 100)} - This will retrieve 100 messages from history, 50 before the marker * and 50 after the marker. * * <p>Retrieve 10 messages near the end of history. Provided id is for a message that is the 3rd most recent message. * <br>{@code getHistoryAround(messageId, 10)} - This will retrieve 10 messages from history, 8 before the marker * and 2 after the marker. * * <p>The following {@link net.dv8tion.jda.core.requests.ErrorResponse ErrorResponses} are possible: * <ul> * <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS} * <br>The request was attempted after the account lost access to the * {@link net.dv8tion.jda.core.entities.Guild Guild} or {@link net.dv8tion.jda.client.entities.Group Group} * typically due to being kicked or removed, or after {@link net.dv8tion.jda.core.Permission#MESSAGE_READ Permission.MESSAGE_READ} * was revoked in the {@link net.dv8tion.jda.core.entities.TextChannel TextChannel}</li> * * <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS} * <br>The request was attempted after the account lost * {@link net.dv8tion.jda.core.Permission#MESSAGE_HISTORY Permission.MESSAGE_HISTORY} in the * {@link net.dv8tion.jda.core.entities.TextChannel TextChannel}.</li> * * <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#UNKNOWN_MESSAGE UNKNOWN_MESSAGE} * <br>The provided {@code messageId} is unknown in this MessageChannel, either due to the id being invalid, or * the message it referred to has already been deleted, thus could not be used as a marker.</li> * * <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#UNKNOWN_CHANNEL UNKNOWN_CHANNEL} * <br>The request was attempted after the channel was deleted.</li> * </ul> * * @param messageId * The id of the message that will act as a marker. The id must refer to a message from this MessageChannel. * @param limit * The amount of message to be retrieved around the marker. Minimum: 1, Max: 100. * * @throws java.lang.IllegalArgumentException * <ul> * <li>Provided {@code messageId} is {@code null} or empty.</li> * <li>Provided {@code limit} is less than {@code 1} or greater than {@code 100}.</li> * </ul> * @throws net.dv8tion.jda.core.exceptions.PermissionException * If this is a {@link net.dv8tion.jda.core.entities.TextChannel TextChannel} and the logged in account does not have * <ul> * <li>{@link net.dv8tion.jda.core.Permission#MESSAGE_READ Permission.MESSAGE_READ}</li> * <li>{@link net.dv8tion.jda.core.Permission#MESSAGE_HISTORY Permission.MESSAGE_HISTORY}</li> * </ul> * * @return {@link net.dv8tion.jda.core.requests.RestAction RestAction} - Type: {@link net.dv8tion.jda.core.entities.MessageHistory MessageHistory} * <br>Provides a MessageHistory object with message around the provided message loaded into it. */ @CheckReturnValue default RestAction<MessageHistory> getHistoryAround(String messageId, int limit) { Checks.notEmpty(messageId, "Provided messageId"); Checks.check(limit >= 1 && limit <= 100, "Provided limit was out of bounds. Minimum: 1, Max: 100. Provided: %d", limit); Route.CompiledRoute route = Route.Messages.GET_MESSAGE_HISTORY.compile(this.getId()) .withQueryParams("limit", Integer.toString(limit), "around", messageId); return new RestAction<MessageHistory>(getJDA(), route) { @Override protected void handleResponse(Response response, Request<MessageHistory> request) { if (!response.isOk()) { request.onFailure(response); return; } MessageHistory mHistory = new MessageHistory(MessageChannel.this); EntityBuilder builder = api.getEntityBuilder(); ; LinkedList<Message> msgs = new LinkedList<>(); JSONArray historyJson = response.getArray(); for (int i = 0; i < historyJson.length(); i++) msgs.add(builder.createMessage(historyJson.getJSONObject(i), MessageChannel.this, false)); msgs.forEach(msg -> mHistory.history.put(msg.getIdLong(), msg)); request.onSuccess(mHistory); } }; }