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.matonto.ontology.rest.impl.OntologyRestImplTest.java

private void assertIndividuals(JSONObject responseObject, Set<Individual> set) {
    JSONArray jsonIndividuals = responseObject.optJSONArray("namedIndividuals");
    assertNotNull(jsonIndividuals);/*  ww w  .j  ava2s. c o m*/
    assertEquals(jsonIndividuals.size(), set.size());
    set.forEach(individual -> assertTrue(
            jsonIndividuals.contains(createJsonIRI(((NamedIndividual) individual).getIRI()))));
}

From source file:org.matonto.ontology.rest.impl.OntologyRestImplTest.java

private void assertDataProperties(JSONObject responseObject, Set<DataProperty> set) {
    JSONArray jsonDataProperties = responseObject.optJSONArray("dataProperties");
    assertNotNull(jsonDataProperties);/*w ww .j a  va  2 s. c om*/
    assertEquals(jsonDataProperties.size(), set.size());
    set.forEach(dataProperty -> assertTrue(jsonDataProperties.contains(createJsonIRI(dataProperty.getIRI()))));
}

From source file:org.matonto.ontology.rest.impl.OntologyRestImplTest.java

private void assertObjectProperties(JSONObject responseObject, Set<ObjectProperty> set) {
    JSONArray jsonObjectProperties = responseObject.optJSONArray("objectProperties");
    assertNotNull(jsonObjectProperties);
    assertEquals(jsonObjectProperties.size(), set.size());
    set.forEach(objectProperty -> assertTrue(
            jsonObjectProperties.contains(createJsonIRI(objectProperty.getIRI()))));
}

From source file:org.matonto.ontology.rest.impl.OntologyRestImplTest.java

private void assertAnnotations(JSONObject responseObject, Set<AnnotationProperty> propSet,
        Set<Annotation> annSet) {
    JSONArray jsonAnnotations = responseObject.optJSONArray("annotationProperties");
    assertNotNull(jsonAnnotations);//from w  w w. j ava  2s. co m
    assertEquals(jsonAnnotations.size(), propSet.size() + annSet.size());
    propSet.forEach(annotationProperty -> assertTrue(
            jsonAnnotations.contains(createJsonIRI(annotationProperty.getIRI()))));
    annSet.forEach(annotation -> assertTrue(
            jsonAnnotations.contains(createJsonIRI(annotation.getProperty().getIRI()))));
}

From source file:org.wso2.carbon.apimgt.core.dao.impl.ApiDAOImpl.java

private void deleteEndPointsForOperation(Connection connection, String apiId) throws SQLException, IOException {
    final String query = "DELETE FROM AM_API_RESOURCE_ENDPOINT WHERE API_ID = ?";
    Set<String> endpoints = new HashSet();
    getUriTemplates(connection, apiId).forEach((k, v) -> {
        try {//from w  w w . j  ava 2s. co m
            Map<String, Endpoint> apiEndPointMap = getEndPointsForOperation(connection, apiId,
                    v.getTemplateId());
            apiEndPointMap.forEach((k1, v1) -> {
                if (APIMgtConstants.API_SPECIFIC_ENDPOINT.equals(v1.getApplicableLevel())) {
                    endpoints.add(v1.getId());
                }
            });
        } catch (SQLException | IOException e) {
            log.error("Couldn't retrieve UriTemplates for api : " + apiId, e);
        }
    });
    try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
        preparedStatement.setString(1, apiId);
        preparedStatement.execute();
        endpoints.forEach((value) -> {
            try {
                if (!isEndpointAssociated(connection, value)) {
                    deleteEndpoint(connection, value);
                }
            } catch (SQLException e) {
                log.error("Couldn't delete Endpoint", e);
            }
        });
    }
}

From source file:org.onosproject.ecord.carrierethernet.app.CarrierEthernetPacketNodeManager.java

/**
 * Creates and submits FlowObjectives depending on role of the device in the FC and ingress/egress NI types.
 *
 * @param fc the FC representation//from  ww  w .j av  a  2s .c om
 * @param ingressNi the ingress NI (UNI, INNI, ENNI or GENERIC) of the EVC for this forwarding segment
 * @param  egressNiSet the set of egress NIs (UNI, INNI, ENNI or GENERIC) of the EVC for this forwarding segment
 */
