Java Code Examples for org.apache.camel.Exchange#setProperty()

The following examples show how to use org.apache.camel.Exchange#setProperty() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: gumtree-spoon-ast-diff   File: file_t.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the given {@link org.apache.camel.processor.aggregate.AggregationStrategy} on the {@link Exchange}.
 *
 * @param exchange            the exchange
 * @param aggregationStrategy the strategy
 */
protected void setAggregationStrategyOnExchange(Exchange exchange, AggregationStrategy aggregationStrategy) {
    Map<?, ?> property = exchange.getProperty(Exchange.AGGREGATION_STRATEGY, Map.class);
    Map<Object, AggregationStrategy> map = CastUtils.cast(property);
    if (map == null) {
        map = new ConcurrentHashMap<Object, AggregationStrategy>();
    } else {
        // it is not safe to use the map directly as the exchange doesn't have the deep copy of it's properties
        // we just create a new copy if we need to change the map
        map = new ConcurrentHashMap<Object, AggregationStrategy>(map);
    }
    // store the strategy using this processor as the key
    // (so we can store multiple strategies on the same exchange)
    map.put(this, aggregationStrategy);
    exchange.setProperty(Exchange.AGGREGATION_STRATEGY, map);
}
 
Example 2
Source Project: gumtree-spoon-ast-diff   File: file_s.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the given {@link org.apache.camel.processor.aggregate.AggregationStrategy} on the {@link Exchange}.
 *
 * @param exchange            the exchange
 * @param aggregationStrategy the strategy
 */
protected void setAggregationStrategyOnExchange(Exchange exchange, AggregationStrategy aggregationStrategy) {
    Map<?, ?> property = exchange.getProperty(Exchange.AGGREGATION_STRATEGY, Map.class);
    Map<Object, AggregationStrategy> map = CastUtils.cast(property);
    if (map == null) {
        map = new ConcurrentHashMap<Object, AggregationStrategy>();
    } else {
        // it is not safe to use the map directly as the exchange doesn't have the deep copy of it's properties
        // we just create a new copy if we need to change the map
        map = new ConcurrentHashMap<Object, AggregationStrategy>(map);
    }
    // store the strategy using this processor as the key
    // (so we can store multiple strategies on the same exchange)
    map.put(this, aggregationStrategy);
    exchange.setProperty(Exchange.AGGREGATION_STRATEGY, map);
}
 
Example 3
@Test
@SuppressWarnings("unchecked")
public void testJsonTypeTargetProcessing() throws Exception {
    Exchange exchange = new DefaultExchange(camelContext);
    exchange.getIn().setBody("[{\"name\": \"Bernadette\", \"age\": 27},{\"name\": \"Penny\", \"age\": 29}]");

    new DataMapperStepHandler.JsonTypeTargetProcessor().process(exchange);
    assertThat(exchange.getIn().getBody(String.class)).isEqualTo("[{\"name\": \"Bernadette\", \"age\": 27},{\"name\": \"Penny\", \"age\": 29}]");

    exchange.setProperty(DataMapperStepHandler.DATA_MAPPER_AUTO_CONVERSION, true);
    exchange.getIn().setBody("[{\"name\": \"Bernadette\", \"age\": 27},{\"name\": \"Penny\", \"age\": 29}]");

    new DataMapperStepHandler.JsonTypeTargetProcessor().process(exchange);

    List<String> jsonBeans = exchange.getIn().getBody(List.class);
    assertThat(jsonBeans).isEqualTo(Arrays.asList("{\"name\":\"Bernadette\",\"age\":27}", "{\"name\":\"Penny\",\"age\":29}"));
}
 
Example 4
Source Project: syndesis   File: OnExceptionHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEmptyResponseBodyOnError() {
 
    Map<String,String> configuredProperties = new HashMap<>();
    configuredProperties.put(HTTP_RESPONSE_CODE_PROPERTY       , "200");
    configuredProperties.put(HTTP_ERROR_RESPONSE_CODES_PROPERTY, ERROR_RESPONSE_CODES);
    configuredProperties.put(ERROR_RESPONSE_BODY               , "false");

    Exception e = new SyndesisConnectorException(
            "CONNECTOR_ERROR", "error msg test");

    CamelContext context = new DefaultCamelContext();
    Exchange exchange = new ExchangeBuilder(context).build();
    exchange.setProperty(Exchange.EXCEPTION_CAUGHT, e);

    ApiProviderOnExceptionHandler handler = new ApiProviderOnExceptionHandler();
    handler.setProperties(configuredProperties);
    handler.process(exchange);

    Message in = exchange.getIn();
    Assert.assertEquals(Integer.valueOf(500)             ,in.getHeader(Exchange.HTTP_RESPONSE_CODE));
    Assert.assertEquals(""                               ,in.getBody());
}
 
