Example usage for java.util Collection forEach

List of usage examples for java.util Collection forEach

Introduction

In this page you can find the example usage for java.util Collection forEach.

Prototype

default void forEach(Consumer<? super T> action) 

Source Link

Document

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Usage

From source file:com.qwazr.server.GenericServer.java

private void executeListener(final Collection<Listener> listeners, final Logger logger) {
    if (listeners == null)
        return;//from  w w  w .j a v a 2 s .c o  m
    listeners.forEach(listener -> {
        try {
            listener.accept(this);
        } catch (Exception e) {
            if (logger == null)
                throw ServerException.of("Listeners failure", e);
            else
                LOGGER.log(Level.SEVERE, e, e::getMessage);
        }
    });
}

From source file:org.obiba.agate.web.rest.notification.NotificationsResource.java

/**
 * Lookup active users and verify its access to the application requesting the notification.
 *
 * @param servletRequest/*from  w ww  .  j  a va2  s.  c om*/
 * @param usernames
 * @param emails
 */
private void appendRecipientsFromUsernames(Collection<String> usernames, Collection<User> recipients) {
    if (usernames == null || usernames.isEmpty())
        return;

    List<String> applicationUsernames = userService.findActiveUsersByApplication(getApplicationName()).stream()
            .map(User::getName).collect(Collectors.toList());

    usernames.forEach(username -> {
        User user = userService.findActiveUser(username);
        if (user == null)
            user = userService.findActiveUserByEmail(username);

        if (user != null && applicationUsernames.contains(user.getName()))
            recipients.add(user);
    });
}

From source file:at.grahsl.kafka.connect.mongodb.MongoDbSinkTask.java

List<? extends WriteModel<BsonDocument>> buildWriteModel(Collection<SinkRecord> records,
        String collectionName) {// w  w  w  . ja  v a 2  s  .com

    List<WriteModel<BsonDocument>> docsToWrite = new ArrayList<>(records.size());
    LOGGER.debug("building write model for {} record(s)", records.size());
    records.forEach(record -> {
        SinkDocument doc = sinkConverter.convert(record);
        processorChains
                .getOrDefault(collectionName,
                        processorChains.get(MongoDbSinkConnectorConfig.TOPIC_AGNOSTIC_KEY_NAME))
                .process(doc, record);
        if (doc.getValueDoc().isPresent()) {
            docsToWrite
                    .add(writeModelStrategies
                            .getOrDefault(collectionName,
                                    writeModelStrategies
                                            .get(MongoDbSinkConnectorConfig.TOPIC_AGNOSTIC_KEY_NAME))
                            .createWriteModel(doc));
        } else {
            if (doc.getKeyDoc().isPresent() && sinkConfig.isDeleteOnNullValues(record.topic())) {
                docsToWrite.add(deleteOneModelDefaultStrategies
                        .getOrDefault(collectionName,
                                deleteOneModelDefaultStrategies
                                        .get(MongoDbSinkConnectorConfig.TOPIC_AGNOSTIC_KEY_NAME))
                        .createWriteModel(doc));
            } else {
                LOGGER.error("skipping sink record " + record
                        + "for which neither key doc nor value doc were present");
            }
        }
    });

    return docsToWrite;
}

From source file:org.zanata.magpie.service.PersistentTranslationService.java

/**
 * Translate multiple string in an api trigger
 *
 * Get from database if exists (hash) from same document,
 * if not exist, get latest TF from DB with matching hash,
 * else from MT engine/* w w w .  jav a 2s. c  o m*/
 */
