Example usage for java.util Set forEach

List of usage examples for java.util Set forEach

Introduction

In this page you can find the example usage for java.util Set 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:org.apache.syncope.core.persistence.jpa.dao.AbstractAnyDAO.java

@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
@Override//from  ww w .  ja v  a2s.  c  o  m
@SuppressWarnings("unchecked")
public <S extends Schema> AllowedSchemas<S> findAllowedSchemas(final A any, final Class<S> reference) {
    AllowedSchemas<S> result = new AllowedSchemas<>();

    // schemas given by type and aux classes
    Set<AnyTypeClass> typeOwnClasses = new HashSet<>();
    typeOwnClasses.addAll(any.getType().getClasses());
    typeOwnClasses.addAll(any.getAuxClasses());

    typeOwnClasses.forEach(typeClass -> {
        if (reference.equals(PlainSchema.class)) {
            result.getForSelf().addAll((Collection<? extends S>) typeClass.getPlainSchemas());
        } else if (reference.equals(DerSchema.class)) {
            result.getForSelf().addAll((Collection<? extends S>) typeClass.getDerSchemas());
        } else if (reference.equals(VirSchema.class)) {
            result.getForSelf().addAll((Collection<? extends S>) typeClass.getVirSchemas());
        }
    });

    // schemas given by type extensions
    Map<Group, List<? extends AnyTypeClass>> typeExtensionClasses = new HashMap<>();
    if (any instanceof User) {
        ((User) any).getMemberships().forEach(memb -> {
            memb.getRightEnd().getTypeExtensions().forEach(typeExtension -> {
                typeExtensionClasses.put(memb.getRightEnd(), typeExtension.getAuxClasses());
            });
        });
    } else if (any instanceof AnyObject) {
        ((AnyObject) any).getMemberships().forEach(memb -> {
            memb.getRightEnd().getTypeExtensions().stream()
                    .filter(typeExtension -> any.getType().equals(typeExtension.getAnyType()))
                    .forEachOrdered((typeExtension) -> {
                        typeExtensionClasses.put(memb.getRightEnd(), typeExtension.getAuxClasses());
                    });
        });
    }

    typeExtensionClasses.entrySet().stream().map(entry -> {
        result.getForMemberships().put(entry.getKey(), new HashSet<>());
        return entry;
    }).forEachOrdered((entry) -> {
        entry.getValue().forEach(typeClass -> {
            if (reference.equals(PlainSchema.class)) {
                result.getForMemberships().get(entry.getKey())
                        .addAll((Collection<? extends S>) typeClass.getPlainSchemas());
            } else if (reference.equals(DerSchema.class)) {
                result.getForMemberships().get(entry.getKey())
                        .addAll((Collection<? extends S>) typeClass.getDerSchemas());
            } else if (reference.equals(VirSchema.class)) {
                result.getForMemberships().get(entry.getKey())
                        .addAll((Collection<? extends S>) typeClass.getVirSchemas());
            }
        });
    });

    return result;
}

From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrPropertyUtil.java

/**
 * Sets the user-defined fields for the specified type.
 *
 * @param name                   the type name
 * @param fields                 the user-defined fields
 * @param extensibleTypeProvider the type provider
 */// w  ww.j  av  a 2s .c  o m
public static void setUserFields(@Nonnull final String name, @Nonnull final Set<UserFieldDescriptor> fields,
        @Nonnull final ExtensibleTypeProvider extensibleTypeProvider) {
    // Get type builder
    final ExtensibleTypeBuilder builder;
    final ExtensibleType type = extensibleTypeProvider.getType(name);

    if (type == null) {
        builder = extensibleTypeProvider.buildType(name);
    } else {
        builder = extensibleTypeProvider.updateType(type.getId());
    }

    // Add fields to type
    final String prefix = JcrMetadataAccess.USR_PREFIX + ":";

    fields.forEach(field -> {
        // Encode field name
        final String systemName;
        try {
            systemName = prefix + URLEncoder.encode(field.getSystemName(), USER_PROPERTY_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e.toString(), e);
        }

        // Create field descriptor
        final FieldDescriptorBuilder fieldBuilder = builder.field(systemName);
        fieldBuilder.description(field.getDescription());
        fieldBuilder.displayName(field.getDisplayName());
        fieldBuilder.type(FieldDescriptor.Type.STRING);
        fieldBuilder.property(JcrUserFieldDescriptor.ORDER, Integer.toString(field.getOrder()));
        fieldBuilder.property(JcrUserFieldDescriptor.REQUIRED, Boolean.toString(field.isRequired()));
        fieldBuilder.add();
    });
    builder.build();
}