Example 5
Exchange toExchange(RoutingContext ctx) {
    final Exchange exchange = getEndpoint().createExchange();
    Message in = toCamelMessage(ctx, exchange);

    final String charset = ctx.parsedHeaders().contentType().parameter("charset");
    if (charset != null) {
        exchange.setProperty(Exchange.CHARSET_NAME, charset);
        in.setHeader(Exchange.HTTP_CHARACTER_ENCODING, charset);
    }

    exchange.setIn(in);
    return exchange;
}
 
Example 6
private void dispose(Exchange exchange, Mail mail) throws MessagingException {
    LifecycleUtil.dispose(mail.getMessage());
    LifecycleUtil.dispose(mail);

    // stop routing
    exchange.setProperty(Exchange.ROUTE_STOP, true);
}
 
Example 7
Source Project: gumtree-spoon-ast-diff   File: original.java    License: Apache License 2.0 5 votes vote down vote up
protected void updateNewExchange(Exchange exchange, int index, Iterable<ProcessorExchangePair> allPairs,
                                 Iterator<ProcessorExchangePair> it) {
    exchange.setProperty(Exchange.MULTICAST_INDEX, index);
    if (it.hasNext()) {
        exchange.setProperty(Exchange.MULTICAST_COMPLETE, Boolean.FALSE);
    } else {
        exchange.setProperty(Exchange.MULTICAST_COMPLETE, Boolean.TRUE);
    }
}
 
Example 8
Source Project: gumtree-spoon-ast-diff   File: patched.java    License: Apache License 2.0 5 votes vote down vote up
protected void updateNewExchange(Exchange exchange, int index, Iterable<ProcessorExchangePair> allPairs,
                                 Iterator<ProcessorExchangePair> it) {
    exchange.setProperty(Exchange.MULTICAST_INDEX, index);
    if (it.hasNext()) {
        exchange.setProperty(Exchange.MULTICAST_COMPLETE, Boolean.FALSE);
    } else {
        exchange.setProperty(Exchange.MULTICAST_COMPLETE, Boolean.TRUE);
    }
}
 
Example 9
@Test
public void testJsonTypeTargetProcessingNoArrayType() throws Exception {
    Exchange exchange = new DefaultExchange(camelContext);
    exchange.getIn().setBody("{\"name\": \"Leonard\", \"age\": 30}");

    new DataMapperStepHandler.JsonTypeTargetProcessor().process(exchange);

    assertThat(exchange.getIn().getBody(String.class)).isEqualTo("{\"name\": \"Leonard\", \"age\": 30}");

    exchange.setProperty(DataMapperStepHandler.DATA_MAPPER_AUTO_CONVERSION, true);
    new DataMapperStepHandler.JsonTypeTargetProcessor().process(exchange);

    assertThat(exchange.getIn().getBody(String.class)).isEqualTo("{\"name\": \"Leonard\", \"age\": 30}");
}
 
Example 10
@Test
public void testJsonTypeTargetProcessingNoJsonType() throws Exception {
    Exchange exchange = new DefaultExchange(camelContext);
    exchange.getIn().setBody("something completely different");

    new DataMapperStepHandler.JsonTypeTargetProcessor().process(exchange);

    assertThat(exchange.getIn().getBody(String.class)).isEqualTo("something completely different");

    exchange.setProperty(DataMapperStepHandler.DATA_MAPPER_AUTO_CONVERSION, true);
    new DataMapperStepHandler.JsonTypeTargetProcessor().process(exchange);

    assertThat(exchange.getIn().getBody(String.class)).isEqualTo("something completely different");
}
 
Example 11
private void handleProcessingExceptions(Exchange exchange, String batchJobId, Exception exception) {
    exchange.getIn().setHeader("IngestionMessageType", MessageType.ERROR.name());
    exchange.setProperty("purge.complete", "Errors encountered during purge process");

    messageReport.error(reportStats, new ProcessorSource(BATCH_JOB_STAGE.getName()),
            CoreMessageCode.CORE_0036, exception.toString());
}
 