@Transactional
public List<String> translate(@NotNull Document document, @NotNull List<String> sourceStrings,
        @NotNull Locale fromLocale, @NotNull Locale toLocale, @NotNull BackendID backendID,
        @NotNull StringType stringType, Optional<String> category) throws BadRequestException, MTException {
    // fetch the text flows for later (as part of this new transaction)
    document = documentDAO.reload(document);
    document.getTextFlows();
    if (sourceStrings == null || sourceStrings.isEmpty() || fromLocale == null || toLocale == null
            || backendID == null) {
        throw new BadRequestException();
    }
    if (!authenticatedAccount.hasAuthenticatedAccount()) {
        throw new MTException("not authenticated account trying to trigger MT translation");
    }

    // get translator backend for MT engine by requested backend id
    TranslatorBackend translatorBackend = getTranslatorBackend(backendID);

    BackendLocaleCode mappedFromLocaleCode = translatorBackend.getMappedLocale(fromLocale.getLocaleCode());
    BackendLocaleCode mappedToLocaleCode = translatorBackend.getMappedLocale(toLocale.getLocaleCode());

    List<String> results = new ArrayList<>(sourceStrings);
    Multimap<String, Integer> untranslatedIndexMap = ArrayListMultimap.create();

    Map<Integer, TextFlow> indexTextFlowMap = Maps.newHashMap();

    // search from database
    int matchCount = 0;
    for (int sourceStringIndex = 0; sourceStringIndex < sourceStrings.size(); sourceStringIndex++) {
        String string = sourceStrings.get(sourceStringIndex);
        String contentHash = HashUtil.generateHash(string);
        Optional<TextFlow> matchedHashTf = tryFindTextFlowByContentHashFromDB(document, fromLocale, toLocale,
                backendID, contentHash);

        if (matchedHashTf.isPresent()) {
            // we found a matching text flow in database
            // now check to see if it has translation from the same provider
            TextFlow matchedTf = matchedHashTf.get();
            Optional<TextFlowTarget> matchedTarget = findTargetByLocaleAndProvider(toLocale, backendID,
                    matchedTf);

            if (matchedTarget.isPresent()) {
                TextFlowTarget matchedEntity = matchedTarget.get();
                matchCount++;
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found match, Source {}:{}:{}\nTranslation {}:{}", fromLocale.getLocaleCode(),
                            document.getUrl(), ShortString.shorten(string), toLocale.getLocaleCode(),
                            ShortString.shorten(matchedEntity.getContent()));
                }

                results.set(sourceStringIndex, matchedEntity.getContent());
            } else {
                untranslatedIndexMap.put(string, sourceStringIndex);
                indexTextFlowMap.put(sourceStringIndex, matchedTf);
            }
        } else {
            untranslatedIndexMap.put(string, sourceStringIndex);
        }
    }
    LOG.info("found {} of match sources and translations in database", matchCount);

    // see if we got all translations from database records
    if (untranslatedIndexMap.isEmpty()) {
        return results;
    }

    // translate using requested MT engine
    List<String> sourcesToTranslate = new ArrayList<>(untranslatedIndexMap.keySet());
    Date engineInvokeTime = new Date();
    List<AugmentedTranslation> translations = translatorBackend.translate(sourcesToTranslate,
            mappedFromLocaleCode, mappedToLocaleCode, stringType, category);

    LOG.info("triggered MT engine {} from {} to {}", backendID, fromLocale.getLocaleCode(),
            toLocale.getLocaleCode());

    List<String> requestedTextFlows = Lists.newLinkedList();
    long wordCount = 0;
    long charCount = 0;
    for (int i = 0; i < sourcesToTranslate.size(); i++) {
        String source = sourcesToTranslate.get(i);
        AugmentedTranslation translation = translations.get(i);
        // same string may appear several times in a document therefore has several indexes
        Collection<Integer> indexes = untranslatedIndexMap.get(source);
        indexes.forEach(j -> results.set(j, translation.getPlainTranslation()));

        // see if we already have a matched text flow
        // (either in the same document or copied from other document)
        TextFlow tf = indexTextFlowMap.get(indexes.iterator().next());

        try {
            if (tf == null) {
                tf = createTextFlow(document, source, fromLocale);
            }
            wordCount += tf.getWordCount();
            charCount += tf.getCharCount();
            requestedTextFlows.add(tf.getContentHash());
            TextFlowTarget target = new TextFlowTarget(translation.getPlainTranslation(),
                    translation.getRawTranslation(), tf, toLocale, backendID);
            createOrUpdateTextFlowTarget(target);
        } catch (Exception e) {
            List<Throwable> causalChain = getThrowableList(e);
            Optional<Throwable> duplicateKeyEx = causalChain.stream()
                    .filter(t -> t instanceof SQLException && t.getMessage() != null
                            && t.getMessage().contains("duplicate key value violates unique constraint"))
                    .findAny();
            if (duplicateKeyEx.isPresent()) {
                LOG.warn("concurrent requests for document {}", document.getUrl());
                // we ignore the failed update
                // TODO prevent duplicates from reaching DB: ZNTAMT-51
            }
        }
    }
    requestedMTEvent.fire(new RequestedMTEvent(document, requestedTextFlows, backendID, engineInvokeTime,
            authenticatedAccount.getAuthenticatedAccount().get(), wordCount, charCount));

    return results;
}