From source file:com.thinkbiganalytics.feedmgr.service.feed.datasource.DerivedDatasourceFactory.java

/**
 * Builds the list of data sources for the specified data transformation feed.
 *
 * @param feed the feed//w w w  .ja va 2  s . c  o m
 * @return the list of data sources
 */
@Nonnull
private Set<Datasource.ID> ensureDataTransformationSourceDatasources(@Nonnull final FeedMetadata feed) {
    // Build the data sources from the view model
    final Set<Datasource.ID> datasources = new HashSet<>();
    final Set<String> tableNames = Optional.ofNullable(feed.getDataTransformation())
            .map(FeedDataTransformation::getTableNamesFromViewModel).orElse(Collections.emptySet());

    if (!tableNames.isEmpty()) {
        DatasourceDefinition datasourceDefinition = datasourceDefinitionProvider
                .findByProcessorType(DATA_TRANSFORMATION_DEFINITION);
        if (datasourceDefinition != null) {
            tableNames.forEach(hiveTable -> {
                String schema = StringUtils.trim(StringUtils.substringBefore(hiveTable, "."));
                String table = StringUtils.trim(StringUtils.substringAfterLast(hiveTable, "."));
                String identityString = datasourceDefinition.getIdentityString();
                Map<String, String> props = new HashMap<String, String>();
                props.put("schema", schema);
                props.put("table", table);
                identityString = propertyExpressionResolver.resolveVariables(identityString, props);
                String desc = datasourceDefinition.getDescription();
                if (desc != null) {
                    desc = propertyExpressionResolver.resolveVariables(desc, props);
                }
                String title = identityString;

                DerivedDatasource derivedDatasource = datasourceProvider.ensureDerivedDatasource(
                        datasourceDefinition.getDatasourceType(), identityString, title, desc,
                        new HashMap<String, Object>(props));
                if (derivedDatasource != null) {
                    datasources.add(derivedDatasource.getId());
                }
            });
        }
    }

    // Build the data sources from the data source ids
    final List<String> datasourceIds = Optional.ofNullable(feed.getDataTransformation())
            .map(FeedDataTransformation::getDatasourceIds).orElse(Collections.emptyList());
    datasourceIds.stream().map(datasourceProvider::resolve).forEach(datasources::add);

    return datasources;
}

From source file:org.alfresco.rest.api.impl.PeopleImpl.java

private void validateNamespaces(List<String> aspectNames, Map<String, Object> properties) {
    if (aspectNames != null) {
        Set<QName> aspects = nodes.mapToNodeAspects(aspectNames);
        aspects.forEach(aspect -> {
            if (EXCLUDED_NS.contains(aspect.getNamespaceURI())) {
                throw new IllegalArgumentException(
                        "Namespace cannot be used by People API: " + aspect.toPrefixString());
            }//from   w  w  w .  j a  v a 2s .  co  m
        });
    }

    if (properties != null) {
        Map<QName, Serializable> nodeProps = nodes.mapToNodeProperties(properties);
        nodeProps.keySet().forEach(qname -> {
            if (EXCLUDED_NS.contains(qname.getNamespaceURI())) {
                throw new IllegalArgumentException(
                        "Namespace cannot be used by People API: " + qname.toPrefixString());
            }
        });
    }
}

From source file:org.sardineproject.sbyod.rest.AppWebUser.java

/**
 * Ask if a user with userIp has a access to the service with serviceId.
 *
 * @param userIp_ the IP address of the user
 * @param serviceId_ the ID of the service
 * @return PRECONDITION_FAILED if some parameter was wrong
 *          "enabled : false" if service is disabled
 *          "enabled : true" if service is enabled
 *///w w w. ja v  a 2s  .c o  m
