Example usage for java.util Map forEach

List of usage examples for java.util Map forEach

Introduction

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

Prototype

default void forEach(BiConsumer<? super K, ? super V> action) 

Source Link

Document

Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.

Usage

From source file:io.swagger.v3.core.util.AnnotationsUtils.java

public static Optional<? extends Schema> getSchema(io.swagger.v3.oas.annotations.media.Schema schemaAnnotation,
        io.swagger.v3.oas.annotations.media.ArraySchema arrayAnnotation, boolean isArray,
        Class<?> schemaImplementation, Components components, JsonView jsonViewAnnotation) {
    Map<String, Schema> schemaMap;
    if (schemaImplementation != Void.class) {
        Schema schemaObject = new Schema();
        if (schemaImplementation.getName().startsWith("java.lang")) {
            schemaObject.setType(schemaImplementation.getSimpleName().toLowerCase());
        } else {/*from  w w  w .j  av a 2 s  . c o m*/
            ResolvedSchema resolvedSchema = ModelConverters.getInstance().readAllAsResolvedSchema(
                    new AnnotatedType().type(schemaImplementation).jsonViewAnnotation(jsonViewAnnotation));
            if (resolvedSchema != null) {
                schemaMap = resolvedSchema.referencedSchemas;
                schemaMap.forEach((key, schema) -> {
                    components.addSchemas(key, schema);
                });
                if (resolvedSchema.schema != null && StringUtils.isNotBlank(resolvedSchema.schema.getName())) {
                    schemaObject.set$ref(COMPONENTS_REF + resolvedSchema.schema.getName());
                } else if (resolvedSchema.schema != null) {
                    schemaObject = resolvedSchema.schema;
                }
            }
        }
        if (StringUtils.isBlank(schemaObject.get$ref()) && StringUtils.isBlank(schemaObject.getType())) {
            // default to string
            schemaObject.setType("string");
        }
        if (isArray) {
            Optional<ArraySchema> arraySchema = AnnotationsUtils.getArraySchema(arrayAnnotation, components,
                    jsonViewAnnotation);
            if (arraySchema.isPresent()) {
                arraySchema.get().setItems(schemaObject);
                return arraySchema;
            } else {
                return Optional.empty();
            }
        } else {
            return Optional.of(schemaObject);
        }

    } else {
        Optional<Schema> schemaFromAnnotation = AnnotationsUtils.getSchemaFromAnnotation(schemaAnnotation,
                components, jsonViewAnnotation);
        if (schemaFromAnnotation.isPresent()) {
            if (StringUtils.isBlank(schemaFromAnnotation.get().get$ref())
                    && StringUtils.isBlank(schemaFromAnnotation.get().getType())) {
                // default to string
                schemaFromAnnotation.get().setType("string");
            }
            return Optional.of(schemaFromAnnotation.get());
        } else {
            Optional<ArraySchema> arraySchemaFromAnnotation = AnnotationsUtils.getArraySchema(arrayAnnotation,
                    components, jsonViewAnnotation);
            if (arraySchemaFromAnnotation.isPresent()) {
                if (arraySchemaFromAnnotation.get().getItems() != null
                        && StringUtils.isBlank(arraySchemaFromAnnotation.get().getItems().get$ref())
                        && StringUtils.isBlank(arraySchemaFromAnnotation.get().getItems().getType())) {
                    // default to string
                    arraySchemaFromAnnotation.get().getItems().setType("string");
                }
                return Optional.of(arraySchemaFromAnnotation.get());
            }
        }
    }
    return Optional.empty();
}

From source file:org.openecomp.sdc.be.model.operations.impl.CapabilityOperation.java

public Map<String, List<CapabilityDefinition>> convertCapabilityMap(
        Map<String, CapabilityDefinition> capabilityMap, String ownerId, String ownerName) {

    Map<String, List<CapabilityDefinition>> typeToRequirementMap = new HashMap<>();
    capabilityMap.forEach((capabilityName, capability) -> {
        capability.setName(capabilityName);
        if (typeToRequirementMap.containsKey(capability.getType())) {
            typeToRequirementMap.get(capability.getType()).add(capability);
        } else {//from ww  w.  jav a2  s  .c om
            List<CapabilityDefinition> list = new ArrayList<>();
            list.add(capability);
            typeToRequirementMap.put(capability.getType(), list);
        }
    });
    return typeToRequirementMap;
}

