Search in sources :

Example 1 with SalesforceSession

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

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

the class SubscriptionHelper method createClient.

static BayeuxClient createClient(final SalesforceComponent component) throws SalesforceException {
    // use default Jetty client from SalesforceComponent, its shared by all consumers
    final SalesforceHttpClient httpClient = component.getConfig().getHttpClient();
    Map<String, Object> options = new HashMap<String, Object>();
    options.put(ClientTransport.MAX_NETWORK_DELAY_OPTION, httpClient.getTimeout());
    final SalesforceSession session = component.getSession();
    // check login access token
    if (session.getAccessToken() == null) {
        // lazy login here!
        session.login(null);
    }
    LongPollingTransport transport = new LongPollingTransport(options, httpClient) {

        @Override
        protected void customize(Request request) {
            super.customize(request);
            // add current security token obtained from session
            // replace old token
            request.getHeaders().put(HttpHeader.AUTHORIZATION, "OAuth " + session.getAccessToken());
        }
    };
    BayeuxClient client = new BayeuxClient(getEndpointUrl(component), transport);
    // added eagerly to check for support during handshake
    client.addExtension(REPLAY_EXTENSION);
    return client;
}
Also used : LongPollingTransport(org.cometd.client.transport.LongPollingTransport) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SalesforceSession(org.apache.camel.component.salesforce.internal.SalesforceSession) Request(org.eclipse.jetty.client.api.Request) SalesforceHttpClient(org.apache.camel.component.salesforce.SalesforceHttpClient) BayeuxClient(org.cometd.client.BayeuxClient)

Example 3 with SalesforceSession

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

the class SalesforceComponent method doStart.

@Override
protected void doStart() throws Exception {
    if (loginConfig == null) {
        if (ObjectHelper.isNotEmpty(password)) {
            loginConfig = new SalesforceLoginConfig(loginUrl, clientId, clientSecret, userName, password, lazyLogin);
        } else if (ObjectHelper.isNotEmpty(refreshToken)) {
            loginConfig = new SalesforceLoginConfig(loginUrl, clientId, clientSecret, refreshToken, lazyLogin);
        } else if (ObjectHelper.isNotEmpty(keystore)) {
            loginConfig = new SalesforceLoginConfig(loginUrl, clientId, userName, keystore, lazyLogin);
        } else {
            throw new IllegalArgumentException("Cannot define a login configuration, the component configuration" + " does not contain `password`, `refreshToken` or `keystore` parameters. Specifying one of those" + " determines the type of authentication performed.");
        }
        LOG.debug("Created login configuration: {}", loginConfig);
    } else {
        LOG.debug("Using shared login configuration: {}", loginConfig);
    }
    // create a Jetty HttpClient if not already set
    if (null == httpClient) {
        if (config != null && config.getHttpClient() != null) {
            httpClient = config.getHttpClient();
        } else {
            // set ssl context parameters if set
            final SSLContextParameters contextParameters = sslContextParameters != null ? sslContextParameters : new SSLContextParameters();
            final SslContextFactory sslContextFactory = new SslContextFactory();
            sslContextFactory.setSslContext(contextParameters.createSSLContext(getCamelContext()));
            httpClient = new SalesforceHttpClient(sslContextFactory);
            // default settings, use httpClientProperties to set other properties
            httpClient.setConnectTimeout(CONNECTION_TIMEOUT);
        }
    }
    // set HTTP client parameters
    if (httpClientProperties != null && !httpClientProperties.isEmpty()) {
        IntrospectionSupport.setProperties(getCamelContext().getTypeConverter(), httpClient, new HashMap<String, Object>(httpClientProperties));
    }
    // set HTTP proxy settings
    if (this.httpProxyHost != null && httpProxyPort != null) {
        Origin.Address proxyAddress = new Origin.Address(this.httpProxyHost, this.httpProxyPort);
        ProxyConfiguration.Proxy proxy;
        if (isHttpProxySocks4) {
            proxy = new Socks4Proxy(proxyAddress, isHttpProxySecure);
        } else {
            proxy = new HttpProxy(proxyAddress, isHttpProxySecure);
        }
        if (httpProxyIncludedAddresses != null && !httpProxyIncludedAddresses.isEmpty()) {
            proxy.getIncludedAddresses().addAll(httpProxyIncludedAddresses);
        }
        if (httpProxyExcludedAddresses != null && !httpProxyExcludedAddresses.isEmpty()) {
            proxy.getExcludedAddresses().addAll(httpProxyExcludedAddresses);
        }
        httpClient.getProxyConfiguration().getProxies().add(proxy);
    }
    if (this.httpProxyUsername != null && httpProxyPassword != null) {
        ObjectHelper.notEmpty(httpProxyAuthUri, "httpProxyAuthUri");
        ObjectHelper.notEmpty(httpProxyRealm, "httpProxyRealm");
        final Authentication authentication;
        if (httpProxyUseDigestAuth) {
            authentication = new DigestAuthentication(new URI(httpProxyAuthUri), httpProxyRealm, httpProxyUsername, httpProxyPassword);
        } else {
            authentication = new BasicAuthentication(new URI(httpProxyAuthUri), httpProxyRealm, httpProxyUsername, httpProxyPassword);
        }
        httpClient.getAuthenticationStore().addAuthentication(authentication);
    }
    // support restarts
    if (this.session == null) {
        this.session = new SalesforceSession(getCamelContext(), httpClient, httpClient.getTimeout(), loginConfig);
    }
    // set session before calling start()
    httpClient.setSession(this.session);
    // start the Jetty client to initialize thread pool, etc.
    httpClient.start();
    // login at startup if lazyLogin is disabled
    if (!loginConfig.isLazyLogin()) {
        ServiceHelper.startService(session);
    }
    if (packages != null && packages.length > 0) {
        // parse the packages to create SObject name to class map
        classMap = parsePackages();
        LOG.info("Found {} generated classes in packages: {}", classMap.size(), Arrays.asList(packages));
    } else {
        // use an empty map to avoid NPEs later
        LOG.warn("Missing property packages, getSObject* operations will NOT work");
        classMap = new HashMap<String, Class<?>>(0);
    }
    if (subscriptionHelper != null) {
        ServiceHelper.startService(subscriptionHelper);
    }
}
Also used : Origin(org.eclipse.jetty.client.Origin) DigestAuthentication(org.eclipse.jetty.client.util.DigestAuthentication) URI(java.net.URI) SSLContextParameters(org.apache.camel.util.jsse.SSLContextParameters) HttpProxy(org.eclipse.jetty.client.HttpProxy) Socks4Proxy(org.eclipse.jetty.client.Socks4Proxy) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) ProxyConfiguration(org.eclipse.jetty.client.ProxyConfiguration) Authentication(org.eclipse.jetty.client.api.Authentication) DigestAuthentication(org.eclipse.jetty.client.util.DigestAuthentication) BasicAuthentication(org.eclipse.jetty.client.util.BasicAuthentication) SalesforceSession(org.apache.camel.component.salesforce.internal.SalesforceSession) BasicAuthentication(org.eclipse.jetty.client.util.BasicAuthentication)