@GET
@Path("/{userIp}/service/{serviceId}")
public Response getUserServices(@PathParam("userIp") String userIp_,
        @PathParam("serviceId") String serviceId_) {
    log.debug("AppWebUser: Getting rules for userIp = {} and serviceId = {}", userIp_, serviceId_);

    if (userIp_ == null || serviceId_ == null)
        return Response.status(Response.Status.PRECONDITION_FAILED).build();

    Set<Host> users;
    ServiceId serviceId;
    try {
        users = get(HostService.class).getHostsByIp(Ip4Address.valueOf(userIp_));
        serviceId = ServiceId.serviceId(serviceId_);
    } catch (Exception e) {
        return Response.status(Response.Status.PRECONDITION_FAILED).build();
    }

    // get all connections a user has activated
    Set<Connection> connections = Sets.newHashSet();
    users.forEach(u -> connections.addAll(get(ConnectionStore.class).getConnections(u)));

    // check if the connections contain a service with given service id
    if (connections.stream().map(Connection::getService).map(Service::id).collect(Collectors.toSet())
            .contains(serviceId)) {
        return Response.ok(ENABLED_TRUE).build();
    }
    return Response.ok(ENABLED_FALSE).build();
}

From source file:com.abixen.platform.module.chart.service.impl.AbstractDatabaseService.java