private void createFlowObjectives(CarrierEthernetForwardingConstruct fc,
        CarrierEthernetNetworkInterface ingressNi, Set<CarrierEthernetNetworkInterface> egressNiSet) {

    /////////////////////////////////////////
    // Prepare and submit filtering objective
    /////////////////////////////////////////

    FilteringObjective.Builder filteringObjectiveBuilder = DefaultFilteringObjective.builder().permit()
            .fromApp(appId).withPriority(PRIORITY).withKey(Criteria.matchInPort(ingressNi.cp().port()));

    TrafficTreatment.Builder filterTreatmentBuilder = DefaultTrafficTreatment.builder();

    // In general, nodes would match on the VLAN tag assigned to the EVC/FC
    Criterion filterVlanIdCriterion = Criteria.matchVlanId(fc.vlanId());

    if ((ingressNi.type().equals(CarrierEthernetNetworkInterface.Type.INNI))
            || (ingressNi.type().equals(CarrierEthernetNetworkInterface.Type.ENNI))) {
        // TODO: Check TPID? Also: Is is possible to receive untagged pkts at an INNI/ENNI?
        // Source node of an FC should match on S-TAG if it's an INNI/ENNI
        filterVlanIdCriterion = Criteria.matchVlanId(ingressNi.sVlanId());
        // Translate S-TAG to the one used in the current FC
        filterTreatmentBuilder.setVlanId(fc.vlanId());
    } else if (ingressNi.type().equals(CarrierEthernetNetworkInterface.Type.UNI)) {
        // Source node of an FC should match on CE-VLAN ID (if present) if it's a UNI
        filterVlanIdCriterion = Criteria.matchVlanId(ingressNi.ceVlanId());
        // Obtain related Meter (if it exists) and add it in the treatment in case it may be used
        deviceMeterIdMap.get(fc.id()).forEach(deviceMeterId -> {
            if (deviceMeterId.deviceId().equals(ingressNi.cp().deviceId())) {
                filterTreatmentBuilder.meter(deviceMeterId.meterId());
            }
        });
        // Push S-TAG of current FC on top of existing CE-VLAN ID
        filterTreatmentBuilder.pushVlan().setVlanId(fc.vlanId());
    }

    filteringObjectiveBuilder.addCondition(filterVlanIdCriterion);

    // Do not add meta if there are no instructions (i.e. if not first)
    if (!(ingressNi.type().equals(CarrierEthernetNetworkInterface.Type.GENERIC))) {
        filteringObjectiveBuilder.withMeta(filterTreatmentBuilder.build());
    }

    flowObjectiveService.filter(ingressNi.cp().deviceId(), filteringObjectiveBuilder.add());
    flowObjectiveMap.get(fc.id()).addFirst(Pair.of(ingressNi.cp().deviceId(), filteringObjectiveBuilder.add()));

    ////////////////////////////////////////////////////
    // Prepare and submit next and forwarding objectives
    ////////////////////////////////////////////////////

    TrafficSelector fwdSelector = DefaultTrafficSelector.builder().matchVlanId(fc.vlanId())
            .matchInPort(ingressNi.cp().port()).matchEthType(Ethernet.TYPE_IPV4).build();

    Integer nextId = flowObjectiveService.allocateNextId();

    NextObjective.Type nextType = egressNiSet.size() == 1 ? NextObjective.Type.SIMPLE
            : NextObjective.Type.BROADCAST;

    // Setting higher priority to fwd/next objectives to bypass filter in case of match conflict in OVS switches
    NextObjective.Builder nextObjectiveBuider = DefaultNextObjective.builder().fromApp(appId).makePermanent()
            .withType(nextType).withPriority(PRIORITY + 1).withMeta(fwdSelector).withId(nextId);

    egressNiSet.forEach(egressNi -> {
        // TODO: Check if ingressNi and egressNi are on the same device?
        TrafficTreatment.Builder nextTreatmentBuilder = DefaultTrafficTreatment.builder();
        // If last NI in FC is not UNI, keep the existing S-TAG - it will be translated at the entrance of the next FC
        if (egressNi.type().equals(CarrierEthernetNetworkInterface.Type.UNI)) {
            nextTreatmentBuilder.popVlan();
        }
        Instruction outInstruction = Instructions.createOutput(egressNi.cp().port());
        nextTreatmentBuilder.add(outInstruction);
        nextObjectiveBuider.addTreatment(nextTreatmentBuilder.build());
    });

    NextObjective nextObjective = nextObjectiveBuider.add();

    // Setting higher priority to fwd/next objectives to bypass filter in case of match conflict in OVS switches
    ForwardingObjective forwardingObjective = DefaultForwardingObjective.builder().fromApp(appId)
            .makePermanent().withFlag(ForwardingObjective.Flag.VERSATILE).withPriority(PRIORITY + 1)
            .withSelector(fwdSelector).nextStep(nextId).add();

    flowObjectiveService.next(ingressNi.cp().deviceId(), nextObjective);
    // Add all NextObjectives at the end of the list so that they will be removed last
    flowObjectiveMap.get(fc.id()).addLast(Pair.of(ingressNi.cp().deviceId(), nextObjective));

    flowObjectiveService.forward(ingressNi.cp().deviceId(), forwardingObjective);
    flowObjectiveMap.get(fc.id()).addFirst(Pair.of(ingressNi.cp().deviceId(), forwardingObjective));
}

