Skip to main content

Developing with XCC

Accessing a Keystore

You can use the Java keytool utility to import a MarkLogic certificate into a keystore. See the Java JSSE documentation for details on the use of the keytool and your keystore options.

You can explicitly specify a keystore, as shown in this example, or you can specify a null keystore. Specifying a null keystore causes the TrustManagerFactory to locate your default keystore, as described in the Java Secure Socket Extension (JSSE) Reference Guide.

To enable SSL by accessing certificates in a keystore, import the following classes in addition to those described in Coding Basics:

import com.marklogic.xcc.SecurityOptions;
import com.marklogic.xcc.ContentSource;
import com.marklogic.xcc.ContentSourceFactory;
import java.io.FileInputStream;
import java.net.URI;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.SSLContext;
import java.security.KeyStore;
import java.security.cert.X509Certificate;

Get the signed certificate from a keystore and pass it to the SSLContext.init() method:

protected SecurityOptions newTrustOptions()
  throws Exception
{
// Load key store with trusted signing authorities.
  KeyStore trustedKeyStore = KeyStore.getInstance("JKS");
  trustedKeyStore.load(
    new FileInputStream("C:/users/myname/.keystore"), 
    null);
// Build trust manager to validate server certificates using the
   specified key store.
  TrustManagerFactory trustManagerFactory =
    TrustManagerFactory.getInstance("SunX509");
  trustManagerFactory.init(trustedKeyStore);
  TrustManager[] trust = trustManagerFactory.getTrustManagers();
  SSLContext sslContext = SSLContext.getInstance("SSLv3");
  sslContext.init(null, trust, null);
  return new SecurityOptions(sslContext);
}

Call ContentSourceFactory.newContentSource() with a URI:

ContentSource cs = 
    ContentSourceFactory.newContentSource (uri,
                                           newTrustOptions());

The URI is passed from the command line in this form:

xccs://username:password@hostname:port