Example usage for java.util.stream Stream concat

List of usage examples for java.util.stream Stream concat

Introduction

In this page you can find the example usage for java.util.stream Stream concat.

Prototype

public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) 

Source Link

Document

Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.

Usage

From source file:org.apache.nifi.registry.web.api.SecureLdapIT.java

/** A helper method to lookup identifiers for tenant identities using the REST API
 *
 * @param tenantIdentity - the identity to lookup
 * @return A string containing the identifier of the tenant, or null if the tenant identity is not found.
 *//* w  ww  . j  a v  a 2s  .co  m*/
private String getTenantIdentifierByIdentity(String tenantIdentity) {

    final Tenant[] users = client.target(createURL("tenants/users")).request()
            .header("Authorization", "Bearer " + adminAuthToken).get(Tenant[].class);

    final Tenant[] groups = client.target(createURL("tenants/user-groups")).request()
            .header("Authorization", "Bearer " + adminAuthToken).get(Tenant[].class);

    final Tenant matchedTenant = Stream.concat(Arrays.stream(users), Arrays.stream(groups))
            .filter(tenant -> tenant.getIdentity().equalsIgnoreCase(tenantIdentity)).findFirst().orElse(null);

    return matchedTenant != null ? matchedTenant.getIdentifier() : null;
}

From source file:com.thinkbiganalytics.feedmgr.rest.controller.DatasourceController.java

@GET
@Path("{id}/actions/change")
@Produces(MediaType.APPLICATION_JSON)//from  w ww. j a  v a  2s  .c o  m
@ApiOperation("Constructs and returns a permission change request for a set of users/groups containing the actions that the requester may permit or revoke.")
@ApiResponses({
        @ApiResponse(code = 200, message = "Returns the change request that may be modified by the client and re-posted.", response = PermissionsChange.class),
        @ApiResponse(code = 400, message = "The type is not valid.", response = RestResponseStatus.class),
        @ApiResponse(code = 404, message = "No data source exists with the specified ID.", response = RestResponseStatus.class) })
public Response getAllowedPermissionsChange(@PathParam("id") final String datasourceIdStr,
        @QueryParam("type") final String changeType, @QueryParam("user") final Set<String> userNames,
        @QueryParam("group") final Set<String> groupNames) {
    if (StringUtils.isBlank(changeType)) {
        throw new WebApplicationException("The query parameter \"type\" is required",
                Response.Status.BAD_REQUEST);
    }

    Set<? extends Principal> users = Arrays.stream(this.securityTransform.asUserPrincipals(userNames))
            .collect(Collectors.toSet());
    Set<? extends Principal> groups = Arrays.stream(this.securityTransform.asGroupPrincipals(groupNames))
            .collect(Collectors.toSet());

    return this.securityService
            .createDatasourcePermissionChange(datasourceIdStr,
                    PermissionsChange.ChangeType.valueOf(changeType.toUpperCase()),
                    Stream.concat(users.stream(), groups.stream()).collect(Collectors.toSet()))
            .map(p -> Response.ok(p).build())
            .orElseThrow(() -> new WebApplicationException(
                    "A data source with the given ID does not exist: " + datasourceIdStr,
                    Response.Status.NOT_FOUND));
}

From source file:com.thinkbiganalytics.feedmgr.rest.controller.TemplatesRestController.java

@GET
@Path("/registered/{templateId}/actions/allowed")
@Produces(MediaType.APPLICATION_JSON)/*  www  . j  a  v  a2 s. c o  m*/
@ApiOperation("Gets the list of actions permitted for the given username and/or groups.")
@ApiResponses({ @ApiResponse(code = 200, message = "Returns the actions.", response = ActionGroup.class),
        @ApiResponse(code = 404, message = "A template with the given ID does not exist.", response = RestResponseStatus.class) })
