Example usage for java.util Optional ifPresent

List of usage examples for java.util Optional ifPresent

Introduction

In this page you can find the example usage for java.util Optional ifPresent.

Prototype

public void ifPresent(Consumer<? super T> action) 

Source Link

Document

If a value is present, performs the given action with the value, otherwise does nothing.

Usage

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

@Override
public void onStageInitialize(final IEnrichmentModuleContext context, final DataBucketBean bucket,
        final EnrichmentControlMetadataBean dedup_control,
        final Tuple2<ProcessingStage, ProcessingStage> previous_next,
        final Optional<List<String>> next_grouping_fields) {
    _context.set(context);//from   w ww  .ja v a2s  .c  o m
    _control.set(dedup_control);

    context.getServiceContext().getService(ILoggingService.class, Optional.empty())
            .map(s -> s.getSystemLogger(bucket)).ifPresent(logger -> _logger.set(logger));

    final DedupConfigBean dedup_config = BeanTemplateUtils
            .from(Optional.ofNullable(dedup_control.config()).orElse(Collections.emptyMap()),
                    DedupConfigBean.class)
            .get();

    final DocumentSchemaBean doc_schema = Optional.ofNullable(dedup_config.doc_schema_override())
            .orElse(bucket.data_schema().document_schema()); //(exists by construction)
    _is_system_dedup_stage.set(null == dedup_config.doc_schema_override());

    _deduplication_is_disabled.set((null == doc_schema.deduplication_policy())
            && Optionals.ofNullable(doc_schema.deduplication_fields()).isEmpty()
            && Optionals.ofNullable(doc_schema.deduplication_contexts()).isEmpty());

    // override defaults:
    _doc_schema.set(BeanTemplateUtils.clone(doc_schema)
            .with(DocumentSchemaBean::enabled, Optional.ofNullable(doc_schema.enabled()).orElse(true))
            .with(DocumentSchemaBean::deduplication_timing,
                    Optional.ofNullable(doc_schema.deduplication_timing()).orElse(DeduplicationTiming.custom))
            .with(DocumentSchemaBean::deduplication_policy,
                    Optional.ofNullable(doc_schema.deduplication_policy()).orElse(DeduplicationPolicy.leave))
            .with(DocumentSchemaBean::custom_policy,
                    Optional.ofNullable(doc_schema.custom_policy()).orElse(CustomPolicy.strict))
            .with(DocumentSchemaBean::custom_finalize_all_objects,
                    Optional.ofNullable(doc_schema.custom_finalize_all_objects()).orElse(false))
            .with(DocumentSchemaBean::delete_unhandled_duplicates,
                    Optional.ofNullable(doc_schema.delete_unhandled_duplicates())
                            .orElse(CustomPolicy.very_strict == Optional.ofNullable(doc_schema.custom_policy())
                                    .orElse(CustomPolicy.strict)))
            .with(DocumentSchemaBean::allow_manual_deletion,
                    Optional.ofNullable(doc_schema.allow_manual_deletion()).orElse(false))
            .done());

    final String timestamp_field = Optionals.of(() -> bucket.data_schema().temporal_schema().time_field())
            .orElseGet(() -> AnnotationBean.ROOT_PATH + ".tp");
    _timestamp_field.set(timestamp_field);

    final DataBucketBean context_holder = Optional.ofNullable(doc_schema.deduplication_contexts())
            .filter(l -> !l.isEmpty()) // (if empty or null then fall back to...)            
            .map(contexts -> BeanTemplateUtils.build(DataBucketBean.class)
                    .with(DataBucketBean::multi_bucket_children,
                            ImmutableSet.<String>builder().addAll(contexts).build())
                    .done().get())
            .orElse(bucket);

    //(valid by construction - see validateSchema)
    final Validation<String, Tuple2<Optional<Class<? extends IUnderlyingService>>, Optional<String>>> service_to_use = getDataService(
            _doc_schema.get());

    // Get secured data service -> CRUD for id checking and deletion
    final Optional<ICrudService<JsonNode>> maybe_read_crud = context.getServiceContext()
            .getService(service_to_use.success()._1().get(), service_to_use.success()._2())
            .map(ds -> ((IDataServiceProvider) ds)
                    .secured(context.getServiceContext(), new AuthorizationBean(bucket.owner_id())))
            .flatMap(ds -> ds.getDataService())
            .flatMap(ds -> _doc_schema.get().delete_unhandled_duplicates()
                    || _doc_schema.get().allow_manual_deletion()
                            ? ds.getUpdatableCrudService(JsonNode.class, Arrays.asList(context_holder),
                                    Optional.empty())
                            : ds.getReadableCrudService(JsonNode.class, Arrays.asList(context_holder),
                                    Optional.empty()).map(crud -> (ICrudService<JsonNode>) crud))
    //(just ensure it has a read/update interface even though the update might not be used)
    ;

    maybe_read_crud.ifPresent(read_crud -> _dedup_context.set(read_crud));

    //TODO (ALEPH-20): move this into the DB (See related top level comment)
    final ElasticsearchTechnologyOverride tech_override = BeanTemplateUtils.from(
            Optional.ofNullable(_doc_schema.get().technology_override_schema()).orElse(Collections.emptyMap()),
            ElasticsearchTechnologyOverride.class).get();

    _db_mapper.set(f -> {
        return AnnotationBean._ID.equals(f) ? f
                : tech_override.field_override().getOrDefault(f.replace(".", ":"),
                        f + tech_override.default_modifier());
    });

    _dedup_fields.set(Optional.ofNullable(_doc_schema.get().deduplication_fields())
            .orElse(Arrays.asList(AnnotationBean._ID)));
    _policy.set(
            Optional.ofNullable(_doc_schema.get().deduplication_policy()).orElse(DeduplicationPolicy.leave));

    if ((DeduplicationPolicy.custom == _policy.get()) || (DeduplicationPolicy.custom_update == _policy.get())) {

        Optional<EnrichmentControlMetadataBean> custom_config = Optionals
                .ofNullable(_doc_schema.get().custom_deduplication_configs()).stream()
                .filter(cfg -> Optional.ofNullable(cfg.enabled()).orElse(true)).findFirst();

        custom_config.ifPresent(cfg -> {

            getEnrichmentModules(context, cfg).stream().findFirst()
                    .ifPresent(module -> _custom_handler.set(module));

            _custom_context.set(new DeduplicationEnrichmentContext(context, _doc_schema.get(),
                    j -> getKeyFieldsAgain(j, getKeyFields(_dedup_fields.get()))));

            _custom_handler.optional()
                    .ifPresent(base_module -> base_module.onStageInitialize(_custom_context.get(), bucket, cfg,
                            previous_next, next_grouping_fields));
        });
    }
}

From source file:alfio.manager.PaypalManager.java

