Example usage for com.mongodb MongoClientURI getCredentials

List of usage examples for com.mongodb MongoClientURI getCredentials

Introduction

In this page you can find the example usage for com.mongodb MongoClientURI getCredentials.

Prototype

@Nullable
public MongoCredential getCredentials() 

Source Link

Document

Gets the credentials.

Usage

From source file:com.streamsets.pipeline.stage.common.mongodb.MongoDBConfig.java

License:Apache License

private MongoClient createClient(Stage.Context context, List<Stage.ConfigIssue> issues,
        ReadPreference readPreference, WriteConcern writeConcern) {
    MongoClientOptions.Builder optionBuilder = new MongoClientOptions.Builder()
            .connectionsPerHost(connectionsPerHost).connectTimeout(connectTimeout)
            .cursorFinalizerEnabled(cursorFinalizerEnabled).heartbeatConnectTimeout(heartbeatConnectTimeout)
            .heartbeatFrequency(heartbeatFrequency).heartbeatSocketTimeout(heartbeatSocketTimeout)
            .localThreshold(localThreshold).maxConnectionIdleTime(maxConnectionIdleTime)
            .maxConnectionLifeTime(maxConnectionLifeTime).maxWaitTime(maxWaitTime)
            .minConnectionsPerHost(minConnectionsPerHost).minHeartbeatFrequency(minHeartbeatFrequency)
            .serverSelectionTimeout(serverSelectionTimeout).socketKeepAlive(socketKeepAlive)
            .socketTimeout(socketTimeout).sslEnabled(sslEnabled)
            .sslInvalidHostNameAllowed(sslInvalidHostNameAllowed)
            .threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);

    // the default value of requiredReplicaSetName is null, so it should be set only if a non-empty string is provided
    if (!requiredReplicaSetName.isEmpty()) {
        optionBuilder = optionBuilder.requiredReplicaSetName(requiredReplicaSetName);
    }/*from ww  w .j a v a  2  s . c  o m*/
    // read preference is only set by the source
    if (readPreference != null) {
        optionBuilder = optionBuilder.readPreference(readPreference);
    }
    // write concern is only set by the target
    if (writeConcern != null) {
        optionBuilder = optionBuilder.writeConcern(writeConcern);
    }

    MongoClientURI mongoURI;
    List<ServerAddress> servers = new ArrayList<>();
    try {
        mongoURI = new MongoClientURI(connectionString, optionBuilder);
    } catch (IllegalArgumentException e) {
        issues.add(context.createConfigIssue(Groups.MONGODB.name(), MONGO_CONFIG_PREFIX + "connectionString",
                Errors.MONGODB_00, e.toString()));
        return null;
    }

    validateServerList(context, mongoURI.getHosts(), servers, issues);
    if (!issues.isEmpty()) {
        return null;
    }

    MongoClient mongoClient = null;
    List<MongoCredential> credentials;
    try {
        credentials = createCredentials();
    } catch (StageException ex) {
        issues.add(context.createConfigIssue(Groups.MONGODB.name(), MONGO_CONFIG_PREFIX + "connectionString",
                Errors.MONGODB_34, ex.toString()));
        return null;
    }

    if (credentials.isEmpty()) {
        Optional.ofNullable(mongoURI.getCredentials()).ifPresent(credentials::add);
    }

    try {
        if (isSingleMode) {
            mongoClient = new MongoClient(servers.get(0), credentials, mongoURI.getOptions());
        } else {
            mongoClient = new MongoClient(servers, credentials, mongoURI.getOptions());
        }
    } catch (MongoException e) {
        issues.add(context.createConfigIssue(Groups.MONGODB.name(), MONGO_CONFIG_PREFIX + "connectionString",
                Errors.MONGODB_01, e.toString()));
    }

    return mongoClient;
}

From source file:io.opentracing.contrib.mongo.TracingMongoClient.java

License:Apache License