From source file:com.qwazr.search.annotations.AnnotatedIndexService.java

/**
 * Buid a collection of Map by reading the IndexFields of the annotated documents
 *
 * @param rows a collection of records//from www .j av a  2 s  . com
 * @return a new array of map objects
 */
private Collection<Map<String, Object>> newMapCollection(final Collection<T> rows) {
    if (rows == null || rows.isEmpty())
        return null;
    final Collection<Map<String, Object>> list = new ArrayList<>(rows.size());
    rows.forEach(row -> list.add(newMap(row)));
    return list;
}

From source file:com.hortonworks.streamline.streams.cluster.resource.ClusterCatalogResource.java

@DELETE
@Path("/clusters/{id}")
@Timed/*from   ww  w.j av a 2  s  .c  o m*/
public Response removeCluster(@PathParam("id") Long clusterId, @Context SecurityContext securityContext) {
    assertNoNamespaceRefersCluster(clusterId);
    SecurityUtil.checkRoleOrPermissions(authorizer, securityContext, Roles.ROLE_SERVICE_POOL_SUPER_ADMIN,
            NAMESPACE, clusterId, DELETE);

    // remove all services / service configurations / components / component processes in this cluster
    Collection<Service> services = environmentService.listServices(clusterId);
    services.forEach(svc -> {
        environmentService.listServiceConfigurations(svc.getId())
                .forEach(sc -> environmentService.removeServiceConfiguration(sc.getId()));

        Collection<Component> components = environmentService.listComponents(svc.getId());
        components.forEach(component -> {
            environmentService.listComponentProcesses(component.getId()).forEach(
                    componentProcess -> environmentService.removeComponentProcess(componentProcess.getId()));

            environmentService.removeComponent(component.getId());
        });

        environmentService.removeService(svc.getId());
    });

    Cluster removedCluster = environmentService.removeCluster(clusterId);
    if (removedCluster != null) {
        SecurityUtil.removeAcl(authorizer, securityContext, NAMESPACE, clusterId);
        return WSUtils.respondEntity(removedCluster, OK);
    }

    throw EntityNotFoundException.byId(clusterId.toString());
}

From source file:com.hortonworks.streamline.streams.security.service.SecurityCatalogService.java

private Set<Role> doGetChildRoles(Long parentRoleId, Map<Long, State> state) {
    State curState = state.get(parentRoleId);
    Set<Role> childRoles = new HashSet<>();
    if (curState == State.VISITING) {
        throw new IllegalStateException("Cycle");
    } else if (curState != State.VISITED) {
        state.put(parentRoleId, State.VISITING);
        List<QueryParam> qps = QueryParam.params(RoleHierarchy.PARENT_ID, String.valueOf(parentRoleId));
        Collection<RoleHierarchy> res = dao.find(RoleHierarchy.NAMESPACE, qps);
        res.forEach(rh -> {
            childRoles.add(getRole(rh.getChildId()));
            childRoles.addAll(doGetChildRoles(rh.getChildId(), state));
        });/*w w w. ja v  a 2s.  c om*/
        state.put(parentRoleId, State.VISITED);
    }
    return childRoles;
}

From source file:com.holonplatform.auth.jwt.internal.DefaultJwtAuthenticator.java

