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, final MongoDriverInformation mongoDriverInformation) 

Source Link

Document

Creates a Mongo described by a URI.

Usage

From source file:at.ac.tuwien.dsg.smartcom.manager.messaging.logging.dao.MongoDBLoggingDAO.java

License:Apache License

public MongoDBLoggingDAO(String host, int port, String database) throws UnknownHostException {
    this(new MongoClient(host, port), database, LOGGING_COLLECTION);
}

From source file:at.ac.tuwien.dsg.smartcom.services.dao.MongoDBMessageInfoDAO.java

License:Apache License

/**
 * Create a new MongoDB message info DAO providing the host and port of the MongoDB instance and
 * the name of the database that should be used. It will use the default collection of this
 * resolver in the MongoDB database.//w w w .  jav a  2  s  .  co  m
 *
 * @param host address of the MongoDB instance
 * @param port port number of the MongoDB instance
 * @param database name of the database that should be used.
 * @throws java.net.UnknownHostException if the database cannot be resolved
 * @see MongoDBMessageInfoDAO#COLLECTION
 */
public MongoDBMessageInfoDAO(String host, int port, String database) throws UnknownHostException {
    this(new MongoClient(host, port), database, COLLECTION);
}

From source file:bariopendatalab.ImportData.java

/**
 * @param args the command line arguments
 *///from  w ww  .j  a  v  a  2s.com
public static void main(String[] args) {
    int i = 0;
    try {
        MongoClient client = new MongoClient("localhost", 27017);
        DBAccess dbaccess = new DBAccess(client);
        dbaccess.dropDB();
        dbaccess.createDB();
        FileReader reader = new FileReader(new File(args[0]));
        Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().withIgnoreEmptyLines().withDelimiter(',')
                .parse(reader);
        i = 2;
        for (CSVRecord record : records) {
            String type = record.get("Tipologia");
            if (type == null || type.length() == 0) {
                Logger.getLogger(ImportData.class.getName()).log(Level.WARNING, "No type in line {0}", i);
            }

            String description = record.get("Nome");
            if (description != null && description.length() == 0) {
                description = null;
            }

            String address = record.get("Indirizzo");
            if (address != null && address.length() == 0) {
                address = null;
            }

            String civ = record.get("Civ");
            if (civ != null && civ.length() == 0) {
                civ = null;
            }

            if (address != null && civ != null) {
                address += ", " + civ;
            }

            String note = record.get("Note");
            if (note != null && note.length() == 0) {
                note = null;
            }

            String longitudine = record.get("Longitudine");
            String latitudine = record.get("Latitudine");
            if (longitudine != null && latitudine != null) {
                if (longitudine.length() > 0 && latitudine.length() > 0) {
                    try {
                        dbaccess.insert(type, description, address, note, Utils
                                .get2DPoint(Double.parseDouble(latitudine), Double.parseDouble(longitudine)));
                    } catch (NumberFormatException nex) {
                        dbaccess.insert(type, description, address, note, null);
                    }
                } else {
                    dbaccess.insert(type, description, address, note, null);
                }
            } else {
                dbaccess.insert(type, description, address, note, null);
            }
            i++;
        }
        reader.close();
    } catch (Exception ex) {
        Logger.getLogger(ImportData.class.getName()).log(Level.SEVERE, "Error line " + i, ex);
    }
}

From source file:bariopendatalab.ImportJsonData.java

/**
 * @param args the command line arguments
 */// w  w w .j  a  v a 2 s  .  c o  m
public static void main(String[] args) {
    try {
        MongoClient client = new MongoClient("localhost", 27017);
        DBAccess dbaccess = new DBAccess(client);
        dbaccess.dropDB();
        dbaccess.createDB();
        File dirFile = new File(args[0]);
        File[] listFiles = dirFile.listFiles();
        for (File file : listFiles) {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line;
            while (reader.ready()) {
                line = reader.readLine();
                if (line.length() > 0) {
                    if (file.getName().startsWith("municipi")) {
                        Document document = Document.parse(line);
                        dbaccess.insertMunicipi(document);
                    } else {
                        Document document = Document.parse(line);
                        document.put("type", new BsonString(file.getName().replace(".geojson", "")));
                        dbaccess.insertDocument(document);
                    }
                }
            }
            reader.close();
        }
    } catch (Exception ex) {
        Logger.getLogger(ImportJsonData.class.getName()).log(Level.SEVERE, "Error line ", ex);
    }
}

From source file:bariopendatalab.server.DBWrapper.java

private DBWrapper() {
    MongoClient client = new MongoClient("localhost", 27017);
    dba = new DBAccess(client);
    String filename = "weight.matrix";
    try {/*from   w w w .  ja v a2  s.c  o m*/
        filename = ServerConfig.getInstance().getProperty("matrix.file");
        life = new LifeQuality(new File(filename), dba,
                Utils.getNormalizationType(ServerConfig.getInstance().getProperty("mbd.normalization")));
    } catch (IOException ex) {
        Logger.getLogger(DBWrapper.class.getName()).log(Level.SEVERE, null, ex);
        life = new LifeQuality(new File(filename), dba, NormalizationType.NO);
    }
}