public String createCheckoutRequest(Event event, String reservationId, OrderSummary orderSummary,
        CustomerName customerName, String email, String billingAddress, Locale locale,
        boolean postponeAssignment) throws Exception {

    APIContext apiContext = getApiContext(event);

    Optional<String> experienceProfileId = getOrCreateWebProfile(event, locale, apiContext);

    List<Transaction> transactions = buildPaymentDetails(event, orderSummary, reservationId, locale);
    String eventName = event.getShortName();

    Payer payer = new Payer();
    payer.setPaymentMethod("paypal");

    Payment payment = new Payment();
    payment.setIntent("sale");
    payment.setPayer(payer);/*from  www .j  a va2s  .  c  o  m*/
    payment.setTransactions(transactions);
    RedirectUrls redirectUrls = new RedirectUrls();

    String baseUrl = StringUtils.removeEnd(
            configurationManager.getRequiredValue(
                    Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.BASE_URL)),
            "/");
    String bookUrl = baseUrl + "/event/" + eventName + "/reservation/" + reservationId + "/book";

    UriComponentsBuilder bookUrlBuilder = UriComponentsBuilder.fromUriString(bookUrl)
            .queryParam("fullName", customerName.getFullName())
            .queryParam("firstName", customerName.getFirstName())
            .queryParam("lastName", customerName.getLastName()).queryParam("email", email)
            .queryParam("billingAddress", billingAddress).queryParam("postponeAssignment", postponeAssignment)
            .queryParam("hmac", computeHMAC(customerName, email, billingAddress, event));
    String finalUrl = bookUrlBuilder.toUriString();

    redirectUrls.setCancelUrl(finalUrl + "&paypal-cancel=true");
    redirectUrls.setReturnUrl(finalUrl + "&paypal-success=true");
    payment.setRedirectUrls(redirectUrls);

    experienceProfileId.ifPresent(payment::setExperienceProfileId);

    Payment createdPayment = payment.create(apiContext);

    TicketReservation reservation = ticketReservationRepository.findReservationById(reservationId);
    //add 15 minutes of validity in case the paypal flow is slow
    ticketReservationRepository.updateValidity(reservationId,
            DateUtils.addMinutes(reservation.getValidity(), 15));

    if (!"created".equals(createdPayment.getState())) {
        throw new Exception(createdPayment.getFailureReason());
    }

    //extract url for approval
    return createdPayment.getLinks().stream().filter(l -> "approval_url".equals(l.getRel())).findFirst()
            .map(Links::getHref).orElseThrow(IllegalStateException::new);

}

From source file:com.cloudbees.jenkins.support.SupportPlugin.java

public static void writeBundle(OutputStream outputStream, final List<Component> components) throws IOException {
    StringBuilder manifest = new StringBuilder();
    StringWriter errors = new StringWriter();
    PrintWriter errorWriter = new PrintWriter(errors);
    appendManifestHeader(manifest);//from   ww  w .j  av  a 2s. c om
    List<Content> contents = appendManifestContents(manifest, errorWriter, components);
    contents.add(new StringContent("manifest.md", manifest.toString()));
    try {
        try (BulkChange change = new BulkChange(ContentMappings.get());
                ZipArchiveOutputStream binaryOut = new ZipArchiveOutputStream(
                        new BufferedOutputStream(outputStream, 16384))) {
            Optional<ContentFilter> maybeFilter = getContentFilter();
            Optional<FilteredOutputStream> maybeFilteredOut = maybeFilter
                    .map(filter -> new FilteredOutputStream(binaryOut, filter));
            OutputStream textOut = maybeFilteredOut.map(OutputStream.class::cast).orElse(binaryOut);
            OutputStreamSelector selector = new OutputStreamSelector(() -> binaryOut, () -> textOut);
            IgnoreCloseOutputStream unfilteredOut = new IgnoreCloseOutputStream(binaryOut);
            IgnoreCloseOutputStream filteredOut = new IgnoreCloseOutputStream(selector);
            for (Content content : contents) {
                if (content == null) {
                    continue;
                }
                final String name = maybeFilter.map(filter -> filter.filter(content.getName()))
                        .orElseGet(content::getName);
                final ZipArchiveEntry entry = new ZipArchiveEntry(name);
                entry.setTime(content.getTime());
                try {
                    binaryOut.putArchiveEntry(entry);
                    binaryOut.flush();
                    OutputStream out = content.shouldBeFiltered() ? filteredOut : unfilteredOut;
                    if (content instanceof PrefilteredContent && maybeFilter.isPresent()) {
                        ((PrefilteredContent) content).writeTo(out, maybeFilter.get());
                    } else {
                        content.writeTo(out);
                    }
                    out.flush();
                } catch (Throwable e) {
                    String msg = "Could not attach ''" + name + "'' to support bundle";
                    logger.log(Level.WARNING, msg, e);
                    errorWriter.println(msg);
                    errorWriter
                            .println("-----------------------------------------------------------------------");
                    errorWriter.println();
                    SupportLogFormatter.printStackTrace(e, errorWriter);
                    errorWriter.println();
                } finally {
                    maybeFilteredOut.ifPresent(FilteredOutputStream::reset);
                    selector.reset();
                    binaryOut.closeArchiveEntry();
                }
            }
            errorWriter.close();
            String errorContent = errors.toString();
            if (StringUtils.isNotBlank(errorContent)) {
                try {
                    binaryOut.putArchiveEntry(new ZipArchiveEntry("manifest/errors.txt"));
                    textOut.write(errorContent.getBytes(StandardCharsets.UTF_8));
                    textOut.flush();
                    binaryOut.closeArchiveEntry();
                } catch (IOException e) {
                    logger.log(Level.WARNING, "Could not write manifest/errors.txt to zip archive", e);
                }
            }
            binaryOut.flush();
            change.commit();
        }
    } finally {
        outputStream.flush();
    }
}

From source file:com.github.lukaszbudnik.dqueue.QueueClientImpl.java

@Override
public Future<Optional<Item>> consume(Map<String, ?> filters) {
    if (filters == null) {
        throw new IllegalArgumentException(
                "Filters cannot be null, if no filters are to be used pass an empty map");
    }//  ww w.  ja  v a  2  s  .c  o m

    Future<Optional<Item>> itemFuture = executorService.submit(() -> {

        String filterNames;
        if (filters.isEmpty()) {
            filterNames = NO_FILTERS;
        } else {
            filterNames = String.join("_", filters.keySet());
        }

        String wholeOperationMetricName = "dqueue.consume." + filterNames + ".whole.timer";

        Optional<Timer.Context> consumeTimer = Optional.ofNullable(metricRegistry)
                .map(m -> m.timer(wholeOperationMetricName).time());

        InterProcessMutex interProcessMutex = new InterProcessMutex(zookeeperClient, "/dqueue/" + filterNames);

        try {
            String mutexAcquireOperationMetricName = "dqueue.consume." + filterNames + ".mutextAcquire.timer";
            executeAndMeasureTime(() -> interProcessMutex.acquire(), mutexAcquireOperationMetricName);

            String tableName = createTableIfNotExists("consume", filterNames, filters);

            Select.Where select = buildSelect(tableName, filters);
            String cassandraSelectOperationMetricName = "dqueue.consume." + filterNames
                    + ".cassandraSelect.timer";
            ResultSet resultSet = executeAndMeasureTime(() -> session.executeAsync(select).getUninterruptibly(),
                    cassandraSelectOperationMetricName);
            Row row = resultSet.one();

            if (row == null) {
                return Optional.empty();
            }

            UUID startTime = row.getUUID("start_time");
            ByteBuffer contents = row.getBytes("contents");

            Delete.Where delete = buildDelete(tableName, startTime, filters);

            String cassandraDeleteOperationMetricName = "dqueue.consume." + filterNames
                    + ".cassandraDelete.timer";
            executeAndMeasureTime(() -> session.executeAsync(delete).getUninterruptibly(),
                    cassandraDeleteOperationMetricName);

            return Optional.of(new Item(startTime, contents, filters));
        } finally {
            interProcessMutex.release();
            consumeTimer.ifPresent(Timer.Context::stop);
        }
    });

    return itemFuture;
}