private List<Map<String, DataSourceValueWeb>> getData(Connection connection,
        DatabaseDataSource databaseDataSource, Set<String> chartColumnsSet) {
    ResultSet rs;//from  ww w. j a  v  a 2  s. co  m
    List<Map<String, DataSourceValueWeb>> data = new ArrayList<>();
    try {
        Statement statement = connection.createStatement();
        rs = statement.executeQuery(buildQueryForChartData(databaseDataSource, chartColumnsSet));

        if (rs != null) {
            while (rs.next()) {
                final ResultSet row = rs;
                Map<String, DataSourceValueWeb> rowMap = new HashMap<>();
                chartColumnsSet.forEach(chartColumnsSetElement -> {
                    rowMap.put(chartColumnsSetElement, getDataFromColumn(row, chartColumnsSetElement));
                });
                data.add(rowMap);
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
        throw new DataParsingException("Error when parsing data from db. " + e.getMessage());
    }
    return data;
}

From source file:com.adobe.ags.curly.controller.ActionRunner.java

private void applyVariablesToMap(Map<String, String> variables, Map<String, String> target) {
    Set<String> variableTokens = ActionUtils.getVariableNames(action);

    Set removeSet = new HashSet<>();
    Map<String, String> newValues = new HashMap<>();

    target.forEach((paramName, paramValue) -> {
        StringProperty paramNameProperty = new SimpleStringProperty(paramName);
        variableTokens.forEach((String originalName) -> {
            String[] variableNameParts = originalName.split("\\|");
            String variableName = variableNameParts[0];
            String variableNameMatchPattern = Pattern.quote("${" + originalName + "}");
            String val = variables.get(variableName);
            if (val == null) {
                val = "";
            }//w  w w.j av a  2 s. c  om
            String variableValue = Matcher.quoteReplacement(val);
            //----
            String newParamValue = newValues.containsKey(paramNameProperty.get())
                    ? newValues.get(paramNameProperty.get())
                    : paramValue;
            String newParamName = paramNameProperty.get().replaceAll(variableNameMatchPattern, variableValue);
            paramNameProperty.set(newParamName);
            newParamValue = newParamValue.replaceAll(variableNameMatchPattern, variableValue);
            if (!newParamName.equals(paramName) || !newParamValue.equals(paramValue)) {
                removeSet.add(paramNameProperty.get());
                removeSet.add(paramName);
                newValues.put(newParamName, newParamValue);
            }
        });
    });
    target.keySet().removeAll(removeSet);
    target.putAll(newValues);
}

From source file:org.apache.tinkerpop.gremlin.process.computer.traversal.strategy.decoration.VertexProgramStrategy.java

@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    // VertexPrograms can only execute at the root level of a Traversal and should not be applied locally prior to RemoteStrategy
    if (!(traversal.getParent() instanceof EmptyStep)
            || traversal.getStrategies().getStrategy(RemoteStrategy.class).isPresent())
        return;/*w w w .jav a 2  s .  c  om*/

    // back propagate as()-labels off of vertex computing steps
    Step<?, ?> currentStep = traversal.getEndStep();
    final Set<String> currentLabels = new HashSet<>();
    while (!(currentStep instanceof EmptyStep)) {
        if (currentStep instanceof VertexComputing && !(currentStep instanceof ProgramVertexProgramStep)) { // todo: is there a general solution?
            currentLabels.addAll(currentStep.getLabels());
            currentStep.getLabels().forEach(currentStep::removeLabel);
        } else {
            currentLabels.forEach(currentStep::addLabel);
            currentLabels.clear();
        }
        currentStep = currentStep.getPreviousStep();
    }

    // push GraphStep forward in the chain to reduce the number of TraversalVertexProgram compilations
    currentStep = traversal.getStartStep();
    while (!(currentStep instanceof EmptyStep)) {
        if (currentStep instanceof GraphStep && currentStep.getNextStep() instanceof VertexComputing) {
            int index = TraversalHelper.stepIndex(currentStep.getNextStep(), traversal);
            traversal.removeStep(currentStep);
            traversal.addStep(index, currentStep);
        } else
            currentStep = currentStep.getNextStep();
    }

    // wrap all non-VertexComputing steps into a TraversalVertexProgramStep
    currentStep = traversal.getStartStep();
    while (!(currentStep instanceof EmptyStep)) {
        Traversal.Admin<?, ?> computerTraversal = new DefaultTraversal<>();
        Step<?, ?> firstLegalOLAPStep = getFirstLegalOLAPStep(currentStep);
        Step<?, ?> lastLegalOLAPStep = getLastLegalOLAPStep(currentStep);
        if (!(firstLegalOLAPStep instanceof EmptyStep)) {
            int index = TraversalHelper.stepIndex(firstLegalOLAPStep, traversal);
            TraversalHelper.removeToTraversal(firstLegalOLAPStep, lastLegalOLAPStep.getNextStep(),
                    (Traversal.Admin) computerTraversal);
            final TraversalVertexProgramStep traversalVertexProgramStep = new TraversalVertexProgramStep(
                    traversal, computerTraversal);
            traversal.addStep(index, traversalVertexProgramStep);
        }
        currentStep = traversal.getStartStep();
        while (!(currentStep instanceof EmptyStep)) {
            if (!(currentStep instanceof VertexComputing))
                break;
            currentStep = currentStep.getNextStep();
        }
    }
    // if the last vertex computing step is a TraversalVertexProgramStep convert to OLTP with ComputerResultStep
    TraversalHelper.getLastStepOfAssignableClass(VertexComputing.class, traversal).ifPresent(step -> {
        if (step instanceof TraversalVertexProgramStep) {
            final ComputerResultStep computerResultStep = new ComputerResultStep<>(traversal);
            ((TraversalVertexProgramStep) step).getGlobalChildren().get(0).getEndStep().getLabels()
                    .forEach(computerResultStep::addLabel);
            // labeling should happen in TraversalVertexProgram (perhaps MapReduce)
            TraversalHelper.insertAfterStep(computerResultStep, (Step) step, traversal);
        }
    });
    // if there is a dangling vertex computing step, add an identity traversal (solve this in the future with a specialized MapReduce)
    if (traversal.getEndStep() instanceof VertexComputing
            && !(traversal.getEndStep() instanceof TraversalVertexProgramStep)) {
        final TraversalVertexProgramStep traversalVertexProgramStep = new TraversalVertexProgramStep(traversal,
                __.identity().asAdmin());
        traversal.addStep(traversalVertexProgramStep);
        traversal.addStep(new ComputerResultStep<>(traversal));
    }
    // all vertex computing steps needs the graph computer function
    traversal.getSteps().stream().filter(step -> step instanceof VertexComputing)
            .forEach(step -> ((VertexComputing) step).setComputer(this.computer));
}

From source file:ddf.catalog.definition.impl.DefinitionParser.java

private void undoAttributes(Set<AttributeDescriptor> attributes) {
    attributes.forEach(attributeRegistry::deregister);
}

From source file:com.widowcrawler.terminator.parse.Parser.java

private void agentSpec() throws ParseException {
    //System.out.println("agentSpec()");
    Set<String> userAgents = userAgents();
    Set<Rule> ruleSet = new HashSet<>();

    whitespace();/*from w  w  w . ja  v  a 2  s. c om*/

    while (isRuleLineStart()) {
        Rule rule = ruleLine();

        if (rule != null) {
            ruleSet.add(rule);
            //System.out.println(rule.getRuleType());
            //System.out.println(rule.getPathMatch());
        }

        whitespace();
    }

    userAgents.forEach(userAgent -> ruleSets.put(userAgent, ruleSet));
}