public Response getAllowedActions(@PathParam("templateId") String templateIdStr,
        @QueryParam("user") Set<String> userNames, @QueryParam("group") Set<String> groupNames) {
    log.debug("Get allowed actions for template: {}", templateIdStr);

    Set<? extends Principal> users = Arrays.stream(this.securityTransform.asUserPrincipals(userNames))
            .collect(Collectors.toSet());
    Set<? extends Principal> groups = Arrays.stream(this.securityTransform.asGroupPrincipals(groupNames))
            .collect(Collectors.toSet());

    return this.securityService
            .getAllowedTemplateActions(templateIdStr,
                    Stream.concat(users.stream(), groups.stream()).collect(Collectors.toSet()))
            .map(g -> Response.ok(g).build()).orElseThrow(() -> new WebApplicationException(
                    "A template with the given ID does not exist: " + templateIdStr, Status.NOT_FOUND));
}

From source file:com.ikanow.aleph2.graph.titan.utils.TitanGraphBuildingUtils.java

/** Calls user merge on the various possibly duplicate elements, and sorts out user responses
 * @param tx//from w  w w.ja  v  a  2s . com
 * @param config
 * @param security_service
 * @param logger
 * @param maybe_merger
 * @param titan_mapper
 * @param element_type
 * @param key
 * @param new_elements
 * @param existing_elements
 * @return
 */
protected static <O extends Element> List<O> invokeUserMergeCode(final TitanTransaction tx,
        final GraphSchemaBean config, final Tuple2<String, ISecurityService> security_service,
        final Optional<IBucketLogger> logger,
        final Optional<Tuple2<IEnrichmentBatchModule, GraphMergeEnrichmentContext>> maybe_merger,
        final org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper titan_mapper,
        final MutableStatsBean mutable_stats, final Class<O> element_type, final String bucket_path,
        final ObjectNode key, final Collection<ObjectNode> new_elements, final Collection<O> existing_elements,
        final Map<ObjectNode, Vertex> mutable_existing_vertex_store) {
    if (existing_elements.isEmpty() && (1 == new_elements.size()) && !config.custom_finalize_all_objects()) {

        return validateUserElement(new_elements.stream().findFirst().get(), config)
                .bind(el -> addGraphSON2Graph(bucket_path, key, el, mutable_existing_vertex_store,
                        Collections.emptyMap(), tx, element_type, mutable_stats))
                .<List<O>>validation(fail -> {
                    if (Vertex.class.isAssignableFrom(element_type))
                        mutable_stats.vertex_errors++;
                    else if (Edge.class.isAssignableFrom(element_type))
                        mutable_stats.edge_errors++;

                    logger.ifPresent(l -> l.inefficientLog(Level.DEBUG,
                            BeanTemplateUtils.clone(fail)
                                    .with(BasicMessageBean::source, "GraphBuilderEnrichmentService")
                                    .with(BasicMessageBean::command, "system.onObjectBatch").done()));
                    //(keep this here for c/p purposes .. if want to attach an expensive "details" object then could do that by copying the fields across one by one)                        
                    //                        logger.ifPresent(l -> l.log(Level.DEBUG,                        
                    //                              ErrorUtils.lazyBuildMessage(true, () -> "GraphBuilderEnrichmentService", 
                    //                                    () -> "system.onObjectBatch", 
                    //                                    () -> null, 
                    //                                    () -> ErrorUtils.get("MESSAGE", params),
                    //                                    () -> null)
                    //                                    ));                  

                    return Collections.emptyList();
                }, success -> Arrays.<O>asList(success));
    } else {
        // (just gives me the elements indexed by their ids so we can get them back again later)
        // (we'll convert to string as a slightly inefficient way of ensuring the same code can handle both edge andv vertex cases)
        final Map<String, Optional<O>> mutable_existing_element_vs_id_store = existing_elements.stream()
                .collect(Collectors.toMap(e -> e.id().toString(), e -> Optional.of(e)));

        return maybe_merger.<List<O>>map(merger -> {

            final Stream<Tuple2<Long, IBatchRecord>> in_stream = Stream.concat(
                    new_elements.stream().map(j -> Tuples._2T(0L, new BatchRecordUtils.JsonBatchRecord(j))),
                    existing_elements.stream().sorted((a, b) -> ((Long) a.id()).compareTo((Long) b.id())) // (ensure first found element has the lowest id)
                            .map(v -> _mapper.convertValue(titan_mapper.convertValue(v, Map.class),
                                    JsonNode.class))
                            .map(j -> Tuples._2T(0L, new BatchRecordUtils.InjectedJsonBatchRecord(j))));

            merger._2().initializeMerge(element_type);

            merger._1().onObjectBatch(in_stream, Optional.of(new_elements.size()), Optional.of(key));

            return merger._2().getAndResetElementList().stream()
                    .map(o -> addGraphSON2Graph(bucket_path, key, o, mutable_existing_vertex_store,
                            mutable_existing_element_vs_id_store, tx, element_type, mutable_stats))
                    .<O>flatMap(v -> v.validation(fail -> {
                        if (Vertex.class.isAssignableFrom(element_type))
                            mutable_stats.vertex_errors++;
                        else if (Edge.class.isAssignableFrom(element_type))
                            mutable_stats.edge_errors++;

                        logger.ifPresent(l -> l.inefficientLog(Level.DEBUG,
                                BeanTemplateUtils.clone(fail)
                                        .with(BasicMessageBean::source, "GraphBuilderEnrichmentService")
                                        .with(BasicMessageBean::command, "system.onObjectBatch").done()));

                        return Stream.empty();
                    }, success -> Stream.of(success))).collect(Collectors.toList());
        }).orElse(Collections.emptyList());
    }
}