@SuppressWarnings("unchecked")
@Override//from   ww w .  j  a v  a 2s. co m
public Authentication authenticate(BearerAuthenticationToken authenticationToken)
        throws AuthenticationException {

    // check configuration
    if (getConfiguration() == null) {
        throw new UnexpectedAuthenticationException(
                "JWT authenticator not correctly configured: missing JWTConfiguration");
    }

    // validate
    if (authenticationToken == null) {
        throw new UnexpectedAuthenticationException("Null authentication token");
    }

    // Get JWT token
    String jwt = (String) authenticationToken.getCredentials();
    if (jwt == null) {
        throw new UnexpectedAuthenticationException("Missing JWT token");
    }

    // decode and get claims

    Claims claims = null;

    try {

        JwtParser parser = Jwts.parser();

        if (getConfiguration().getSignatureAlgorithm() != JwtSignatureAlgorithm.NONE) {
            // Token expected to be signed (JWS)
            if (getConfiguration().getSignatureAlgorithm().isSymmetric()) {
                parser = parser.setSigningKey(getConfiguration().getSharedKey()
                        .orElseThrow(() -> new UnexpectedAuthenticationException(
                                "JWT authenticator not correctly configured: missing shared key for symmetric signature algorithm ["
                                        + getConfiguration().getSignatureAlgorithm().getDescription()
                                        + "] - JWT configuration: [" + getConfiguration() + "]")));
            } else {
                parser = parser.setSigningKey(getConfiguration().getPublicKey()
                        .orElseThrow(() -> new UnexpectedAuthenticationException(
                                "JWT authenticator not correctly configured: missing public key for asymmetric signature algorithm ["
                                        + getConfiguration().getSignatureAlgorithm().getDescription()
                                        + "] - JWT configuration: [" + getConfiguration() + "]")));
            }
            claims = parser.parseClaimsJws(jwt).getBody();
        } else {
            // not signed (JWT)
            claims = parser.parseClaimsJwt(jwt).getBody();
        }

    } catch (@SuppressWarnings("unused") ExpiredJwtException eje) {
        throw new ExpiredCredentialsException("Expired JWT token");
    } catch (@SuppressWarnings("unused") MalformedJwtException | UnsupportedJwtException mje) {
        throw new InvalidTokenException("Malformed or unsupported JWT token");
    } catch (@SuppressWarnings("unused") SignatureException sje) {
        throw new InvalidTokenException("Invalid JWT token signature");
    } catch (Exception e) {
        throw new UnexpectedAuthenticationException(ExceptionUtils.getRootCauseMessage(e), e);
    }

    // check claims
    if (claims == null) {
        throw new UnexpectedAuthenticationException("No valid claims found in JWT token");
    }

    String principalName = claims.getSubject();
    if (principalName == null) {
        throw new UnknownAccountException("No principal id (subject) found in JWT token");
    }

    // check required claims
    Collection<String> required = getRequiredClaims();
    if (required != null && !required.isEmpty()) {
        for (String claim : required) {
            Object value = claims.get(claim);
            if (value == null) {
                throw new InvalidTokenException("Missing required JWT claim: " + claim);
            }
        }
    }

    // check issuer

    Collection<String> issuers = getIssuers();
    if (issuers != null && !issuers.isEmpty()) {
        String tokenIssuer = claims.getIssuer();
        if (tokenIssuer == null) {
            throw new InvalidTokenException("Missing required JWT Issuer");
        }

        if (!issuers.contains(tokenIssuer)) {
            throw new InvalidTokenException("JWT Issuer mismatch");
        }
    }

    // build Authentication

    Authentication.Builder auth = Authentication.builder(principalName).scheme("Bearer").root(false);

    // set claims as details
    claims.forEach((n, v) -> {
        if (AuthenticationClaims.CLAIM_NAME_PERMISSIONS.equals(n)) {
            Collection<String> permissions = (Collection<String>) v;
            if (permissions != null) {
                permissions.forEach(p -> auth.withPermission(Permission.create(p)));
            }
        } else {
            auth.withParameter(n, v);
        }
    });

    return auth.build();
}

From source file:com.autonomy.aci.client.util.AciParameters.java

/**
 * Puts the collection of <tt>parameters</tt> into this collection. If any of the specified parameters already
 * exists in this collection, they are replaced. Does nothing if <tt>parameters</tt> is <tt>null</tt>.
 * @param parameters The parameters to put into this collection
 * @throws IllegalArgumentException if any of the <tt>parameters</tt> are <tt>null</tt>
 *//*from   w  w w.  j  a v  a 2  s  .co  m*/
public void putAll(final Collection<? extends AciParameter> parameters) {
    if (parameters != null) {
        parameters.forEach(this::put);
    }
}

From source file:org.apache.gobblin.runtime.SafeDatasetCommit.java

private void submitLineageEvent(String dataset, Collection<TaskState> states) {
    Collection<LineageEventBuilder> events = LineageInfo.load(states);
    // Send events
    events.forEach(event -> event.submit(metricContext));
    log.info(String.format("Submitted %d lineage events for dataset %s", events.size(), dataset));
}