From source file:org.commonjava.indy.promote.data.PromotionManager.java

private PathsPromoteResult runPathPromotions(final PathsPromoteRequest request, final Set<String> pending,
        final Set<String> prevComplete, final Set<String> prevSkipped, final List<Transfer> contents,
        ValidationResult validation, final ValidationRequest validationRequest) throws IndyWorkflowException {
    if (pending == null || pending.isEmpty()) {
        return new PathsPromoteResult(request, pending, prevComplete, prevSkipped, validation);
    }/*from   www .  j a  va 2  s .c om*/

    StoreKey targetKey = request.getTarget();

    final Set<String> complete = prevComplete == null ? new HashSet<>() : new HashSet<>(prevComplete);
    final Set<String> skipped = prevSkipped == null ? new HashSet<>() : new HashSet<>(prevSkipped);

    List<String> errors = new ArrayList<>();

    ArtifactStore sourceStore = null;
    try {
        sourceStore = storeManager.getArtifactStore(request.getSource());
    } catch (IndyDataException e) {
        String msg = String.format("Failed to retrieve artifact store: %s. Reason: %s", request.getSource(),
                e.getMessage());
        errors.add(msg);
        logger.error(msg, e);
    }

    ArtifactStore targetStore = null;
    try {
        targetStore = storeManager.getArtifactStore(request.getTarget());
    } catch (IndyDataException e) {
        String msg = String.format("Failed to retrieve artifact store: %s. Reason: %s", request.getTarget(),
                e.getMessage());
        errors.add(msg);
        logger.error(msg, e);
    }

    if (targetStore == null) {
        String msg = String.format("Failed to retrieve artifact store: %s", request.getTarget());
        errors.add(msg);
        logger.error(msg);
    }

    if (errors.isEmpty()) {
        ArtifactStore src = sourceStore;
        ArtifactStore tgt = targetStore;

        AtomicReference<IndyWorkflowException> wfError = new AtomicReference<>();

        Set<PathTransferResult> results = byPathTargetLocks.lockAnd(targetKey, config.getLockTimeoutSeconds(),
                k -> {
                    logger.info("Running promotions from: {} (key: {})\n  to: {} (key: {})", src,
                            request.getSource(), tgt, request.getTarget());

                    DrainingExecutorCompletionService<PathTransferResult> svc = new DrainingExecutorCompletionService<>(
                            transferService);

                    try {
                        detectOverloadVoid(() -> contents.forEach((transfer) -> svc
                                .submit(newPathsPromoteTransfer(transfer, src, tgt, request))));

                        Set<PathTransferResult> pathResults = new HashSet<>();
                        try {
                            svc.drain(ptr -> pathResults.add(ptr));
                        } catch (InterruptedException | ExecutionException e) {
                            Set<String> paths;
                            try {
                                paths = validationRequest.getSourcePaths();
                            } catch (PromotionValidationException e1) {
                                paths = contents.stream().map(txfr -> txfr.getPath())
                                        .collect(Collectors.toSet());
                            }

                            logger.error(
                                    String.format("Error waiting for promotion of: %s to: %s\nPaths:\n\n%s\n\n",
                                            request.getSource(), targetKey, paths),
                                    e);
                        }

                        try {
                            clearStoreNFC(validationRequest.getSourcePaths(), tgt);
                        } catch (IndyDataException | PromotionValidationException e) {
                            String msg = String.format("Failed to promote to: %s. Reason: %s", tgt,
                                    e.getMessage());
                            errors.add(msg);
                            logger.error(msg, e);
                        }
                        return pathResults;
                    } catch (IndyWorkflowException e) {
                        wfError.set(e);
                        return null;
                    }
                }, (k, lock) -> {
                    String error = String.format(
                            "Failed to acquire promotion lock on target: %s in %d seconds.", targetKey,
                            config.getLockTimeoutSeconds());

                    errors.add(error);
                    logger.warn(error);

                    return false;
                });

        if (wfError.get() != null) {
            throw wfError.get();
        }

        if (results != null) {
            results.forEach(pathResult -> {
                if (pathResult.traversed) {
                    pending.remove(pathResult.path);
                }

                if (pathResult.skipped) {
                    skipped.add(pathResult.path);
                }

                if (pathResult.completed) {
                    complete.add(pathResult.path);
                }

                if (pathResult.error != null) {
                    errors.add(pathResult.error);
                }
            });
        }
    }

    String error = null;

    if (!errors.isEmpty()) {
        error = StringUtils.join(errors, "\n");
    }

    PathsPromoteResult result = new PathsPromoteResult(request, pending, complete, skipped, error, validation);

    if (request.isFireEvents()) {
        PathsPromoteCompleteEvent evt = new PathsPromoteCompleteEvent(result);
        fireEvent(promoteCompleteEvent, evt);
    }
    return result;
}

