Example usage for com.mongodb MongoClientURI getUsername

List of usage examples for com.mongodb MongoClientURI getUsername

Introduction

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

Prototype

@Nullable
public String getUsername() 

Source Link

Document

Gets the username

Usage

From source file:com.cloudbees.demo.beesshop.util.MongodbDBFactoryBean.java

License:Apache License

@Override
public void afterPropertiesSet() throws Exception {
    MongoClientURI mongoDbUri = new MongoClientURI(uri);
    logger.info("host=" + mongoDbUri.getHosts() + ",username=" + mongoDbUri.getUsername() + ",database="
            + mongoDbUri.getDatabase() + ",collection=" + mongoDbUri.getCollection());

    mongoClient = new MongoClient(mongoDbUri);
    db = mongoClient.getDB(mongoDbUri.getDatabase());
}

From source file:com.zjy.mongo.splitter.MongoCollectionSplitter.java

License:Apache License

protected DB getConfigDB() {
    Mongo mongo;//from w w  w .j  av a  2 s .  c  om
    MongoClientURI inputURI = MongoConfigUtil.getInputURI(getConfiguration());
    MongoClientURI authURI = MongoConfigUtil.getAuthURI(getConfiguration());

    final DBCollection inputCollection;
    if (authURI != null && authURI.getUsername() != null && authURI.getPassword() != null) {
        inputCollection = MongoConfigUtil.getCollectionWithAuth(inputURI, authURI);
    } else {
        inputCollection = MongoConfigUtil.getCollection(inputURI);
    }

    DB db = inputCollection.getDB();
    mongo = db.getMongo();
    if (authURI != null) {
        if (authURI.getUsername() != null && authURI.getPassword() != null) {
            authDB = mongo.getDB(authURI.getDatabase());
        }
    }

    return mongo.getDB("config");
}

From source file:com.zjy.mongo.util.MongoConfigUtil.java

License:Apache License

/**
 * Get an authenticated DBCollection from a MongodB URI.
 * @param authURI the URI with which to authenticate
 * @param uri the MongoDB URI/* ww w. j  a  v a  2 s .  c o  m*/
 * @return the authenticated DBCollection
 */
public static DBCollection getCollectionWithAuth(final MongoClientURI uri, final MongoClientURI authURI) {
    //Make sure auth uri is valid and actually has a username/pw to use
    if (authURI == null || authURI.getUsername() == null || authURI.getPassword() == null) {
        throw new IllegalArgumentException(
                "auth URI is empty or does not contain a valid username/password combination.");
    }

    DBCollection coll;
    try {
        Mongo mongo = getMongoClient(authURI);
        coll = mongo.getDB(uri.getDatabase()).getCollection(uri.getCollection());
        return coll;
    } catch (Exception e) {
        throw new IllegalArgumentException("Couldn't connect and authenticate to get collection", e);
    }
}

From source file:de.adorsys.oauth.tokenstore.mongodb.MongoDbProvider.java

License:Apache License

@SuppressWarnings("ReplaceAllDot")
private String createLogUri(MongoClientURI clientURI) {
    StringBuilder sb = new StringBuilder();
    String password = clientURI.getPassword() == null ? null
            : new String(clientURI.getPassword()).replaceAll(".", "x");
    String username = clientURI.getUsername();
    for (String host : clientURI.getHosts()) {
        sb.append("mongodb://");
        if (username != null) {
            sb.append(username);//from   www . j av  a 2  s.c o  m
            if (password != null) {
                sb.append(':').append(password);
            }
            sb.append('@');
        }
        sb.append(host).append(" ");
    }

    return sb.toString();
}

From source file:localdomain.localhost.MongoDbTroubleshooter.java

License:Open Source License

