Example usage for com.mongodb MongoCredential createCredential

List of usage examples for com.mongodb MongoCredential createCredential

Introduction

In this page you can find the example usage for com.mongodb MongoCredential createCredential.

Prototype

public static MongoCredential createCredential(final String userName, final String database,
        final char[] password) 

Source Link

Document

Creates a MongoCredential instance with an unspecified mechanism.

Usage

From source file:DataAccess.DAO.LoginDAO.java

public String validate(String username, String password) {

    String returnText = LOGIN_FAILURE;

    Mongo mongo = new Mongo("localhost", 27017);
    DB db = mongo.getDB("Restaurant");

    try {/*from   www. j av a  2s  . c  o  m*/

        //boolean auth = db.authenticate(username, password.toCharArray());
        MongoCredential credential2 = MongoCredential.createCredential(username, "Restaurant",
                password.toCharArray());
        MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential2));

        DB db2 = mongoClient.getDB("Restaurant");
        System.out.println("Connect to database successfully");

        DBCollection coll = db2.getCollection("Users");
        System.out.println("Collection users selected successfully");
        BasicDBObject document2 = new BasicDBObject();
        document2.put("UserName", username);
        document2.put("Password", password);
        //coll.insert(document2);
        DBCursor cur2 = coll.find(document2);

        System.out.println(cur2.toString());

        while (cur2.hasNext()) {
            System.out.println(cur2.next());
        }

        System.out.println("Login is successful!");

        if (credential2 != null) {

            DBCollection table = db.getCollection("Users");

            BasicDBObject document = new BasicDBObject();
            document.put("UserName", username);
            table.insert(document);
            DBCursor cur = table.find(document);

            while (cur.hasNext()) {
                System.out.println(cur.next());
            }

            HttpSession session = SessionBean.getSession();
            session.setAttribute("UserName", user);

            System.out.println("Login is successful!");
            returnText = LOGIN_SUCCESS;

            return "admins";
        } else {

            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
                    "Incorrect Username and Passowrd", "Please enter correct username and Password"));

            System.out.println("Login is failed!");
            return "login";
        }
        //System.out.println("Done");

        //return returnText;

    } catch (MongoException e) {
        e.printStackTrace();
    } finally {
        mongo.close();
    }
    return returnText;
}

From source file:de.tum.in.mongodb.MongoDBServiceConfiguration.java

License:Apache License

/**
 * Registers MongoDB Service/*from   www.jav  a 2s  .  c o  m*/
 */
private void doRegister(final ComponentContext componentContext, final Map<String, Object> properties) {
    this.m_properties = properties;
    this.m_host = (String) this.m_properties.get(MONGO_DB_HOST);
    this.m_port = (int) this.m_properties.get(MONGO_DB_PORT);
    this.m_dbname = (String) this.m_properties.get(MONGO_DB_DBNAME);
    this.m_username = (String) this.m_properties.get(MONGO_DB_USERNAME);
    this.m_password = (String) this.m_properties.get(MONGO_DB_PASSWORD);

    if (this.m_username != null) {
        final MongoCredential credential = MongoCredential.createCredential(this.m_username, this.m_dbname,
                this.m_password.toCharArray());
        this.m_mongoClient = new MongoClient(new ServerAddress(this.m_host), Arrays.asList(credential));
        LOGGER.info("Authenticated as '" + this.m_username + "'");
    }

    this.registerMongoDBService(componentContext);
}

From source file:edu.stanford.epad.common.util.MongoDBOperations.java

License:Open Source License

/**
 * Connection to mongo database/*  w ww . j  a  v a2  s  .c  o  m*/
 * @return
 */
public static DB getMongoDB() {
    if (mongoDB == null) {
        try {
            String mongoHost = EPADConfig.mongoHostname;
            if (mongoHost == null)
                return null;
            MongoClient mongoClient = null;
            if (EPADConfig.mongoUser == null) {
                mongoClient = new MongoClient(mongoHost);
            } else {
                MongoCredential credential = MongoCredential.createCredential(EPADConfig.mongoUser,
                        EPADConfig.mongoDB, EPADConfig.mongoPassword.toCharArray());
                mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential));
            }
            mongoDB = mongoClient.getDB(EPADConfig.mongoDB);
        } catch (Exception e) {
            log.warning("Error connecting to MongoDB", e);
        }
    }
    return mongoDB;
}

From source file:ELK.ELKController.java

License:Apache License