From source file:org.apache.tinkerpop.gremlin.structure.io.Model.java

public void saveAsCsv(final String file) throws Exception {
    final File f = new File(file);
    f.getParentFile().mkdirs();//from  w  w  w  . j  ava2s  .  c om

    final List<Compatibility> compatibilities = Stream
            .concat(Stream.of(GraphSONCompatibility.values()), Stream.of(GryoCompatibility.values()))
            .collect(Collectors.toList());

    final List<String> headers = new ArrayList<>();
    headers.add("resource");
    headers.addAll(compatibilities.stream().map(c -> {
        if (c instanceof GryoCompatibility)
            return "gryo-" + ((GryoCompatibility) c).name();
        else if (c instanceof GraphSONCompatibility)
            return "graphson-" + ((GraphSONCompatibility) c).name();
        else
            throw new IllegalStateException("No support for the provided Compatibility type");
    }).collect(Collectors.toList()));

    try (final PrintWriter writer = new PrintWriter(f)) {
        writer.println(String.join(",", headers));

        final List<Entry> sorted = new ArrayList<>(entries());
        Collections.sort(sorted, (o1, o2) -> o1.getResourceName().compareTo(o2.getResourceName()));

        sorted.forEach(e -> {
            writer.write(e.getResourceName());
            writer.write(",");
            final List<String> compatibleList = new ArrayList<>();
            compatibilities.forEach(c -> compatibleList.add(Boolean.toString(e.isCompatibleWith(c))));
            writer.println(String.join(",", compatibleList));
        });
    }
}

From source file:com.thinkbiganalytics.feedmgr.rest.controller.TemplatesRestController.java

@GET
@Path("/registered/{templateId}/actions/change")
@Produces(MediaType.APPLICATION_JSON)/*from  w ww .  j  a v  a  2s.  c  om*/
@ApiOperation("Constructs and returns a permission change request for a set of users/groups containing the actions that the requester may permit or revoke.")
@ApiResponses({
        @ApiResponse(code = 200, message = "Returns the change request that may be modified by the client and re-posted.", response = PermissionsChange.class),
        @ApiResponse(code = 400, message = "The type is not valid.", response = RestResponseStatus.class),
        @ApiResponse(code = 404, message = "No template exists with the specified ID.", response = RestResponseStatus.class) })
