Example usage for com.mongodb MongoClient MongoClient

List of usage examples for com.mongodb MongoClient MongoClient

Introduction

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

Prototype

public MongoClient(final MongoClientURI uri) 

Source Link

Document

Creates a Mongo described by a URI.

Usage

From source file:br.edu.ifpb.bdnc.start.write.factory.MongoConnectionFactory.java

public static MongoClient getConnection() {
    return new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
}

From source file:br.gov.frameworkdemoiselle.component.audit.processors.rest.MONGOProcessors.java

License:Open Source License

/**
 *
 * @param trail/*  w  w  w.ja v  a2  s.  com*/
 */
@Override
public void execute(@Observes @AuditProcessor Trail trail) {

    super.execute(trail);

    try {
        //TODO Verificar alternativas para superar a depreciao das classes abaixo
        MongoClient mongo = new MongoClient(config.getServerUrl());
        DB db = mongo.getDB(config.getDataBaseName());
        DBCollection table = db.getCollection(config.getTableName());

        BasicDBObject document = new BasicDBObject();
        document.put("ClassName", trail.getClassName());
        document.put("How", trail.getHow());
        document.put("IdName", trail.getIdName());
        document.put("LayerName", trail.getLayerName());
        document.put("ObjSerial", trail.getObjSerial());
        document.put("ProcessorName", trail.getProcessorName());
        document.put("Profile", trail.getProfile());
        document.put("SystemName", trail.getSystemName());
        document.put("UserName", trail.getUserName());
        document.put("What", trail.getWhat());
        document.put("When", trail.getWhen());
        document.put("Where", trail.getWhere());
        table.insert(document);

    } catch (Exception e) {
        fail("MONGOProcessors :" + e.getMessage(), trail);
    }
}

From source file:br.gov.frameworkdemoiselle.component.billing.processors.mongo.MONGOProcessors.java

License:Open Source License

/**
 *
 * @param trail//from   w ww  . j a  v  a 2  s .co m
 */
@Override
public void execute(@Observes @BillingProcessor Trail trail) {

    super.execute(trail);

    try {
        //TODO Verificar alternativas para superar a depreciao das classes abaixo
        MongoClient mongo = new MongoClient(config.getServerUrl());
        DB db = mongo.getDB(config.getDataBaseName());
        Boolean authentication = Boolean.TRUE;

        if (!"".equals(config.getDatabaseUser())) {
            authentication = db.authenticate(config.getDatabaseUser(), config.getDatabasePass().toCharArray());
        }

        if (authentication) {
            DBCollection table = db.getCollection(config.getCollectionName());

            BasicDBObject document = new BasicDBObject();
            document.put("ClassName", trail.getClassName());
            document.put("IdName", trail.getIdName());
            document.put("LayerName", trail.getLayerName());
            document.put("ObjSerial", trail.getObjSerial());
            document.put("ProcessorName", trail.getProcessorName());
            document.put("Profile", trail.getProfile());
            document.put("SystemName", trail.getSystemName());
            document.put("UserName", trail.getUserName());
            document.put("What", trail.getWhat());
            document.put("When", trail.getWhen());
            document.put("Where", trail.getWhere());
            table.insert(document);
        } else {
            fail("MONGOProcessors : Authentication failed!", trail);
            throw new RuntimeException("Authentication failed!");
        }

    } catch (Exception e) {
        fail("MONGOProcessors :" + e.getMessage(), trail);
    }
}

From source file:br.ufg.inf.everemind.db.DatabaseConnection.java

License:Open Source License

private static MongoDatabase herokuConnection() throws UnknownHostException {
    MongoClientURI connectionString = new MongoClientURI("");
    MongoClient mongoClient = new MongoClient(connectionString);
    MongoDatabase database = mongoClient.getDatabase("");
    return database;
}

From source file:cfel.service.DatabaseServive.java

License:Open Source License