Example 12
protected void copyResultToCamel(Exchange exchange, ProcessInstance pi) {
    exchange.setProperty(PROCESS_ID_PROPERTY, pi.getProcessInstanceId());

    Map<String, Object> returnVars = getFlowableEndpoint().getReturnVarMap();

    if (returnVars != null && returnVars.size() > 0) {

        Map<String, Object> processVariables = null;
        if (repositoryService.isFlowable5ProcessDefinition(pi.getProcessDefinitionId())) {
            // There is no command context at this, point, therefore we need to wrap it in one to get the v5 variables
            processVariables = managementService.executeCommand(commandContext -> {
                Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler();
                return compatibilityHandler.getVariables(pi);
            });
        } else {
            processVariables = ((ExecutionEntity) pi).getVariables();
        }

        if (processVariables != null) {
            for (String variableName : returnVars.keySet()) {
                if (processVariables.containsKey(variableName)) {
                    exchange.setProperty(variableName, processVariables.get(variableName));
                }
            }
        }
    }
}
 
Example 13
@Override
public void process(Exchange exchange) {
    exchange.setProperty("optimizeBit", true);
}
 
Example 14
Source Project: gumtree-spoon-ast-diff   File: file_s.java    License: Apache License 2.0 4 votes vote down vote up
protected static void setToEndpoint(Exchange exchange, Processor processor) {
    if (processor instanceof Producer) {
        Producer producer = (Producer) processor;
        exchange.setProperty(Exchange.TO_ENDPOINT, producer.getEndpoint().getEndpointUri());
    }
}
 
Example 15
Source Project: flowable-engine   File: CamelBehavior.java    License: Apache License 2.0 4 votes vote down vote up
protected void copyVariablesToProperties(Map<String, Object> variables, Exchange exchange) {
    for (Map.Entry<String, Object> var : variables.entrySet()) {
        exchange.setProperty(var.getKey(), var.getValue());
    }
}
 
Example 16
Source Project: gumtree-spoon-ast-diff   File: file_t.java    License: Apache License 2.0 4 votes vote down vote up
protected static void setToEndpoint(Exchange exchange, Processor processor) {
    if (processor instanceof Producer) {
        Producer producer = (Producer) processor;
        exchange.setProperty(Exchange.TO_ENDPOINT, producer.getEndpoint().getEndpointUri());
    }
}
 
Example 17
Source Project: gumtree-spoon-ast-diff   File: file_s.java    License: Apache License 2.0 4 votes vote down vote up
protected static void setToEndpoint(Exchange exchange, Processor processor) {
    if (processor instanceof Producer) {
        Producer producer = (Producer) processor;
        exchange.setProperty(Exchange.TO_ENDPOINT, producer.getEndpoint().getEndpointUri());
    }
}
 
Example 18
Source Project: gumtree-spoon-ast-diff   File: patched.java    License: Apache License 2.0 4 votes vote down vote up
protected static void setToEndpoint(Exchange exchange, Processor processor) {
    if (processor instanceof Producer) {
        Producer producer = (Producer) processor;
        exchange.setProperty(Exchange.TO_ENDPOINT, producer.getEndpoint().getEndpointUri());
    }
}
 
Example 19
Source Project: gumtree-spoon-ast-diff   File: file_s.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Common work which must be done when we are done multicasting.
 * <p/>
 * This logic applies for both running synchronous and asynchronous as there are multiple exist points
 * when using the asynchronous routing engine. And therefore we want the logic in one method instead
 * of being scattered.
 *
 * @param original     the original exchange
 * @param subExchange  the current sub exchange, can be <tt>null</tt> for the synchronous part
 * @param pairs        the pairs with the exchanges to process
 * @param callback     the callback
 * @param doneSync     the <tt>doneSync</tt> parameter to call on callback
 * @param forceExhaust whether or not error handling is exhausted
 */