From source file:blusunrize.immersiveengineering.api.energy.wires.ImmersiveNetHandler.java

public void removeConnection(World world, Connection con, Vec3d vecStart, Vec3d vecEnd) {
    if (con == null || world == null)
        return;//w w w. j  a va 2  s .co  m
    int dim = world.provider.getDimension();
    resetCachedIndirectConnections(world, con.start);
    Map<BlockPos, Set<Connection>> connsInDim = getMultimap(world.provider.getDimension());
    Set<Connection> reverseConns = connsInDim.get(con.end);
    Set<Connection> forwardConns = connsInDim.get(con.start);
    Optional<Connection> back = reverseConns.stream().filter(con::hasSameConnectors).findAny();
    reverseConns.removeIf(con::hasSameConnectors);
    forwardConns.removeIf(con::hasSameConnectors);
    Map<BlockPos, BlockWireInfo> mapForDim = blockWireMap.lookup(world.provider.getDimension());
    BiConsumer<BlockPos, Map<BlockPos, BlockWireInfo>> handle = (p, map) -> {
        if (mapForDim != null) {
            BlockWireInfo info = map.get(p);
            if (info != null) {
                for (int i = 0; i < 2; i++) {
                    Set<Triple<Connection, Vec3d, Vec3d>> s = i == 0 ? info.in : info.near;
                    s.removeIf((t) -> t.getLeft().hasSameConnectors(con));
                    if (s.isEmpty())
                        map.remove(p);
                }
                if (info.near.isEmpty() && info.in.isEmpty())
                    map.remove(p);
            }
        }
    };
    raytraceAlongCatenaryRelative(con, (p) -> {
        handle.accept(p.getLeft(), mapForDim);
        return false;
    }, (p) -> handle.accept(p.getLeft(), mapForDim), vecStart, vecEnd);

    IImmersiveConnectable iic = toIIC(con.end, world);
    if (iic != null) {
        iic.removeCable(con);
        back.ifPresent(iic::removeCable);
    }
    iic = toIIC(con.start, world);
    if (iic != null) {
        iic.removeCable(con);
        back.ifPresent(iic::removeCable);
    }

    if (world.isBlockLoaded(con.start))
        world.addBlockEvent(con.start, world.getBlockState(con.start).getBlock(), -1, 0);
    if (world.isBlockLoaded(con.end))
        world.addBlockEvent(con.end, world.getBlockState(con.end).getBlock(), -1, 0);

    IESaveData.setDirty(dim);
}

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