From source file:org.apache.metron.common.stellar.StellarArithmeticTest.java

@Test
public void verifyExpectedReturnTypes() throws Exception {
    Token<Integer> integer = mock(Token.class);
    when(integer.getValue()).thenReturn(1);

    Token<Long> lng = mock(Token.class);
    when(lng.getValue()).thenReturn(1L);

    Token<Double> dbl = mock(Token.class);
    when(dbl.getValue()).thenReturn(1.0D);

    Token<Float> flt = mock(Token.class);
    when(flt.getValue()).thenReturn(1.0F);

    Map<Pair<String, String>, Class<? extends Number>> expectedReturnTypeMappings = new HashMap<Pair<String, String>, Class<? extends Number>>() {
        {/*  ww w .  ja  va 2s  . co  m*/
            put(Pair.of("TO_FLOAT(3.0)", "TO_LONG(1)"), Float.class);
            put(Pair.of("TO_FLOAT(3)", "3.0"), Double.class);
            put(Pair.of("TO_FLOAT(3)", "TO_FLOAT(3)"), Float.class);
            put(Pair.of("TO_FLOAT(3)", "3"), Float.class);

            put(Pair.of("TO_LONG(1)", "TO_LONG(1)"), Long.class);
            put(Pair.of("TO_LONG(1)", "3.0"), Double.class);
            put(Pair.of("TO_LONG(1)", "TO_FLOAT(3)"), Float.class);
            put(Pair.of("TO_LONG(1)", "3"), Long.class);

            put(Pair.of("3.0", "TO_LONG(1)"), Double.class);
            put(Pair.of("3.0", "3.0"), Double.class);
            put(Pair.of("3.0", "TO_FLOAT(3)"), Double.class);
            put(Pair.of("3.0", "3"), Double.class);

            put(Pair.of("3", "TO_LONG(1)"), Long.class);
            put(Pair.of("3", "3.0"), Double.class);
            put(Pair.of("3", "TO_FLOAT(3)"), Float.class);
            put(Pair.of("3", "3"), Integer.class);
        }
    };

    expectedReturnTypeMappings.forEach((pair, expectedClass) -> {
        assertTrue(
                run(pair.getLeft() + " * " + pair.getRight(), ImmutableMap.of()).getClass() == expectedClass);
        assertTrue(
                run(pair.getLeft() + " + " + pair.getRight(), ImmutableMap.of()).getClass() == expectedClass);
        assertTrue(
                run(pair.getLeft() + " - " + pair.getRight(), ImmutableMap.of()).getClass() == expectedClass);
        assertTrue(
                run(pair.getLeft() + " / " + pair.getRight(), ImmutableMap.of()).getClass() == expectedClass);
    });
}