From source file:bd.conecion.java

public DBCollection get_colletion() {
    mongo = new MongoClient(url, 27017);
    DB db = mongo.getDB(database);
    return db.getCollection(tabla);
}

From source file:bhl.pages.database.MongoConnection.java

License:Open Source License

/**
 * Connect to the database/*from  w w  w .j  a v a2s . com*/
 * @throws Exception 
 */
private void connect() throws Exception {
    if (db == null) {
        MongoClient mongoClient = new MongoClient(host, MONGO_PORT);
        db = mongoClient.getDB(this.databaseName);
        //boolean auth = db.authenticate( user, password.toCharArray() );
        //if ( !auth )
        //    throw new DbException( "MongoDB authentication failed");
    }
}

From source file:biopolis.headless.BiopolisPersistencyLayer.java

public BiopolisPersistencyLayer(BiopolisProperties props) throws BiopolisGeneralException, SQLException {
    org.neo4j.jdbc.Driver driver = new org.neo4j.jdbc.Driver();
    this.connNeo4j = driver.connect("jdbc:neo4j://" + props.neo4j_endpoint, new Properties());
    try {//  w w  w.  j a  v  a  2 s  .co  m
        System.out.println(props.mongo_host);
        MongoClientOptions mco = new MongoClientOptions.Builder().connectionsPerHost(10)
                .threadsAllowedToBlockForConnectionMultiplier(10).build();
        mongo = new MongoClient(new ServerAddress("localhost"), mco); //addresses is a pre-populated List 
    } catch (MongoException e) {
        e.printStackTrace();
        throw new BiopolisGeneralException("Mongo exception problem");
    } catch (UnknownHostException e) {
        e.printStackTrace();
        throw new BiopolisGeneralException("Mongo connection problem");
    }
    DB dbo = mongo.getDB(BiopolisPersistencyLayer.dbName);
    if (dbo.collectionExists(BiopolisPersistencyLayer.collectionNamePlaces)) {
        this.dbcolPlaces = dbo.getCollection(BiopolisPersistencyLayer.collectionNamePlaces);

    } else {
        this.dbcolPlaces = dbo.createCollection(BiopolisPersistencyLayer.collectionNamePlaces, null);
        this.dbcolPlaces.createIndex(new BasicDBObject("loc", "2dsphere"));
    }

    if (dbo.collectionExists(collectionNameSearches)) {
        this.dbcolSearches = dbo.getCollection(collectionNameSearches);

    } else {
        this.dbcolSearches = dbo.createCollection(collectionNameSearches, null);
        this.dbcolSearches.createIndex(new BasicDBObject("biopolisttl", 1),
                new BasicDBObject("expireAfterSeconds", props.expire_search));
    }
    this.segSZ = props.segment_size;
}

From source file:bom.BOM.java

/**
 * @param args the command line arguments
 *//* ww  w  .  jav  a2 s. co  m*/
public static void main(String[] args) {
    // TODO code application logic here
    try {

        MongoClient mongoClient = new MongoClient("localhost", 5000);
        // Now connect to your databases
        //mongod --port 5000 --dbpath D:\mongodbdata\ (please mention above created path)
        //mongo --port 5000
        DB db = mongoClient.getDB("bomdb");
        System.out.println("Connect to database successfully");

        //DBCollection col1 = db.createCollection("Parts",p1);
        DBCollection col2 = db.getCollection("BOM");
        System.out.println("Collection created successfully");

        List<BillOfMaterial> list;
        LocalDataSource ds = new LocalDataSource();
        list = ds.LoadBom(1000);
        // To connect to mongodb server

        for (BillOfMaterial Element : list) {
            for (Parts ElementPart : Element.partList) {
                for (Operation ElementOp : ElementPart.optList) {
                    BasicDBObject doc = new BasicDBObject("BOM_Name", Element.getBOM_Name())
                            .append("Level", Element.getLevel()).append("Stock", Element.getStock()).

                            append("Parts", new BasicDBObject("Part_ID", ElementPart.getPart_ID())
                                    .append("Part_Name", ElementPart.getPart_Name())
                                    .append("Diameter", ElementPart.getDiamter())
                                    .append("Dept", ElementPart.getDept()).append("Area", ElementPart.getArea())
                                    .append("Quantity", ElementPart.getQuantity()).

                                    append("Material",
                                            new BasicDBObject("Material_ID", ElementPart.getMaterial_ID())
                                                    .append("Material_Name", ElementPart.getMaterial_Name()).

                                                    append("Operation", new BasicDBObject("Operation_ID",
                                                            ElementOp.getOperation_ID())
                                                                    .append("Operation_Name",
                                                                            ElementOp.getOperation_Name())
                                                                    .append("Equipment_Name",
                                                                            ElementOp.getEquipment_Name())
                                                                    .append("No_of_Staff",
                                                                            ElementOp.getNo_of_Staff())
                                                                    .append("Operation_Time", ElementOp
                                                                            .getOperation_Time()
                                                                            .get(Calendar.MINUTE)
                                                                            * ElementOp.getOperation_Time()
                                                                                    .get(Calendar.SECOND))
                                                                    .append("Assembly_Time", ElementOp
                                                                            .getAssembly_Time()
                                                                            .get(Calendar.MINUTE)
                                                                            * ElementOp.getAssembly_Time()
                                                                                    .get(Calendar.SECOND))
                                                                    .append("Set_Up_Time", ElementOp
                                                                            .getSet_Up_Time()
                                                                            .get(Calendar.MINUTE)
                                                                            * ElementOp.getSet_Up_Time()
                                                                                    .get(Calendar.SECOND))
                                                                    .

                                                                    append("Contractor", new BasicDBObject(
                                                                            "Contractor_ID",
                                                                            ElementOp.getContractor_ID())
                                                                                    .append("Contractor_Name",
                                                                                            ElementOp
                                                                                                    .getContractor_Name())))));

                    col2.insert(doc);
                }
            }
        }

        System.out.println("Document inserted successfully");
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }

}