Example 4 with SalesforceSession

use of org.apache.camel.component.salesforce.internal.SalesforceSession 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)

Example 5 with SalesforceSession

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

the class CamelSalesforceMojo method createHttpClient.

protected SalesforceHttpClient createHttpClient() throws MojoExecutionException {
    final SalesforceHttpClient httpClient;
    // set ssl context parameters
    try {
        final SSLContextParameters contextParameters = sslContextParameters != null ? sslContextParameters : new SSLContextParameters();
        final SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setSslContext(contextParameters.createSSLContext());
        httpClient = new SalesforceHttpClient(sslContextFactory);
    } catch (GeneralSecurityException e) {
        throw new MojoExecutionException("Error creating default SSL context: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new MojoExecutionException("Error creating default SSL context: " + e.getMessage(), e);
    }
    // default settings
    httpClient.setConnectTimeout(DEFAULT_TIMEOUT);
    httpClient.setTimeout(DEFAULT_TIMEOUT);
    // enable redirects, no need for a RedirectListener class in Jetty 9
    httpClient.setFollowRedirects(true);
    // set HTTP client parameters
    if (httpClientProperties != null && !httpClientProperties.isEmpty()) {
        try {
            IntrospectionSupport.setProperties(httpClient, new HashMap<String, Object>(httpClientProperties));
        } catch (Exception e) {
            throw new MojoExecutionException("Error setting HTTP client properties: " + e.getMessage(), e);
        }
    }
    // wait for 1 second longer than the HTTP client response timeout
    responseTimeout = httpClient.getTimeout() + 1000L;
    // set HTTP proxy settings
    if (this.httpProxyHost != null && httpProxyPort != null) {
        Origin.Address proxyAddress = new Origin.Address(this.httpProxyHost, this.httpProxyPort);
        ProxyConfiguration.Proxy proxy;
        if (isHttpProxySocks4) {
            proxy = new Socks4Proxy(proxyAddress, isHttpProxySecure);
        } else {
            proxy = new HttpProxy(proxyAddress, isHttpProxySecure);
        }
        if (httpProxyIncludedAddresses != null && !httpProxyIncludedAddresses.isEmpty()) {
            proxy.getIncludedAddresses().addAll(httpProxyIncludedAddresses);
        }
        if (httpProxyExcludedAddresses != null && !httpProxyExcludedAddresses.isEmpty()) {
            proxy.getExcludedAddresses().addAll(httpProxyExcludedAddresses);
        }
        httpClient.getProxyConfiguration().getProxies().add(proxy);
    }
    if (this.httpProxyUsername != null && httpProxyPassword != null) {
        ObjectHelper.notEmpty(httpProxyAuthUri, "httpProxyAuthUri");
        ObjectHelper.notEmpty(httpProxyRealm, "httpProxyRealm");
        final Authentication authentication;
        if (httpProxyUseDigestAuth) {
            authentication = new DigestAuthentication(URI.create(httpProxyAuthUri), httpProxyRealm, httpProxyUsername, httpProxyPassword);
        } else {
            authentication = new BasicAuthentication(URI.create(httpProxyAuthUri), httpProxyRealm, httpProxyUsername, httpProxyPassword);
        }
        httpClient.getAuthenticationStore().addAuthentication(authentication);
    }
    // set session before calling start()
    final SalesforceSession session = new SalesforceSession(new DefaultCamelContext(), httpClient, httpClient.getTimeout(), new SalesforceLoginConfig(loginUrl, clientId, clientSecret, userName, password, false));
    httpClient.setSession(session);
    try {
        httpClient.start();
    } catch (Exception e) {
        throw new MojoExecutionException("Error creating HTTP client: " + e.getMessage(), e);
    }
    return httpClient;
}
Also used : Origin(org.eclipse.jetty.client.Origin) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) DigestAuthentication(org.eclipse.jetty.client.util.DigestAuthentication) SalesforceHttpClient(org.apache.camel.component.salesforce.SalesforceHttpClient) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) SalesforceException(org.apache.camel.component.salesforce.api.SalesforceException) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) SalesforceLoginConfig(org.apache.camel.component.salesforce.SalesforceLoginConfig) SSLContextParameters(org.apache.camel.util.jsse.SSLContextParameters) HttpProxy(org.eclipse.jetty.client.HttpProxy) Socks4Proxy(org.eclipse.jetty.client.Socks4Proxy) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) ProxyConfiguration(org.eclipse.jetty.client.ProxyConfiguration) DigestAuthentication(org.eclipse.jetty.client.util.DigestAuthentication) BasicAuthentication(org.eclipse.jetty.client.util.BasicAuthentication) Authentication(org.eclipse.jetty.client.api.Authentication) SalesforceSession(org.apache.camel.component.salesforce.internal.SalesforceSession) BasicAuthentication(org.eclipse.jetty.client.util.BasicAuthentication) SObject(org.apache.camel.component.salesforce.api.dto.SObject)