From source file:net.minecraftforge.registries.GameData.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static Multimap<ResourceLocation, ResourceLocation> injectSnapshot(
        Map<ResourceLocation, ForgeRegistry.Snapshot> snapshot, boolean injectFrozenData,
        boolean isLocalWorld) {
    FMLLog.log.info("Injecting existing registry data into this {} instance",
            FMLCommonHandler.instance().getEffectiveSide().isServer() ? "server" : "client");
    RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.validateContent(name));
    RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.dump(name));
    RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.resetDelegates());

    List<ResourceLocation> missingRegs = snapshot.keySet().stream()
            .filter(name -> !RegistryManager.ACTIVE.registries.containsKey(name)).collect(Collectors.toList());
    if (missingRegs.size() > 0) {
        String text = "Forge Mod Loader detected missing/unknown registrie(s).\n\n" + "There are "
                + missingRegs.size() + " missing registries in this save.\n"
                + "If you continue the missing registries will get removed.\n"
                + "This may cause issues, it is advised that you create a world backup before continuing.\n\n"
                + "Missing Registries:\n";

        for (ResourceLocation s : missingRegs)
            text += s.toString() + "\n";

        if (!StartupQuery.confirm(text))
            StartupQuery.abort();/*  www  .  j a  va 2  s  .c  o  m*/
    }

    RegistryManager STAGING = new RegistryManager("STAGING");

    final Map<ResourceLocation, Map<ResourceLocation, Integer[]>> remaps = Maps.newHashMap();
    final LinkedHashMap<ResourceLocation, Map<ResourceLocation, Integer>> missing = Maps.newLinkedHashMap();
    // Load the snapshot into the "STAGING" registry
    snapshot.forEach((key, value) -> {
        final Class<? extends IForgeRegistryEntry> clazz = RegistryManager.ACTIVE.getSuperType(key);
        remaps.put(key, Maps.newLinkedHashMap());
        missing.put(key, Maps.newHashMap());
        loadPersistentDataToStagingRegistry(RegistryManager.ACTIVE, STAGING, remaps.get(key), missing.get(key),
                key, value, clazz);
    });

    snapshot.forEach((key, value) -> {
        value.dummied.forEach(dummy -> {
            Map<ResourceLocation, Integer> m = missing.get(key);
            ForgeRegistry<?> reg = STAGING.getRegistry(key);

            // Currently missing locally, we just inject and carry on
            if (m.containsKey(dummy)) {
                if (reg.markDummy(dummy, m.get(dummy)))
                    m.remove(dummy);
            } else if (isLocalWorld) {
                if (ForgeRegistry.DEBUG)
                    FMLLog.log.debug("Registry {}: Resuscitating dummy entry {}", key, dummy);
            } else {
                // The server believes this is a dummy block identity, but we seem to have one locally. This is likely a conflict
                // in mod setup - Mark this entry as a dummy
                int id = reg.getID(dummy);
                FMLLog.log.warn(
                        "Registry {}: The ID {} is currently locally mapped - it will be replaced with a dummy for this session",
                        key, id);
                reg.markDummy(dummy, id);
            }
        });
    });

    int count = missing.values().stream().mapToInt(Map::size).sum();
    if (count > 0) {
        FMLLog.log.debug("There are {} mappings missing - attempting a mod remap", count);
        Multimap<ResourceLocation, ResourceLocation> defaulted = ArrayListMultimap.create();
        Multimap<ResourceLocation, ResourceLocation> failed = ArrayListMultimap.create();

        missing.entrySet().stream().filter(e -> e.getValue().size() > 0).forEach(m -> {
            ResourceLocation name = m.getKey();
            ForgeRegistry<?> reg = STAGING.getRegistry(name);
            RegistryEvent.MissingMappings<?> event = reg.getMissingEvent(name, m.getValue());
            MinecraftForge.EVENT_BUS.post(event);

            List<MissingMappings.Mapping<?>> lst = event.getAllMappings().stream()
                    .filter(e -> e.getAction() == MissingMappings.Action.DEFAULT).collect(Collectors.toList());
            if (!lst.isEmpty()) {
                FMLLog.log.error("Unidentified mapping from registry {}", name);
                lst.forEach(map -> {
                    FMLLog.log.error("    {}: {}", map.key, map.id);
                    if (!isLocalWorld)
                        defaulted.put(name, map.key);
                });
            }
            event.getAllMappings().stream().filter(e -> e.getAction() == MissingMappings.Action.FAIL)
                    .forEach(fail -> failed.put(name, fail.key));

            final Class<? extends IForgeRegistryEntry> clazz = RegistryManager.ACTIVE.getSuperType(name);
            processMissing(clazz, name, STAGING, event, m.getValue(), remaps.get(name), defaulted.get(name),
                    failed.get(name));
        });

        if (!defaulted.isEmpty() && !isLocalWorld)
            return defaulted;

        if (!defaulted.isEmpty()) {
            StringBuilder buf = new StringBuilder();
            buf.append("Forge Mod Loader detected missing registry entries.\n\n").append("There are ")
                    .append(defaulted.size()).append(" missing entries in this save.\n")
                    .append("If you continue the missing entries will get removed.\n")
                    .append("A world backup will be automatically created in your saves directory.\n\n");

            defaulted.asMap().forEach((name, entries) -> {
                buf.append("Missing ").append(name).append(":\n");
                entries.forEach(rl -> buf.append("    ").append(rl).append("\n"));
            });

            boolean confirmed = StartupQuery.confirm(buf.toString());
            if (!confirmed)
                StartupQuery.abort();

            try {
                String skip = System.getProperty("fml.doNotBackup");
                if (skip == null || !"true".equals(skip)) {
                    ZipperUtil.backupWorld();
                } else {
                    for (int x = 0; x < 10; x++)
                        FMLLog.log.error("!!!!!!!!!! UPDATING WORLD WITHOUT DOING BACKUP !!!!!!!!!!!!!!!!");
                }
            } catch (IOException e) {
                StartupQuery.notify("The world backup couldn't be created.\n\n" + e);
                StartupQuery.abort();
            }
        }

        if (!defaulted.isEmpty()) {
            if (isLocalWorld)
                FMLLog.log.error(
                        "There are unidentified mappings in this world - we are going to attempt to process anyway");
        }

    }

    if (injectFrozenData) {
        // If we're loading from disk, we can actually substitute air in the block map for anything that is otherwise "missing". This keeps the reference in the map, in case
        // the block comes back later
        missing.forEach((name, m) -> {
            ForgeRegistry<?> reg = STAGING.getRegistry(name);
            m.forEach((rl, id) -> reg.markDummy(rl, id));
        });

        // If we're loading up the world from disk, we want to add in the new data that might have been provisioned by mods
        // So we load it from the frozen persistent registry
        RegistryManager.ACTIVE.registries.forEach((name, reg) -> {
            final Class<? extends IForgeRegistryEntry> clazz = RegistryManager.ACTIVE.getSuperType(name);
            loadFrozenDataToStagingRegistry(STAGING, name, remaps.get(name), clazz);
        });
    }

    // Validate that all the STAGING data is good
    STAGING.registries.forEach((name, reg) -> reg.validateContent(name));

    // Load the STAGING registry into the ACTIVE registry
    for (Map.Entry<ResourceLocation, ForgeRegistry<? extends IForgeRegistryEntry<?>>> r : RegistryManager.ACTIVE.registries
            .entrySet()) {
        final Class<? extends IForgeRegistryEntry> registrySuperType = RegistryManager.ACTIVE
                .getSuperType(r.getKey());
        loadRegistry(r.getKey(), STAGING, RegistryManager.ACTIVE, registrySuperType, true);
    }

    // Dump the active registry
    RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.dump(name));

    // Tell mods that the ids have changed
    Loader.instance().fireRemapEvent(remaps, false);

    // The id map changed, ensure we apply object holders
    ObjectHolderRegistry.INSTANCE.applyObjectHolders();

    // Return an empty list, because we're good
    return ArrayListMultimap.create();
}