From source file:org.apache.nifi.web.api.FlowResource.java

/**
 * Updates the specified process group.//from  ww w.  ja v a 2 s . c  o  m
 *
 * @param httpServletRequest       request
 * @param id                       The id of the process group.
 * @param requestScheduleComponentsEntity A scheduleComponentsEntity.
 * @return A processGroupEntity.
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("process-groups/{id}")
@ApiOperation(value = "Schedule or unschedule comopnents in the specified Process Group.", notes = "", response = ScheduleComponentsEntity.class, authorizations = {
        @Authorization(value = "Read - /flow", type = ""),
        @Authorization(value = "Write - /{component-type}/{uuid} - For every component being scheduled/unscheduled", type = "") })
@ApiResponses(value = {
        @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
        @ApiResponse(code = 401, message = "Client could not be authenticated."),
        @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
        @ApiResponse(code = 404, message = "The specified resource could not be found."),
        @ApiResponse(code = 409, message = "The request was valid but NiFi was not in the appropriate state to process it. Retrying the same request later may be successful.") })
public Response scheduleComponents(@Context HttpServletRequest httpServletRequest,
        @ApiParam(value = "The process group id.", required = true) @PathParam("id") String id,
        @ApiParam(value = "The request to schedule or unschedule. If the comopnents in the request are not specified, all authorized components will be considered.", required = true) final ScheduleComponentsEntity requestScheduleComponentsEntity) {

    // ensure the same id is being used
    if (!id.equals(requestScheduleComponentsEntity.getId())) {
        throw new IllegalArgumentException(String.format(
                "The process group id (%s) in the request body does "
                        + "not equal the process group id of the requested resource (%s).",
                requestScheduleComponentsEntity.getId(), id));
    }

    final ScheduledState state;
    if (requestScheduleComponentsEntity.getState() == null) {
        throw new IllegalArgumentException("The scheduled state must be specified.");
    } else {
        try {
            state = ScheduledState.valueOf(requestScheduleComponentsEntity.getState());
        } catch (final IllegalArgumentException iae) {
            throw new IllegalArgumentException(String.format("The scheduled must be one of [%s].",
                    StringUtils.join(EnumSet.of(ScheduledState.RUNNING, ScheduledState.STOPPED), ", ")));
        }
    }

    // ensure its a supported scheduled state
    if (ScheduledState.DISABLED.equals(state) || ScheduledState.STARTING.equals(state)
            || ScheduledState.STOPPING.equals(state)) {
        throw new IllegalArgumentException(String.format("The scheduled must be one of [%s].",
                StringUtils.join(EnumSet.of(ScheduledState.RUNNING, ScheduledState.STOPPED), ", ")));
    }

    // if the components are not specified, gather all components and their current revision
    if (requestScheduleComponentsEntity.getComponents() == null) {
        // get the current revisions for the components being updated
        final Set<Revision> revisions = serviceFacade.getRevisionsFromGroup(id, group -> {
            final Set<String> componentIds = new HashSet<>();

            // ensure authorized for each processor we will attempt to schedule
            group.findAllProcessors().stream()
                    .filter(ScheduledState.RUNNING.equals(state) ? ProcessGroup.SCHEDULABLE_PROCESSORS
                            : ProcessGroup.UNSCHEDULABLE_PROCESSORS)
                    .filter(processor -> processor.isAuthorized(authorizer, RequestAction.WRITE,
                            NiFiUserUtils.getNiFiUser()))
                    .forEach(processor -> {
                        componentIds.add(processor.getIdentifier());
                    });

            // ensure authorized for each input port we will attempt to schedule
            group.findAllInputPorts().stream()
                    .filter(ScheduledState.RUNNING.equals(state) ? ProcessGroup.SCHEDULABLE_PORTS
                            : ProcessGroup.UNSCHEDULABLE_PORTS)
                    .filter(inputPort -> inputPort.isAuthorized(authorizer, RequestAction.WRITE,
                            NiFiUserUtils.getNiFiUser()))
                    .forEach(inputPort -> {
                        componentIds.add(inputPort.getIdentifier());
                    });

            // ensure authorized for each output port we will attempt to schedule
            group.findAllOutputPorts().stream()
                    .filter(ScheduledState.RUNNING.equals(state) ? ProcessGroup.SCHEDULABLE_PORTS
                            : ProcessGroup.UNSCHEDULABLE_PORTS)
                    .filter(outputPort -> outputPort.isAuthorized(authorizer, RequestAction.WRITE,
                            NiFiUserUtils.getNiFiUser()))
                    .forEach(outputPort -> {
                        componentIds.add(outputPort.getIdentifier());
                    });

            return componentIds;
        });

        // build the component mapping
        final Map<String, RevisionDTO> componentsToSchedule = new HashMap<>();
        revisions.forEach(revision -> {
            final RevisionDTO dto = new RevisionDTO();
            dto.setClientId(revision.getClientId());
            dto.setVersion(revision.getVersion());
            componentsToSchedule.put(revision.getComponentId(), dto);
        });

        // set the components and their current revision
        requestScheduleComponentsEntity.setComponents(componentsToSchedule);
    }

    if (isReplicateRequest()) {
        return replicate(HttpMethod.PUT, requestScheduleComponentsEntity);
    }

    final Map<String, RevisionDTO> requestComponentsToSchedule = requestScheduleComponentsEntity
            .getComponents();
    final Map<String, Revision> requestComponentRevisions = requestComponentsToSchedule.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, e -> getRevision(e.getValue(), e.getKey())));
    final Set<Revision> requestRevisions = new HashSet<>(requestComponentRevisions.values());

    return withWriteLock(serviceFacade, requestScheduleComponentsEntity, requestRevisions, lookup -> {
        // ensure access to the flow
        authorizeFlow();

        // ensure access to every component being scheduled
        requestComponentsToSchedule.keySet().forEach(componentId -> {
            final Authorizable connectable = lookup.getLocalConnectable(componentId);
            connectable.authorize(authorizer, RequestAction.WRITE, NiFiUserUtils.getNiFiUser());
        });
    }, () -> serviceFacade.verifyScheduleComponents(id, state, requestComponentRevisions.keySet()),
            (revisions, scheduleComponentsEntity) -> {
                final ScheduledState scheduledState = ScheduledState
                        .valueOf(scheduleComponentsEntity.getState());

                final Map<String, RevisionDTO> componentsToSchedule = scheduleComponentsEntity.getComponents();
                final Map<String, Revision> componentRevisions = componentsToSchedule.entrySet().stream()
                        .collect(Collectors.toMap(Map.Entry::getKey,
                                e -> getRevision(e.getValue(), e.getKey())));

                // update the process group
                final ScheduleComponentsEntity entity = serviceFacade.scheduleComponents(id, scheduledState,
                        componentRevisions);
                return clusterContext(generateOkResponse(entity)).build();
            });
}

From source file:org.apache.nifi.registry.ranger.RangerBasePluginWithPolicies.java

private PolicyLookup createPolicyLookup(final ServicePolicies servicePolicies) {
    final Map<String, AccessPolicy> policiesByIdentifier = new HashMap<>();
    final Map<String, Map<RequestAction, AccessPolicy>> policiesByResource = new HashMap<>();

    logger.debug(//from  w  ww  .j a  v  a  2s.c om
            "Converting Ranger ServicePolicies model into NiFi Registry policy model for viewing purposes in NiFi Registry UI.");

    servicePolicies.getPolicies().stream().forEach(policy -> {
        // only consider policies that are enabled
        if (Boolean.TRUE.equals(policy.getIsEnabled())) {
            // get all the resources for this policy - excludes/recursive support disabled
            final Set<String> resources = policy.getResources().values().stream().filter(resource -> {
                final boolean isMissingResource;
                final boolean isWildcard;
                if (resource.getValues() == null) {
                    isMissingResource = true;
                    isWildcard = false;
                } else {
                    isMissingResource = false;
                    isWildcard = resource.getValues().stream()
                            .anyMatch(value -> value.contains(WILDCARD_ASTERISK));
                }

                final boolean isExclude = Boolean.TRUE.equals(resource.getIsExcludes());
                final boolean isRecursive = Boolean.TRUE.equals(resource.getIsRecursive());

                if (isMissingResource) {
                    logger.warn(
                            "Encountered resources missing values. Skipping policy for viewing purposes. Will still be used for access decisions.");
                }
                if (isWildcard) {
                    logger.warn(String.format(
                            "Resources [%s] include a wildcard value. Skipping policy for viewing purposes. "
                                    + "Will still be used for access decisions.",
                            StringUtils.join(resource.getValues(), ", ")));
                }
                if (isExclude) {
                    logger.warn(String.format(
                            "Resources [%s] marked as an exclude policy. Skipping policy for viewing purposes. "
                                    + "Will still be used for access decisions.",
                            StringUtils.join(resource.getValues(), ", ")));
                }
                if (isRecursive) {
                    logger.warn(String.format(
                            "Resources [%s] marked as a recursive policy. Skipping policy for viewing purposes. "
                                    + "Will still be used for access decisions.",
                            StringUtils.join(resource.getValues(), ", ")));
                }

                return !isMissingResource && !isWildcard && !isExclude && !isRecursive;
            }).flatMap(resource -> resource.getValues().stream()).collect(Collectors.toSet());

            policy.getPolicyItems().forEach(policyItem -> {
                // get all the users for this policy item, excluding unknown users
                final Set<String> userIds = policyItem.getUsers().stream()
                        .map(userIdentity -> getUser(userIdentity)).filter(Objects::nonNull)
                        .map(user -> user.getIdentifier()).collect(Collectors.toSet());

                // get all groups for this policy item, excluding unknown groups
                final Set<String> groupIds = policyItem.getGroups().stream()
                        .map(groupName -> getGroup(groupName)).filter(Objects::nonNull)
                        .map(group -> group.getIdentifier()).collect(Collectors.toSet());

                // check if this policy item is a delegate admin
                final boolean isDelegateAdmin = Boolean.TRUE.equals(policyItem.getDelegateAdmin());

                policyItem.getAccesses().forEach(access -> {
                    try {
                        // interpret the request action
                        final RequestAction action = RequestAction.valueOf(access.getType());

                        // function for creating an access policy
                        final Function<String, AccessPolicy> createPolicy = resource -> new AccessPolicy.Builder()
                                .identifierGenerateFromSeed(resource + access.getType()).resource(resource)
                                .action(action).addUsers(userIds).addGroups(groupIds).build();

                        resources.forEach(resource -> {
                            // create the access policy for the specified resource
                            final AccessPolicy accessPolicy = createPolicy.apply(resource);
                            policiesByIdentifier.put(accessPolicy.getIdentifier(), accessPolicy);
                            policiesByResource.computeIfAbsent(resource, r -> new HashMap<>()).put(action,
                                    accessPolicy);

                            // if this is a delegate admin, also create the admin policy for the specified resource
                            if (isDelegateAdmin) {
                                //  build the admin resource identifier
                                final String adminResource;
                                if (resource.startsWith("/")) {
                                    adminResource = "/policies" + resource;
                                } else {
                                    adminResource = "/policies/" + resource;
                                }

                                final AccessPolicy adminAccessPolicy = createPolicy.apply(adminResource);
                                policiesByIdentifier.put(adminAccessPolicy.getIdentifier(), adminAccessPolicy);
                                policiesByResource.computeIfAbsent(adminResource, ar -> new HashMap<>())
                                        .put(action, adminAccessPolicy);
                            }
                        });
                    } catch (final IllegalArgumentException e) {
                        logger.warn(String.format(
                                "Unrecognized request action '%s'. Skipping policy for viewing purposes. Will still be used for access decisions.",
                                access.getType()));
                    }
                });
            });
        }
    });

    return new PolicyLookup(policiesByIdentifier, policiesByResource);
}

From source file:com.confighub.core.store.Store.java

/**
 * @param repository/*  w w w.  ja va2s  . co  m*/
 * @param user
 * @param id
 * @param name
 * @param type
 * @param assignmentIds
 * @param depthLabel
 * @return
 * @throws ConfigException
 */
