Java Examples for org.apache.camel.AsyncCallback

The following java examples will help you to understand the usage of org.apache.camel.AsyncCallback. These source code samples are taken from different open source projects.

Example 1
Project: camel-cookbook-examples-master  File: SlowOperationProcessor.java View source code
@Override
public boolean process(final Exchange exchange, final AsyncCallback asyncCallback) {
    final boolean completedSynchronously = false;
    backgroundExecutor.submit(new Runnable() {

        @Override
        public void run() {
            log.info("Running operation asynchronously");
            try {
                log.info("Doing something slowly");
                // this runs slowly
                Thread.sleep(200);
                log.info("...done");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            // the current thread will continue to process the exchange
            // through the remainder of the route
            asyncCallback.done(completedSynchronously);
        }
    });
    return completedSynchronously;
}
Example 2
Project: camel-master  File: RedeliveryErrorHandler.java View source code
public Boolean call() throws Exception {
    // prepare for redelivery
    prepareExchangeForRedelivery(exchange, data);
    // letting onRedeliver be executed at first
    deliverToOnRedeliveryProcessor(exchange, data);
    if (log.isTraceEnabled()) {
        log.trace("Redelivering exchangeId: {} -> {} for Exchange: {}", new Object[] { exchange.getExchangeId(), outputAsync, exchange });
    }
    // emmit event we are doing redelivery
    EventHelper.notifyExchangeRedelivery(exchange.getContext(), exchange, data.redeliveryCounter);
    // process the exchange (also redelivery)
    boolean sync;
    if (data.redeliverFromSync) {
        // this redelivery task was scheduled from synchronous, which we forced to be asynchronous from
        // this error handler, which means we have to invoke the callback with false, to have the callback
        // be notified when we are done
        sync = outputAsync.process(exchange, new AsyncCallback() {

            public void done(boolean doneSync) {
                log.trace("Redelivering exchangeId: {} done sync: {}", exchange.getExchangeId(), doneSync);
                // mark we are in sync mode now
                data.sync = false;
                // and it has not been handled by the error processor
                if (isDone(exchange)) {
                    callback.done(false);
                    return;
                }
                // error occurred so loop back around which we do by invoking the processAsyncErrorHandler
                processAsyncErrorHandler(exchange, callback, data);
            }
        });
    } else {
        // this redelivery task was scheduled from asynchronous, which means we should only
        // handle when the asynchronous task was done
        sync = outputAsync.process(exchange, new AsyncCallback() {

            public void done(boolean doneSync) {
                log.trace("Redelivering exchangeId: {} done sync: {}", exchange.getExchangeId(), doneSync);
                // this callback should only handle the async case
                if (doneSync) {
                    return;
                }
                // mark we are in async mode now
                data.sync = false;
                // and it has not been handled by the error processor
                if (isDone(exchange)) {
                    callback.done(doneSync);
                    return;
                }
                // error occurred so loop back around which we do by invoking the processAsyncErrorHandler
                processAsyncErrorHandler(exchange, callback, data);
            }
        });
    }
    return sync;
}
Example 3
Project: iSpace-master  File: SolrConsumer.java View source code
@Override
protected int poll() throws Exception {
    String queryString = getSolrEndpoint().getQuery();
    queryString = queryString.replaceAll("FROMLAST", format.format(lastRetrievalTime));
    lastRetrievalTime = new Date();
    SolrQuery query = new SolrQuery(queryString);
    if (getSolrEndpoint().getQueryHandler() != null) {
        query.setQueryType(getSolrEndpoint().getQueryHandler());
    }
    /** Search and set result set. Notice that this will return the results upto the 
		 * configured number of rows. More results may thus be in the repository. */
    QueryResponse response = getSolrEndpoint().getServer().query(query);
    if (response.getStatus() != 0) {
        log.error("Failed to execute retrieval request. Failed with status '" + response.getStatus() + "'.");
    }
    /** Get the result set. */
    ResultSet results = Utilities.getResultSet(response, (int) response.getResults().getNumFound(), queryString);
    /** Either deliver the complete result set as on batch, or as a stream. */
    if (getSolrEndpoint().getDeliveryMode().equals("batch")) {
        Exchange exchange = getEndpoint().createExchange();
        exchange.getIn().setBody(results);
        getAsyncProcessor().process(exchange, new AsyncCallback() {

            public void done(boolean doneSync) {
                LOG.trace("Done processing sending Batch.");
            }
        });
    } else {
        /** Iterate through the result set and inject the io objects. */
        for (Object io : results.informationobjects) {
            Exchange exchange = getEndpoint().createExchange();
            exchange.getIn().setBody(io);
            getAsyncProcessor().process(exchange, new AsyncCallback() {

                public void done(boolean doneSync) {
                    LOG.trace("Done processing streaming information objects.");
                }
            });
        }
        for (Facet facet : results.facets) {
            Exchange exchange = getEndpoint().createExchange();
            exchange.getIn().setBody(facet);
            getAsyncProcessor().process(exchange, new AsyncCallback() {

                public void done(boolean doneSync) {
                    LOG.trace("Done streaming facets.");
                }
            });
        }
    /** TODO Should the suggestions and statistics also be injected? */
    }
    return 0;
}
Example 4
Project: camelinaction2-master  File: TimeoutProducer.java View source code
@Override
public boolean process(final Exchange exchange, final AsyncCallback callback) {
    // validate that the message has some data
    try {
        String body = exchange.getIn().getBody(String.class);
        if (body == null || body.contains("Donkey")) {
            throw new IllegalArgumentException("Real developers ride Camels");
        }
    } catch (Exception e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    }
    CallRemoteSystemTask task = new CallRemoteSystemTask(exchange, callback, timeout);
    executor.submit(task);
    return false;
}
Example 5
Project: karaf-webconsole-master  File: TraceProcessor.java View source code
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
    CamelContext context = exchange.getContext();
    if (!context.isTracing()) {
        return super.process(exchange, callback);
    }
    properties.put("exchangeId", exchange.getExchangeId());
    properties.put("exchangeProperties", (Serializable) exchange.getProperties());
    Message msg = exchange.getIn();
    if (msg != null) {
        properties.put("exchangeInId", msg.getMessageId());
        properties.put("exchangeInHeaders", new HashMap<String, Object>(msg.getHeaders()));
        Object body = msg.getBody();
        if (body instanceof Serializable) {
            properties.put("exchangeInBody", (Serializable) body);
        } else {
            properties.put("exchangeInBody", "- not serializable -");
        }
    } else {
        properties.put("exchangeInId", null);
    }
    msg = exchange.getOut();
    if (msg != null) {
        properties.put("exchangeOutId", msg.getMessageId());
        properties.put("exchangeOutHeaders", new HashMap<String, Object>(msg.getHeaders()));
        Object body = msg.getBody();
        if (body instanceof Serializable) {
            properties.put("exchangeOutBody", (Serializable) body);
        } else {
            properties.put("exchangeOutBody", "- not serializable -");
        }
    } else {
        properties.put("exchangeOutId", null);
    }
    return super.process(exchange, callback);
}
Example 6
Project: quickstarts-master  File: CountingProcessor.java View source code
@Override
public boolean process(Exchange exchange, final AsyncCallback callback) {
    final long time = System.currentTimeMillis();
    return super.process(exchange, new AsyncCallback() {

        @Override
        public void done(boolean doneSync) {
            if (doneSync) {
                long processingTime = System.currentTimeMillis() - time;
                _logger.info("Route node " + _node.getLabel() + " took " + processingTime + " ms");
            }
            callback.done(doneSync);
        }
    });
}
Example 7
Project: activemq-master  File: BrokerProducer.java View source code
protected boolean processInOnly(final Exchange exchange, final AsyncCallback callback) {
    try {
        ActiveMQMessage message = getMessage(exchange);
        if (message != null) {
            message.setDestination(brokerEndpoint.getDestination());
            //if the ProducerBrokerExchange is null the broker will create it
            ProducerBrokerExchange producerBrokerExchange = (ProducerBrokerExchange) exchange.getProperty(BrokerEndpoint.PRODUCER_BROKER_EXCHANGE);
            brokerEndpoint.inject(producerBrokerExchange, message);
        }
    } catch (Exception e) {
        exchange.setException(e);
    }
    callback.done(true);
    return true;
}
Example 8
Project: camel-extra-master  File: FirebaseProducer.java View source code
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
    final Message in = exchange.getIn();
    final Message out = exchange.getOut();
    String firebaseKey = (String) in.getHeader(endpoint.getKeyName());
    Object value = in.getBody();
    DatabaseReference ref = FirebaseDatabase.getInstance(endpoint.getFirebaseApp()).getReference(rootReference).child(firebaseKey);
    final boolean reply = endpoint.isReply();
    out.setHeaders(in.getHeaders());
    if (reply) {
        // Wait for reply
        processReply(exchange, callback, value, ref);
    } else {
        // Fire and forget
        ref.setValue(value);
        out.setBody(in.getBody());
        callback.done(true);
    }
    return !reply;
}
Example 9
Project: camelinaction-master  File: ErpProducer.java View source code
public boolean process(final Exchange exchange, final AsyncCallback callback) {
    // simulate async communication using a thread pool in which will return a reply in 5 seconds.
    executor.submit(new ERPTask(exchange, callback));
    // return false to tell Camel that we process asynchronously
    // which enables the Camel routing engine to know this and act accordingly
    // notice the ERPTask must invoke the callback.done(false) because what
    // we return here must match the boolean in the callback.done method.
    log.info("Returning false (processing will continue asynchronously)");
    return false;
}
Example 10
Project: CamelInAction-source-master  File: ErpProducer.java View source code
public boolean process(final Exchange exchange, final AsyncCallback callback) {
    // simulate async communication using a thread pool in which will return a reply in 5 seconds.
    executor.submit(new ERPTask(exchange, callback));
    // return false to tell Camel that we process asynchronously
    // which enables the Camel routing engine to know this and act accordingly
    // notice the ERPTask must invoke the callback.done(false) because what
    // we return here must match the boolean in the callback.done method.
    log.info("Returning false (processing will continue asynchronously)");
    return false;
}
Example 11
Project: camel-spring-amqp-master  File: SpringAMQPProducer.java View source code
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
    if (!isRunAllowed()) {
        if (exchange.getException() == null)
            exchange.setException(new RejectedExecutionException("SpringAMQPProducer not started yet!"));
        callback.done(true);
        return true;
    }
    if (this.threadPool == null) {
        if (exchange.getException() == null)
            exchange.setException(new RejectedExecutionException("SpringAMQPProducer is not yet initialized!"));
        callback.done(true);
        return true;
    }
    this.threadPool.submit(new AMQPProducerTask(exchange, callback));
    return false;
}
Example 12
Project: camel-undertow-master  File: UndertowProducer.java View source code
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
    try {
        final UndertowClient client = UndertowClient.getInstance();
        XnioWorker worker = Xnio.getInstance().createWorker(OptionMap.EMPTY);
        IoFuture<ClientConnection> connect = client.connect(endpoint.getHttpURI(), worker, new ByteBufferSlicePool(BufferAllocator.DIRECT_BYTE_BUFFER_ALLOCATOR, 8192, 8192 * 8192), OptionMap.EMPTY);
        ClientRequest request = new ClientRequest();
        request.setProtocol(Protocols.HTTP_1_1);
        request.setPath(endpoint.getHttpURI().getPath());
        Object body = getRequestBody(request, exchange);
        TypeConverter tc = endpoint.getCamelContext().getTypeConverter();
        ByteBuffer bodyAsByte = tc.convertTo(ByteBuffer.class, body);
        if (body != null) {
            request.getRequestHeaders().put(Headers.CONTENT_LENGTH, bodyAsByte.array().length);
        }
        connect.get().sendRequest(request, new UndertowProducerCallback(bodyAsByte, exchange, callback));
    } catch (IOException e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    }
    // use async routing engine
    return false;
}
Example 13
Project: dcm4che-master  File: DicomConsumer.java View source code
@Override
public void onDimseRQ(Association as, PresentationContext pc, Dimse dimse, Attributes cmd, PDVInputStream data) throws IOException {
    final int msgid = cmd.getInt(Tag.MessageID, 0);
    Exchange exchange = getEndpoint().createExchange(dimse, cmd, data);
    AsyncCallback callback = new EndpointDimseRQHandlerAsyncCallback(as, pc, dimse, msgid, exchange);
    AsyncProcessorHelper.process(getAsyncProcessor(), exchange, callback);
}
Example 14
Project: atricore-idbus-master  File: OsgiIDBusServlet.java View source code
@Override
protected void service(HttpServletRequest req, HttpServletResponse r) throws ServletException, IOException {
    // FIX For a bug in CXF!
    HttpServletResponse res = new WHttpServletResponse(r);
    // Lookup identity mediation registry
    if (registry == null)
        registry = lookupIdentityMediationUnitRegistry();
    if (registry == null) {
        logger.error("No identity mediation registry found ");
        throw new ServletException("No identity mediation registry found!");
    }
    HttpConsumer consumer = resolveConsumer(req);
    if (consumer == null) {
        log("No HTTP Consumer found for " + req.getRequestURL().toString() + " Sending 404 (Not Found) HTTP Status.");
        logger.warn("Make sure your appliance is STARTED");
        res.setStatus(HttpServletResponse.SC_NOT_FOUND);
        // TODO : Send 404 page
        return;
    }
    IDBusHttpEndpoint endpoint = (IDBusHttpEndpoint) consumer.getEndpoint();
    final Continuation continuation = ContinuationSupport.getContinuation(req, null);
    if (continuation.isNew()) {
        logger.trace("New Continuation");
        // Have camel process the HTTP exchange.
        final HttpExchange exchange = new HttpExchange(endpoint, req, res);
        boolean sync = consumer.getAsyncProcessor().process(exchange, new AsyncCallback() {

            public void done(boolean sync) {
                if (sync) {
                    return;
                }
                continuation.setObject(exchange);
                continuation.resume();
            }
        });
        if (!sync) {
            // Wait for the exchange to get processed.
            // This might block until it completes or it might return via an exception and
            // then this method is re-invoked once the the exchange has finished processing
            logger.trace("New Continuation suspended");
            continuation.suspend(0);
        }
        // HC: The getBinding() is interesting because it illustrates the
        // impedance miss-match between HTTP's stream oriented protocol, and
        // Camels more message oriented protocol exchanges.
        // now lets output to the response
        logger.trace("Writing response");
        consumer.getBinding().writeResponse(exchange, res);
        return;
    }
    if (continuation.isResumed()) {
        logger.trace("Resumed Continuation");
        HttpExchange exchange = (HttpExchange) continuation.getObject();
        // now lets output to the response
        consumer.getBinding().writeResponse(exchange, res);
        return;
    }
}
Example 15
Project: camel-disruptor-master  File: DisruptorProducer.java View source code
@Override
public boolean process(final Exchange exchange, final AsyncCallback callback) {
    WaitForTaskToComplete wait = waitForTaskToComplete;
    if (exchange.getProperty(Exchange.ASYNC_WAIT) != null) {
        wait = exchange.getProperty(Exchange.ASYNC_WAIT, WaitForTaskToComplete.class);
    }
    if (wait == WaitForTaskToComplete.Always || (wait == WaitForTaskToComplete.IfReplyExpected && ExchangeHelper.isOutCapable(exchange))) {
        // do not handover the completion as we wait for the copy to complete, and copy its result back when it done
        final Exchange copy = prepareCopy(exchange, false);
        // latch that waits until we are complete
        final CountDownLatch latch = new CountDownLatch(1);
        // we should wait for the reply so install a on completion so we know when its complete
        copy.addOnCompletion(new SynchronizationAdapter() {

            @Override
            public void onDone(final Exchange response) {
                // check for timeout, which then already would have invoked the latch
                if (latch.getCount() == 0) {
                    if (log.isTraceEnabled()) {
                        log.trace("{}. Timeout occurred so response will be ignored: {}", this, response.hasOut() ? response.getOut() : response.getIn());
                    }
                } else {
                    if (log.isTraceEnabled()) {
                        log.trace("{} with response: {}", this, response.hasOut() ? response.getOut() : response.getIn());
                    }
                    try {
                        ExchangeHelper.copyResults(exchange, response);
                    } finally {
                        // always ensure latch is triggered
                        latch.countDown();
                    }
                }
            }

            @Override
            public boolean allowHandover() {
                // at this point in the routing (at this leg), instead of at the very last (this ensure timeout is honored)
                return false;
            }

            @Override
            public String toString() {
                return "onDone at endpoint: " + endpoint;
            }
        });
        doPublish(copy);
        if (timeout > 0) {
            if (log.isTraceEnabled()) {
                log.trace("Waiting for task to complete using timeout (ms): {} at [{}]", timeout, endpoint.getEndpointUri());
            }
            // lets see if we can get the task done before the timeout
            boolean done = false;
            try {
                done = latch.await(timeout, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
            }
            if (!done) {
                // Remove timed out Exchange from disruptor endpoint.
                // We can't actually remove a published exchange from an active Disruptor.
                // Instead we prevent processing of the exchange by setting a Property on the exchange and the value
                // would be an AtomicBoolean. This is set by the Producer and the Consumer would look up that Property and
                // check the AtomicBoolean. If the AtomicBoolean says that we are good to proceed, it will process the
                // exchange. If false, it will simply disregard the exchange.
                // But since the Property map is a Concurrent one, maybe we don't need the AtomicBoolean. Check with Simon.
                // Also check the TimeoutHandler of the new Disruptor 3.0.0, consider making the switch to the latest version.
                exchange.setProperty(DisruptorEndpoint.DISRUPTOR_IGNORE_EXCHANGE, true);
                exchange.setException(new ExchangeTimedOutException(exchange, timeout));
                // count down to indicate timeout
                latch.countDown();
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Waiting for task to complete (blocking) at [{}]", endpoint.getEndpointUri());
            }
            // no timeout then wait until its done
            try {
                latch.await();
            } catch (InterruptedException e) {
            }
        }
    } else {
        // no wait, eg its a InOnly then just publish to the ringbuffer and return
        // handover the completion so its the copy which performs that, as we do not wait
        final Exchange copy = prepareCopy(exchange, true);
        doPublish(copy);
    }
    // we use OnCompletion on the Exchange to callback and wait for the Exchange to be done
    // so we should just signal the callback we are done synchronously
    callback.done(true);
    return true;
}
Example 16
Project: camel-salesforce-master  File: AbstractRestProcessor.java View source code
@Override
public final boolean process(final Exchange exchange, final AsyncCallback callback) {
    // pre-process request message
    try {
        processRequest(exchange);
    } catch (SalesforceException e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    } catch (RuntimeException e) {
        exchange.setException(new SalesforceException(e.getMessage(), e));
        callback.done(true);
        return true;
    }
    // call Salesforce asynchronously
    try {
        // call Operation using REST client
        switch(operationName) {
            case GET_VERSIONS:
                restClient.getVersions(new RestClient.ResponseCallback() {

                    @Override
                    public void onResponse(InputStream response, SalesforceException exception) {
                        // process response entity and create out message
                        processResponse(exchange, response, exception, callback);
                    }
                });
                break;
            case GET_RESOURCES:
                restClient.getResources(new RestClient.ResponseCallback() {

                    @Override
                    public void onResponse(InputStream response, SalesforceException exception) {
                        processResponse(exchange, response, exception, callback);
                    }
                });
                break;
            case GET_GLOBAL_OBJECTS:
                restClient.getGlobalObjects(new RestClient.ResponseCallback() {

                    @Override
                    public void onResponse(InputStream response, SalesforceException exception) {
                        processResponse(exchange, response, exception, callback);
                    }
                });
                break;
            case GET_BASIC_INFO:
                String sObjectName = getParameter(SOBJECT_NAME, exchange, USE_BODY, NOT_OPTIONAL);
                restClient.getBasicInfo(sObjectName, new RestClient.ResponseCallback() {

                    @Override
                    public void onResponse(InputStream response, SalesforceException exception) {
                        processResponse(exchange, response, exception, callback);
                    }
                });
                break;
            case GET_DESCRIPTION:
                sObjectName = getParameter(SOBJECT_NAME, exchange, USE_BODY, NOT_OPTIONAL);
                restClient.getDescription(sObjectName, new RestClient.ResponseCallback() {

                    @Override
                    public void onResponse(InputStream response, SalesforceException exception) {
                        processResponse(exchange, response, exception, callback);
                    }
                });
                break;
            case GET_SOBJECT:
                {
                    String sObjectIdValue;
                    // determine parameters from input AbstractSObject
                    final AbstractSObjectBase sObjectBase = exchange.getIn().getBody(AbstractSObjectBase.class);
                    if (sObjectBase != null) {
                        sObjectName = sObjectBase.getClass().getSimpleName();
                        sObjectIdValue = sObjectBase.getId();
                    } else {
                        sObjectName = getParameter(SOBJECT_NAME, exchange, IGNORE_BODY, NOT_OPTIONAL);
                        sObjectIdValue = getParameter(SOBJECT_ID, exchange, USE_BODY, NOT_OPTIONAL);
                    }
                    final String sObjectId = sObjectIdValue;
                    // use sObject name to load class
                    setResponseClass(exchange, sObjectName);
                    // get optional field list
                    String fieldsValue = getParameter(SOBJECT_FIELDS, exchange, IGNORE_BODY, IS_OPTIONAL);
                    String[] fields = null;
                    if (fieldsValue != null) {
                        fields = fieldsValue.split(",");
                    }
                    restClient.getSObject(sObjectName, sObjectId, fields, new RestClient.ResponseCallback() {

                        @Override
                        public void onResponse(InputStream response, SalesforceException exception) {
                            processResponse(exchange, response, exception, callback);
                            restoreFields(exchange, sObjectBase, sObjectId, null, null);
                        }
                    });
                    break;
                }
            case CREATE_SOBJECT:
                {
                    // determine parameters from input AbstractSObject
                    AbstractSObjectBase sObjectBase = exchange.getIn().getBody(AbstractSObjectBase.class);
                    if (sObjectBase != null) {
                        sObjectName = sObjectBase.getClass().getSimpleName();
                    } else {
                        sObjectName = getParameter(SOBJECT_NAME, exchange, IGNORE_BODY, NOT_OPTIONAL);
                    }
                    restClient.createSObject(sObjectName, getRequestStream(exchange), new RestClient.ResponseCallback() {

                        @Override
                        public void onResponse(InputStream response, SalesforceException exception) {
                            processResponse(exchange, response, exception, callback);
                        }
                    });
                    break;
                }
            case UPDATE_SOBJECT:
                {
                    // determine parameters from input AbstractSObject
                    final AbstractSObjectBase sObjectBase = exchange.getIn().getBody(AbstractSObjectBase.class);
                    String sObjectId;
                    if (sObjectBase != null) {
                        sObjectName = sObjectBase.getClass().getSimpleName();
                        // remember the sObject Id
                        sObjectId = sObjectBase.getId();
                        // clear base object fields, which cannot be updated
                        sObjectBase.clearBaseFields();
                    } else {
                        sObjectName = getParameter(SOBJECT_NAME, exchange, IGNORE_BODY, NOT_OPTIONAL);
                        sObjectId = getParameter(SOBJECT_ID, exchange, IGNORE_BODY, NOT_OPTIONAL);
                    }
                    final String finalsObjectId = sObjectId;
                    restClient.updateSObject(sObjectName, sObjectId, getRequestStream(exchange), new RestClient.ResponseCallback() {

                        @Override
                        public void onResponse(InputStream response, SalesforceException exception) {
                            processResponse(exchange, response, exception, callback);
                            restoreFields(exchange, sObjectBase, finalsObjectId, null, null);
                        }
                    });
                    break;
                }
            case DELETE_SOBJECT:
                {
                    // determine parameters from input AbstractSObject
                    final AbstractSObjectBase sObjectBase = exchange.getIn().getBody(AbstractSObjectBase.class);
                    String sObjectIdValue;
                    if (sObjectBase != null) {
                        sObjectName = sObjectBase.getClass().getSimpleName();
                        sObjectIdValue = sObjectBase.getId();
                    } else {
                        sObjectName = getParameter(SOBJECT_NAME, exchange, IGNORE_BODY, NOT_OPTIONAL);
                        sObjectIdValue = getParameter(SOBJECT_ID, exchange, USE_BODY, NOT_OPTIONAL);
                    }
                    final String sObjectId = sObjectIdValue;
                    restClient.deleteSObject(sObjectName, sObjectId, new RestClient.ResponseCallback() {

                        @Override
                        public void onResponse(InputStream response, SalesforceException exception) {
                            processResponse(exchange, response, exception, callback);
                            restoreFields(exchange, sObjectBase, sObjectId, null, null);
                        }
                    });
                    break;
                }
            case GET_SOBJECT_WITH_ID:
                {
                    Object oldValue = null;
                    String sObjectExtIdValue;
                    final String sObjectExtIdName = getParameter(SOBJECT_EXT_ID_NAME, exchange, IGNORE_BODY, NOT_OPTIONAL);
                    // determine parameters from input AbstractSObject
                    final AbstractSObjectBase sObjectBase = exchange.getIn().getBody(AbstractSObjectBase.class);
                    if (sObjectBase != null) {
                        sObjectName = sObjectBase.getClass().getSimpleName();
                        oldValue = getAndClearPropertyValue(sObjectBase, sObjectExtIdName);
                        sObjectExtIdValue = oldValue.toString();
                    } else {
                        sObjectName = getParameter(SOBJECT_NAME, exchange, IGNORE_BODY, NOT_OPTIONAL);
                        sObjectExtIdValue = getParameter(SOBJECT_EXT_ID_VALUE, exchange, USE_BODY, NOT_OPTIONAL);
                    }
                    // use sObject name to load class
                    setResponseClass(exchange, sObjectName);
                    final Object finalOldValue = oldValue;
                    restClient.getSObjectWithId(sObjectName, sObjectExtIdName, sObjectExtIdValue, new RestClient.ResponseCallback() {

                        @Override
                        public void onResponse(InputStream response, SalesforceException exception) {
                            processResponse(exchange, response, exception, callback);
                            restoreFields(exchange, sObjectBase, null, sObjectExtIdName, finalOldValue);
                        }
                    });
                    break;
                }
            case UPSERT_SOBJECT:
                {
                    String sObjectExtIdValue;
                    final String sObjectExtIdName = getParameter(SOBJECT_EXT_ID_NAME, exchange, IGNORE_BODY, NOT_OPTIONAL);
                    // determine parameters from input AbstractSObject
                    Object oldValue = null;
                    final AbstractSObjectBase sObjectBase = exchange.getIn().getBody(AbstractSObjectBase.class);
                    if (sObjectBase != null) {
                        sObjectName = sObjectBase.getClass().getSimpleName();
                        oldValue = getAndClearPropertyValue(sObjectBase, sObjectExtIdName);
                        sObjectExtIdValue = oldValue.toString();
                        // clear base object fields, which cannot be updated
                        sObjectBase.clearBaseFields();
                    } else {
                        sObjectName = getParameter(SOBJECT_NAME, exchange, IGNORE_BODY, NOT_OPTIONAL);
                        sObjectExtIdValue = getParameter(SOBJECT_EXT_ID_VALUE, exchange, IGNORE_BODY, NOT_OPTIONAL);
                    }
                    final Object finalOldValue = oldValue;
                    restClient.upsertSObject(sObjectName, sObjectExtIdName, sObjectExtIdValue, getRequestStream(exchange), new RestClient.ResponseCallback() {

                        @Override
                        public void onResponse(InputStream response, SalesforceException exception) {
                            processResponse(exchange, response, exception, callback);
                            restoreFields(exchange, sObjectBase, null, sObjectExtIdName, finalOldValue);
                        }
                    });
                    break;
                }
            case DELETE_SOBJECT_WITH_ID:
                {
                    final String sObjectExtIdName = getParameter(SOBJECT_EXT_ID_NAME, exchange, IGNORE_BODY, NOT_OPTIONAL);
                    // determine parameters from input AbstractSObject
                    Object oldValue = null;
                    final AbstractSObjectBase sObjectBase = exchange.getIn().getBody(AbstractSObjectBase.class);
                    String sObjectExtIdValue;
                    if (sObjectBase != null) {
                        sObjectName = sObjectBase.getClass().getSimpleName();
                        oldValue = getAndClearPropertyValue(sObjectBase, sObjectExtIdName);
                        sObjectExtIdValue = oldValue.toString();
                    } else {
                        sObjectName = getParameter(SOBJECT_NAME, exchange, IGNORE_BODY, NOT_OPTIONAL);
                        sObjectExtIdValue = getParameter(SOBJECT_EXT_ID_VALUE, exchange, USE_BODY, NOT_OPTIONAL);
                    }
                    final Object finalOldValue = oldValue;
                    restClient.deleteSObjectWithId(sObjectName, sObjectExtIdName, sObjectExtIdValue, new RestClient.ResponseCallback() {

                        @Override
                        public void onResponse(InputStream response, SalesforceException exception) {
                            processResponse(exchange, response, exception, callback);
                            restoreFields(exchange, sObjectBase, null, sObjectExtIdName, finalOldValue);
                        }
                    });
                    break;
                }
            case GET_BLOB_FIELD:
                {
                    // get blob field name
                    final String sObjectBlobFieldName = getParameter(SOBJECT_BLOB_FIELD_NAME, exchange, IGNORE_BODY, NOT_OPTIONAL);
                    // determine parameters from input AbstractSObject
                    final AbstractSObjectBase sObjectBase = exchange.getIn().getBody(AbstractSObjectBase.class);
                    String sObjectIdValue;
                    if (sObjectBase != null) {
                        sObjectName = sObjectBase.getClass().getSimpleName();
                        sObjectIdValue = sObjectBase.getId();
                    } else {
                        sObjectName = getParameter(SOBJECT_NAME, exchange, IGNORE_BODY, NOT_OPTIONAL);
                        sObjectIdValue = getParameter(SOBJECT_ID, exchange, USE_BODY, NOT_OPTIONAL);
                    }
                    final String sObjectId = sObjectIdValue;
                    restClient.getBlobField(sObjectName, sObjectId, sObjectBlobFieldName, new RestClient.ResponseCallback() {

                        @Override
                        public void onResponse(InputStream response, SalesforceException exception) {
                            processResponse(exchange, response, exception, callback);
                            restoreFields(exchange, sObjectBase, sObjectId, null, null);
                        }
                    });
                    break;
                }
            case QUERY:
                final String sObjectQuery = getParameter(SOBJECT_QUERY, exchange, USE_BODY, NOT_OPTIONAL);
                // use sObject name to load class
                setResponseClass(exchange, null);
                restClient.query(sObjectQuery, new RestClient.ResponseCallback() {

                    @Override
                    public void onResponse(InputStream response, SalesforceException exception) {
                        processResponse(exchange, response, exception, callback);
                    }
                });
                break;
            case QUERY_MORE:
                // reuse SOBJECT_QUERY parameter name for nextRecordsUrl
                final String nextRecordsUrl = getParameter(SOBJECT_QUERY, exchange, USE_BODY, NOT_OPTIONAL);
                // use custom response class property
                setResponseClass(exchange, null);
                restClient.queryMore(nextRecordsUrl, new RestClient.ResponseCallback() {

                    @Override
                    public void onResponse(InputStream response, SalesforceException exception) {
                        processResponse(exchange, response, exception, callback);
                    }
                });
                break;
            case SEARCH:
                final String sObjectSearch = getParameter(SOBJECT_SEARCH, exchange, USE_BODY, NOT_OPTIONAL);
                restClient.search(sObjectSearch, new RestClient.ResponseCallback() {

                    @Override
                    public void onResponse(InputStream response, SalesforceException exception) {
                        processResponse(exchange, response, exception, callback);
                    }
                });
                break;
        }
    } catch (SalesforceException e) {
        exchange.setException(new SalesforceException(String.format("Error processing %s: [%s] \"%s\"", operationName, e.getStatusCode(), e.getMessage()), e));
        callback.done(true);
        return true;
    } catch (RuntimeException e) {
        exchange.setException(new SalesforceException(String.format("Unexpected Error processing %s: \"%s\"", operationName, e.getMessage()), e));
        callback.done(true);
        return true;
    }
    // continue routing asynchronously
    return false;
}
Example 17
Project: camunda-bpm-camel-master  File: BatchConsumer.java View source code
private boolean processExchange(final Exchange exchange) throws Exception {
    taskProcessor.process(exchange);
    final Processor currentProcessor = getProcessor();
    if (currentProcessor instanceof AsyncProcessor) {
        ((AsyncProcessor) currentProcessor).process(exchange, new AsyncCallback() {

            @Override
            public void done(boolean doneSync) {
            // we are not interested in this event
            }
        });
    } else {
        currentProcessor.process(exchange);
    }
    return true;
}
Example 18
Project: signalk-server-java-master  File: SkStompEndpoint.java View source code
protected void send(final Exchange exchange, final AsyncCallback callback) {
    final StompFrame frame = new StompFrame(SEND);
    if (logger.isDebugEnabled())
        logger.debug("STOMP: sending :" + exchange);
    frame.addHeader(DESTINATION, StompFrame.encodeHeader(destination));
    Map<String, Object> headers = exchange.getIn().getHeaders();
    if (headers != null) {
        for (String key : headers.keySet()) {
            if (headers.get(key) instanceof String) {
                if (logger.isDebugEnabled())
                    logger.debug("STOMP: encode header :" + key + "=" + (String) headers.get(key));
                frame.addHeader(Buffer.ascii(key), StompFrame.encodeHeader((String) headers.get(key)));
            }
        }
    }
    frame.content(utf8(exchange.getIn().getBody().toString()));
    connection.getDispatchQueue().execute(new Task() {

        @Override
        public void run() {
            connection.send(frame, new Callback<Void>() {

                @Override
                public void onFailure(Throwable e) {
                    exchange.setException(e);
                    callback.done(false);
                }

                @Override
                public void onSuccess(Void v) {
                    callback.done(false);
                }
            });
        }
    });
}
Example 19
Project: bio2rdf-rest-master  File: CamelStat.java View source code
public void initStatisticsInterceptor() throws NullPointerException {
    theContext.addInterceptStrategy(new InterceptStrategy() {

        public Processor wrapProcessorInInterceptors(CamelContext context, final ProcessorDefinition<?> node, final Processor target, Processor nextTarget) throws Exception {
            return new DelegateAsyncProcessor(target) {

                public boolean process(Exchange exchange, AsyncCallback callback) {
                    CamelStat.this.addRowByTargetNode(node.getId());
                    return super.process(exchange, callback);
                }
            };
        }
    });
}
Example 20
Project: camel-webinar-master  File: HelloWorldProducer.java View source code
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
    encode(exchange);
    LOG.info("HelloWorldProducer: async send request");
    return super.process(exchange, callback);
}
Example 21
Project: camel-hibersap-master  File: HibersapProducer.java View source code
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
    boolean sync = true;
    try {
        process(exchange);
    } catch (Exception e) {
        exchange.setException(e);
    } finally {
        callback.done(sync);
    }
    return sync;
}
Example 22
Project: geobatch-master  File: JMSFlowManager.java View source code
/**
     * The AsyncProcessor defines a single process() method which is very similar to it's
     * synchronous Processor.process() brethren. Here are the differences: A non-null AsyncCallback
     * MUST be supplied which will be notified when the exchange processing is completed. It MUST
     * not throw any exceptions that occurred while processing the exchange. Any such exceptions
     * must be stored on the exchange's Exception property. It MUST know if it will complete the
     * processing synchronously or asynchronously. The method will return true if it does complete
     * synchronously, otherwise it returns false. When the processor has completed processing the
     * exchange, it must call the callback.done(boolean sync) method. The sync parameter MUST match
     * the value returned by the process() method.
     * 
     * @author Carlo Cancellieri - carlo.cancellieri@geo-solutions.it
     */
public boolean process(Exchange exchange, AsyncCallback callback) {
    try {
        process(exchange);
    } catch (Throwable t) {
    } finally {
        callback.done(true);
    }
    return true;
}