Search in sources :

Example 16 with CamelException

use of org.apache.camel.CamelException in project camel by apache.

the class BulkApiProcessor method processCreateBatch.

private void processCreateBatch(final Exchange exchange, final AsyncCallback callback) throws SalesforceException {
    String jobId;
    // since request is in the body, use headers or endpoint params
    ContentType contentType = ContentType.fromValue(getParameter(CONTENT_TYPE, exchange, IGNORE_BODY, NOT_OPTIONAL));
    jobId = getParameter(JOB_ID, exchange, IGNORE_BODY, NOT_OPTIONAL);
    InputStream request;
    try {
        request = exchange.getIn().getMandatoryBody(InputStream.class);
    } catch (CamelException e) {
        String msg = "Error preparing batch request: " + e.getMessage();
        throw new SalesforceException(msg, e);
    }
    bulkClient.createBatch(request, jobId, contentType, new BulkApiClient.BatchInfoResponseCallback() {

        @Override
        public void onResponse(BatchInfo batchInfo, SalesforceException ex) {
            processResponse(exchange, batchInfo, ex, callback);
        }
    });
}
Also used : SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) ContentType(org.apache.camel.component.salesforce.api.dto.bulk.ContentType) CamelException(org.apache.camel.CamelException) InputStream(java.io.InputStream) DefaultBulkApiClient(org.apache.camel.component.salesforce.internal.client.DefaultBulkApiClient) BulkApiClient(org.apache.camel.component.salesforce.internal.client.BulkApiClient) BatchInfo(org.apache.camel.component.salesforce.api.dto.bulk.BatchInfo)

Example 17 with CamelException

use of org.apache.camel.CamelException in project camel by apache.

the class PushTopicHelper method updateTopic.

private void updateTopic(String topicId) throws CamelException {
    final String query = config.getSObjectQuery();
    LOG.info("Updating Topic {} with Query [{}]", topicName, query);
    final SyncResponseCallback callback = new SyncResponseCallback();
    try {
        // update the query, notifyForFields and notifyForOperations fields
        final PushTopic topic = new PushTopic();
        topic.setQuery(query);
        topic.setNotifyForFields(config.getNotifyForFields());
        if (preApi29) {
            topic.setNotifyForOperations(config.getNotifyForOperations());
        } else {
            topic.setNotifyForOperationCreate(config.getNotifyForOperationCreate());
            topic.setNotifyForOperationDelete(config.getNotifyForOperationDelete());
            topic.setNotifyForOperationUndelete(config.getNotifyForOperationUndelete());
            topic.setNotifyForOperationUpdate(config.getNotifyForOperationUpdate());
        }
        restClient.updateSObject("PushTopic", topicId, new ByteArrayInputStream(OBJECT_MAPPER.writeValueAsBytes(topic)), callback);
        if (!callback.await(API_TIMEOUT, TimeUnit.SECONDS)) {
            throw new SalesforceException("API call timeout!", null);
        }
        final SalesforceException callbackException = callback.getException();
        if (callbackException != null) {
            throw callbackException;
        }
    } catch (SalesforceException e) {
        throw new CamelException(String.format("Error updating topic %s with query [%s] : %s", topicName, query, e.getMessage()), e);
    } catch (InterruptedException e) {
        // reset interrupt status
        Thread.currentThread().interrupt();
        throw new CamelException(String.format("Error updating topic %s with query [%s] : %s", topicName, query, e.getMessage()), e);
    } catch (IOException e) {
        throw new CamelException(String.format("Error updating topic %s with query [%s] : %s", topicName, query, e.getMessage()), e);
    } finally {
        if (callback.getResponse() != null) {
            try {
                callback.getResponse().close();
            } catch (IOException ignore) {
            }
        }
    }
}
Also used : PushTopic(org.apache.camel.component.salesforce.internal.dto.PushTopic) QueryRecordsPushTopic(org.apache.camel.component.salesforce.internal.dto.QueryRecordsPushTopic) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) ByteArrayInputStream(java.io.ByteArrayInputStream) CamelException(org.apache.camel.CamelException) IOException(java.io.IOException) SyncResponseCallback(org.apache.camel.component.salesforce.internal.client.SyncResponseCallback)