protected void doDone(Exchange original, Exchange subExchange, final Iterable<ProcessorExchangePair> pairs,
                      AsyncCallback callback, boolean doneSync, boolean forceExhaust) {

    // we are done so close the pairs iterator
    if (pairs != null && pairs instanceof Closeable) {
        IOHelper.close((Closeable) pairs, "pairs", LOG);
    }

    AggregationStrategy strategy = getAggregationStrategy(subExchange);
    // invoke the on completion callback
    if (strategy instanceof CompletionAwareAggregationStrategy) {
        ((CompletionAwareAggregationStrategy) strategy).onCompletion(subExchange);
    }

    // cleanup any per exchange aggregation strategy
    removeAggregationStrategyFromExchange(original);

    // we need to know if there was an exception, and if the stopOnException option was enabled
    // also we would need to know if any error handler has attempted redelivery and exhausted
    boolean stoppedOnException = false;
    boolean exception = false;
    boolean exhaust = forceExhaust || subExchange != null && (subExchange.getException() != null || ExchangeHelper.isRedeliveryExhausted(subExchange));
    if (original.getException() != null || subExchange != null && subExchange.getException() != null) {
        // there was an exception and we stopped
        stoppedOnException = isStopOnException();
        exception = true;
    }

    // must copy results at this point
    if (subExchange != null) {
        if (stoppedOnException) {
            // if we stopped due an exception then only propagte the exception
            original.setException(subExchange.getException());
        } else {
            // copy the current result to original so it will contain this result of this eip
            ExchangeHelper.copyResults(original, subExchange);
        }
    }

    // .. and then if there was an exception we need to configure the redelivery exhaust
    // for example the noErrorHandler will not cause redelivery exhaust so if this error
    // handled has been in use, then the exhaust would be false (if not forced)
    if (exception) {
        // multicast uses error handling on its output processors and they have tried to redeliver
        // so we shall signal back to the other error handlers that we are exhausted and they should not
        // also try to redeliver as we will then do that twice
        original.setProperty(Exchange.REDELIVERY_EXHAUSTED, exhaust);
    }

    callback.done(doneSync);
}
 
Example 20
Source Project: syncope   File: DeleteProducer.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void process(final Exchange exchange) throws Exception {
    String key = exchange.getIn().getBody(String.class);
    Set<String> excludedResources = exchange.getProperty("excludedResources", Set.class);
    Boolean nullPriorityAsync = exchange.getProperty("nullPriorityAsync", Boolean.class);

    if (null != getAnyTypeKind()) {
        List<PropagationTaskInfo> taskInfos;
        PropagationReporter reporter;
        switch (getAnyTypeKind()) {
            case USER:
                PropagationByResource<String> propByRes = new PropagationByResource<>();
                propByRes.set(ResourceOperation.DELETE, userDAO.findAllResourceKeys(key));

                PropagationByResource<Pair<String, String>> propByLinkedAccount = new PropagationByResource<>();
                userDAO.findLinkedAccounts(key).forEach(account -> propByLinkedAccount.add(
                        ResourceOperation.DELETE,
                        Pair.of(account.getResource().getKey(), account.getConnObjectKeyValue())));

                // Note here that we can only notify about "delete", not any other
                // task defined in workflow process definition: this because this
                // information could only be available after uwfAdapter.delete(), which
                // will also effectively remove user from db, thus making virtually
                // impossible by NotificationManager to fetch required user information
                taskInfos = getPropagationManager().getUserDeleteTasks(
                        key,
                        propByRes,
                        propByLinkedAccount,
                        excludedResources);
                reporter = getPropagationTaskExecutor().execute(taskInfos, nullPriorityAsync, getExecutor());
                exchange.setProperty("statuses", reporter.getStatuses());
                break;

            case GROUP:
                taskInfos = new ArrayList<>();
                // Generate propagation tasks for deleting users from group resources, if they are on those
                // resources only because of the reason being deleted (see SYNCOPE-357)
                groupDataBinder.findUsersWithTransitiveResources(key).
                        forEach((anyKey, anyPropByRes) -> taskInfos.addAll(
                        getPropagationManager().getDeleteTasks(
                                AnyTypeKind.USER,
                                anyKey,
                                anyPropByRes,
                                null,
                                excludedResources)));
                groupDataBinder.findAnyObjectsWithTransitiveResources(key).
                        forEach((anyKey, anyPropByRes) -> {
                            taskInfos.addAll(getPropagationManager().getDeleteTasks(
                                    AnyTypeKind.ANY_OBJECT,
                                    anyKey,
                                    anyPropByRes,
                                    null,
                                    excludedResources));
                        });
                // Generate propagation tasks for deleting this group from resources
                taskInfos.addAll(getPropagationManager().getDeleteTasks(
                        AnyTypeKind.GROUP,
                        key,
                        null,
                        null,
                        null));
                reporter = getPropagationTaskExecutor().execute(taskInfos, nullPriorityAsync, getExecutor());
                exchange.setProperty("statuses", reporter.getStatuses());
                break;

            case ANY_OBJECT:
                taskInfos = getPropagationManager().getDeleteTasks(
                        AnyTypeKind.ANY_OBJECT,
                        key,
                        null,
                        null,
                        excludedResources);
                reporter = getPropagationTaskExecutor().execute(taskInfos, nullPriorityAsync, getExecutor());
                exchange.setProperty("statuses", reporter.getStatuses());
                break;

            default:
                break;
        }
    }
}