public ELKController(String mongoURIString) throws IOException {
    MongoCredential cred = MongoCredential.createCredential("admin", "cmpe283", "admin".toCharArray());
    final MongoClient mongoClient = new MongoClient(new ServerAddress("ds047107.mongolab.com:47107"),
            Arrays.asList(cred));
    final MongoDatabase blogDatabase = mongoClient.getDatabase("cmpe283");

    userDAO = new UserDAO(blogDatabase);
    sessionDAO = new SessionDAO(blogDatabase);

    // statsDAO= new StatsDAO(mongoClient.getDatabase("cmpe283project1"));
    //  AvailabiltyManager av =new AvailabiltyManager();
    //  av.start();

    //  Thread statsThread= new Thread(new statsCollector());
    // statsThread.start();

    cfg = createFreemarkerConfiguration();
    // this.si = null;
    // this.rootFolder = null;

    //  si = new ServiceInstance(new URL(SJSULAB.getVmwareHostURL()), SJSULAB.getVmwareLogin(), SJSULAB.getVmwarePassword(), true);
    //  rootFolder = si.getRootFolder();

    setPort(8082);// ww w.  ja v  a2s.co m
    initializeRoutes();
    VMsDBCollection = mongoClient.getDatabase("cmpe283").getCollection("virtual_machines");
    if (VMsDBCollection != null) {
        System.out.println("VMs DB Collection found");
    } else
        System.out.println("Sorry VMs DB Collection NOT found");

}

From source file:es.dheraspi.sums.model.DAOMongoDB.java

@Override
public void insertSummoner(Summoner summoner, String region) {
    MongoCredential credential = MongoCredential.createCredential(user, dbname, password.toCharArray());
    try (MongoClient mongoClient = new MongoClient(new ServerAddress(host), Arrays.asList(credential))) {
        db = mongoClient.getDatabase(dbname);
        MongoCollection<Document> coll = db.getCollection("summoners");

        int profileIconID = summoner.getProfileIconID();

        Bson doc = new Document("$set", new Document("_id", summoner.getID()))
                .append("name", summoner.getName()).append("level", summoner.getLevel())
                .append("profileIconID", profileIconID < 0 ? 0 : profileIconID);

        Bson filter = Filters.eq("_id", region);
        switch (region) {
        case "EUW":
            break;
        case "EUNE":
            break;
        case "NA":
            break;
        case "LAN":
            break;
        case "LAS":
            break;
        case "BR":
            break;
        case "TR":
            break;
        case "RU":
            break;
        case "OCE":
            break;
        case "KR":
            break;
        case "JP":
            break;
        }/*from   w  w  w  .  ja  va  2  s  .c o m*/
        UpdateOptions options = new UpdateOptions().upsert(true);

        coll.updateOne(filter, doc, options);
    } catch (APIException ex) {
        //Some unknown error when trying to get matchList
    }
}

From source file:es.dheraspi.sums.model.DAOMongoDB.java

@Override
public Map<String, String> getLanesSumsAnalysis(Summoner summoner) {
    Map<String, String> lanes_data = new HashMap<String, String>();
    MongoCredential credential = MongoCredential.createCredential(user, dbname, password.toCharArray());
    try (MongoClient mongoClient = new MongoClient(new ServerAddress(host), Arrays.asList(credential))) {
        db = mongoClient.getDatabase(dbname);
        MongoCollection<Document> coll = db.getCollection("analysis");

        Bson query = new Document("_id", Long.toString(summoner.getID()));
        FindIterable<Document> iterable = coll.find(query);

        try {//from w w w. j a v  a  2s . c o  m
            Document bot_doc = (Document) iterable.first().get("bot");
            Document mid_doc = (Document) iterable.first().get("mid");
            Document jun_doc = (Document) iterable.first().get("jun");
            Document top_doc = (Document) iterable.first().get("top");

            Iterator<String> kiter = bot_doc.keySet().iterator();
            Iterator<Object> viter = bot_doc.values().iterator();
            String bot = "";
            try {
                bot = bot + "[{\"summoners\": \"" + kiter.next() + "\", \"wins\": " + viter.next() + "}";
                for (int i = 0; i < bot_doc.size() - 1; i++) {
                    bot = bot + ",{\"summoners\": \"" + kiter.next() + "\", \"wins\": " + viter.next() + "}";
                }
                bot = bot + "]";
            } catch (NoSuchElementException ex) {
            }

            kiter = mid_doc.keySet().iterator();
            viter = mid_doc.values().iterator();
            String mid = "";
            try {
                mid = mid + "[{\"summoners\": \"" + kiter.next() + "\", \"wins\": " + viter.next() + "}";
                for (int i = 0; i < mid_doc.size() - 1; i++) {
                    mid = mid + ",{\"summoners\": \"" + kiter.next() + "\", \"wins\": " + viter.next() + "}";
                }
                mid = mid + "]";
            } catch (NoSuchElementException ex) {
            }

            kiter = jun_doc.keySet().iterator();
            viter = jun_doc.values().iterator();
            String jun = "";
            try {
                jun = jun + "[{\"summoners\": \"" + kiter.next() + "\", \"wins\": " + viter.next() + "}";
                for (int i = 0; i < jun_doc.size() - 1; i++) {
                    jun = jun + ",{\"summoners\": \"" + kiter.next() + "\", \"wins\": " + viter.next() + "}";
                }
                jun = jun + "]";
            } catch (NoSuchElementException ex) {
            }

            kiter = top_doc.keySet().iterator();
            viter = top_doc.values().iterator();
            String top = "";
            try {
                top = top + "[{\"summoners\": \"" + kiter.next() + "\", \"wins\": " + viter.next() + "}";
                for (int i = 0; i < top_doc.size() - 1; i++) {
                    top = top + ",{\"summoners\": \"" + kiter.next() + "\", \"wins\": " + viter.next() + "}";
                }
                top = top + "]";
            } catch (NoSuchElementException ex) {
            }

            if (!bot.equals(""))
                lanes_data.put("bot", bot);
            if (!mid.equals(""))
                lanes_data.put("mid", mid);
            if (!jun.equals(""))
                lanes_data.put("jun", jun);
            if (!top.equals(""))
                lanes_data.put("top", top);
        } catch (NullPointerException ex) {
            // No games found
        }

        return lanes_data;
    }
}

