List of usage examples for java.util.function Consumer accept
void accept(T t);
From source file:org.apache.nifi.web.api.ApplicationResource.java
/** * Authorizes the specified process group. * * @param processGroupAuthorizable process group * @param authorizer authorizer * @param lookup lookup * @param action action * @param authorizeReferencedServices whether to authorize referenced services * @param authorizeTemplates whether to authorize templates * @param authorizeControllerServices whether to authorize controller services *///from ww w . ja va2 s. c o m protected void authorizeProcessGroup(final ProcessGroupAuthorizable processGroupAuthorizable, final Authorizer authorizer, final AuthorizableLookup lookup, final RequestAction action, final boolean authorizeReferencedServices, final boolean authorizeTemplates, final boolean authorizeControllerServices, final boolean authorizeTransitiveServices) { final Consumer<Authorizable> authorize = authorizable -> authorizable.authorize(authorizer, action, NiFiUserUtils.getNiFiUser()); // authorize the process group authorize.accept(processGroupAuthorizable.getAuthorizable()); // authorize the contents of the group - these methods return all encapsulated components (recursive) processGroupAuthorizable.getEncapsulatedProcessors().forEach(processorAuthorizable -> { // authorize the processor authorize.accept(processorAuthorizable.getAuthorizable()); // authorize any referenced services if necessary if (authorizeReferencedServices) { AuthorizeControllerServiceReference.authorizeControllerServiceReferences(processorAuthorizable, authorizer, lookup, authorizeTransitiveServices); } }); processGroupAuthorizable.getEncapsulatedConnections().stream() .map(connection -> connection.getAuthorizable()).forEach(authorize); processGroupAuthorizable.getEncapsulatedInputPorts().forEach(authorize); processGroupAuthorizable.getEncapsulatedOutputPorts().forEach(authorize); processGroupAuthorizable.getEncapsulatedFunnels().forEach(authorize); processGroupAuthorizable.getEncapsulatedLabels().forEach(authorize); processGroupAuthorizable.getEncapsulatedProcessGroups().stream().map(group -> group.getAuthorizable()) .forEach(authorize); processGroupAuthorizable.getEncapsulatedRemoteProcessGroups().forEach(authorize); // authorize templates if necessary if (authorizeTemplates) { processGroupAuthorizable.getEncapsulatedTemplates().forEach(authorize); } // authorize controller services if necessary if (authorizeControllerServices) { processGroupAuthorizable.getEncapsulatedControllerServices().forEach(controllerServiceAuthorizable -> { // authorize the controller service authorize.accept(controllerServiceAuthorizable.getAuthorizable()); // authorize any referenced services if necessary if (authorizeReferencedServices) { AuthorizeControllerServiceReference.authorizeControllerServiceReferences( controllerServiceAuthorizable, authorizer, lookup, authorizeTransitiveServices); } }); } }
From source file:net.dv8tion.jda.entities.impl.TextChannelImpl.java
@Override public void sendFileAsync(File file, Message message, Consumer<Message> callback) { checkVerification();//w w w .java 2 s.c om if (!checkPermission(getJDA().getSelfInfo(), Permission.MESSAGE_WRITE)) throw new PermissionException(Permission.MESSAGE_WRITE); if (!checkPermission(getJDA().getSelfInfo(), Permission.MESSAGE_ATTACH_FILES)) throw new PermissionException(Permission.MESSAGE_ATTACH_FILES); Thread thread = new Thread(() -> { Message messageReturn; try { messageReturn = sendFile(file, message); } catch (RateLimitedException e) { JDAImpl.LOG.warn("Got ratelimited when trying to upload file. Providing null to callback."); messageReturn = null; } if (callback != null) callback.accept(messageReturn); }); thread.setName("TextChannelImpl sendFileAsync Channel: " + id); thread.setDaemon(true); thread.start(); }
From source file:org.opendaylight.controller.cluster.raft.utils.InMemoryJournal.java
@Override public Future<Void> doAsyncReplayMessages(final String persistenceId, final long fromSequenceNr, final long toSequenceNr, final long max, final Consumer<PersistentRepr> replayCallback) { LOG.trace("doAsyncReplayMessages for {}: fromSequenceNr: {}, toSequenceNr: {}", persistenceId, fromSequenceNr, toSequenceNr); return Futures.future(new Callable<Void>() { @Override/* w w w.ja v a 2 s . c o m*/ public Void call() throws Exception { CountDownLatch blockLatch = blockReadMessagesLatches.remove(persistenceId); if (blockLatch != null) { Uninterruptibles.awaitUninterruptibly(blockLatch); } Map<Long, Object> journal = journals.get(persistenceId); if (journal == null) { return null; } synchronized (journal) { int count = 0; for (Map.Entry<Long, Object> entry : journal.entrySet()) { if (++count <= max && entry.getKey() >= fromSequenceNr && entry.getKey() <= toSequenceNr) { PersistentRepr persistentMessage = new PersistentImpl(deserialize(entry.getValue()), entry.getKey(), persistenceId, null, false, null, null); replayCallback.accept(persistentMessage); } } } return null; } }, context().dispatcher()); }
From source file:com.heliosdecompiler.helios.tasks.DecompileTask.java
@Override public void run() { LoadedFile loadedFile = Helios.getLoadedFile(fileName); byte[] classFile = loadedFile.getAllData().get(className); PreDecompileEvent event = new PreDecompileEvent(transformer, classFile); Events.callEvent(event);//from w ww .j a v a 2 s . co m classFile = event.getBytes(); StringBuilder output = new StringBuilder(); if (transformer instanceof Decompiler) { if (((Decompiler) transformer).decompile(loadedFile.getClassNode(className), classFile, output)) { CompilationUnit cu = null; try { cu = JavaParser.parse( new ByteArrayInputStream(output.toString().getBytes(StandardCharsets.UTF_8)), "UTF-8", false); this.compilationUnit = cu; } catch (ParseException | TokenMgrError e) { StringBuilder message = new StringBuilder("/*\n"); Consumer<String> write = msg -> { message.append(" * ").append(msg).append("\n"); }; write.accept("Error: Helios could not parse this file. Hyperlinks will not be inserted"); write.accept("The error has been inserted at the bottom of the output"); if (transformer instanceof CFRDecompiler) { write.accept(""); write.accept("I noticed you are using CFR"); write.accept( "Try nagging the author to output valid Java even if the code is undecompilable"); } message.append(" */\n\n"); output.insert(0, message.toString()); message.setLength(0); message.append("\n/*\n"); StringBuilder exceptionToString = new StringBuilder(); e.printStackTrace(new PrintWriter(new StringBuilderWriter(exceptionToString))); String[] lines = exceptionToString.toString().split("\r*\n"); for (String line : lines) { write.accept(line); } message.append(" */"); output.append(message.toString()); } finally { if (cu != null) { String result = output.toString(); result = result.replaceAll("\r*\n", "\n"); output = new StringBuilder(result); try { handle(cu, output.toString()); } catch (Throwable t) { textArea.links.clear(); StringBuilder message = new StringBuilder("/*\n"); Consumer<String> write = msg -> { message.append(" * ").append(msg).append("\n"); }; write.accept( "Error: Helios could not parse this file. Hyperlinks will not be inserted"); write.accept("The error has been inserted at the bottom of the output"); message.append(" */\n\n"); output.insert(0, message.toString()); message.setLength(0); message.append("\n/*\n"); StringBuilder exceptionToString = new StringBuilder(); t.printStackTrace(new PrintWriter(new StringBuilderWriter(exceptionToString))); String[] lines = exceptionToString.toString().split("\r*\n"); for (String line : lines) { write.accept(line); } message.append(" */"); output.append(message.toString()); t.printStackTrace(); } } } textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); textArea.setCodeFoldingEnabled(true); } textArea.setText(output.toString()); if (jumpTo != null) { Events.callEvent(new SearchRequest(jumpTo, false, false, false, true)); } } else if (transformer instanceof Disassembler) { if (((Disassembler) transformer).disassembleClassNode(loadedFile.getClassNode(className), classFile, output)) { textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); textArea.setCodeFoldingEnabled(true); } textArea.setText(output.toString()); } }
From source file:org.lenskit.gradle.LenskitPlugin.java
public void apply(Project project) { final LenskitExtension lenskit = project.getExtensions().create("lenskit", LenskitExtension.class, project); for (MetaProperty prop : DefaultGroovyMethods.getMetaClass(lenskit).getProperties()) { String prjProp = "lenskit." + prop.getName(); if (project.hasProperty(prjProp)) { Object val = project.findProperty(prjProp); String vstr = val != null ? val.toString() : null; logger.info("setting property {} to {}", prjProp, val); Class type = prop.getType(); Consumer<Object> set = (v) -> prop.setProperty(lenskit, v); if (type.equals(Property.class)) { Method m = null;//w w w. j av a 2 s . c o m try { m = lenskit.getClass().getMethod("get" + StringUtils.capitalize(prop.getName())); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } Type t = m.getGenericReturnType(); Map<TypeVariable<?>, Type> args = TypeUtils.getTypeArguments(t, Property.class); Type rt = args.get(Property.class.getTypeParameters()[0]); type = TypeUtils.getRawType(rt, Object.class); set = (v) -> ((Property) prop.getProperty(lenskit)).set(v); } if (type.equals(List.class)) {// if the type is list update the val using strtokenizer StringTokenizer tok = new StringTokenizer(vstr, StringMatcherFactory.INSTANCE.splitMatcher(), StringMatcherFactory.INSTANCE.quoteMatcher()); val = DefaultGroovyMethods.toList(tok); } else if (type.equals(String.class)) { val = vstr; } else { val = StringConvert.INSTANCE.convertFromString(type, vstr); } set.accept(val); } } }
From source file:com.example.app.profile.model.client.ClientDAO.java
/** * Save the given Client into the database by merging it * * @param client the client to save// w w w . ja va 2 s .c om * * @return the persisted client */ @SuppressWarnings("ConstantConditions") public Client saveClient(Client client) { Consumer<Client> presave = (toSave) -> { if (toSave.getProfileType() == null) toSave.setProfileType(_profileTypeProvider.client()); //Repository Name will be null if it is a completely fresh Repository if (toSave.getPrimaryLocation().getRepository().getName() == null) toSave.getPrimaryLocation().getRepository() .setName(_appUtil.copyLocalizedObjectKey(toSave.getName())); if (toSave.getPrimaryLocation().getProfileType() == null) { toSave.getPrimaryLocation().setProfileType(new ProfileType()); toSave.getPrimaryLocation().getProfileType() .setName(_appUtil.copyLocalizedObjectKey(toSave.getName())); toSave.getPrimaryLocation().getProfileType() .setProgrammaticIdentifier(GloballyUniqueStringGenerator.getUniqueString()); } if (toSave.getPrimaryLocation().getName() == null) toSave.getPrimaryLocation().setName(_appUtil.copyLocalizedObjectKey(toSave.getName())); if (toSave.getRepository().getName() == null) toSave.getRepository().setName(_appUtil.copyLocalizedObjectKey(toSave.getName())); }; if (isAttached(client)) { return doInTransaction(session -> { presave.accept(client); session.saveOrUpdate(client); return client; }); } else { return doInTransaction(session -> { presave.accept(client); return (Client) session.merge(client); }); } }
From source file:org.elasticsearch.client.RequestConvertersTests.java
private static void setRandomWaitForActiveShards(Consumer<ActiveShardCount> setter, Map<String, String> expectedParams) { if (randomBoolean()) { String waitForActiveShardsString; int waitForActiveShards = randomIntBetween(-1, 5); if (waitForActiveShards == -1) { waitForActiveShardsString = "all"; } else {// ww w.ja va 2 s .c om waitForActiveShardsString = String.valueOf(waitForActiveShards); } setter.accept(ActiveShardCount.parseString(waitForActiveShardsString)); expectedParams.put("wait_for_active_shards", waitForActiveShardsString); } }
From source file:com.evolveum.midpoint.model.impl.lens.AssignmentEvaluator.java
private void addIfNotThere(Collection<PrismReferenceValue> collection, Consumer<PrismReferenceValue> setter, PrismReferenceValue refVal, String collectionName, Object targetDesc) { if (!collection.contains(refVal)) { LOGGER.trace("Adding target {} to {}", targetDesc, collectionName); setter.accept(refVal); } else {//w w w.j a v a 2s.c om LOGGER.trace("Would add target {} to {}, but it's already there", targetDesc, collectionName); } }
From source file:com.diversityarrays.kdxplore.data.kdx.CurationData.java
@Override public void visitSamplesForPlotOrSpecimen(PlotOrSpecimen pos, Consumer<KdxSample> visitor) { int plotId = pos.getPlotId(); for (CurationCellId ccid : samplesByCurationCellId.keySet()) { if (ccid.plotId == plotId) { for (KdxSample s : samplesByCurationCellId.get(ccid)) { visitor.accept(s); }/*w ww . java2 s. co m*/ } } }
From source file:com.diversityarrays.kdxplore.data.kdx.CurationData.java
public void getKdxSamples(TraitInstance ti, Consumer<KdxSample> consumer) { if (TraitDataType.CALC == ti.trait.getTraitDataType()) { List<KdxSample> list = calculatedSamplesByTraitInstance.get(ti); if (list != null) { for (KdxSample s : list) { consumer.accept(s); }/* w ww . j a va 2 s . c o m*/ } } else { for (Plot plot : plots) { if (plot.isActivated()) { KdxSample sm = getEditStateSampleFor(ti, plot); if (sm != null) { consumer.accept(sm); } } } } }