List of usage examples for com.google.common.collect ImmutableList stream
default Stream<E> stream()
From source file:com.facebook.buck.ide.intellij.IjProjectWriter.java
private Path writeWorkspace(Path projectIdeaConfigDir, ImmutableList<ContentRoot> contentRoots) throws IOException { ImmutableSortedSet<String> excludedPaths = contentRoots.stream() .flatMap(contentRoot -> contentRoot.getFolders().stream()) .filter(ijSourceFolder -> ExcludeFolder.FOLDER_IJ_NAME.equals(ijSourceFolder.getType())) .map(IjSourceFolder::getPath).map(Object::toString).collect(MoreCollectors.toImmutableSortedSet()); WorkspaceUpdater workspaceUpdater = new WorkspaceUpdater(projectIdeaConfigDir); workspaceUpdater.updateOrCreateWorkspace(excludedPaths); return Paths.get(workspaceUpdater.getWorkspaceFile().toString()); }
From source file:org.eclipse.milo.opcua.sdk.client.session.SessionFsmFactory.java
@SuppressWarnings("Duplicates") private static CompletableFuture<Unit> transferSubscriptions(FsmContext<State, Event> ctx, OpcUaClient client, OpcUaSession session) {// w w w . j a v a 2s. c o m UaStackClient stackClient = client.getStackClient(); OpcUaSubscriptionManager subscriptionManager = client.getSubscriptionManager(); ImmutableList<UaSubscription> subscriptions = subscriptionManager.getSubscriptions(); if (subscriptions.isEmpty()) { return completedFuture(Unit.VALUE); } CompletableFuture<Unit> transferFuture = new CompletableFuture<>(); UInteger[] subscriptionIdsArray = subscriptions.stream().map(UaSubscription::getSubscriptionId) .toArray(UInteger[]::new); TransferSubscriptionsRequest request = new TransferSubscriptionsRequest( client.newRequestHeader(session.getAuthenticationToken()), subscriptionIdsArray, true); LOGGER.debug("[{}] Sending TransferSubscriptionsRequest...", ctx.getInstanceId()); stackClient.sendRequest(request).thenApply(TransferSubscriptionsResponse.class::cast) .whenComplete((tsr, ex) -> { if (tsr != null) { List<TransferResult> results = l(tsr.getResults()); LOGGER.debug("[{}] TransferSubscriptions supported: {}", ctx.getInstanceId(), tsr.getResponseHeader().getServiceResult()); if (LOGGER.isDebugEnabled()) { try { Stream<UInteger> subscriptionIds = subscriptions.stream() .map(UaSubscription::getSubscriptionId); Stream<StatusCode> statusCodes = results.stream() .map(TransferResult::getStatusCode); //noinspection UnstableApiUsage String[] ss = Streams .zip(subscriptionIds, statusCodes, (i, s) -> String .format("id=%s/%s", i, StatusCodes.lookup(s.getValue()).map(sa -> sa[0]) .orElse(s.toString()))) .toArray(String[]::new); LOGGER.debug("[{}] TransferSubscriptions results: {}", ctx.getInstanceId(), Arrays.toString(ss)); } catch (Throwable t) { LOGGER.error("[{}] error logging TransferSubscription results", ctx.getInstanceId(), t); } } client.getConfig().getExecutor().execute(() -> { for (int i = 0; i < results.size(); i++) { TransferResult result = results.get(i); if (!result.getStatusCode().isGood()) { UaSubscription subscription = subscriptions.get(i); subscriptionManager.transferFailed(subscription.getSubscriptionId(), result.getStatusCode()); } } }); transferFuture.complete(Unit.VALUE); } else { StatusCode statusCode = UaException.extract(ex).map(UaException::getStatusCode) .orElse(StatusCode.BAD); // Bad_ServiceUnsupported is the correct response when transfers aren't supported but // server implementations tend to interpret the spec in their own unique way... if (statusCode.getValue() == StatusCodes.Bad_NotImplemented || statusCode.getValue() == StatusCodes.Bad_NotSupported || statusCode.getValue() == StatusCodes.Bad_OutOfService || statusCode.getValue() == StatusCodes.Bad_ServiceUnsupported) { LOGGER.debug("[{}] TransferSubscriptions not supported: {}", ctx.getInstanceId(), statusCode); client.getConfig().getExecutor().execute(() -> { // transferFailed() will remove the subscription, but that is okay // because the list from getSubscriptions() above is a copy. for (UaSubscription subscription : subscriptions) { subscriptionManager.transferFailed(subscription.getSubscriptionId(), statusCode); } }); transferFuture.complete(Unit.VALUE); } else { transferFuture.completeExceptionally(ex); } } }); return transferFuture; }
From source file:com.google.javascript.jscomp.ScopeSubject.java
public DeclarationSubject declares(String name) { AbstractVar<?, ?> var = getVar(name); if (var == null) { ImmutableList<AbstractVar<?, ?>> declared = ImmutableList.copyOf(actual().getAllAccessibleVariables()); ImmutableList<String> names = declared.stream().map(AbstractVar::getName).collect(toImmutableList()); if (names.size() > 10) { names = ImmutableList.<String>builder().addAll(names.subList(0, 9)) .add("and " + (names.size() - 9) + " others").build(); }/*from w w w . j a va 2s.c om*/ failWithBadResults("declares", name, "declares", Joiner.on(", ").join(names)); } return new DeclarationSubject(var); }
From source file:com.google.errorprone.bugpatterns.ParameterComment.java
private Description matchNewClassOrMethodInvocation(MethodSymbol symbol, ImmutableList<Commented<ExpressionTree>> arguments, Tree tree) { if (symbol.getParameters().isEmpty()) { return NO_MATCH; }/* w w w . j a v a 2 s. c om*/ SuggestedFix.Builder fix = SuggestedFix.builder(); forEachPair(arguments.stream(), Stream.concat(symbol.getParameters().stream(), Stream.iterate(getLast(symbol.getParameters()), x -> x)), (commented, param) -> { ImmutableList<Comment> comments = commented.afterComments().isEmpty() ? commented.beforeComments() : commented.afterComments(); boolean matchStandardForm = !commented.afterComments().isEmpty(); comments.stream().filter(c -> matchingParamComment(c, param, matchStandardForm)).findFirst() .ifPresent(c -> fixParamComment(fix, commented, param, c)); }); return fix.isEmpty() ? NO_MATCH : describeMatch(tree, fix.build()); }
From source file:com.spectralogic.ds3autogen.java.generators.responsemodels.BaseResponseGenerator.java
/** * Retrieves the list of parameters needed to create the response POJO *///from w w w . ja v a2 s . c o m @Override public ImmutableList<Arguments> toParamList(final ImmutableList<Ds3ResponseCode> ds3ResponseCodes) { if (isEmpty(ds3ResponseCodes)) { return ImmutableList.of(); } return ds3ResponseCodes.stream().filter(i -> i.getCode() < ERROR_CODE_THRESHOLD) //Filter error codes .map(BaseResponseGenerator::toParam).filter(Optional::isPresent) //Filters out empty optional arguments .map(Optional::get) //Get the Arguments object out of the optional .sorted(new CustomArgumentComparator()) //Sorts the arguments by name .collect(GuavaCollectors.immutableList()); }
From source file:eu.redzoo.article.javaworld.stability.service.payment.SyncPaymentService.java
@Path("paymentmethods") @GET/*from w w w .ja v a 2 s . c om*/ @Produces(MediaType.APPLICATION_JSON) public ImmutableSet<PaymentMethod> getPaymentMethods(@QueryParam("addr") String address) { Score score = NEUTRAL; try { ImmutableList<Payment> pmts = paymentDao.getPayments(address, 50); score = pmts.isEmpty() ? client.target(creditScoreURI).queryParam("addr", address).request().get(Score.class) : (pmts.stream().filter(pmt -> pmt.isDelayed()).count() >= 1) ? NEGATIVE : POSITIVE; } catch (RuntimeException rt) { LOG.fine("error occurred by calculating score. Fallback to " + score + " " + rt.toString()); } return SCORE_TO_PAYMENTMETHOD.apply(score); }
From source file:com.google.javascript.jscomp.testing.ScopeSubject.java
public DeclarationSubject declares(String name) { AbstractVar<?, ?> var = getVar(name); if (var == null) { ImmutableList<AbstractVar<?, ?>> declared = ImmutableList.copyOf(actual.getAllAccessibleVariables()); ImmutableList<String> names = declared.stream().map(AbstractVar::getName).collect(toImmutableList()); if (names.size() > 10) { names = ImmutableList.<String>builder().addAll(names.subList(0, 9)) .add("and " + (names.size() - 9) + " others").build(); }//from w w w. jav a2s . c o m failWithoutActual(fact("expected to declare", name), simpleFact("but did not"), fact("did declare", Joiner.on(", ").join(names)), fact("scope was", actual)); } return new DeclarationSubject(var); }
From source file:com.rodrigodev.xgen4j.model.information.template.InformationClassTemplateModel.java
private InformationClassTemplateModel(InformationClassTemplateModelBuilder builder, @NonNull ImmutableList<ErrorExceptionClassFilePair> errorExceptionPairs, @NonNull ErrorCodeClassFile errorCodeClassFile) { super(builder); ImmutableList.Builder<ErrorTemplateModel> errorsListBuilder = ImmutableList.builder(); errorExceptionPairs.stream().map(ErrorTemplateModel::new).forEach(errorsListBuilder::add); this.errors = errorsListBuilder.build(); this.errorCode = new ErrorCodeTemplateModel(errorCodeClassFile); }
From source file:de.gfelbing.microservice.core.http.jetty.server.JettyServer.java
/** * Constructor creating a jetty server and initializes a ContextHandlerCollection, * which can be filled by addHandler().// w w w. ja v a 2s . c om * * @param hosts IPs / Hostnames jetty will bind itself to. * @param port Port to which the jetty server will bind itself. */ public JettyServer(final ImmutableList<String> hosts, final Integer port) { this.healthState = new AtomicReference<>(State.CREATED); this.server = new Server(); final ImmutableList<Connector> connectors = hosts.stream().map(host -> { ServerConnector connector = new ServerConnector(server); connector.setHost(host); connector.setPort(port); return connector; }).collect(GuavaCollect.immutableList()); this.server.setConnectors(connectors.toArray(new Connector[connectors.size()])); this.contextHandler = new ContextHandlerCollection(); this.server.setHandler(contextHandler); }
From source file:keywhiz.service.daos.SecretController.java
/** * @param expireMaxTime timestamp for farthest expiry to include * @return all existing sanitized secrets and their groups matching criteria. * *//*w ww .ja v a 2 s.co m*/ public List<SanitizedSecretWithGroups> getExpiringSanitizedSecrets(@Nullable Long expireMaxTime) { ImmutableList<SecretSeriesAndContent> secrets = secretDAO.getSecrets(expireMaxTime, null); Map<Long, SecretSeriesAndContent> secretIds = secrets.stream().collect(toMap(s -> s.series().id(), s -> s)); Map<Long, List<Group>> groupsForSecrets = aclDAO.getGroupsForSecrets(secretIds.keySet()); return secrets.stream().map(s -> { List<Group> groups = groupsForSecrets.get(s.series().id()); if (groups == null) { groups = ImmutableList.of(); } return fromSecretSeriesAndContentAndGroups(s, groups); }).collect(toList()); }