From source file:es.dheraspi.sums.model.DAOMongoDB.java

@Override
public String getLanesChampsSums(Summoner summoner) {
    MongoCredential credential = MongoCredential.createCredential(user, dbname, password.toCharArray());
    try (MongoClient mongoClient = new MongoClient(new ServerAddress(host), Arrays.asList(credential))) {
        db = mongoClient.getDatabase(dbname);
        MongoCollection<Document> coll = db.getCollection("analysis");

        Bson query = new Document("_id", Long.toString(summoner.getID()));
        FindIterable<Document> iterable = coll.find(query);

        Document doc = iterable.iterator().next();
        Document result = (Document) doc.get("lane_champ_sums");

        return result.toJson();
    } catch (NoSuchElementException | NullPointerException ex) {
        return "empty";
    }/*from   w w w  . j  a  v  a  2  s  . c om*/
}

From source file:foam.dao.MongoDAO.java

License:Open Source License

public MongoDAO(String host, int port, String dbName, String collectionName, String username, String password) {
    if (SafetyUtil.isEmpty(dbName) || SafetyUtil.isEmpty(collectionName)) {
        throw new IllegalArgumentException("Illegal arguments");
    }/*  w  ww  . j a  v  a  2s. c  om*/

    host = (host != null) ? host : "localhost";

    MongoClient mongoClient;

    if (isUserPassProvided(username, password)) {
        MongoCredential credential = MongoCredential.createCredential(username, dbName, password.toCharArray());
        mongoClient = new MongoClient(new ServerAddress(host, port), Arrays.asList(credential));
    } else {
        mongoClient = new MongoClient(host, port);
    }

    this.database = mongoClient.getDatabase(dbName);
    this.collectionName = collectionName;
}

From source file:io.awacs.repository.MongoRepository.java

License:Apache License

@Override
public void init(Configuration configuration) throws InitializationException {
    try {//from   w  w  w . j a v a2 s  .com
        String[] addrs = configuration.getString(ADDRESS, DEFAULT_ADDRESS).split(",");
        List<ServerAddress> addresses = new LinkedList<>();
        for (String addr : addrs) {
            String[] hostport = addr.split(":");
            addresses.add(new ServerAddress(hostport[0], Integer.valueOf(hostport[1])));
        }

        String db = configuration.getString(DB, DEFAULT_DB);

        List<MongoCredential> credentials = new LinkedList<>();
        String[] creds = configuration.getString(CREDENTIAL, DEFAULT_CREDENTIAL).split(",");
        if (!creds[0].equals("")) {
            for (String credential : creds) {
                int _1split = credential.indexOf(':');
                int _2split = credential.indexOf('@');
                if (_1split == -1 || _2split == -1) {
                    throw new MongoSecurityException(null, credential);
                }
                String username = credential.substring(0, _1split);
                String password = credential.substring(_1split + 1, _2split);
                String authDb = credential.substring(_2split + 1);
                credentials.add(MongoCredential.createCredential(username, authDb, password.toCharArray()));
            }
        }
        mongoConnection = new MongoConnection(addresses, credentials, db);
    } catch (Exception e) {
        e.printStackTrace();
        throw new InitializationException();
    }
}

From source file:io.debezium.connector.mongodb.ConnectionContext.java

License:Apache License

/**
 * @param config the configuration/*from   w  ww  .j a  v  a2 s.c  o  m*/
 */
public ConnectionContext(Configuration config) {
    this.config = config;

    this.useHostsAsSeeds = config.getBoolean(MongoDbConnectorConfig.AUTO_DISCOVER_MEMBERS);
    final String username = config.getString(MongoDbConnectorConfig.USER);
    final String password = config.getString(MongoDbConnectorConfig.PASSWORD);
    final String adminDbName = ReplicaSetDiscovery.ADMIN_DATABASE_NAME;

    // Set up the client pool so that it ...
    MongoClients.Builder clientBuilder = MongoClients.create();
    if (username != null || password != null) {
        clientBuilder.withCredential(
                MongoCredential.createCredential(username, adminDbName, password.toCharArray()));
    }
    pool = clientBuilder.build();

    this.replicaSets = ReplicaSets.parse(hosts());

    final int initialDelayInMs = config.getInteger(MongoDbConnectorConfig.CONNECT_BACKOFF_INITIAL_DELAY_MS);
    final long maxDelayInMs = config.getLong(MongoDbConnectorConfig.CONNECT_BACKOFF_MAX_DELAY_MS);
    this.primaryBackoffStrategy = DelayStrategy.exponential(initialDelayInMs, maxDelayInMs);
}