Aggregations

SalesforceSession (org.apache.camel.component.salesforce.internal.SalesforceSession)5 SalesforceHttpClient (org.apache.camel.component.salesforce.SalesforceHttpClient)3 SalesforceException (org.apache.camel.component.salesforce.api.SalesforceException)3 SSLContextParameters (org.apache.camel.util.jsse.SSLContextParameters)3 SslContextFactory (org.eclipse.jetty.util.ssl.SslContextFactory)3 IOException (java.io.IOException)2 GeneralSecurityException (java.security.GeneralSecurityException)2 SObject (org.apache.camel.component.salesforce.api.dto.SObject)2 DefaultRestClient (org.apache.camel.component.salesforce.internal.client.DefaultRestClient)2 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)2 HttpProxy (org.eclipse.jetty.client.HttpProxy)2 Origin (org.eclipse.jetty.client.Origin)2 ProxyConfiguration (org.eclipse.jetty.client.ProxyConfiguration)2 Socks4Proxy (org.eclipse.jetty.client.Socks4Proxy)2 Authentication (org.eclipse.jetty.client.api.Authentication)2 BasicAuthentication (org.eclipse.jetty.client.util.BasicAuthentication)2 DigestAuthentication (org.eclipse.jetty.client.util.DigestAuthentication)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 File (java.io.File)1 URI (java.net.URI)1