From source file:org.apache.metron.common.stellar.evaluators.ArithmeticEvaluatorTest.java

@Test
public void verifyExpectedReturnTypes() throws Exception {
    Token<Integer> integer = mock(Token.class);
    when(integer.getValue()).thenReturn(1);

    Token<Long> lng = mock(Token.class);
    when(lng.getValue()).thenReturn(1L);

    Token<Double> dbl = mock(Token.class);
    when(dbl.getValue()).thenReturn(1.0D);

    Token<Float> flt = mock(Token.class);
    when(flt.getValue()).thenReturn(1.0F);

    Map<Pair<Token<? extends Number>, Token<? extends Number>>, Class<? extends Number>> expectedReturnTypeMappings = new HashMap<Pair<Token<? extends Number>, Token<? extends Number>>, Class<? extends Number>>() {
        {//from w  w  w .  ja  v a2 s. co m
            put(Pair.of(flt, lng), Float.class);
            put(Pair.of(flt, dbl), Double.class);
            put(Pair.of(flt, flt), Float.class);
            put(Pair.of(flt, integer), Float.class);

            put(Pair.of(lng, lng), Long.class);
            put(Pair.of(lng, dbl), Double.class);
            put(Pair.of(lng, flt), Float.class);
            put(Pair.of(lng, integer), Long.class);

            put(Pair.of(dbl, lng), Double.class);
            put(Pair.of(dbl, dbl), Double.class);
            put(Pair.of(dbl, flt), Double.class);
            put(Pair.of(dbl, integer), Double.class);

            put(Pair.of(integer, lng), Long.class);
            put(Pair.of(integer, dbl), Double.class);
            put(Pair.of(integer, flt), Float.class);
            put(Pair.of(integer, integer), Integer.class);
        }
    };

    expectedReturnTypeMappings.forEach((pair, expectedClass) -> {
        assertTrue(evaluator.evaluate(ArithmeticEvaluator.ArithmeticEvaluatorFunctions.addition(), pair)
                .getValue().getClass() == expectedClass);
        assertTrue(evaluator.evaluate(ArithmeticEvaluator.ArithmeticEvaluatorFunctions.division(), pair)
                .getValue().getClass() == expectedClass);
        assertTrue(evaluator.evaluate(ArithmeticEvaluator.ArithmeticEvaluatorFunctions.subtraction(), pair)
                .getValue().getClass() == expectedClass);
        assertTrue(evaluator.evaluate(ArithmeticEvaluator.ArithmeticEvaluatorFunctions.multiplication(), pair)
                .getValue().getClass() == expectedClass);
    });
}