public CtxLevel updateOrCreateLevel(final Repository repository, final UserAccount user, final Long id,
        final String name, final CtxLevel.LevelType type, final Collection<Long> assignmentIds,
        final String depthLabel) throws ConfigException {
    if (Utils.anyNull(repository, name)) {
        throw new ConfigException(Error.Code.MISSING_PARAMS);
    }

    if (!repository.hasWriteAccess(user)) {
        throw new ConfigException(Error.Code.USER_ACCESS_DENIED);
    }

    if (!repository.canUserManageContext(user)) {
        throw new ConfigException(Error.Code.CONTEXT_EDIT_DISABLED);
    }

    Depth depth = repository.getDepthFromLabel(depthLabel);
    CtxLevel ctxLevel;

    boolean updatePropertyContextStrings = false;
    boolean isNew = id == null;
    boolean levelTypeChanged = false;

    if (!isNew) {
        ctxLevel = getLevel(id, repository);

        if (null == ctxLevel) {
            throw new ConfigException(Error.Code.NOT_FOUND);
        }

        updatePropertyContextStrings = !ctxLevel.getName().equals(name);
        ctxLevel.setName(name);
        levelTypeChanged = !ctxLevel.getType().equals(type);
    } else {
        ctxLevel = new CtxLevel(repository, depth);
        ctxLevel.setName(name);
    }

    // when do the property contexts need to be re-written ?
    // - if a Level type changes to Group
    // - if a Level type changes from Group
    // - if level name has changed

    updatePropertyContextStrings |= levelTypeChanged
            && (CtxLevel.LevelType.Group.equals(type) || CtxLevel.LevelType.Group.equals(ctxLevel.getType()));

    // Check access to the edited level
    AccessRuleWrapper accessRuleWrapper = null;
    boolean accessControlled = repository.isAccessControlEnabled();
    if (accessControlled) {
        accessRuleWrapper = repository.getRulesWrapper(user);

        if (!isLevelModificationAllowed(accessRuleWrapper, accessControlled, ctxLevel)) {
            throw new ConfigException(Error.Code.LEVEL_EDITING_ACCESS_DENIED, ctxLevel.toJson());
        }
    }

    // Collect all level assignments;
    // Check write access to them
    // Make sure they are assignable to this level
    Set<CtxLevel> assignments = new HashSet<>();
    if (null != assignmentIds) {
        for (Long lid : assignmentIds) {
            CtxLevel l = getLevel(lid, repository);
            if (null == l) {
                throw new ConfigException(Error.Code.NOT_FOUND);
            }

            // ToDo, this should be a better check - not just that type is same
            if (l.getType().equals(type)) {
                throw new ConfigException(Error.Code.GROUP_TO_GROUP_ASSIGNMENT, l.toJson());
            }

            if (!isLevelModificationAllowed(accessRuleWrapper, accessControlled, l)) {
                throw new ConfigException(Error.Code.LEVEL_EDITING_ACCESS_DENIED, l.toJson());
            }

            assignments.add(l);
        }
    }

    // If this is a new level, just save and return
    if (isNew) {
        ctxLevel.setType(type);
        if (CtxLevel.LevelType.Group == type) {
            ctxLevel.setMembers(assignments);
        } else if (CtxLevel.LevelType.Member == type) {
            assignments.forEach(group -> group.addMember(ctxLevel));
        }

        // ToDo: should we save assignments

        saveOrUpdateAudited(user, repository, ctxLevel);
        return ctxLevel;
    }

    // This is an edited level, so...

    // Type of the level has not changed.
    if (!levelTypeChanged) {

        if (CtxLevel.LevelType.Group == type) {
            ctxLevel.setMembers(assignments);
        } else if (CtxLevel.LevelType.Member == type) {
            Set<CtxLevel> currentGroups = ctxLevel.getGroups();

            if (null != currentGroups) {
                // get groups that should not longer have level as a member
                currentGroups.removeAll(assignments);
                currentGroups.forEach(group -> group.removeMember(ctxLevel));
            }

            // refresh assignments
            assignments.forEach(group -> group.addMember(ctxLevel));
        } else if (CtxLevel.LevelType.Standalone == type) {
            ctxLevel.setMembers(null);
        }

        // ToDo: should we save assignments

        saveOrUpdateAudited(user, repository, ctxLevel);

        if (updatePropertyContextStrings) {
            if (null != ctxLevel.getProperties()) {
                ctxLevel.getProperties().forEach(Property::updateContextString);
            }

            if (null != ctxLevel.getFiles()) {
                ctxLevel.getFiles().forEach(RepoFile::updateContextString);
            }
        }

        return ctxLevel;
    }

    // Level type has changed
    switch (ctxLevel.getType()) {
    case Group: {
        ctxLevel.setMembers(null);
        if (CtxLevel.LevelType.Member == type) {
            assignments.forEach(group -> group.addMember(ctxLevel));
        }

        break;
    }

    case Member: {
        Set<CtxLevel> currentGroups = ctxLevel.getGroups();
        if (null != currentGroups) {
            currentGroups.forEach(group -> group.removeMember(ctxLevel));
        }

        if (CtxLevel.LevelType.Group == type) {
            ctxLevel.setMembers(assignments);
        }

        break;
    }

    case Standalone: {
        if (CtxLevel.LevelType.Group == type) {
            ctxLevel.setMembers(assignments);
        }

        else if (CtxLevel.LevelType.Member == type) {
            assignments.forEach(group -> group.addMember(ctxLevel));
        }

        break;
    }
    }

    ctxLevel.setType(type);
    if (updatePropertyContextStrings) {
        if (null != ctxLevel.getProperties()) {
            ctxLevel.getProperties().forEach(Property::updateContextString);
        }
        if (null != ctxLevel.getFiles()) {
            ctxLevel.getFiles().forEach(RepoFile::updateContextString);
        }
    }

    saveOrUpdateAudited(user, repository, ctxLevel);

    return ctxLevel;
}