From source file:br.bireme.scl.BrokenLinks.java

License:Open Source License

public static int createLinks(final String outCheckFile, final String outEncoding, final String mstName,
        final String mstEncoding, final String host, final int port, final String user, final String password,
        final boolean clearCol, final String[] allowedMessages) throws BrumaException, IOException {
    if (outCheckFile == null) {
        throw new NullPointerException("outCheckFile");
    }//  w w w  . j  a v  a 2s. c o m
    if (outEncoding == null) {
        throw new NullPointerException("outEncoding");
    }
    if (mstName == null) {
        throw new NullPointerException("mstName");
    }
    if (mstEncoding == null) {
        throw new NullPointerException("mstEncoding");
    }
    if (host == null) {
        throw new NullPointerException("host");
    }
    if (port <= 0) {
        throw new IllegalArgumentException("port <= 0");
    }
    if (allowedMessages == null) {
        throw new NullPointerException("allowedMessages");
    }

    final Master mst = MasterFactory.getInstance(mstName).setEncoding(mstEncoding).open();
    final String mName = new File(mst.getMasterName()).getName();
    final BufferedReader in = new BufferedReader(
            new InputStreamReader(new FileInputStream(outCheckFile), outEncoding));
    final MongoClient mongoClient = new MongoClient(host, port);
    final DB db = mongoClient.getDB(SOCIAL_CHECK_DB);
    // map -> mfn ->  url,occ
    final Map<Integer, Map<String, Integer>> occMap = new HashMap<Integer, Map<String, Integer>>();
    final boolean checkPassword = false;
    if (checkPassword) {
        final boolean auth = db.authenticate(user, password.toCharArray());
        if (!auth) {
            throw new IllegalArgumentException("invalid user/password");
        }
    }

    final DBCollection coll = db.getCollection(BROKEN_LINKS_COL);
    final DBCollection ccColl = db.getCollection(CC_FIELDS_COL);
    final DBCollection hColl = db.getCollection(HISTORY_COL);

    if (ccColl.findOne() == null) {
        if (!createCcFieldsCollection(ccColl)) {
            throw new IOException("CC fields collection creation failed");
        }
    }
    final int idTag = getIsisIdField(mName, ccColl);
    final int urlTag = getIsisUrlFields(mName, ccColl);
    if (urlTag <= 0) {
        throw new IOException("Missing Isis url fields");
    }
    final List<Integer> tags = getIsisCcFields(mName, ccColl);
    final Set<String> allowedMess = new HashSet<String>(Arrays.asList(allowedMessages));
    final Map<String, Integer> idMap = getIdMfn(mst, idTag);
    int tell = 0;
    int tot = 0;

    if (clearCol) {
        coll.dropIndexes();
        coll.remove(new BasicDBObject());
    }

    System.out.println("Saving documents ...");
    while (true) {
        final String line = in.readLine();
        if (line == null) {
            break;
        }
        final String lineT = line.trim();
        if (!lineT.isEmpty()) {
            final String[] split = lineT.split(" *\\| *", 4); //id|url|msg|master
            if (split.length < 4) {
                throw new IOException("Wrong line format: " + line);
            }
            final int openPos = split[2].indexOf('('); // cut extra data               
            final String prefix = (openPos > 0) ? split[2].substring(0, openPos) : split[2];

            if (allowedMess.contains(prefix.trim())) {
                final Integer id = idMap.get(split[0]);
                if (id == null) {
                    throw new IOException("id[" + split[0] + "] not found");
                }

                final String url_e = EncDecUrl.encodeUrl(split[1], outEncoding, false);

                saveRecord(mName, id, url_e, split[2], urlTag, tags, mst, coll, hColl, occMap);
                tot++;
            }
            if (++tell % 5000 == 0) {
                System.out.println("++" + tell);
            }
        }
    }

    System.out.print("\nFixing urls that do not start with http:// ... ");
    MongoOperations.fixMissingHttp(coll, hColl);
    System.out.println(" - OK");

    //removeOldDocs(coll);

    if (clearCol) {
        createIndex(coll);
    }

    in.close();
    mst.close();

    return tot;
}