Search in sources :

Example 1 with DefaultRestClient

use of org.apache.camel.component.salesforce.internal.client.DefaultRestClient in project camel by apache.

the class SalesforceComponentVerifier method verifyConnectivity.

// *********************************
// Connectivity validation
// *********************************
@Override
protected Result verifyConnectivity(Map<String, Object> parameters) {
    // Default is success
    ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY);
    try {
        SalesforceEndpointConfig configuration = new SalesforceEndpointConfig();
        setProperties(configuration, parameters);
        SalesforceLoginConfig loginConfig = new SalesforceLoginConfig();
        setProperties(loginConfig, parameters);
        // Create a dummy SslContextFactory which is needed by SalesforceHttpClient
        // or the underlying jetty client fails with a NPE
        SSLContextParameters contextParameters = new SSLContextParameters();
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setSslContext(contextParameters.createSSLContext(getCamelContext()));
        SalesforceHttpClient httpClient = new SalesforceHttpClient(sslContextFactory);
        httpClient.setConnectTimeout(SalesforceComponent.CONNECTION_TIMEOUT);
        configureHttpProxy(httpClient, parameters);
        SalesforceSession session = new SalesforceSession(getCamelContext(), httpClient, httpClient.getTimeout(), loginConfig);
        DefaultRestClient client = new DefaultRestClient(httpClient, configuration.getApiVersion(), configuration.getFormat(), session);
        httpClient.setSession(session);
        httpClient.start();
        // For authentication check is is enough to use
        session.start();
        client.start();
        client.getVersions((response, exception) -> processSalesforceException(builder, Optional.ofNullable(exception)));
        client.stop();
        session.stop();
        httpClient.stop();
        httpClient.destroy();
    } catch (NoSuchOptionException e) {
        builder.error(ResultErrorBuilder.withMissingOption(e.getOptionName()).build());
    } catch (SalesforceException e) {
        processSalesforceException(builder, Optional.of(e));
    } catch (Exception e) {
        builder.error(ResultErrorBuilder.withException(e).build());
        throw new RuntimeException(e);
    }
    return builder.build();
}
Also used : ResultBuilder(org.apache.camel.impl.verifier.ResultBuilder) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) NoSuchOptionException(org.apache.camel.NoSuchOptionException) SalesforceSession(org.apache.camel.component.salesforce.internal.SalesforceSession) DefaultRestClient(org.apache.camel.component.salesforce.internal.client.DefaultRestClient) URISyntaxException(java.net.URISyntaxException) NoSuchOptionException(org.apache.camel.NoSuchOptionException) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) SSLContextParameters(org.apache.camel.util.jsse.SSLContextParameters)

Example 2 with DefaultRestClient

use of org.apache.camel.component.salesforce.internal.client.DefaultRestClient in project camel by apache.

the class SalesforceConsumer method doStart.

@Override
protected void doStart() throws Exception {
    super.doStart();
    final SalesforceEndpointConfig config = endpoint.getConfiguration();
    // is a query configured in the endpoint?
    if (config.getSObjectQuery() != null) {
        // Note that we don't lookup topic if the query is not specified
        // create REST client for PushTopic operations
        SalesforceComponent component = endpoint.getComponent();
        RestClient restClient = new DefaultRestClient(component.getConfig().getHttpClient(), endpoint.getConfiguration().getApiVersion(), endpoint.getConfiguration().getFormat(), component.getSession());
        // don't forget to start the client
        ServiceHelper.startService(restClient);
        try {
            PushTopicHelper helper = new PushTopicHelper(config, topicName, restClient);
            helper.createOrUpdateTopic();
        } finally {
            // don't forget to stop the client
            ServiceHelper.stopService(restClient);
        }
    }
    // subscribe to topic
    subscriptionHelper.subscribe(topicName, this);
    subscribed = true;
}
Also used : RestClient(org.apache.camel.component.salesforce.internal.client.RestClient) DefaultRestClient(org.apache.camel.component.salesforce.internal.client.DefaultRestClient) DefaultRestClient(org.apache.camel.component.salesforce.internal.client.DefaultRestClient) PushTopicHelper(org.apache.camel.component.salesforce.internal.streaming.PushTopicHelper)