From source file:org.apache.metron.stellar.common.evaluators.ArithmeticEvaluatorTest.java

@Test
public void verifyExpectedReturnTypes() throws Exception {
    Token<Integer> integer = mock(Token.class);
    when(integer.getValue()).thenReturn(1);

    Token<Long> lng = mock(Token.class);
    when(lng.getValue()).thenReturn(1L);

    Token<Double> dbl = mock(Token.class);
    when(dbl.getValue()).thenReturn(1.0D);

    Token<Float> flt = mock(Token.class);
    when(flt.getValue()).thenReturn(1.0F);

    Map<Pair<Token<? extends Number>, Token<? extends Number>>, Class<? extends Number>> expectedReturnTypeMappings = new HashMap<Pair<Token<? extends Number>, Token<? extends Number>>, Class<? extends Number>>() {
        {//from   www  .j a va 2  s  .co m
            put(Pair.of(flt, lng), Float.class);
            put(Pair.of(flt, dbl), Double.class);
            put(Pair.of(flt, flt), Float.class);
            put(Pair.of(flt, integer), Float.class);

            put(Pair.of(lng, lng), Long.class);
            put(Pair.of(lng, dbl), Double.class);
            put(Pair.of(lng, flt), Float.class);
            put(Pair.of(lng, integer), Long.class);

            put(Pair.of(dbl, lng), Double.class);
            put(Pair.of(dbl, dbl), Double.class);
            put(Pair.of(dbl, flt), Double.class);
            put(Pair.of(dbl, integer), Double.class);

            put(Pair.of(integer, lng), Long.class);
            put(Pair.of(integer, dbl), Double.class);
            put(Pair.of(integer, flt), Float.class);
            put(Pair.of(integer, integer), Integer.class);
        }
    };

    expectedReturnTypeMappings.forEach((pair, expectedClass) -> {
        assertTrue(evaluator.evaluate(ArithmeticEvaluator.ArithmeticEvaluatorFunctions.addition(null), pair)
                .getValue().getClass() == expectedClass);
        assertTrue(evaluator.evaluate(ArithmeticEvaluator.ArithmeticEvaluatorFunctions.division(null), pair)
                .getValue().getClass() == expectedClass);
        assertTrue(evaluator.evaluate(ArithmeticEvaluator.ArithmeticEvaluatorFunctions.subtraction(null), pair)
                .getValue().getClass() == expectedClass);
        assertTrue(
                evaluator.evaluate(ArithmeticEvaluator.ArithmeticEvaluatorFunctions.multiplication(null), pair)
                        .getValue().getClass() == expectedClass);
    });
}

From source file:org.apache.samza.system.kafka.KafkaSystemAdmin.java

/**
 * Uses the kafka consumer to fetch the metadata for the {@code topicPartitions}.
 */// w  w  w.j a  v a  2s.co m