Example 18 with CamelException

use of org.apache.camel.CamelException in project camel by apache.

the class PushTopicHelper method createOrUpdateTopic.

public void createOrUpdateTopic() throws CamelException {
    final String query = config.getSObjectQuery();
    final SyncResponseCallback callback = new SyncResponseCallback();
    // lookup Topic first
    try {
        // use SOQL to lookup Topic, since Name is not an external ID!!!
        restClient.query("SELECT Id, Name, Query, ApiVersion, IsActive, " + "NotifyForFields, NotifyForOperations, NotifyForOperationCreate, " + "NotifyForOperationDelete, NotifyForOperationUndelete, " + "NotifyForOperationUpdate, Description " + "FROM PushTopic WHERE Name = '" + topicName + "'", callback);
        if (!callback.await(API_TIMEOUT, TimeUnit.SECONDS)) {
            throw new SalesforceException("API call timeout!", null);
        }
        final SalesforceException callbackException = callback.getException();
        if (callbackException != null) {
            throw callbackException;
        }
        QueryRecordsPushTopic records = OBJECT_MAPPER.readValue(callback.getResponse(), QueryRecordsPushTopic.class);
        if (records.getTotalSize() == 1) {
            PushTopic topic = records.getRecords().get(0);
            LOG.info("Found existing topic {}: {}", topicName, topic);
            // check if we need to update topic
            final boolean notifyOperationsChanged;
            if (preApi29) {
                notifyOperationsChanged = notEquals(config.getNotifyForOperations(), topic.getNotifyForOperations());
            } else {
                notifyOperationsChanged = notEquals(config.getNotifyForOperationCreate(), topic.getNotifyForOperationCreate()) || notEquals(config.getNotifyForOperationDelete(), topic.getNotifyForOperationDelete()) || notEquals(config.getNotifyForOperationUndelete(), topic.getNotifyForOperationUndelete()) || notEquals(config.getNotifyForOperationUpdate(), topic.getNotifyForOperationUpdate());
            }
            if (!query.equals(topic.getQuery()) || notEquals(config.getNotifyForFields(), topic.getNotifyForFields()) || notifyOperationsChanged) {
                if (!config.isUpdateTopic()) {
                    String msg = "Query doesn't match existing Topic and updateTopic is set to false";
                    throw new CamelException(msg);
                }
                // otherwise update the topic
                updateTopic(topic.getId());
            }
        } else {
            createTopic();
        }
    } catch (SalesforceException e) {
        throw new CamelException(String.format("Error retrieving Topic %s: %s", topicName, e.getMessage()), e);
    } catch (IOException e) {
        throw new CamelException(String.format("Un-marshaling error retrieving Topic %s: %s", topicName, e.getMessage()), e);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new CamelException(String.format("Un-marshaling error retrieving Topic %s: %s", topicName, e.getMessage()), e);
    } finally {
        // close stream to close HttpConnection
        if (callback.getResponse() != null) {
            try {
                callback.getResponse().close();
            } catch (IOException e) {
            // ignore
            }
        }
    }
}
Also used : SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) PushTopic(org.apache.camel.component.salesforce.internal.dto.PushTopic) QueryRecordsPushTopic(org.apache.camel.component.salesforce.internal.dto.QueryRecordsPushTopic) QueryRecordsPushTopic(org.apache.camel.component.salesforce.internal.dto.QueryRecordsPushTopic) CamelException(org.apache.camel.CamelException) IOException(java.io.IOException) SyncResponseCallback(org.apache.camel.component.salesforce.internal.client.SyncResponseCallback)

Example 19 with CamelException

use of org.apache.camel.CamelException in project camel by apache.

the class SubscriptionHelper method unsubscribe.