public DatabaseServive(String host, String dbName) {
    try {//from  w ww . java2s .c  om
        mFS = new GridFS(mDB = new MongoClient(host).getDB(dbName));
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}

From source file:ch.qos.logback.contrib.mongodb.DefaultMongoClientFactory.java

License:Open Source License

/**
 * Creates a {@link com.mongodb.Mongo} instance
 * @param uri - database URI//w w  w .ja  v  a  2s.c  o  m
 * @return the MongoClient instance
 * @throws UnknownHostException
 */
@Override
public MongoClient createMongoClient(MongoClientURI uri) throws UnknownHostException {
    return new MongoClient(uri);
}

From source file:cn.cnic.bigdatalab.flume.sink.mongodb.MongoSink.java

License:Apache License

/**
 * {@inheritDoc}/*from  ww w . j  a  va  2s  .c om*/
 *
 * @param context
 */
@Override
public void configure(Context context) {
    try {
        if (!"INJECTED".equals(context.getString(CONF_URI))) {
            this.mongoClientURI = new MongoClientURI(context.getString(CONF_URI),
                    MongoClientOptions.builder().writeConcern(WriteConcern.SAFE));
            this.mongoClient = new MongoClient(mongoClientURI);
            if (mongoClientURI.getDatabase() != null) {
                this.mongoDefaultDb = mongoClient.getDB(mongoClientURI.getDatabase());
            }
            if (mongoClientURI.getCollection() != null) {
                this.mongoDefaultCollection = mongoDefaultDb.getCollection(mongoClientURI.getCollection());
            }
        }
        final String mappingFilename = context.getString(CONF_MAPPING_FILE);
        this.eventParser = (mappingFilename == null) ? new EventParser()
                : new EventParser(MappingDefinition.load(mappingFilename));

        this.isDynamicMode = context.getBoolean(CONF_DYNAMIC, DEFAULT_DYNAMIC);
        if (!isDynamicMode && mongoDefaultCollection == null) {
            throw new MongoSinkException(
                    "Default MongoDB collection must be specified unless dynamic mode is enabled");
        }
        this.dynamicDBField = context.getString(CONF_DYNAMIC_DB_FIELD, DEFAULT_DYNAMIC_DB_FIELD);
        this.dynamicCollectionField = context.getString(CONF_DYNAMIC_COLLECTION_FIELD,
                DEFAULT_DYNAMIC_COLLECTION_FIELD);

        this.sinkCounter = new SinkCounter(this.getName());
        this.batchSize = context.getInteger(CONF_BATCH_SIZE, DEFAULT_BATCH_SIZE);

        this.updateInsteadReplace = context.getBoolean(CONF_UPDATE_INSTEAD_REPLACE,
                DEFAULT_UPDATE_INSTEAD_REPLACE);

    } catch (IOException ex) {
        throw new MongoSinkException(ex);
    }
}

From source file:co.cask.hydrator.plugin.realtime.sink.MongoDBRealtimeSink.java

License:Apache License

@Override
public void initialize(RealtimeContext context) throws Exception {
    super.initialize(context);
    MongoClientURI clientURI = new MongoClientURI(config.connectionString);
    mongoClient = new MongoClient(clientURI);
    mongoDatabase = mongoClient.getDatabase(config.dbName);
}

From source file:co.dewald.log.MongoDBAppender.java

License:Open Source License

/**
 * @return initialised state.//from   w w  w  .ja va 2 s. c o  m
 */
protected boolean init() {
    if (mongo != null)
        return true;

    try {
        mongo = new MongoClient(host);
        db = mongo.getDB(database);
        logs = db.getCollection(collection);

        mongo.setWriteConcern(WriteConcern.NORMAL);
        logs.createIndex(index); // timestamp is indexed in descending order

        return true;
    } catch (final UnknownHostException e) {
        System.out.println("BAD: Nothing can be logged to MongoDB!");
        e.printStackTrace();
        return false;
    }
}

From source file:com.aankam.servlet.MongoCrudServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  w  w  .j ava 2 s .c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    MongoClientURI uri = new MongoClientURI("mongodb://Username:Pasword@ds061721.mongolab.com:61721/cs612");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());

    response.setContentType("text/html;charset=UTF-8");

    String serialNo = request.getParameter("serialNo");
    String name = request.getParameter("name");
    String emailId = request.getParameter("emailId");
    String operation = request.getParameter("operation");

    BasicDBObject customer;
    BasicDBObject updateQuery;
    BasicDBObject deleteQuery;
    BasicDBObject searchQuery;
    DBCollection customersCollection;
    customersCollection = db.getCollection("Customers");
    DBObject searchResult = null;
    boolean flag = false;
    DBCursor cursor;
    switch (operation) {
    case "create":
        customer = new BasicDBObject();
        customer.put("serialNo", serialNo);
        customer.put("name", name);
        customer.put("emailId", emailId);
        customersCollection.insert(customer);
        break;
    case "update":
        updateQuery = new BasicDBObject();
        updateQuery.append("serialNo", serialNo);
        cursor = customersCollection.find(updateQuery);
        customer = new BasicDBObject();
        customer.put("serialNo", serialNo);
        customer.put("name", name);
        customer.put("emailId", emailId);
        if (cursor.hasNext()) {
            customersCollection.update(updateQuery, customer);
            flag = true;
        }

        break;
    case "delete":
        deleteQuery = new BasicDBObject();
        deleteQuery.append("serialNo", serialNo);
        customersCollection.remove(deleteQuery);
        break;
    case "search":
        searchQuery = new BasicDBObject();
        searchQuery.append("serialNo", serialNo);
        cursor = customersCollection.find(searchQuery);
        while (cursor.hasNext()) {
            searchResult = cursor.next();
        }
        break;
    default:
        break;

    }
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet MongoCrudServlet</title>");
        out.println("</head>");
        out.println("<body>");

        switch (operation) {
        case "create":
            out.println("<h3>Customer was successfully created.</h3>");
            break;
        case "update":
            if (flag == true) {
                out.println("<h3>Customer was successfully updated.</h3>");
            } else {
                out.println("<h3>Customer was not found to update.</h3>");
            }

            break;
        case "delete":
            out.println("<h3>Customer was successfully deleted.</h3>");
            break;
        case "search":
            if (searchResult != null) {
                out.println("<h3>The following customer was found:</h3>");
                out.println("<h4>Serial No :" + searchResult.get("serialNo") + "</h4>");
                out.println("<h4>Name :" + searchResult.get("name") + "</h4>");
                out.println("<h4>Email Id :" + searchResult.get("emailId") + "</h4>");
            } else {
                out.println("<h3>Customer not found.</h3>");
            }
            break;
        default:
            break;
        }
        out.println("<a href=\"index.html\">Back to Main Form</a>");
        out.println("</body>");
        out.println("</html>");
    }
}