private OffsetsMaps fetchTopicPartitionsMetadata(List<TopicPartition> topicPartitions) {
    Map<SystemStreamPartition, String> oldestOffsets = new HashMap<>();
    Map<SystemStreamPartition, String> newestOffsets = new HashMap<>();
    Map<SystemStreamPartition, String> upcomingOffsets = new HashMap<>();
    final Map<TopicPartition, Long> oldestOffsetsWithLong = new HashMap<>();
    final Map<TopicPartition, Long> upcomingOffsetsWithLong = new HashMap<>();

    threadSafeKafkaConsumer.execute(consumer -> {
        Map<TopicPartition, Long> beginningOffsets = consumer.beginningOffsets(topicPartitions);
        LOG.debug("Beginning offsets for topic-partitions: {} is {}", topicPartitions, beginningOffsets);
        oldestOffsetsWithLong.putAll(beginningOffsets);
        Map<TopicPartition, Long> endOffsets = consumer.endOffsets(topicPartitions);
        LOG.debug("End offsets for topic-partitions: {} is {}", topicPartitions, endOffsets);
        upcomingOffsetsWithLong.putAll(endOffsets);
        return Optional.empty();
    });

    oldestOffsetsWithLong.forEach((topicPartition, offset) -> oldestOffsets
            .put(KafkaUtil.toSystemStreamPartition(systemName, topicPartition), String.valueOf(offset)));

    upcomingOffsetsWithLong.forEach((topicPartition, offset) -> {
        upcomingOffsets.put(KafkaUtil.toSystemStreamPartition(systemName, topicPartition),
                String.valueOf(offset));

        // Kafka's beginning Offset corresponds to the offset for the oldest message.
        // Kafka's end offset corresponds to the offset for the upcoming message, and it is the newest offset + 1.
        // When upcoming offset is <=0, the topic appears empty, we put oldest offset 0 and the newest offset null.
        // When upcoming offset is >0, we subtract the upcoming offset by one for the newest offset.
        // For normal case, the newest offset will correspond to the offset of the newest message in the stream;
        // But for the big message, it is not the case. Seeking on the newest offset gives nothing for the newest big message.
        // For now, we keep it as is for newest offsets the same as historical metadata structure.
        if (offset <= 0) {
            LOG.warn(
                    "Empty Kafka topic partition {} with upcoming offset {}. Skipping newest offset and setting oldest offset to 0 to consume from beginning",
                    topicPartition, offset);
            oldestOffsets.put(KafkaUtil.toSystemStreamPartition(systemName, topicPartition), "0");
        } else {
            newestOffsets.put(KafkaUtil.toSystemStreamPartition(systemName, topicPartition),
                    String.valueOf(offset - 1));
        }
    });
    return new OffsetsMaps(oldestOffsets, newestOffsets, upcomingOffsets);
}

From source file:de.micromata.genome.tpsb.soapui.DelegateToSoapUiTestBuilderHttpClientRequestTransport.java

private HttpResponse execute(SubmitContext submitContext, ExtendedHttpMethod method, HttpContext httpContext,
        Map<String, String> httpRequestParameter) throws Exception {
    boolean passtoremote = false;
    if (passtoremote == true) {
        return HttpClientSupport.execute(method, httpContext);

    }//from   w ww .j  a  v  a 2s . co  m
    byte[] reqData = null;
    if (method.getRequestEntity() != null && method.getRequestEntity().getContent() != null) {
        reqData = filterRequestData(IOUtils.toByteArray(method.getRequestEntity().getContent()));
    }
    Header[] soaphaedera = method.getHeaders("SOAPAction");
    String soapAction = "";
    if (soaphaedera != null && soaphaedera.length > 0) {
        soapAction = method.getHeaders("SOAPAction")[0].getValue();
    }
    String uri = method.getURI().toString();
    //    testBuilder.initWithUri(uri);
    testBuilder//
            .createNewPostRequestIntern(submitContext) //
            .initWithUri(uri).setRequestMethod(method.getMethod()).setRequestData(reqData);
    if (StringUtils.isNotBlank(soapAction) == true) {
        testBuilder.addRequestHeader("SOAPAction", soapAction);
    }
    Header[] allHeaders = method.getAllHeaders();
    for (Header h : allHeaders) {
        testBuilder.addRequestHeader(h.getName(), h.getValue());
    }
    httpRequestParameter.forEach((k, v) -> testBuilder.getHttpRequest().addRequestParameter(k, v));
    MockHttpServletResponse httpr = testBuilder.executeServletRequest() //
            .getHttpResponse();

    byte[] respData = filterResponseData(httpr.getOutputBytes());
    //    String outp = httpr.getOutputString();
    BasicStatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), httpr.getStatus(),
            null);
    BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine);
    httpResponse.setEntity(new ByteArrayEntity(respData));
    httpResponse = filterBasicHttpResponse(httpResponse);
    //        WsdlSinglePartHttpResponse wsdls = new WsdlSinglePartHttpResponse();
    method.setHttpResponse(httpResponse);
    try {
        method.setURI(new URI("http://localhost/dummy"));
    } catch (URISyntaxException ex) {
        throw new RuntimeException(ex);
    }
    return httpResponse;
}