public TracingMongoClient(Tracer tracer, final MongoClientURI uri,
        final MongoDriverInformation mongoDriverInformation) {
    this(tracer, toServerAddressList(uri.getHosts()),
            uri.getCredentials() != null ? Collections.singletonList(uri.getCredentials())
                    : Collections.<MongoCredential>emptyList(),
            uri.getOptions(), mongoDriverInformation);
}

From source file:org.apache.jackrabbit.oak.plugins.document.mongo.replica.NodeCollectionProvider.java

License:Apache License

private MongoClient prepareClientForHostname(String hostname) throws UnknownHostException {
    ServerAddress address;//from w  w w. j  a  v  a 2 s  .co m
    if (hostname.contains(":")) {
        String[] hostSplit = hostname.split(":");
        if (hostSplit.length != 2) {
            throw new IllegalArgumentException("Not a valid hostname: " + hostname);
        }
        address = new ServerAddress(hostSplit[0], Integer.parseInt(hostSplit[1]));
    } else {
        address = new ServerAddress(hostname);
    }

    MongoClientURI originalUri = new MongoClientURI(originalMongoUri);
    List<MongoCredential> credentialList = new ArrayList<MongoCredential>(1);
    if (originalUri.getCredentials() != null) {
        credentialList.add(originalUri.getCredentials());
    }
    return new MongoClient(address, credentialList, originalUri.getOptions());
}

From source file:org.craftercms.commons.mongo.MongoScriptRunner.java

License:Open Source License

private List<String> getCommands(final Path scriptPath) throws MongoDataException {
    List<String> commandList = new ArrayList<>();
    if (SystemUtils.IS_OS_WINDOWS) {
        commandList.add("CMD");
        commandList.add("/C");
    }/*www  .j a v  a  2  s .c  o m*/
    if (StringUtils.isBlank(mongoClientBin)) {
        throw new MongoDataException("Unable to run scripts, mongo client bin path is not set ");
    }
    String pwd = null;
    String authSource = null;
    String user = null;
    MongoClientURI uri = new MongoClientURI(connectionStr);
    if (uri.getCredentials() != null) {
        authSource = uri.getCredentials().getSource();
        user = uri.getCredentials().getUserName();
        if (uri.getCredentials().getPassword() != null) {
            pwd = new String(uri.getCredentials().getPassword());
        }
    }
    String replicaSetName = "";
    if (uri.getHosts().size() > 1) {
        replicaSetName = uri.getOptions().getRequiredReplicaSetName() + "/";
    }
    final String host = StringUtils.trim(replicaSetName + StringUtils.join(uri.getHosts(), ","));
    commandList.add(mongoClientBin);
    commandList.add("--host");
    commandList.add(host);
    commandList.add(uri.getDatabase());
    if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(pwd) && StringUtils.isNotBlank(authSource)) {
        commandList.add("-u");
        commandList.add(user);
        commandList.add("-p");
        commandList.add(pwd);
        commandList.add("--authenticationDatabase");
        commandList.add(authSource);
    }
    commandList.add(scriptPath.toAbsolutePath().toString());
    return commandList;
}

From source file:org.graylog.plugins.metrics.mongodb.providers.MongoDBReporterProvider.java

License:Open Source License

@Override
public MongoDBReporter get() {
    final MongoClientURI mongoClientURI = configuration.getUri();
    final MongoCredential credentials = mongoClientURI.getCredentials();
    return MongoDBReporter.forRegistry(metricRegistry).serverAddresses(extractServerAddresses(mongoClientURI))
            .mongoCredentials(/*  w w  w  .  j  ava2s.  c om*/
                    credentials == null ? new MongoCredential[0] : new MongoCredential[] { credentials })
            .mongoClientOptions(mongoClientURI.getOptions()).withDatabaseName(mongoClientURI.getDatabase())
            .additionalFields(configuration.getAdditionalFields())
            .convertDurationsTo(configuration.getUnitDurations()).convertRatesTo(configuration.getUnitRates())
            .filter(new RegexMetricFilter(configuration.getIncludeMetrics())).build();
}