@SuppressWarnings("unchecked")
@Test/*from  ww  w.  j  av a2s .  c  o  m*/
public void test_buildGraph_handleMerge() {
    // Titan
    final TitanGraph titan = getSimpleTitanGraph();
    final org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper titan_mapper = titan.io(IoCore.graphson())
            .mapper().create().createMapper();
    TitanManagement mgmt = titan.openManagement();
    mgmt.makePropertyKey(GraphAnnotationBean.a2_p).dataType(String.class).cardinality(Cardinality.SET).make();
    mgmt.commit();
    // Graph schema
    final GraphSchemaBean graph_schema = BeanTemplateUtils.build(GraphSchemaBean.class)
            .with(GraphSchemaBean::deduplication_fields,
                    Arrays.asList(GraphAnnotationBean.name, GraphAnnotationBean.type))
            .with(GraphSchemaBean::custom_finalize_all_objects, false).done().get();
    // Security service
    final MockSecurityService mock_security = new MockSecurityService();
    final String user = "nobody";
    mock_security.setGlobalMockRole("nobody:DataBucketBean:read,write:test:security:*", true);
    mock_security.setGlobalMockRole(
            "nobody:DataBucketBean:read,write:aleph2_testing:other_user:test:security:*", true); // (equivalent for test bucket)
    // Bucket
    final DataBucketBean bucket = BeanTemplateUtils.build(DataBucketBean.class)
            .with(DataBucketBean::full_name, "/test/security").done().get();
    // Simple merger
    final IEnrichmentModuleContext delegate_context = Mockito.mock(IEnrichmentModuleContext.class);
    Mockito.when(delegate_context.getNextUnusedId()).thenReturn(0L);
    final Optional<Tuple2<IEnrichmentBatchModule, GraphMergeEnrichmentContext>> maybe_merger = Optional
            .of(Tuples._2T((IEnrichmentBatchModule) new SimpleGraphMergeService(),
                    new GraphMergeEnrichmentContext(delegate_context, graph_schema)));
    maybe_merger.ifPresent(t2 -> t2._1().onStageInitialize(t2._2(), null, null, null, null));
    // Stream of incoming objects

    // State:
    final LinkedList<ObjectNode> mutable_new_element_keys = new LinkedList<>();
    final MutableStatsBean mutable_stats = new MutableStatsBean();

    // Call merge with empty graph
    {
        final List<ObjectNode> vertices_and_edges = test_buildGraph_getUserGeneratedAssets_run();

        final TitanTransaction tx = titan.buildTransaction().start();

        // (tested in test_buildGraph_collectUserGeneratedAssets, assumed to work here)
        final Stream<Tuple4<ObjectNode, List<ObjectNode>, List<ObjectNode>, List<Vertex>>> ret_val_s = TitanGraphBuildingUtils
                .buildGraph_collectUserGeneratedAssets(tx, graph_schema, Tuples._2T(user, mock_security),
                        Optional.empty(), bucket, mutable_stats, vertices_and_edges.stream());

        TitanGraphBuildingUtils.buildGraph_handleMerge(tx, graph_schema, Tuples._2T(user, mock_security),
                Optional.empty(), mutable_stats, mutable_new_element_keys, maybe_merger, bucket, ret_val_s);

        // Check graph
        assertEquals(2, StreamUtils.stream(tx.query().has(GraphAnnotationBean.type, "ip").vertices()).count());
        assertEquals(3,
                StreamUtils.stream(tx.query().has(GraphAnnotationBean.type, "host").vertices()).count());
        assertEquals(5, StreamUtils.stream(tx.query().edges()).count());

        // Check stats
        assertEquals(5L, mutable_stats.vertices_created);
        assertEquals(0L, mutable_stats.vertices_updated);
        assertEquals(5L, mutable_stats.vertices_emitted);
        assertEquals(0L, mutable_stats.vertex_matches_found);
        assertEquals(0L, mutable_stats.vertex_errors);
        assertEquals(5L, mutable_stats.edges_created);
        assertEquals(0L, mutable_stats.edges_updated);
        assertEquals(6L, mutable_stats.edges_emitted);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.edge_errors);

        //(delete everything read for next test)
        mutable_stats.reset();
        tx.vertices().forEachRemaining(v -> v.remove());
        tx.edges().forEachRemaining(v -> v.remove());
        tx.commit();
    }
    // With some existing edges and vertices
    {
        final List<ObjectNode> vertices_and_edges = test_buildGraph_getUserGeneratedAssets_run();

        final TitanTransaction tx = titan.buildTransaction().start();
        rebuildSimpleGraph(tx, bucket.full_name());

        // (tested in test_buildGraph_collectUserGeneratedAssets, assumed to work here)
        final Stream<Tuple4<ObjectNode, List<ObjectNode>, List<ObjectNode>, List<Vertex>>> ret_val_s = TitanGraphBuildingUtils
                .buildGraph_collectUserGeneratedAssets(tx, graph_schema, Tuples._2T(user, mock_security),
                        Optional.empty(), bucket, mutable_stats, vertices_and_edges.stream());

        TitanGraphBuildingUtils.buildGraph_handleMerge(tx, graph_schema, Tuples._2T(user, mock_security),
                Optional.empty(), mutable_stats, mutable_new_element_keys, maybe_merger, bucket, ret_val_s);

        // Check graph
        assertEquals(2, StreamUtils.stream(tx.query().has(GraphAnnotationBean.type, "ip").vertices()).count());
        assertEquals(3,
                StreamUtils.stream(tx.query().has(GraphAnnotationBean.type, "host").vertices()).count());
        assertEquals(
                "Should have the right number of edges: " + StreamUtils.stream(tx.query().edges())
                        .map(e -> titan_mapper
                                .convertValue(e, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.joining("\n")),
                6, StreamUtils.stream(tx.query().edges()).count()); //(+1 for the extra "wrong type" one i added)

        // Check stats
        assertEquals(3L, mutable_stats.vertices_created);
        assertEquals(2L, mutable_stats.vertices_updated);
        assertEquals(5L, mutable_stats.vertices_emitted);
        assertEquals(2L, mutable_stats.vertex_matches_found);
        assertEquals(0L, mutable_stats.vertex_errors);
        assertEquals(4L, mutable_stats.edges_created);
        assertEquals(1L, mutable_stats.edges_updated);
        assertEquals(6L, mutable_stats.edges_emitted);
        assertEquals(1L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.edge_errors);

        //(delete everything read for next test)
        mutable_stats.reset();
        tx.vertices().forEachRemaining(v -> v.remove());
        tx.edges().forEachRemaining(v -> v.remove());
        tx.commit();
    }
    // Existing elements, but will be ignored because in test mode
    {
        final DataBucketBean test_bucket = BucketUtils.convertDataBucketBeanToTest(
                BeanTemplateUtils.clone(bucket).with(DataBucketBean::full_name, "/something/else").done(), // (needs different name) 
                "nobody");

        final List<ObjectNode> vertices_and_edges = test_buildGraph_getUserGeneratedAssets_run();

        final TitanTransaction tx = titan.buildTransaction().start();
        rebuildSimpleGraph(tx, bucket.full_name());

        // (tested in test_buildGraph_collectUserGeneratedAssets, assumed to work here)
        final Stream<Tuple4<ObjectNode, List<ObjectNode>, List<ObjectNode>, List<Vertex>>> ret_val_s = TitanGraphBuildingUtils
                .buildGraph_collectUserGeneratedAssets(tx, graph_schema, Tuples._2T(user, mock_security),
                        Optional.empty(), test_bucket, mutable_stats, vertices_and_edges.stream());

        TitanGraphBuildingUtils.buildGraph_handleMerge(tx, graph_schema, Tuples._2T(user, mock_security),
                Optional.empty(), mutable_stats, mutable_new_element_keys, maybe_merger, bucket, ret_val_s);

        // Check graph
        assertEquals(3, StreamUtils.stream(tx.query().has(GraphAnnotationBean.type, "ip").vertices()).count()); //(+1 for the existing node that _doesn't_ get merged because of the test mode)
        assertEquals(4,
                StreamUtils.stream(tx.query().has(GraphAnnotationBean.type, "host").vertices()).count()); //(+1 for the existing node that _doesn't_ get merged because of the test mode)
        assertEquals(
                "Should have the right number of edges: " + StreamUtils.stream(tx.query().edges())
                        .map(e -> titan_mapper
                                .convertValue(e, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.joining("\n")),
                7, StreamUtils.stream(tx.query().edges()).count()); //(+1 for the extra "wrong type" one i added, +1 for the existing edge that _doesn't_ get merged because of the test mode)

        // Check stats
        assertEquals(5L, mutable_stats.vertices_created);
        assertEquals(0L, mutable_stats.vertices_updated);
        assertEquals(5L, mutable_stats.vertices_emitted);
        assertEquals(0L, mutable_stats.vertex_matches_found);
        assertEquals(0L, mutable_stats.vertex_errors);
        assertEquals(5L, mutable_stats.edges_created);
        assertEquals(0L, mutable_stats.edges_updated);
        assertEquals(6L, mutable_stats.edges_emitted);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.edge_errors);

        //(delete everything read for next test)
        mutable_stats.reset();
        tx.vertices().forEachRemaining(v -> v.remove());
        tx.edges().forEachRemaining(v -> v.remove());
        tx.commit();
    }
    // Existing elents, but will be ignored because _they_ are from a test mode... 
    {

        final List<ObjectNode> vertices_and_edges = test_buildGraph_getUserGeneratedAssets_run();

        final TitanTransaction tx = titan.buildTransaction().start();
        {
            //(just make sure i don't accidentally run with test_bucket)
            final DataBucketBean test_bucket = BucketUtils.convertDataBucketBeanToTest(bucket, "other_user");
            rebuildSimpleGraph(tx, test_bucket.full_name());
        }

        // (tested in test_buildGraph_collectUserGeneratedAssets, assumed to work here)
        final Stream<Tuple4<ObjectNode, List<ObjectNode>, List<ObjectNode>, List<Vertex>>> ret_val_s = TitanGraphBuildingUtils
                .buildGraph_collectUserGeneratedAssets(tx, graph_schema, Tuples._2T(user, mock_security),
                        Optional.empty(), bucket, mutable_stats, vertices_and_edges.stream());

        TitanGraphBuildingUtils.buildGraph_handleMerge(tx, graph_schema, Tuples._2T(user, mock_security),
                Optional.empty(), mutable_stats, mutable_new_element_keys, maybe_merger, bucket, ret_val_s);

        // Check graph
        assertEquals(3, StreamUtils.stream(tx.query().has(GraphAnnotationBean.type, "ip").vertices()).count()); //(+1 for the existing node that _doesn't_ get merged because of the test mode)
        assertEquals(4,
                StreamUtils.stream(tx.query().has(GraphAnnotationBean.type, "host").vertices()).count()); //(+1 for the existing node that _doesn't_ get merged because of the test mode)
        assertEquals(
                "Should have the right number of edges: " + StreamUtils.stream(tx.query().edges())
                        .map(e -> titan_mapper
                                .convertValue(e, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.joining("\n")),
                7, StreamUtils.stream(tx.query().edges()).count()); //(+1 for the extra "wrong type" one i added, +1 for the existing edge that _doesn't_ get merged because of the test mode)

        // Check stats
        assertEquals(5L, mutable_stats.vertices_created);
        assertEquals(0L, mutable_stats.vertices_updated);
        assertEquals(5L, mutable_stats.vertices_emitted);
        assertEquals(0L, mutable_stats.vertex_matches_found);
        assertEquals(0L, mutable_stats.vertex_errors);
        assertEquals(5L, mutable_stats.edges_created);
        assertEquals(0L, mutable_stats.edges_updated);
        assertEquals(6L, mutable_stats.edges_emitted);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.edge_errors);

        //(delete everything read for next test)
        mutable_stats.reset();
        tx.vertices().forEachRemaining(v -> v.remove());
        tx.edges().forEachRemaining(v -> v.remove());
        tx.commit();
    }
    // Existing elements, but will be ignored because security is turned off
    {
        mock_security.setGlobalMockRole("nobody:DataBucketBean:read,write:test:security:*", false);

        final List<ObjectNode> vertices_and_edges = test_buildGraph_getUserGeneratedAssets_run();

        final TitanTransaction tx = titan.buildTransaction().start();
        rebuildSimpleGraph(tx, bucket.full_name());

        // (tested in test_buildGraph_collectUserGeneratedAssets, assumed to work here)
        final Stream<Tuple4<ObjectNode, List<ObjectNode>, List<ObjectNode>, List<Vertex>>> ret_val_s = TitanGraphBuildingUtils
                .buildGraph_collectUserGeneratedAssets(tx, graph_schema, Tuples._2T(user, mock_security),
                        Optional.empty(), bucket, mutable_stats, vertices_and_edges.stream());

        TitanGraphBuildingUtils.buildGraph_handleMerge(tx, graph_schema, Tuples._2T(user, mock_security),
                Optional.empty(), mutable_stats, mutable_new_element_keys, maybe_merger, bucket, ret_val_s);

        // Check graph
        assertEquals(3, StreamUtils.stream(tx.query().has(GraphAnnotationBean.type, "ip").vertices()).count()); //(+1 for the existing node that _doesn't_ get merged because of the test mode)
        assertEquals(4,
                StreamUtils.stream(tx.query().has(GraphAnnotationBean.type, "host").vertices()).count()); //(+1 for the existing node that _doesn't_ get merged because of the test mode)
        assertEquals(
                "Should have the right number of edges: " + StreamUtils.stream(tx.query().edges())
                        .map(e -> titan_mapper
                                .convertValue(e, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.joining("\n")),
                7, StreamUtils.stream(tx.query().edges()).count()); //(+1 for the extra "wrong type" one i added, +1 for the existing edge that _doesn't_ get merged because of the test mode)

        // Check stats
        assertEquals(5L, mutable_stats.vertices_created);
        assertEquals(0L, mutable_stats.vertices_updated);
        assertEquals(5L, mutable_stats.vertices_emitted);
        assertEquals(0L, mutable_stats.vertex_matches_found);
        assertEquals(0L, mutable_stats.vertex_errors);
        assertEquals(5L, mutable_stats.edges_created);
        assertEquals(0L, mutable_stats.edges_updated);
        assertEquals(6L, mutable_stats.edges_emitted);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.edge_errors);

        //(delete everything read for next test)
        mutable_stats.reset();
        tx.vertices().forEachRemaining(v -> v.remove());
        tx.edges().forEachRemaining(v -> v.remove());
        tx.commit();
    }
}