public void run() throws Exception {
    try (PrintWriter writer = new PrintWriter(System.out)) {

        MongoClientURI mongoClientUri = new MongoClientURI(uri);
        writer.println("" + "host=" + mongoClientUri.getHosts() + ",username=" + mongoClientUri.getUsername()
                + ",database=" + mongoClientUri.getDatabase() + ",collection=" + mongoClientUri.getCollection()
                + "");

        writer.println();//from w  ww .java  2s.  c  o  m
        writer.println();

        writer.println("# MongoClient");
        writer.println();

        MongoClient mongoClient = new MongoClient(mongoClientUri);
        writer.println("" + mongoClient + "");

        writer.println();
        writer.println();
        writer.println("# Databases");
        writer.println();

        try {
            List<String> databaseNames = mongoClient.getDatabaseNames();
            for (String databaseName : databaseNames) {
                writer.println("* " + databaseName
                        + (databaseName.equals(mongoClientUri.getDatabase()) ? " - default database" : ""));
            }
        } catch (Exception e) {
            writer.println("Could not list the databases of the MongoDB instance: '" + e.getMessage() + "'");

        }

        writer.println();
        writer.println();
        writer.println("# Database");
        writer.println();

        DB db = mongoClient.getDB(mongoClientUri.getDatabase());
        writer.println("DB: " + db.getName() + "");

        writer.println();
        writer.println();
        writer.println("## Collections");
        writer.println();
        Set<String> myCollections = db.getCollectionNames();
        if (myCollections.isEmpty()) {
            writer.println("NO COLLECTIONS!");

        } else {

            for (String collection : myCollections) {
                DBCollection dbCollection = db.getCollection(collection);
                writer.println("* " + dbCollection.getName() + " - " + dbCollection.getCount() + " entries");
            }
        }
    }
}

From source file:localdomain.localhost.MyServlet.java