Example 3 with DefaultRestClient

use of org.apache.camel.component.salesforce.internal.client.DefaultRestClient in project camel by apache.

the class CamelSalesforceMojo method execute.

/**
     * Execute the mojo to generate SObject DTOs
     *
     * @throws MojoExecutionException
     */
public void execute() throws MojoExecutionException {
    engine = createVelocityEngine();
    // make sure we can load both templates
    if (!engine.resourceExists(SOBJECT_POJO_VM) || !engine.resourceExists(SOBJECT_QUERY_RECORDS_VM) || !engine.resourceExists(SOBJECT_POJO_OPTIONAL_VM) || !engine.resourceExists(SOBJECT_QUERY_RECORDS_OPTIONAL_VM)) {
        throw new MojoExecutionException("Velocity templates not found");
    }
    // connect to Salesforce
    final SalesforceHttpClient httpClient = createHttpClient();
    final SalesforceSession session = httpClient.getSession();
    getLog().info("Salesforce login...");
    try {
        session.login(null);
    } catch (SalesforceException e) {
        String msg = "Salesforce login error " + e.getMessage();
        throw new MojoExecutionException(msg, e);
    }
    getLog().info("Salesforce login successful");
    // create rest client
    RestClient restClient;
    try {
        restClient = new DefaultRestClient(httpClient, version, PayloadFormat.JSON, session);
        // remember to start the active client object
        ((DefaultRestClient) restClient).start();
    } catch (Exception e) {
        final String msg = "Unexpected exception creating Rest client: " + e.getMessage();
        throw new MojoExecutionException(msg, e);
    }
    try {
        // use Jackson json
        final ObjectMapper mapper = JsonUtils.createObjectMapper();
        // call getGlobalObjects to get all SObjects
        final Set<String> objectNames = new TreeSet<String>();
        final SyncResponseCallback callback = new SyncResponseCallback();
        try {
            getLog().info("Getting Salesforce Objects...");
            restClient.getGlobalObjects(callback);
            if (!callback.await(responseTimeout, TimeUnit.MILLISECONDS)) {
                throw new MojoExecutionException("Timeout waiting for getGlobalObjects!");
            }
            final SalesforceException ex = callback.getException();
            if (ex != null) {
                throw ex;
            }
            final GlobalObjects globalObjects = mapper.readValue(callback.getResponse(), GlobalObjects.class);
            // create a list of object names
            for (SObject sObject : globalObjects.getSobjects()) {
                objectNames.add(sObject.getName());
            }
        } catch (Exception e) {
            String msg = "Error getting global Objects: " + e.getMessage();
            throw new MojoExecutionException(msg, e);
        }
        // check if we are generating POJOs for all objects or not
        if ((includes != null && includes.length > 0) || (excludes != null && excludes.length > 0) || ObjectHelper.isNotEmpty(includePattern) || ObjectHelper.isNotEmpty(excludePattern)) {
            filterObjectNames(objectNames);
        } else {
            getLog().warn(String.format("Generating Java classes for all %s Objects, this may take a while...", objectNames.size()));
        }
        // for every accepted name, get SObject description
        final Set<SObjectDescription> descriptions = new HashSet<SObjectDescription>();
        getLog().info("Retrieving Object descriptions...");
        for (String name : objectNames) {
            try {
                callback.reset();
                restClient.getDescription(name, callback);
                if (!callback.await(responseTimeout, TimeUnit.MILLISECONDS)) {
                    throw new MojoExecutionException("Timeout waiting for getDescription for sObject " + name);
                }
                final SalesforceException ex = callback.getException();
                if (ex != null) {
                    throw ex;
                }
                descriptions.add(mapper.readValue(callback.getResponse(), SObjectDescription.class));
            } catch (Exception e) {
                String msg = "Error getting SObject description for '" + name + "': " + e.getMessage();
                throw new MojoExecutionException(msg, e);
            }
        }
        // validate package name
        if (!packageName.matches(PACKAGE_NAME_PATTERN)) {
            throw new MojoExecutionException("Invalid package name " + packageName);
        }
        if (outputDirectory.getAbsolutePath().contains("$")) {
            outputDirectory = new File("generated-sources/camel-salesforce");
        }
        final File pkgDir = new File(outputDirectory, packageName.trim().replace('.', File.separatorChar));
        if (!pkgDir.exists()) {
            if (!pkgDir.mkdirs()) {
                throw new MojoExecutionException("Unable to create " + pkgDir);
            }
        }
        getLog().info("Generating Java Classes...");
        // generate POJOs for every object description
        final GeneratorUtility utility = new GeneratorUtility(useStringsForPicklists);
        // should we provide a flag to control timestamp generation?
        final String generatedDate = new Date().toString();
        for (SObjectDescription description : descriptions) {
            try {
                processDescription(pkgDir, description, utility, generatedDate);
            } catch (IOException e) {
                throw new MojoExecutionException("Unable to generate source files for: " + description.getName(), e);
            }
        }
        getLog().info(String.format("Successfully generated %s Java Classes", descriptions.size() * 2));
    } finally {
        // remember to stop the client
        try {
            ((DefaultRestClient) restClient).stop();
        } catch (Exception ignore) {
        }
        // Salesforce session stop
        try {
            session.stop();
        } catch (Exception ignore) {
        }
        // release HttpConnections
        try {
            httpClient.stop();
        } catch (Exception ignore) {
        }
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) RestClient(org.apache.camel.component.salesforce.internal.client.RestClient) DefaultRestClient(org.apache.camel.component.salesforce.internal.client.DefaultRestClient) IOException(java.io.IOException) SalesforceHttpClient(org.apache.camel.component.salesforce.SalesforceHttpClient) DefaultRestClient(org.apache.camel.component.salesforce.internal.client.DefaultRestClient) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) Date(java.util.Date) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) SalesforceSession(org.apache.camel.component.salesforce.internal.SalesforceSession) TreeSet(java.util.TreeSet) SObject(org.apache.camel.component.salesforce.api.dto.SObject) SObjectDescription(org.apache.camel.component.salesforce.api.dto.SObjectDescription) GlobalObjects(org.apache.camel.component.salesforce.api.dto.GlobalObjects) File(java.io.File) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SyncResponseCallback(org.apache.camel.component.salesforce.internal.client.SyncResponseCallback) HashSet(java.util.HashSet)