From source file:alfio.manager.TicketReservationManager.java

/**
 * Set the tickets attached to the reservation to the ACQUIRED state and the ticket reservation to the COMPLETE state. Additionally it will save email/fullName/billingaddress/userLanguage.
 *///from   www  .ja  v a 2  s.  co  m
void completeReservation(int eventId, String reservationId, String email, CustomerName customerName,
        Locale userLanguage, String billingAddress, Optional<String> specialPriceSessionId,
        PaymentProxy paymentProxy) {
    if (paymentProxy != PaymentProxy.OFFLINE) {
        TicketStatus ticketStatus = paymentProxy.isDeskPaymentRequired() ? TicketStatus.TO_BE_PAID
                : TicketStatus.ACQUIRED;
        AdditionalServiceItemStatus asStatus = paymentProxy.isDeskPaymentRequired()
                ? AdditionalServiceItemStatus.TO_BE_PAID
                : AdditionalServiceItemStatus.ACQUIRED;
        acquireItems(ticketStatus, asStatus, paymentProxy, reservationId, email, customerName,
                userLanguage.getLanguage(), billingAddress, eventId);
        final TicketReservation reservation = ticketReservationRepository.findReservationById(reservationId);
        pluginManager.handleReservationConfirmation(reservation, eventId);
        extensionManager.handleReservationConfirmation(reservation, eventId);
        //cleanup unused special price codes...
        specialPriceSessionId.ifPresent(specialPriceRepository::unbindFromSession);
    }

    auditingRepository.insert(reservationId, null, eventId, Audit.EventType.RESERVATION_COMPLETE, new Date(),
            Audit.EntityType.RESERVATION, reservationId);
}

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