public Response getAllowedPermissionsChange(@PathParam("templateId") String templateIdStr,
        @QueryParam("type") String changeType, @QueryParam("user") Set<String> userNames,
        @QueryParam("group") Set<String> groupNames) {
    if (StringUtils.isBlank(changeType)) {
        throw new WebApplicationException("The query parameter \"type\" is required", Status.BAD_REQUEST);
    }

    Set<? extends Principal> users = Arrays.stream(this.securityTransform.asUserPrincipals(userNames))
            .collect(Collectors.toSet());
    Set<? extends Principal> groups = Arrays.stream(this.securityTransform.asGroupPrincipals(groupNames))
            .collect(Collectors.toSet());

    return this.securityService
            .createTemplatePermissionChange(templateIdStr, ChangeType.valueOf(changeType.toUpperCase()),
                    Stream.concat(users.stream(), groups.stream()).collect(Collectors.toSet()))
            .map(p -> Response.ok(p).build()).orElseThrow(() -> new WebApplicationException(
                    "A template with the given ID does not exist: " + templateIdStr, Status.NOT_FOUND));
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.IkanowV1SyncService_Buckets.java

/** Builds a V2 bucket out of a V1 source
 * @param src_json/*w  ww.j a  v  a2  s  .c  o  m*/
 * @return
 * @throws JsonParseException
 * @throws JsonMappingException
 * @throws IOException
 * @throws ParseException
 */
protected static DataBucketBean getBucketFromV1Source(final JsonNode src_json)
        throws JsonParseException, JsonMappingException, IOException, ParseException {
    // (think we'll use key instead of _id):
    //final String _id = safeJsonGet(JsonUtils._ID, src_json).asText(); 
    final String key = safeJsonGet("key", src_json).asText();
    final String created = safeJsonGet("created", src_json).asText();
    final String modified = safeJsonGet("modified", src_json).asText();
    final String title = safeJsonGet("title", src_json).asText();
    final String description = safeJsonGet("description", src_json).asText();
    final String owner_id = safeJsonGet("ownerId", src_json).asText();

    final JsonNode tags = safeJsonGet("tags", src_json); // collection of strings
    //final JsonNode comm_ids = safeJsonGet("communityIds", src_json); // collection of strings
    final JsonNode px_pipeline = safeJsonGet("processingPipeline", src_json); // collection of JSON objects, first one should have data_bucket
    final JsonNode px_pipeline_first_el = ((ObjectNode) px_pipeline.get(0))
            .without(Arrays.asList("test_params"));
    final JsonNode data_bucket_tmp = safeJsonGet("data_bucket", px_pipeline_first_el);// (WARNING: mutable, see below)
    final JsonNode scripting = safeJsonGet("scripting", data_bucket_tmp);

    // HANDLE SUBSTITUTION
    final String sub_prefix = Optional.ofNullable(scripting.get("sub_prefix")).map(x -> x.asText())
            .orElse("$$SCRIPT_");
    final String sub_suffix = Optional.ofNullable(scripting.get("sub_suffix")).map(x -> x.asText())
            .orElse("$$");
    final List<UnaryOperator<String>> search_replace = StreamSupport
            .stream(Spliterators.spliteratorUnknownSize(scripting.fieldNames(), Spliterator.ORDERED), false)
            .filter(f -> !f.equals("sub_prefix") && !f.equals("sub_suffix")) // (remove non language fields)
            .map(lang -> Tuples._2T(scripting.get(lang), lang))
            // Get (separator regex, entire script, sub prefix)
            .map(scriptobj_lang -> Tuples._3T(safeJsonGet("separator_regex", scriptobj_lang._1()).asText(),
                    safeJsonGet("script", scriptobj_lang._1()).asText(), sub_prefix + scriptobj_lang._2()))
            // Split each "entire script" up into blocks of format (bloc, lang)
            .<Stream<Tuple2<String, String>>>map(regex_script_lang -> Stream.concat(
                    Stream.of(Tuples._2T(regex_script_lang._2(), regex_script_lang._3())),
                    regex_script_lang._1().isEmpty()
                            ? Stream.of(Tuples._2T(regex_script_lang._2(), regex_script_lang._3()))
                            : Arrays.stream(regex_script_lang._2().split(regex_script_lang._1()))
                                    .<Tuple2<String, String>>map(s -> Tuples._2T(s, regex_script_lang._3()))))
            // Associate a per-lang index with each  script block -> (replacement, string_sub)
            .<Tuple2<String, String>>flatMap(stream -> StreamUtils.zip(stream, Stream.iterate(0, i -> i + 1),
                    (script_lang, i) -> Tuples._2T(
                            script_lang._1().replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r"),
                            i == 0 ? script_lang._2() + sub_suffix // (entire thing)
                                    : script_lang._2() + "_" + i + sub_suffix))) //(broken down components)

            .<UnaryOperator<String>>map(t2 -> (String s) -> s.replace(t2._2(), t2._1()))
            //(need to escape "s and newlines)
            .collect(Collectors.toList());

    // Apply the list of transforms to the string
    ((ObjectNode) data_bucket_tmp).remove("scripting"); // (WARNING: mutable)
    final String data_bucket_str = search_replace.stream().reduce(data_bucket_tmp.toString(),
            (acc, s) -> s.apply(acc), (acc1, acc2) -> acc1);

    // Convert back to the bucket JSON
    final JsonNode data_bucket = ((ObjectNode) _mapper.readTree(data_bucket_str))
            .without(Arrays.asList("test_params"));

    final DataBucketBean bucket = BeanTemplateUtils.build(data_bucket, DataBucketBean.class)
            .with(DataBucketBean::_id, getBucketIdFromV1SourceKey(key))
            .with(DataBucketBean::created, parseJavaDate(created))
            .with(DataBucketBean::modified, parseJavaDate(modified)).with(DataBucketBean::display_name, title)
            .with(DataBucketBean::description, description).with(DataBucketBean::owner_id, owner_id)
            .with(DataBucketBean::tags, StreamSupport.stream(tags.spliterator(), false).map(jt -> jt.asText())
                    .collect(Collectors.toSet()))
            .done().get();

    return bucket;

}

From source file:com.ikanow.aleph2.analytics.services.AnalyticsContext.java

@Override
public Collection<Object> getUnderlyingArtefacts() {
    if (_state_name == State.IN_TECHNOLOGY) {
        if (!_mutable_state.service_manifest_override.isSet()) {
            throw new RuntimeException(ErrorUtils.SERVICE_RESTRICTIONS);
        }//from   ww w  . j  av a 2s .  c o m
        return Stream.concat(Stream.of(this, _service_context, new SharedErrorUtils()) //(last one gives us the core_shared_lib)
                ,
                _mutable_state.service_manifest_override.get().stream()
                        .map(t2 -> _service_context.getService(t2._1(), t2._2()))
                        .filter(service -> service.isPresent())
                        .flatMap(service -> service.get().getUnderlyingArtefacts().stream()))
                .collect(Collectors.toSet());
    } else {
        throw new RuntimeException(ErrorUtils.TECHNOLOGY_NOT_MODULE);
    }
}

From source file:alfio.manager.EventManager.java

MapSqlParameterSource[] prepareTicketsBulkInsertParameters(ZonedDateTime creation, Event event,
        int requestedTickets, TicketStatus ticketStatus) {

    //FIXME: the date should be inserted as ZonedDateTime !
    Date creationDate = Date.from(creation.toInstant());

    List<TicketCategory> categories = ticketCategoryRepository.findByEventId(event.getId());
    Stream<MapSqlParameterSource> boundedTickets = categories.stream().filter(IS_CATEGORY_BOUNDED)
            .flatMap(tc -> generateTicketsForCategory(tc, event, creationDate, 0));
    int generatedTickets = categories.stream().filter(IS_CATEGORY_BOUNDED)
            .mapToInt(TicketCategory::getMaxTickets).sum();
    if (generatedTickets >= requestedTickets) {
        return boundedTickets.toArray(MapSqlParameterSource[]::new);
    }//w  w w  .j  ava  2 s  .  c  o m

    return Stream.concat(boundedTickets,
            generateEmptyTickets(event, creationDate, requestedTickets - generatedTickets, ticketStatus))
            .toArray(MapSqlParameterSource[]::new);
}

From source file:com.adobe.acs.commons.mcp.impl.processes.renovator.Renovator.java

private Stream<String> getAllReplicationPaths() {
    return Stream.concat(replicatorQueue.getActivateOperations().keySet().stream(),
            replicatorQueue.getDeactivateOperations().keySet().stream()).distinct();
}