public void unsubscribe(String topicName, SalesforceConsumer consumer) throws CamelException {
    // channel name
    final String channelName = getChannelName(topicName);
    // listen for unsubscribe error
    final CountDownLatch latch = new CountDownLatch(1);
    final String[] unsubscribeError = { null };
    final Exception[] unsubscribeFailure = { null };
    final ClientSessionChannel.MessageListener unsubscribeListener = new ClientSessionChannel.MessageListener() {

        public void onMessage(ClientSessionChannel channel, Message message) {
            LOG.debug("[CHANNEL:META_UNSUBSCRIBE]: {}", message);
            Object subscription = message.get(SUBSCRIPTION_FIELD);
            if (subscription != null) {
                String unsubscribedChannelName = subscription.toString();
                if (channelName.equals(unsubscribedChannelName)) {
                    if (!message.isSuccessful()) {
                        unsubscribeError[0] = (String) message.get(ERROR_FIELD);
                        unsubscribeFailure[0] = getFailure(message);
                    } else {
                        // forget subscription
                        LOG.info("Unsubscribed from channel {}", unsubscribedChannelName);
                    }
                    latch.countDown();
                }
            }
        }
    };
    client.getChannel(META_UNSUBSCRIBE).addListener(unsubscribeListener);
    try {
        // unsubscribe from channel
        final ClientSessionChannel.MessageListener listener = listenerMap.remove(consumer);
        if (listener != null) {
            LOG.info("Unsubscribing from channel {}...", channelName);
            final ClientSessionChannel clientChannel = client.getChannel(channelName);
            clientChannel.unsubscribe(listener);
            // confirm unsubscribe
            try {
                if (!latch.await(CHANNEL_TIMEOUT, SECONDS)) {
                    String message;
                    if (unsubscribeFailure[0] != null) {
                        message = String.format("Error unsubscribing from topic %s: %s", topicName, unsubscribeFailure[0].getMessage());
                    } else if (unsubscribeError[0] != null) {
                        message = String.format("Error unsubscribing from topic %s: %s", topicName, unsubscribeError[0]);
                    } else {
                        message = String.format("Timeout error unsubscribing from topic %s after %s seconds", topicName, CHANNEL_TIMEOUT);
                    }
                    throw new CamelException(message, unsubscribeFailure[0]);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            // probably shutting down, forget unsubscribe and return
            }
        }
    } finally {
        client.getChannel(META_UNSUBSCRIBE).removeListener(unsubscribeListener);
    }
}
Also used : Message(org.cometd.bayeux.Message) CamelException(org.apache.camel.CamelException) CountDownLatch(java.util.concurrent.CountDownLatch) ClientSessionChannel(org.cometd.bayeux.client.ClientSessionChannel) CamelException(org.apache.camel.CamelException) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException)

Example 20 with CamelException

use of org.apache.camel.CamelException in project camel by apache.

the class SubscriptionHelper method doStart.