Aggregations

DefaultRestClient (org.apache.camel.component.salesforce.internal.client.DefaultRestClient)3 SalesforceException (org.apache.camel.component.salesforce.api.SalesforceException)2 SalesforceSession (org.apache.camel.component.salesforce.internal.SalesforceSession)2 RestClient (org.apache.camel.component.salesforce.internal.client.RestClient)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 File (java.io.File)1 IOException (java.io.IOException)1 URISyntaxException (java.net.URISyntaxException)1 GeneralSecurityException (java.security.GeneralSecurityException)1 Date (java.util.Date)1 HashSet (java.util.HashSet)1 TreeSet (java.util.TreeSet)1 NoSuchOptionException (org.apache.camel.NoSuchOptionException)1 SalesforceHttpClient (org.apache.camel.component.salesforce.SalesforceHttpClient)1 GlobalObjects (org.apache.camel.component.salesforce.api.dto.GlobalObjects)1 SObject (org.apache.camel.component.salesforce.api.dto.SObject)1 SObjectDescription (org.apache.camel.component.salesforce.api.dto.SObjectDescription)1 SyncResponseCallback (org.apache.camel.component.salesforce.internal.client.SyncResponseCallback)1 PushTopicHelper (org.apache.camel.component.salesforce.internal.streaming.PushTopicHelper)1 ResultBuilder (org.apache.camel.impl.verifier.ResultBuilder)1