From source file:alfio.manager.TicketReservationManager.java

private void acquireItems(TicketStatus ticketStatus, AdditionalServiceItemStatus asStatus,
        PaymentProxy paymentProxy, String reservationId, String email, CustomerName customerName,
        String userLanguage, String billingAddress, int eventId) {
    Map<Integer, Ticket> preUpdateTicket = ticketRepository.findTicketsInReservation(reservationId).stream()
            .collect(toMap(Ticket::getId, Function.identity()));
    int updatedTickets = ticketRepository.updateTicketsStatusWithReservationId(reservationId,
            ticketStatus.toString());// www  . j  a  v  a2s .c o m
    Map<Integer, Ticket> postUpdateTicket = ticketRepository.findTicketsInReservation(reservationId).stream()
            .collect(toMap(Ticket::getId, Function.identity()));

    postUpdateTicket.forEach((id, ticket) -> {
        auditUpdateTicket(preUpdateTicket.get(id), Collections.emptyMap(), ticket, Collections.emptyMap(),
                eventId);
    });

    int updatedAS = additionalServiceItemRepository.updateItemsStatusWithReservationUUID(reservationId,
            asStatus);
    Validate.isTrue(updatedTickets + updatedAS > 0, "no items have been updated");
    specialPriceRepository.updateStatusForReservation(singletonList(reservationId), Status.TAKEN.toString());
    ZonedDateTime timestamp = ZonedDateTime.now(ZoneId.of("UTC"));
    int updatedReservation = ticketReservationRepository.updateTicketReservation(reservationId,
            TicketReservationStatus.COMPLETE.toString(), email, customerName.getFullName(),
            customerName.getFirstName(), customerName.getLastName(), userLanguage, billingAddress, timestamp,
            paymentProxy.toString());
    Validate.isTrue(updatedReservation == 1,
            "expected exactly one updated reservation, got " + updatedReservation);
    waitingQueueManager.fireReservationConfirmed(reservationId);
    if (paymentProxy == PaymentProxy.PAYPAL || paymentProxy == PaymentProxy.ADMIN) {
        //we must notify the plugins about ticket assignment and send them by email
        Event event = eventRepository.findByReservationId(reservationId);
        TicketReservation reservation = findById(reservationId).orElseThrow(IllegalStateException::new);
        findTicketsInReservation(reservationId).stream()
                .filter(ticket -> StringUtils.isNotBlank(ticket.getFullName())
                        || StringUtils.isNotBlank(ticket.getFirstName())
                        || StringUtils.isNotBlank(ticket.getEmail()))
                .forEach(ticket -> {
                    Locale locale = Locale.forLanguageTag(ticket.getUserLanguage());
                    if (paymentProxy == PaymentProxy.PAYPAL) {
                        sendTicketByEmail(ticket, locale, event,
                                getTicketEmailGenerator(event, reservation, locale));
                    }
                    pluginManager.handleTicketAssignment(ticket);
                    extensionManager.handleTicketAssignment(ticket);
                });

    }
}