@SuppressWarnings("unchecked")
@Test/*from w w w  .  j  av a 2 s.c  o  m*/
public void test_invokeUserMergeCode() {
    // (Also tests addGraphSON2Graph)
    // (Also tests insertProperties)
    // (Also tests denestProperties)

    // This has a massive set of params, here we go:
    final TitanGraph titan = getSimpleTitanGraph();
    TitanManagement mgmt = titan.openManagement();
    mgmt.makePropertyKey(GraphAnnotationBean.a2_p).dataType(String.class).cardinality(Cardinality.SET).make();
    mgmt.commit();
    final TitanTransaction tx = titan.buildTransaction().start();
    final Vertex v1 = tx.addVertex("existing_1");
    v1.property("existing", true);
    final Vertex v2 = tx.addVertex("existing_2");
    v2.property("existing", true);
    final Edge e1 = v1.addEdge("existing_1_2", v2);
    e1.property("existing", true);
    final Edge e2 = v2.addEdge("existing_2_1", v1);
    e2.property("existing", true);
    // Graph schema
    final GraphSchemaBean graph_schema = BeanTemplateUtils.build(GraphSchemaBean.class)
            .with(GraphSchemaBean::deduplication_fields,
                    Arrays.asList(GraphAnnotationBean.name, GraphAnnotationBean.type))
            .with(GraphSchemaBean::custom_finalize_all_objects, false).done().get();
    // Security service
    final MockSecurityService mock_security = new MockSecurityService();
    final String user = "nobody";
    mock_security.setGlobalMockRole("nobody:DataBucketBean:read,write:test:security:*", true);
    // Simple merger
    final IEnrichmentModuleContext delegate_context = Mockito.mock(IEnrichmentModuleContext.class);
    Mockito.when(delegate_context.getNextUnusedId()).thenReturn(0L);
    final Optional<Tuple2<IEnrichmentBatchModule, GraphMergeEnrichmentContext>> maybe_merger = Optional
            .of(Tuples._2T((IEnrichmentBatchModule) new SimpleGraphMergeService(),
                    new GraphMergeEnrichmentContext(delegate_context, graph_schema)));
    maybe_merger.ifPresent(t2 -> t2._1().onStageInitialize(t2._2(), null, null, null, null));
    // special titan mapper
    final org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper titan_mapper = titan.io(IoCore.graphson())
            .mapper().create().createMapper();
    // Bucket
    final String bucket_path = "/test/security";
    // Key
    final ObjectNode vertex_key_1 = _mapper.createObjectNode().put(GraphAnnotationBean.name, "alex")
            .put(GraphAnnotationBean.type, "person");
    final ObjectNode vertex_key_2 = _mapper.createObjectNode().put(GraphAnnotationBean.name, "caleb")
            .put(GraphAnnotationBean.type, "person");
    final ObjectNode edge_key = (ObjectNode) ((ObjectNode) _mapper.createObjectNode()
            .put(GraphAnnotationBean.label, "test_label").set(GraphAnnotationBean.inV, vertex_key_1))
                    .set(GraphAnnotationBean.outV, vertex_key_2);
    // New elements (note can mess about with different keys because they are checked higher up in the stack, here things are just "pre-grouped" lists)
    final List<ObjectNode> new_vertices = Arrays.asList(
            (ObjectNode) ((ObjectNode) _mapper.createObjectNode().put(GraphAnnotationBean.type, "vertex")
                    .put(GraphAnnotationBean.label, "test_v_1").set(GraphAnnotationBean.id, vertex_key_1))
                            // (set some properties)
                            .set(GraphAnnotationBean.properties,
                                    ((ObjectNode) _mapper.createObjectNode().put("props_str", "str").set(
                                            "props_array",
                                            _mapper.convertValue(Arrays.asList("a", "r", "r"), JsonNode.class)))
                                                    .set("props_obj",
                                                            _mapper.createObjectNode().put(
                                                                    GraphAnnotationBean.value, "obj_str"))),
            (ObjectNode) ((ObjectNode) _mapper.createObjectNode().put(GraphAnnotationBean.type, "vertex")
                    .put(GraphAnnotationBean.label, "test_v_2").set(GraphAnnotationBean.id, vertex_key_2)));
    final List<ObjectNode> new_edges = Arrays.asList(
            (ObjectNode) ((ObjectNode) ((ObjectNode) _mapper.createObjectNode()
                    .put(GraphAnnotationBean.type, "edge").put(GraphAnnotationBean.label, "test_e_1")
                    .set(GraphAnnotationBean.inV, vertex_key_1)).set(GraphAnnotationBean.outV, vertex_key_2))
                            // (set some properties)
                            .set(GraphAnnotationBean.properties,
                                    (ObjectNode) _mapper.createObjectNode().put("props_long", 5L).set(
                                            "props_obj",
                                            _mapper.createObjectNode().set(GraphAnnotationBean.value,
                                                    _mapper.convertValue(Arrays.asList("a", "r", "r"),
                                                            JsonNode.class)))),
            (ObjectNode) ((ObjectNode) _mapper.createObjectNode().put(GraphAnnotationBean.type, "edge")
                    .put(GraphAnnotationBean.label, "test_e_2").set(GraphAnnotationBean.inV, vertex_key_1))
                            .set(GraphAnnotationBean.outV, vertex_key_2));
    // Existing elements
    final List<Vertex> existing_vertices = Arrays.asList(v1);
    final List<Edge> existing_edges = Arrays.asList(e1);
    // State
    final Map<ObjectNode, Vertex> mutable_existing_vertex_store = new HashMap<>();
    mutable_existing_vertex_store.put(vertex_key_1, v1);
    mutable_existing_vertex_store.put(vertex_key_2, v2);
    final MutableStatsBean mutable_stats = new MutableStatsBean();

    // Vertices, no existing elements
    {
        mutable_stats.reset();

        List<Vertex> ret_val = TitanGraphBuildingUtils.invokeUserMergeCode(tx, graph_schema,
                Tuples._2T(user, mock_security), Optional.empty(), maybe_merger, titan_mapper, mutable_stats,
                Vertex.class, bucket_path, vertex_key_1, Arrays.asList(new_vertices.get(0)),
                Collections.emptyList(), Collections.emptyMap());

        assertEquals(1, ret_val.size());
        assertEquals(
                Optionals.streamOf(tx.query().hasNot("existing").vertices(), false)
                        .map(v -> titan_mapper
                                .convertValue(v, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.toList()),
                ret_val.stream()
                        .map(v -> titan_mapper
                                .convertValue(v, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.toList()));

        ret_val.stream()
                .forEach(v -> assertEquals(Arrays.asList(bucket_path),
                        Optionals.streamOf(v.properties(GraphAnnotationBean.a2_p), false)
                                .map(p -> p.value().toString()).collect(Collectors.toList())));

        // Stats
        assertEquals(0L, mutable_stats.edge_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.edges_created);
        assertEquals(0L, mutable_stats.edges_emitted);
        assertEquals(0L, mutable_stats.edges_updated);
        assertEquals(0L, mutable_stats.vertex_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(1L, mutable_stats.vertices_created);
        assertEquals(0L, mutable_stats.vertices_emitted);
        assertEquals(0L, mutable_stats.vertices_updated);

        // Check the properties situation:
        assertEquals(1, Optionals.streamOf(tx.query().has("props_str", "str").vertices(), false).count());
        assertEquals(1,
                Optionals.streamOf(
                        tx.query().has("props_array", Arrays.asList("a", "r", "r").toArray()).vertices(), false)
                        .count());
        assertEquals(1, Optionals.streamOf(tx.query().has("props_obj", "obj_str").vertices(), false).count());

        // Check that we did actually add another vertex:
        assertEquals(3, Optionals.streamOf(tx.query().vertices(), false).count());
        // Time
        assertEquals(1,
                Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tc).vertices(), false).count()); // (added/updated time)
        assertEquals(1,
                Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tm).vertices(), false).count()); // (added/updated time)

        // (clear the graph ready for the next test)
        tx.query().hasNot("existing").vertices().forEach(v -> ((Vertex) v).remove());
    }
    // Vertices, existing elements, multiple new elements
    {
        mutable_stats.reset();

        List<Vertex> ret_val = TitanGraphBuildingUtils.invokeUserMergeCode(tx, graph_schema,
                Tuples._2T(user, mock_security), Optional.empty(), maybe_merger, titan_mapper, mutable_stats,
                Vertex.class, bucket_path, vertex_key_1, new_vertices, existing_vertices,
                Collections.emptyMap());

        assertEquals(1, ret_val.size());
        assertEquals(0, Optionals.streamOf(tx.query().hasNot("existing").vertices(), false).count()); // (since i've overwritten an existing one...)
        assertEquals(
                Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_p).vertices(), false)
                        .map(v -> titan_mapper
                                .convertValue(v, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.toList()),
                ret_val.stream()
                        .map(v -> titan_mapper
                                .convertValue(v, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.toList()));

        ret_val.stream()
                .forEach(v -> assertEquals(Arrays.asList(bucket_path),
                        Optionals.streamOf(v.properties(GraphAnnotationBean.a2_p), false)
                                .map(p -> p.value().toString()).collect(Collectors.toList())));

        // Stats
        assertEquals(0L, mutable_stats.edge_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.edges_created);
        assertEquals(0L, mutable_stats.edges_emitted);
        assertEquals(0L, mutable_stats.edges_updated);
        assertEquals(0L, mutable_stats.vertex_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.vertices_created);
        assertEquals(0L, mutable_stats.vertices_emitted);
        assertEquals(1L, mutable_stats.vertices_updated);

        // Check that we didn't actually add another vertex:
        assertEquals(2, Optionals.streamOf(tx.query().vertices(), false).count());
        // Time
        assertEquals(1,
                Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tc).vertices(), false).count()); // (added/updated time)
        assertEquals(1,
                Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tm).vertices(), false).count()); // (added/updated time)

        // (clear the graph ready for the next test)
        tx.query().hasNot("existing").vertices().forEach(v -> ((Vertex) v).remove());
        tx.query().has(GraphAnnotationBean.a2_p).vertices().forEach(
                v -> ((Vertex) v).properties(GraphAnnotationBean.a2_p).forEachRemaining(p -> p.remove()));
        tx.query().has(GraphAnnotationBean.a2_tc).vertices().forEach(
                v -> ((Vertex) v).properties(GraphAnnotationBean.a2_tc).forEachRemaining(p -> p.remove()));
        tx.query().has(GraphAnnotationBean.a2_tm).vertices().forEach(
                v -> ((Vertex) v).properties(GraphAnnotationBean.a2_tm).forEachRemaining(p -> p.remove()));
    }
    // Vertices, existing elements, single element
    {
        mutable_stats.reset();

        List<Vertex> ret_val = TitanGraphBuildingUtils.invokeUserMergeCode(tx, graph_schema,
                Tuples._2T(user, mock_security), Optional.empty(), maybe_merger, titan_mapper, mutable_stats,
                Vertex.class, bucket_path, vertex_key_1, new_vertices, existing_vertices,
                Collections.emptyMap());

        assertEquals(1, ret_val.size());
        assertEquals(0, Optionals.streamOf(tx.query().hasNot("existing").vertices(), false).count()); // (since i've overwritten an existing one...)
        assertEquals(
                Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_p).vertices(), false)
                        .map(v -> titan_mapper
                                .convertValue(v, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.toList()),
                ret_val.stream()
                        .map(v -> titan_mapper
                                .convertValue(v, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.toList()));

        ret_val.stream()
                .forEach(v -> assertEquals(Arrays.asList(bucket_path),
                        Optionals.streamOf(v.properties(GraphAnnotationBean.a2_p), false)
                                .map(p -> p.value().toString()).collect(Collectors.toList())));

        // Stats
        assertEquals(0L, mutable_stats.edge_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.edges_created);
        assertEquals(0L, mutable_stats.edges_emitted);
        assertEquals(0L, mutable_stats.edges_updated);
        assertEquals(0L, mutable_stats.vertex_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.vertices_created);
        assertEquals(0L, mutable_stats.vertices_emitted);
        assertEquals(1L, mutable_stats.vertices_updated);

        // Check that we didn't actually add another vertex:
        assertEquals(2, Optionals.streamOf(tx.query().vertices(), false).count());
        // Time
        assertEquals(1,
                Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tc).vertices(), false).count()); // (added/updated time)
        assertEquals(1,
                Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tm).vertices(), false).count()); // (added/updated time)

        // (clear the graph ready for the next test)
        tx.query().hasNot("existing").vertices().forEach(v -> ((Vertex) v).remove());
        tx.query().has(GraphAnnotationBean.a2_p).vertices().forEach(
                v -> ((Vertex) v).properties(GraphAnnotationBean.a2_p).forEachRemaining(p -> p.remove()));
    }
    // Edges, no existing elements, single new element
    {
        mutable_stats.reset();
        final List<Edge> ret_val = TitanGraphBuildingUtils.invokeUserMergeCode(tx, graph_schema,
                Tuples._2T(user, mock_security), Optional.empty(), maybe_merger, titan_mapper, mutable_stats,
                Edge.class, bucket_path, edge_key, Arrays.asList(new_edges.get(0)), Collections.emptyList(),
                mutable_existing_vertex_store);

        assertEquals(1, ret_val.size());
        assertEquals(
                Optionals.streamOf(tx.query().hasNot("existing").edges(), false)
                        .map(v -> titan_mapper
                                .convertValue(v, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.toList()),
                ret_val.stream()
                        .map(v -> titan_mapper
                                .convertValue(v, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.toList()));

        ret_val.stream()
                .forEach(v -> assertEquals(Arrays.asList(bucket_path),
                        Optionals.streamOf(v.properties(GraphAnnotationBean.a2_p), false)
                                .map(p -> p.value().toString()).collect(Collectors.toList())));

        // Stats
        assertEquals(0L, mutable_stats.edge_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(1L, mutable_stats.edges_created);
        assertEquals(0L, mutable_stats.edges_emitted);
        assertEquals(0L, mutable_stats.edges_updated);
        assertEquals(0L, mutable_stats.vertex_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.vertices_created);
        assertEquals(0L, mutable_stats.vertices_emitted);
        assertEquals(0L, mutable_stats.vertices_updated);

        // Check the properties situation:
        assertEquals(1, Optionals.streamOf(tx.query().has("props_long", 5L).edges(), false).count());
        assertEquals(1, Optionals
                .streamOf(tx.query().has("props_obj", Arrays.asList("a", "r", "r").toArray()).edges(), false)
                .count());

        // Check that we did actually add another edge:
        assertEquals(3, Optionals.streamOf(tx.query().edges(), false).count());
        // Time
        assertEquals(1, Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tc).edges(), false).count()); // (added/updated time)
        assertEquals(1, Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tm).edges(), false).count()); // (added/updated time)

        // (clear the graph ready for the next test)
        tx.query().hasNot("existing").edges().forEach(v -> ((Edge) v).remove());
    }
    // Edges, no existing elements, multiple new elements
    {
        mutable_stats.reset();

        List<Edge> ret_val = TitanGraphBuildingUtils.invokeUserMergeCode(tx, graph_schema,
                Tuples._2T(user, mock_security), Optional.empty(), maybe_merger, titan_mapper, mutable_stats,
                Edge.class, bucket_path, edge_key, new_edges, Collections.emptyList(),
                mutable_existing_vertex_store);

        assertEquals(1, ret_val.size());
        assertEquals(
                Optionals.streamOf(tx.query().hasNot("existing").edges(), false)
                        .map(v -> titan_mapper
                                .convertValue(v, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.toList()),
                ret_val.stream()
                        .map(v -> titan_mapper
                                .convertValue(v, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.toList()));

        ret_val.stream()
                .forEach(v -> assertEquals(Arrays.asList(bucket_path),
                        Optionals.streamOf(v.properties(GraphAnnotationBean.a2_p), false)
                                .map(p -> p.value().toString()).collect(Collectors.toList())));

        // Stats
        assertEquals(0L, mutable_stats.edge_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(1L, mutable_stats.edges_created);
        assertEquals(0L, mutable_stats.edges_emitted);
        assertEquals(0L, mutable_stats.edges_updated);
        assertEquals(0L, mutable_stats.vertex_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.vertices_created);
        assertEquals(0L, mutable_stats.vertices_emitted);
        assertEquals(0L, mutable_stats.vertices_updated);

        // Check that we did actually add another edge:
        assertEquals(3, Optionals.streamOf(tx.query().edges(), false).count());
        // Time
        assertEquals(1, Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tc).edges(), false).count()); // (added/updated time)
        assertEquals(1, Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tm).edges(), false).count()); // (added/updated time)

        // (clear the graph ready for the next test)
        tx.query().hasNot("existing").edges().forEach(v -> ((Edge) v).remove());
    }
    // Edges, existing elements, multiple elements (unlike single one)
    {
        mutable_stats.reset();

        List<Edge> ret_val = TitanGraphBuildingUtils.invokeUserMergeCode(tx, graph_schema,
                Tuples._2T(user, mock_security), Optional.empty(), maybe_merger, titan_mapper, mutable_stats,
                Edge.class, bucket_path, edge_key, new_edges, existing_edges, mutable_existing_vertex_store);

        assertEquals(1, ret_val.size());
        assertEquals(0, Optionals.streamOf(tx.query().hasNot("existing").edges(), false).count()); // (since i've overwritten an existing one...)
        assertEquals(
                Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_p).edges(), false)
                        .map(v -> titan_mapper
                                .convertValue(v, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.toList()),
                ret_val.stream()
                        .map(v -> titan_mapper
                                .convertValue(v, org.apache.tinkerpop.shaded.jackson.databind.JsonNode.class)
                                .toString())
                        .collect(Collectors.toList()));

        ret_val.stream()
                .forEach(v -> assertEquals(Arrays.asList(bucket_path),
                        Optionals.streamOf(v.properties(GraphAnnotationBean.a2_p), false)
                                .map(p -> p.value().toString()).collect(Collectors.toList())));

        // Stats
        assertEquals(0L, mutable_stats.edge_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.edges_created);
        assertEquals(0L, mutable_stats.edges_emitted);
        assertEquals(1L, mutable_stats.edges_updated);
        assertEquals(0L, mutable_stats.vertex_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.vertices_created);
        assertEquals(0L, mutable_stats.vertices_emitted);
        assertEquals(0L, mutable_stats.vertices_updated);

        // Check that we didn't actually add another edge:
        assertEquals(2, Optionals.streamOf(tx.query().edges(), false).count());
        // Time
        assertEquals(1, Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tc).edges(), false).count()); // (added/updated time)
        assertEquals(1, Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tm).edges(), false).count()); // (added/updated time)

        // (clear the graph ready for the next test)
        tx.query().hasNot("existing").edges().forEach(v -> ((Edge) v).remove());
        tx.query().has(GraphAnnotationBean.a2_p).edges().forEach(
                v -> ((Edge) v).properties(GraphAnnotationBean.a2_p).forEachRemaining(p -> p.remove()));
        tx.query().has(GraphAnnotationBean.a2_tc).edges().forEach(
                v -> ((Edge) v).properties(GraphAnnotationBean.a2_tc).forEachRemaining(p -> p.remove()));
        tx.query().has(GraphAnnotationBean.a2_tm).edges().forEach(
                v -> ((Edge) v).properties(GraphAnnotationBean.a2_tm).forEachRemaining(p -> p.remove()));
    }
    // Some error cases:
    // 1) Demonstrate a failure, just remove the label
    {
        mutable_stats.reset();

        new_vertices.get(0).remove(GraphAnnotationBean.label);

        List<Vertex> ret_val = TitanGraphBuildingUtils.invokeUserMergeCode(tx, graph_schema,
                Tuples._2T(user, mock_security), Optional.empty(), maybe_merger, titan_mapper, mutable_stats,
                Vertex.class, bucket_path, vertex_key_1, Arrays.asList(new_vertices.get(0)),
                Collections.emptyList(), Collections.emptyMap());

        // Stats
        assertEquals(0L, mutable_stats.edge_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.edges_created);
        assertEquals(0L, mutable_stats.edges_emitted);
        assertEquals(0L, mutable_stats.edges_updated);
        assertEquals(1L, mutable_stats.vertex_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.vertices_created);
        assertEquals(0L, mutable_stats.vertices_emitted);
        assertEquals(0L, mutable_stats.vertices_updated);

        // Time
        assertEquals(0, Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tc).edges(), false).count()); // (added/updated time)
        assertEquals(0, Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tm).edges(), false).count()); // (added/updated time)

        assertEquals(0, ret_val.size());
    }
    // 2) Shouldn't happen, but just check the case where no vertex can be found
    {
        mutable_stats.reset();

        List<Edge> ret_val = TitanGraphBuildingUtils.invokeUserMergeCode(tx, graph_schema,
                Tuples._2T(user, mock_security), Optional.empty(), maybe_merger, titan_mapper, mutable_stats,
                Edge.class, bucket_path, edge_key, new_edges, Collections.emptyList(), Collections.emptyMap());

        // Stats
        assertEquals(1L, mutable_stats.edge_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.edges_created);
        assertEquals(0L, mutable_stats.edges_emitted);
        assertEquals(0L, mutable_stats.edges_updated);
        assertEquals(0L, mutable_stats.vertex_errors);
        assertEquals(0L, mutable_stats.edge_matches_found);
        assertEquals(0L, mutable_stats.vertices_created);
        assertEquals(0L, mutable_stats.vertices_emitted);
        assertEquals(0L, mutable_stats.vertices_updated);

        // Time
        assertEquals(0, Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tc).edges(), false).count()); // (added/updated time)
        assertEquals(0, Optionals.streamOf(tx.query().has(GraphAnnotationBean.a2_tm).edges(), false).count()); // (added/updated time)

        assertEquals(0, ret_val.size());
    }

    tx.commit();

    //Quick test coverage of the simple merger, should avoid me having to do any unit testing for that module elsewhere...
    maybe_merger.ifPresent(t2 -> t2._1().onStageComplete(true));
}

