title: How to connect to MongoDB Enabled with SSL and Auth using java
body: <p><strong>QUESTION</strong>:</p>
  
  <p>I have CA Certificate as <strong>cafile.pem</strong>, PEM Certificate as <strong>mongodb.pem</strong>. I am not sure how to use it in java to authentication and connect MongoDB. Any suggestion would be deeply appreciate. Let me know if you want more information to put up.</p>
  
  <p><strong>Scenario:</strong></p>
  
  <p>I am using <strong>mongo-java-driver-3.4.3.jar</strong> to connect to an <em>SSL enabled, Authentication enabled</em> <strong>MongoDB 3.7.9</strong> sharded cluster with 3 instances. Below is the java code I am trying to connect to this server.</p>
  
  <pre><code>import java.util.ArrayList;
  import java.util.List;
  
  import org.bson.Document;
  
  import com.mongodb.MongoClient;
  import com.mongodb.MongoClientOptions;
  import com.mongodb.MongoCredential;
  import com.mongodb.ReadPreference;
  import com.mongodb.ServerAddress;
  import com.mongodb.client.MongoCollection;
  import com.mongodb.client.MongoDatabase;
  
  public class Starter {
  
      public static void main(String[] args){
  
          List&lt;MongoCredential&gt; mongoCredentials = new ArrayList&lt;MongoCredential&gt;();
          mongoCredentials.add(MongoCredential.
          createScramSha1Credential("admin", "admin", "admin".toCharArray()));
  
          List&lt;ServerAddress&gt; serverAddressArray = new ArrayList&lt;ServerAddress&gt;();
  
          serverAddressArray.add(new ServerAddress("xyz.domain.com", 27017));
  
          MongoClientOptions options = new MongoClientOptions.Builder()
                                          .sslInvalidHostNameAllowed(false)
                                          .sslEnabled(true)
                                          .readPreference(ReadPreference.primaryPreferred())
                                          .build();
          MongoClient mongoClient = new MongoClient(serverAddressArray, mongoCredentials, options);
          try {
              System.out.println("----- Step 1 ------");
              MongoDatabase db = mongoClient.getDatabase("CIM");
              System.out.println("----- Step 2 ------");
              MongoCollection&lt;Document&gt; collection = db.getCollection("orders");
              System.out.println("No of Documents in orders collection: " + collection.count());
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
      }       
  }
  </code></pre>
  
  <p>I get below error;</p>
  
  <pre><code>----- Step 1 ------
  ----- Step 2 ------
  Sep 20, 2018 2:48:02 PM com.mongodb.diagnostics.logging.JULLogger log
  INFO: No server chosen by ReadPreferenceServerSelector{readPreference=ReadPreference{name=primaryPreferred}} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=MULTIPLE, serverDescriptions=[ServerDescription{address=torvm-core16.sigma-systems.com:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
  Sep 20, 2018 2:48:03 PM com.mongodb.diagnostics.logging.JULLogger log
  INFO: Exception in monitor thread while connecting to server xyz.domain.com:27017
  com.mongodb.MongoSocketReadException: Prematurely reached end of stream
      at com.mongodb.connection.SocketStream.read(SocketStream.java:88)
      at com.mongodb.connection.InternalStreamConnection.receiveResponseBuffers(InternalStreamConnection.java:494)
      at com.mongodb.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:224)
      at com.mongodb.connection.CommandHelper.receiveReply(CommandHelper.java:134)
      at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:121)
      at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
      .............
  </code></pre>
  
  <p>Anyways I am able to connect MongoServer as below configuration in RoboMongo3T.</p>
  
  <p><a href="https://i.stack.imgur.com/n58RY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n58RY.png" alt="enter image description here"></a></p>
  
  <p><strong>mongodb.pem</strong></p>
  
  <pre><code>Bag Attributes
      localKeyID: AA 4A 8D C5 AC CE 7A 08 F6 F1 00 2C 78 20 8D 0C 51 DE 66 F5 
  subject=/OU=Domain Control Validated/CN=*.xyz.com
  issuer=/C=US/ST=Arizona/L=Scottsdale/O=GoDaddy.com, Inc./OU=http://certs.godaddy.com/repository//CN=Go Daddy Secure Certificate Authority - G2
  -----BEGIN CERTIFICATE-----
  MIIFPzCCBCegAwIBAgIJAKpTjrMr7rpZMA0GCSqGSIb3DQEBCwUAMIG0MQswCQYD
  .
  .
  .
  -----END CERTIFICATE-----
  Bag Attributes: &lt;No Attributes&gt;
  subject=/C=US/ST=Arizona/L=Scottsdale/O=GoDaddy.com, Inc./OU=http://certs.godaddy.com/repository//CN=Go Daddy Secure Certificate Authority - G2
  issuer=/C=US/ST=Arizona/L=Scottsdale/O=GoDaddy.com, Inc./CN=Go Daddy Root Certificate Authority - G2
  -----BEGIN CERTIFICATE-----
  MIIFPzCCBCegAwIBAgIJAKpTjrMr7rpZMA0GCSqGSIb3DQEBCwUAMIG0MQswCQYD
  .
  .
  .
  -----END CERTIFICATE-----
  Bag Attributes
      localKeyID: AA 4A 8D C5 AC CE 7A 08 F6 F1 00 2C 78 20 8D 0C 51 DE 66 F5 
  Key Attributes: &lt;No Attributes&gt;
  -----BEGIN PRIVATE KEY-----
  MIIFPzCCBCegAwIBAgIJAKpTjrMr7rpZMA0GCSqGSIb3DQEBCwUAMIG0MQswCQYD
  .
  .
  .
  -----END PRIVATE KEY-----
  </code></pre>
  
  <p><strong>cafile.pem</strong></p>
  
  <pre><code>-----BEGIN CERTIFICATE-----
  MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh
  .
  .
  .
  .
  .
  
  -----END CERTIFICATE-----
  </code></pre>