Search in sources :

Example 61 with SalesforceException

use of org.apache.camel.component.salesforce.api.SalesforceException in project camel by apache.

the class XmlRestProcessor method processResponse.

@Override
protected void processResponse(Exchange exchange, InputStream responseEntity, SalesforceException exception, AsyncCallback callback) {
    final XStream localXStream = xStream.get();
    try {
        // do we need to un-marshal a response
        if (responseEntity != null) {
            final Class<?> responseClass = exchange.getProperty(RESPONSE_CLASS, Class.class);
            Object response;
            if (responseClass != null) {
                // its ok to call this multiple times, as xstream ignores duplicate calls
                localXStream.processAnnotations(responseClass);
                final String responseAlias = exchange.getProperty(RESPONSE_ALIAS, String.class);
                if (responseAlias != null) {
                    // extremely dirty, need to flush entire cache if its holding on to an old alias!!!
                    final CachingMapper mapper = (CachingMapper) localXStream.getMapper();
                    try {
                        if (mapper.realClass(responseAlias) != responseClass) {
                            mapper.flushCache();
                        }
                    } catch (CannotResolveClassException ignore) {
                        // recent XStream versions add a ClassNotFoundException to cache
                        mapper.flushCache();
                    }
                    localXStream.alias(responseAlias, responseClass);
                }
                response = responseClass.newInstance();
                localXStream.fromXML(responseEntity, response);
            } else {
                // return the response as a stream, for getBlobField
                response = responseEntity;
            }
            exchange.getOut().setBody(response);
        } else {
            exchange.setException(exception);
        }
        // copy headers and attachments
        exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders());
        exchange.getOut().getAttachmentObjects().putAll(exchange.getIn().getAttachmentObjects());
    } catch (XStreamException e) {
        String msg = "Error parsing XML response: " + e.getMessage();
        exchange.setException(new SalesforceException(msg, e));
    } catch (Exception e) {
        String msg = "Error creating XML response: " + e.getMessage();
        exchange.setException(new SalesforceException(msg, e));
    } finally {
        // cleanup temporary exchange headers
        exchange.removeProperty(RESPONSE_CLASS);
        exchange.removeProperty(RESPONSE_ALIAS);
        // consume response entity
        if (responseEntity != null) {
            try {
                responseEntity.close();
            } catch (IOException ignored) {
            }
        }
        // notify callback that exchange is done
        callback.done(false);
    }
}
Also used : SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) XStreamException(com.thoughtworks.xstream.XStreamException) XStream(com.thoughtworks.xstream.XStream) CachingMapper(com.thoughtworks.xstream.mapper.CachingMapper) IOException(java.io.IOException) CannotResolveClassException(com.thoughtworks.xstream.mapper.CannotResolveClassException) XStreamException(com.thoughtworks.xstream.XStreamException) IOException(java.io.IOException) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CannotResolveClassException(com.thoughtworks.xstream.mapper.CannotResolveClassException)

Example 62 with SalesforceException

use of org.apache.camel.component.salesforce.api.SalesforceException in project camel by apache.

the class XmlRestProcessor method getRequestStream.

@Override
protected InputStream getRequestStream(final Object object) throws SalesforceException {
    final XStream localXStream = xStream.get();
    // first process annotations on the class, for things like alias, etc.
    localXStream.processAnnotations(object.getClass());
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    // make sure we write the XML with the right encoding
    try {
        localXStream.toXML(object, new OutputStreamWriter(out, StringUtil.__UTF8));
    } catch (UnsupportedEncodingException e) {
        String msg = "Error marshaling request: " + e.getMessage();
        throw new SalesforceException(msg, e);
    }
    return new ByteArrayInputStream(out.toByteArray());
}
Also used : SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) ByteArrayInputStream(java.io.ByteArrayInputStream) XStream(com.thoughtworks.xstream.XStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) OutputStreamWriter(java.io.OutputStreamWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 63 with SalesforceException

use of org.apache.camel.component.salesforce.api.SalesforceException 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 64 with SalesforceException

use of org.apache.camel.component.salesforce.api.SalesforceException 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 65 with SalesforceException

use of org.apache.camel.component.salesforce.api.SalesforceException 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

SalesforceException (org.apache.camel.component.salesforce.api.SalesforceException)79 InputStream (java.io.InputStream)35 Request (org.eclipse.jetty.client.api.Request)25 BulkApiClient (org.apache.camel.component.salesforce.internal.client.BulkApiClient)12 DefaultBulkApiClient (org.apache.camel.component.salesforce.internal.client.DefaultBulkApiClient)12 DefaultRestClient (org.apache.camel.component.salesforce.internal.client.DefaultRestClient)12 IOException (java.io.IOException)11 BatchInfo (org.apache.camel.component.salesforce.api.dto.bulk.BatchInfo)11 RestClient (org.apache.camel.component.salesforce.internal.client.RestClient)11 UnsupportedEncodingException (java.io.UnsupportedEncodingException)10 JobInfo (org.apache.camel.component.salesforce.api.dto.bulk.JobInfo)10 AbstractSObjectBase (org.apache.camel.component.salesforce.api.dto.AbstractSObjectBase)9 HashMap (java.util.HashMap)7 CamelException (org.apache.camel.CamelException)7 Message (org.apache.camel.Message)7 ByteArrayInputStream (java.io.ByteArrayInputStream)5 List (java.util.List)5 Map (java.util.Map)5 CreateSObjectResult (org.apache.camel.component.salesforce.api.dto.CreateSObjectResult)3 SyncResponseCallback (org.apache.camel.component.salesforce.internal.client.SyncResponseCallback)3