License:Apache License

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    PrintWriter writer = resp.getWriter();

    writer.println("<html>");
    writer.println("<head><title>MyServlet</title></head>");
    writer.println("<body><h1>MyServlet</h1>");

    writer.println("<h2>MongoDB</h2>");

    String uriAsString = System.getProperty("MONGOHQ_URL_MYDB", "mongodb://localhost/local");

    MongoClient mongoClient = null;//w  ww . ja  v a  2 s. c o  m
    try {
        writer.println("<h4>MongoClientURI</h4>");

        MongoClientURI uri = new MongoClientURI(uriAsString);
        writer.println("<p>" + "host=" + uri.getHosts() + ",username=" + uri.getUsername() + ",database="
                + uri.getDatabase() + ",collection=" + uri.getCollection() + "</p>");

        writer.println("<h4>MongoClient</h4>");

        mongoClient = new MongoClient(uri);
        writer.println("<p>" + mongoClient + "</p>");

        writer.println("<h4>Databases</h4>");

        try {
            List<String> databaseNames = mongoClient.getDatabaseNames();
            writer.println("<ul>");
            for (String databaseName : databaseNames) {
                writer.println("<li>" + databaseName
                        + (databaseName.equals(uri.getDatabase()) ? " - default database" : ""));
            }
            writer.println("</ul>");
        } catch (Exception e) {
            writer.println("<p>Could not list the databases of the MongoDB instance: <code>" + e.getMessage()
                    + "</code></p>");

        }

        writer.println("<h4>Database</h4>");

        DB db = mongoClient.getDB(uri.getDatabase());
        writer.println("<p>DB: " + db.getName() + "</p>");

        writer.println("<h4>Collections</h4>");
        Set<String> myCollections = db.getCollectionNames();
        if (myCollections.isEmpty()) {
            writer.println("<p>NO COLLECTIONS!</p>");

        } else {

            writer.println("<ul>");
            for (String collection : myCollections) {
                DBCollection dbCollection = db.getCollection(collection);
                writer.println(
                        "<li>" + dbCollection.getName() + " - " + dbCollection.getCount() + " entries</li>");
            }
            writer.println("</ul>");
        }
        writer.println("<h4>Success!</h4>");
        writer.println("SUCCESS to access the mongodb database");

    } catch (Exception e) {
        writer.println("<code><pre>");
        e.printStackTrace(writer);
        writer.println("</pre></code>");

        e.printStackTrace();
    } finally {
        if (mongoClient != null) {
            try {
                mongoClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    writer.println("</body></html>");

}

From source file:mx.org.cedn.avisosconagua.mongo.UpdateIssueDate.java

License:Open Source License

public static void main(String[] arg) throws Exception {
    MongoClientURI mongoClientURI = new MongoClientURI(System.getenv("MONGOHQ_URL"));
    MongoClient mongoClient = new MongoClient(mongoClientURI);
    DB mongoDB = mongoClient.getDB(mongoClientURI.getDatabase());
    String GENERATED_COL = "GeneratedFiles";
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
    SimpleDateFormat isoformater = new SimpleDateFormat("YYYY-MM-dd HH:mm");
    if (null != mongoClientURI.getUsername()) {
        mongoDB.authenticate(mongoClientURI.getUsername(), mongoClientURI.getPassword());
    }/*  w w w . ja v a 2  s.  c o m*/
    DBCollection col = mongoDB.getCollection(GENERATED_COL);
    DBCursor cursor = col.find();
    for (DBObject obj : cursor) {
        String date = (String) obj.get("issueDate");
        Date fec = null;
        try {
            fec = sdf.parse(date);
        } catch (ParseException npe) {

        }
        if (null != fec) {
            date = isoformater.format(fec);
            DBObject act = col.findOne(obj);
            obj.put("issueDate", date);
            col.update(act, obj);
        }
    }
}

From source file:org.alfresco.mongo.MongoClientFactory.java

License:Open Source License

/**
 * Create an instance of the factory.  The URI given must not contain a database name or user/password details.
 * This forces the client URI to be an instance that can be shared between instances of this factory.
 * // w  w  w  .  j a va2s . co m
 * @param mongoClientURI            the client URI, which <b>must not</b> reference a database, username or password
 * @param username                  the username to use when connecting (<tt>null</tt> allowed and empty string is ignored)
 * @param password                  the user password for the database (<tt>null</tt> allowed and empty string is ignored)
 * 
 * @throws IllegalArgumentException if the arguments are null when not allowed or contain invalid information
 */
public MongoClientFactory(MongoClientURI mongoClientURI, String username, String password)
        throws UnknownHostException {
    validateMongoClientURI(mongoClientURI);

    if (mongoClientURI.getDatabase() != null) {
        throw new IllegalArgumentException(
                "The provided 'mongoClientURI' instance may not reference a specific database: "
                        + MongoClientFactory.toStringSafe(mongoClientURI));
    } else if (mongoClientURI.getUsername() != null) {
        throw new IllegalArgumentException(
                "The provided 'mongoClientURI' instance may not reference a specific username: "
                        + MongoClientFactory.toStringSafe(mongoClientURI));
    } else if (mongoClientURI.getPassword() != null) {
        throw new IllegalArgumentException(
                "The provided 'mongoClientURI' instance may not reference a specific password: "
                        + MongoClientFactory.toStringSafe(mongoClientURI));
    }

    // Reformat the URI if credentials were supplied
    if (username != null && username.length() > 0) {
        String userPwdCombo = username;
        if (password != null && password.length() > 0) {
            userPwdCombo = username + ":" + password;
        }
        String mongoClientURIstr = mongoClientURI.getURI().replace("mongodb://",
                "mongodb://" + userPwdCombo + "@");
        mongoClientURI = new MongoClientURI(mongoClientURIstr);
    }

    // Construct the client
    mongoClient = new MongoClient(mongoClientURI);

    // Done
    if (logger.isInfoEnabled()) {
        logger.info("New MongoDB client created using URL: " + MongoClientFactory.toStringSafe(mongoClientURI));
    }
}

From source file:org.basex.modules.MongoDB.java

License:BSD License

/**
 * Mongodb connection with options.//  w  w w .j a v  a 2 s. c o  m
 * @param url
 * @param options
 * @return
 * @throws QueryException
 */
public Str connection(final Str url, final Map options) throws QueryException {
    MongoClientURI uri = new MongoClientURI(url.toJava());
    String handler = "mongoClient" + mongoClients.size();
    try {
        MongoClient mongoClient = new MongoClient(uri);
        mongoClients.put(handler, mongoClient);
        return mongoConnect(handler, uri.getDatabase(), uri.getUsername(), uri.getPassword(), options);
    } catch (final MongoException ex) {
        throw MongoDBErrors.mongoExceptionError(ex);
    } catch (UnknownHostException ex) {
        throw MongoDBErrors.generalExceptionError(ex);
    }
}

From source file:org.basex.modules.nosql.MongoDB.java

License:BSD License

/**
 * Mongodb connection with options./*from  w w w .  j a v  a2  s  . c o  m*/
 * @param url mongodb url like: "mongodb://127.0.0.1:27017/basex"
 * @param options nosql options
 * @return Str
 * @throws QueryException query exception
 */
public Str connect(final Str url, final Map options) throws QueryException {
    MongoClientURI uri = new MongoClientURI(url.toJava());
    String handler = "mongoClient" + mongoClients.size();
    try {
        MongoClient mongoClient = new MongoClient(uri);
        mongoClients.put(handler, mongoClient);
        return mongoConnect(handler, uri.getDatabase(), uri.getUsername(), uri.getPassword(), options);
    } catch (final MongoException ex) {
        throw MongoDBErrors.mongoExceptionError(ex);
    } catch (UnknownHostException ex) {
        throw MongoDBErrors.generalExceptionError(ex);
    }
}