From source file:com.bouncestorage.swiftproxy.v1.ObjectResource.java

private Response.ResponseBuilder addObjectHeaders(Response.ResponseBuilder responseBuilder,
        BlobMetadata metaData, Optional<Map<String, Object>> overwrites) {
    Map<String, String> userMetadata = metaData.getUserMetadata();
    userMetadata.entrySet().stream().filter(entry -> !RESERVED_METADATA.contains(entry.getKey()))
            .forEach(entry -> responseBuilder.header(META_HEADER_PREFIX + entry.getKey(), entry.getValue()));
    if (userMetadata.containsKey(DYNAMIC_OBJECT_MANIFEST)) {
        responseBuilder.header(DYNAMIC_OBJECT_MANIFEST, userMetadata.get(DYNAMIC_OBJECT_MANIFEST));
    }//  ww w .  ja v a2s.c  om

    String contentType = Strings.isNullOrEmpty(metaData.getContentMetadata().getContentType())
            ? MediaType.APPLICATION_OCTET_STREAM
            : metaData.getContentMetadata().getContentType();

    Map<String, Supplier<Object>> defaultHeaders = ImmutableMap.<String, Supplier<Object>>builder()
            .put(HttpHeaders.CONTENT_DISPOSITION, () -> metaData.getContentMetadata().getContentDisposition())
            .put(HttpHeaders.CONTENT_ENCODING, () -> metaData.getContentMetadata().getContentEncoding())
            .put(HttpHeaders.CONTENT_LENGTH, metaData::getSize)
            .put(HttpHeaders.LAST_MODIFIED, metaData::getLastModified).put(HttpHeaders.ETAG, metaData::getETag)
            .put(STATIC_OBJECT_MANIFEST, () -> userMetadata.containsKey(STATIC_OBJECT_MANIFEST))
            .put(HttpHeaders.DATE, Date::new).put(HttpHeaders.CONTENT_TYPE, () -> contentType).build();

    overwrites.ifPresent(headers -> headers.forEach((k, v) -> responseBuilder.header(k, v)));
    defaultHeaders.forEach((k, v) -> {
        if (!overwrites.isPresent() || !overwrites.get().containsKey(k)) {
            responseBuilder.header(k, v.get());
        }
    });

    return responseBuilder;
}