@Override
protected void doStart() throws Exception {
    // create CometD client
    this.client = createClient(component);
    // reset all error conditions
    handshakeError = null;
    handshakeException = null;
    connectError = null;
    connectException = null;
    // listener for handshake error or exception
    if (handshakeListener == null) {
        // first start
        handshakeListener = new ClientSessionChannel.MessageListener() {

            public void onMessage(ClientSessionChannel channel, Message message) {
                LOG.debug("[CHANNEL:META_HANDSHAKE]: {}", message);
                if (!message.isSuccessful()) {
                    LOG.warn("Handshake failure: {}", message);
                    handshakeError = (String) message.get(ERROR_FIELD);
                    handshakeException = getFailure(message);
                    if (handshakeError != null) {
                        // refresh oauth token, if it's a 401 error
                        if (handshakeError.startsWith("401::")) {
                            try {
                                LOG.info("Refreshing OAuth token...");
                                session.login(session.getAccessToken());
                                LOG.info("Refreshed OAuth token for re-handshake");
                            } catch (SalesforceException e) {
                                LOG.error("Error renewing OAuth token on 401 error: " + e.getMessage(), e);
                            }
                        }
                    }
                    // restart if handshake fails for any reason
                    restartClient();
                } else if (!listenerMap.isEmpty()) {
                    reconnecting = true;
                }
            }
        };
    }
    client.getChannel(META_HANDSHAKE).addListener(handshakeListener);
    // listener for connect error
    if (connectListener == null) {
        connectListener = new ClientSessionChannel.MessageListener() {

            public void onMessage(ClientSessionChannel channel, Message message) {
                LOG.debug("[CHANNEL:META_CONNECT]: {}", message);
                if (!message.isSuccessful()) {
                    LOG.warn("Connect failure: {}", message);
                    connectError = (String) message.get(ERROR_FIELD);
                    connectException = getFailure(message);
                } else if (reconnecting) {
                    reconnecting = false;
                    LOG.debug("Refreshing subscriptions to {} channels on reconnect", listenerMap.size());
                    // reconnected to Salesforce, subscribe to existing channels
                    final Map<SalesforceConsumer, ClientSessionChannel.MessageListener> map = new HashMap<SalesforceConsumer, ClientSessionChannel.MessageListener>();
                    map.putAll(listenerMap);
                    listenerMap.clear();
                    for (Map.Entry<SalesforceConsumer, ClientSessionChannel.MessageListener> entry : map.entrySet()) {
                        final SalesforceConsumer consumer = entry.getKey();
                        final String topicName = consumer.getTopicName();
                        subscribe(topicName, consumer);
                    }
                }
            }
        };
    }
    client.getChannel(META_CONNECT).addListener(connectListener);
    // handle fatal disconnects by reconnecting asynchronously
    if (disconnectListener == null) {
        disconnectListener = new ClientSessionChannel.MessageListener() {

            @Override
            public void onMessage(ClientSessionChannel clientSessionChannel, Message message) {
                restartClient();
            }
        };
    }
    client.getChannel(META_DISCONNECT).addListener(disconnectListener);
    // connect to Salesforce cometd endpoint
    client.handshake();
    final long waitMs = MILLISECONDS.convert(CONNECT_TIMEOUT, SECONDS);
    if (!client.waitFor(waitMs, BayeuxClient.State.CONNECTED)) {
        if (handshakeException != null) {
            throw new CamelException(String.format("Exception during HANDSHAKE: %s", handshakeException.getMessage()), handshakeException);
        } else if (handshakeError != null) {
            throw new CamelException(String.format("Error during HANDSHAKE: %s", handshakeError));
        } else if (connectException != null) {
            throw new CamelException(String.format("Exception during CONNECT: %s", connectException.getMessage()), connectException);
        } else if (connectError != null) {
            throw new CamelException(String.format("Error during CONNECT: %s", connectError));
        } else {
            throw new CamelException(String.format("Handshake request timeout after %s seconds", CONNECT_TIMEOUT));
        }
    }
}
Also used : Message(org.cometd.bayeux.Message) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) SalesforceConsumer(org.apache.camel.component.salesforce.SalesforceConsumer) CamelException(org.apache.camel.CamelException) ClientSessionChannel(org.cometd.bayeux.client.ClientSessionChannel) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Aggregations

CamelException (org.apache.camel.CamelException)28 RouteBuilder (org.apache.camel.builder.RouteBuilder)6 SalesforceException (org.apache.camel.component.salesforce.api.SalesforceException)6 IOException (java.io.IOException)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 CamelExecutionException (org.apache.camel.CamelExecutionException)3 SyncResponseCallback (org.apache.camel.component.salesforce.internal.client.SyncResponseCallback)3 PushTopic (org.apache.camel.component.salesforce.internal.dto.PushTopic)3 QueryRecordsPushTopic (org.apache.camel.component.salesforce.internal.dto.QueryRecordsPushTopic)3 XMLReader (org.xml.sax.XMLReader)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 StringWriter (java.io.StringWriter)2 ConnectException (java.net.ConnectException)2 Exchange (org.apache.camel.Exchange)2 Message (org.apache.camel.Message)2 Message (org.cometd.bayeux.Message)2 ClientSessionChannel (org.cometd.bayeux.client.ClientSessionChannel)2 Channel (org.jboss.netty.channel.Channel)2 ChannelFuture (org.jboss.netty.channel.ChannelFuture)2 Test (org.junit.Test)2