Example usage for com.mongodb Mongo Mongo

List of usage examples for com.mongodb Mongo Mongo

Introduction

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

Prototype

@Deprecated
public Mongo() 

Source Link

Document

Creates a Mongo instance based on a (single) mongodb node (localhost, default port)

Usage

From source file:org.ossmeter.rascal.test.RascalTestCaseGenerator.java

License:Open Source License

@Override
public Object start(IApplicationContext context) throws Exception {
    // create platform with mongo db
    Mongo mongo = new Mongo();
    PongoFactory.getInstance().getContributors().add(new OsgiPongoFactoryContributor());
    Platform platform = new Platform(mongo);
    OssmeterLogger logger = (OssmeterLogger) OssmeterLogger.getLogger("RascalTestCaseGenerator");
    logger.addConsoleAppender(OssmeterLogger.DEFAULT_PATTERN);

    // load rascal manager and metric providers
    RascalManager manager = RascalManager.getInstance();
    Evaluator eval = manager.getEvaluator();

    List<IMetricProvider> metricProviders = manager.getMetricProviders();

    // sort metric providers topologically
    metricProviders = new ProjectExecutor(platform, new Project()) {
        public List<IMetricProvider> order(List<IMetricProvider> metrics) {
            List<IMetricProvider> result = new ArrayList<>(metrics.size());
            for (List<IMetricProvider> branch : splitIntoBranches(metrics)) {
                branch.removeAll(result);
                //Collections.reverse(branch);
                result.addAll(branch);/*  w ww .j a v  a  2  s.  c  om*/
            }
            return result;
        }
    }.order(metricProviders);

    System.out.println("Available metric providers:");
    for (IMetricProvider mp : metricProviders) {
        System.out.println(mp.getIdentifier());
    }

    TypeStore extractedTypes = manager.getExtractedTypes();
    TypeStore deltaTypes = new RascalProjectDeltas(eval).getStore();

    // initialise test data dir and read project settings
    File testDataDir = new File(Platform.getInstance().getLocalStorageHomeDirectory().toFile(),
            "rascaltestdata");
    testDataDir.mkdirs();

    List<Project> projects = null;
    File settingsFile = new File(testDataDir, "projects.txt");
    if (settingsFile.exists()) {
        IValue projectSettings = readTextValue(settingsFile, eval);
        projects = loadProjects(projectSettings, platform);
    }

    if (projects == null || projects.size() == 0) {
        logger.error("Please specify projects to import test data from in " + settingsFile.getAbsolutePath());
        logger.error("Format: \"[<name, type, url>, ...]\" where type can be \"svn\" or \"git\".");
        return null;
    }

    final int MAX_DELTAS_PER_REPO = 25;
    Map<String, Integer> deltasProcessed = new HashMap<>();
    Map<String, Iterator<Date>> repositoryDates = new HashMap<>();

    // set up available dates per repository
    for (Project project : projects) {
        for (VcsRepository repo : project.getVcsRepositories()) {
            String firstRevision = platform.getVcsManager().getFirstRevision(repo);
            Date startDate = platform.getVcsManager().getDateForRevision(repo, firstRevision).addDays(-1);
            Date today = new Date();

            Date[] dates = Date.range(startDate.addDays(1), today.addDays(-1));
            repositoryDates.put(repo.getUrl(), Arrays.asList(dates).iterator());

            deltasProcessed.put(repo.getUrl(), 0);
        }
    }

    // generate test data
    boolean moreDatesAvailable;
    do {
        moreDatesAvailable = false;

        for (Project project : projects) {
            for (VcsRepository repo : project.getVcsRepositories()) {
                String repoURL = repo.getUrl();
                Iterator<Date> dateIterator = repositoryDates.get(repoURL);
                if (deltasProcessed.get(repoURL) < MAX_DELTAS_PER_REPO && dateIterator.hasNext()) {
                    Date date = dateIterator.next();
                    moreDatesAvailable |= dateIterator.hasNext();

                    ProjectDelta delta = new ProjectDelta(project, date, platform);
                    if (delta.create() && !delta.getVcsDelta().getRepoDeltas().isEmpty()) {
                        System.out.println("\nProject: " + project.getShortName() + ", date: " + date);

                        File dir = new File(testDataDir,
                                project.getName() + "/" + encode(repoURL) + "/" + date.toString());
                        dir.mkdirs();

                        MetricListExecutor ex = new MetricListExecutor(project.getShortName(), delta, date);
                        ex.setMetricList(metricProviders);
                        ex.run();

                        IValue rascalDelta = RascalMetricProvider.computeDelta(project, delta, manager, logger);
                        IValue rascalASTs = RascalMetricProvider.computeAsts(project, delta, manager, logger);
                        IValue rascalM3s = RascalMetricProvider.computeM3(project, delta, manager, logger);

                        handleNewValue(new File(dir, "delta.bin"), rascalDelta, deltaTypes, eval, logger);
                        handleNewValue(new File(dir, "asts.bin"), rascalASTs, extractedTypes, eval, logger);
                        handleNewValue(new File(dir, "m3s.bin"), rascalM3s, extractedTypes, eval, logger);

                        for (IMetricProvider mp : metricProviders) {
                            IValue result = null;

                            if (mp instanceof RascalMetricProvider) {
                                result = ((RascalMetricProvider) mp).getMetricResult(project, mp, manager);
                            } else if (mp instanceof RascalMetricHistoryWrapper) {
                                // ignore because its automatically derived
                            } else if (mp instanceof RascalFactoidProvider) {
                                RascalFactoidProvider rfp = (RascalFactoidProvider) mp;
                                result = rfp.getMeasuredFactoid(
                                        rfp.adapt(platform.getMetricsRepository(project).getDb()),
                                        eval.getValueFactory());
                            } else {
                                logger.warn("Unknown metric provider: " + mp.getIdentifier());
                                continue;
                            }

                            System.out.println(mp.getFriendlyName());
                            System.out.println("" + result);

                            handleNewValue(new File(dir, mp.getIdentifier()), result, null, eval, logger);
                        }

                        deltasProcessed.put(repoURL, deltasProcessed.get(repoURL) + 1);
                    }
                }
            }
        }
    } while (moreDatesAvailable);

    return null;
}

From source file:org.slc.sli.ingestion.csv.CsvCombine.java

License:Apache License

public CsvCombine() {
    try {
        mongo = new Mongo();
        db = mongo.getDB("StagingDB");
    } catch (Exception e) {
    }
}

From source file:org.springframework.data.document.mongodb.MongoFactoryBean.java

License:Apache License

public void afterPropertiesSet() throws Exception {
    // apply defaults - convenient when used to configure for tests
    // in an application context
    if (mongo == null) {

        if (host == null) {
            logger.warn("Property host not specified. Using default configuration");
            mongo = new Mongo();
        } else {//from   w w w. j a  v  a2 s.co  m
            ServerAddress defaultOptions = new ServerAddress();
            if (mongoOptions == null)
                mongoOptions = new MongoOptions();
            if (replicaPair != null) {
                if (replicaPair.size() < 2) {
                    throw new CannotGetMongoDbConnectionException(
                            "A replica pair must have two server entries");
                }
                mongo = new Mongo(replicaPair.get(0), replicaPair.get(1), mongoOptions);
            } else if (replicaSetSeeds != null) {
                mongo = new Mongo(replicaSetSeeds, mongoOptions);
            } else {
                String mongoHost = host != null ? host : defaultOptions.getHost();
                if (port != null) {
                    mongo = new Mongo(new ServerAddress(mongoHost, port), mongoOptions);
                } else {
                    mongo = new Mongo(mongoHost, mongoOptions);
                }
            }
        }
    }
}

From source file:org.xtext.mongobeans.examples.JavaExample.java

License:Open Source License

public void dealWithMongoEntities() throws UnknownHostException, MongoException {
    DBObject artist = new BasicDBObject();
    artist.put("name", "John Coltrane");
    DBObject album = new BasicDBObject();
    album.put("title", "A Love Supreme");
    album.put("year", 1965);
    List<DBObject> albums = new ArrayList<DBObject>();
    artist.put("albums", albums);

    DB db = new Mongo().getDB("testdb");
    DBCollection dbCollection = db.getCollection("testCollection");
    dbCollection.save(artist);/* w  w w  .j  a  v a2s .co m*/

    DBObject query = new BasicDBObject();
    query.put("name", "John Coltrane");
    DBObject artistFromDB = dbCollection.find(query).next();
    Object albumFromDB = artistFromDB.get("album");
    if (albumFromDB instanceof Collection) {
        Object firstAlbumFromDB = ((Collection<?>) album).iterator().next();
        if (firstAlbumFromDB instanceof DBObject) {
            Object titleFromDB = album.get("title");
            System.out.println(titleFromDB.toString());
        }
    }
}

From source file:uk.ac.ncl.aries.entanglement.cli.export.MongoGraphToAscii.java

License:Apache License

public static void main(String[] args)
        throws UnknownHostException, RevisionLogException, IOException, GraphModelException {
    CommandLineParser parser = new PosixParser();
    Options options = new Options();

    //    options.addOption("g", "format-gdf", false,
    //        "Specifies that the output format is GDF (currently the only option)");

    options.addOption("h", "mongo-host", true, "The MongoDB server host to connect to.");

    options.addOption("d", "mongo-database", true, "The name of a MongoDB database to connect to.");

    options.addOption("g", "graph-name", true,
            "The name of a graph to use (there may be multiple graphs per MongoDB database).");

    options.addOption("b", "graph-branch", true,
            "The name of a graph branch to use (there may be multiple branches per graph).");

    options.addOption("o", "output-file", true, "Specifies a path to a file to use ");

    //    options.addOption(OptionBuilder
    //        .withLongOpt("tags")
    //        .withArgName( "property=value" )
    //        .hasArgs(2)
    //        .withValueSeparator()
    //        .withDescription(
    //        "used to tag files when uploading.")
    //        .create( "t" ));

    if (args.length == 0) {
        printHelpExit(options);/*from   www.ja va2  s .  c  o  m*/
    }

    String mongoHost = null;
    String mongoDatabaseName = null;
    String graphName = null;
    String graphBranch = null;
    String outputFilename = null;

    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("mongo-host")) {
            mongoHost = line.getOptionValue("mongo-host", null);
        } else {
            throw new IllegalArgumentException("You must specify a hostname");
        }

        if (line.hasOption("mongo-database")) {
            mongoDatabaseName = line.getOptionValue("mongo-database", null);
        } else {
            throw new IllegalArgumentException("You must specify a database name");
        }

        if (line.hasOption("graph-name")) {
            graphName = line.getOptionValue("graph-name", null);
        } else {
            throw new IllegalArgumentException("You must specify a graph name");
        }

        if (line.hasOption("graph-branch")) {
            graphBranch = line.getOptionValue("graph-branch", null);
        } else {
            throw new IllegalArgumentException("You must specify a graph branch name");
        }

        if (line.hasOption("output-file")) {
            outputFilename = line.getOptionValue("output-file", null);
        } else {
            throw new IllegalArgumentException("You must specify an output filename");
        }
    } catch (ParseException e) {
        e.printStackTrace();
        printHelpExit(options);
        System.exit(1);
    }

    Mongo m = new Mongo();
    //    Mongo m = new Mongo( "localhost" );
    // or
    //    Mongo m = new Mongo( "localhost" , 27017 );
    // or, to connect to a replica set, supply a seed list of members
    //    Mongo m = new Mongo(Arrays.asList(new ServerAddress("localhost", 27017),
    //                                          new ServerAddress("localhost", 27018),
    //                                          new ServerAddress("localhost", 27019)));
    m.setWriteConcern(WriteConcern.SAFE);
    DB db = m.getDB(mongoDatabaseName);
    //    boolean auth = db.authenticate(myUserName, myPassword);

    exportAscii(m, db, graphName, graphBranch, new File(outputFilename));
    System.out.println("\n\nDone.");
}

From source file:uk.ac.ncl.aries.entanglement.cli.export.MongoGraphToGDF.java

License:Apache License

public static void main(String[] args)
        throws UnknownHostException, RevisionLogException, IOException, GraphModelException {
    CommandLineParser parser = new PosixParser();
    Options options = new Options();

    //    options.addOption("g", "format-gdf", false,
    //        "Specifies that the output format is GDF (currently the only option)");

    options.addOption("h", "mongo-host", true, "The MongoDB server host to connect to.");

    options.addOption("d", "mongo-database", true, "The name of a MongoDB database to connect to.");

    options.addOption("g", "graph-name", true,
            "The name of a graph to use (there may be multiple graphs per MongoDB database).");

    options.addOption("b", "graph-branch", true,
            "The name of a graph branch to use (there may be multiple branches per graph).");

    options.addOption("c", "color-properties", true,
            "An (optional) '.properties' file that contains node type -> RGB mappings.");

    options.addOption("o", "output-file", true, "Specifies a path to a file to use ");

    //    options.addOption(OptionBuilder
    //        .withLongOpt("tags")
    //        .withArgName( "property=value" )
    //        .hasArgs(2)
    //        .withValueSeparator()
    //        .withDescription(
    //        "used to tag files when uploading.")
    //        .create( "t" ));

    if (args.length == 0) {
        printHelpExit(options);/*  ww  w .  ja v  a2  s  .c  o  m*/
    }

    String mongoHost = null;
    String mongoDatabaseName = null;
    String graphName = null;
    String graphBranch = null;
    String colorPropsFilename = null;
    String outputFilename = null;

    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("mongo-host")) {
            mongoHost = line.getOptionValue("mongo-host", null);
        } else {
            throw new IllegalArgumentException("You must specify a hostname");
        }

        if (line.hasOption("mongo-database")) {
            mongoDatabaseName = line.getOptionValue("mongo-database", null);
        } else {
            throw new IllegalArgumentException("You must specify a database name");
        }

        if (line.hasOption("graph-name")) {
            graphName = line.getOptionValue("graph-name", null);
        } else {
            throw new IllegalArgumentException("You must specify a graph name");
        }

        if (line.hasOption("graph-branch")) {
            graphBranch = line.getOptionValue("graph-branch", null);
        } else {
            throw new IllegalArgumentException("You must specify a graph branch name");
        }

        if (line.hasOption("output-file")) {
            outputFilename = line.getOptionValue("output-file", null);
        } else {
            throw new IllegalArgumentException("You must specify an output filename");
        }

        if (line.hasOption("color-properties")) {
            colorPropsFilename = line.getOptionValue("color-properties", null);
        }
    } catch (ParseException e) {
        e.printStackTrace();
        printHelpExit(options);
        System.exit(1);
    }

    Mongo m = new Mongo();
    //    Mongo m = new Mongo( "localhost" );
    // or
    //    Mongo m = new Mongo( "localhost" , 27017 );
    // or, to connect to a replica set, supply a seed list of members
    //    Mongo m = new Mongo(Arrays.asList(new ServerAddress("localhost", 27017),
    //                                          new ServerAddress("localhost", 27018),
    //                                          new ServerAddress("localhost", 27019)));
    m.setWriteConcern(WriteConcern.SAFE);
    DB db = m.getDB(mongoDatabaseName);
    //    boolean auth = db.authenticate(myUserName, myPassword);

    Map<String, Color> nodeColorMappings = new HashMap<>();
    if (colorPropsFilename != null) {
        nodeColorMappings.putAll(loadColorMappings(new File(colorPropsFilename)));
    }

    exportGdf(m, db, nodeColorMappings, graphName, graphBranch, new File(outputFilename));
    System.out.println("\n\nDone.");
}

From source file:uk.ac.ncl.aries.entanglement.cli.export.MongoGraphToGephi.java

License:Apache License

public static void main(String[] args)
        throws UnknownHostException, RevisionLogException, IOException, GraphModelException {
    CommandLineParser parser = new PosixParser();
    Options options = new Options();

    //    options.addOption("g", "format-gdf", false,
    //        "Specifies that the output format is GDF (currently the only option)");

    options.addOption("h", "mongo-host", true, "The MongoDB server host to connect to.");

    options.addOption("d", "mongo-database", true, "The name of a MongoDB database to connect to.");

    options.addOption("g", "graph-name", true,
            "The name of a graph to use (there may be multiple graphs per MongoDB database).");

    options.addOption("b", "graph-branch", true,
            "The name of a graph branch to use (there may be multiple branches per graph).");

    options.addOption("o", "output-file", true, "Specifies a path to a file to use ");

    if (args.length == 0) {
        printHelpExit(options);//ww  w  .  ja  v  a2 s. c  o  m
    }

    String mongoHost = null;
    String mongoDatabaseName = null;
    String graphName = null;
    String graphBranch = null;
    String outputFilename = null;

    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("mongo-host")) {
            mongoHost = line.getOptionValue("mongo-host", null);
        } else {
            throw new IllegalArgumentException("You must specify a hostname");
        }

        if (line.hasOption("mongo-database")) {
            mongoDatabaseName = line.getOptionValue("mongo-database", null);
        } else {
            throw new IllegalArgumentException("You must specify a database name");
        }

        if (line.hasOption("graph-name")) {
            graphName = line.getOptionValue("graph-name", null);
        } else {
            throw new IllegalArgumentException("You must specify a graph name");
        }

        if (line.hasOption("graph-branch")) {
            graphBranch = line.getOptionValue("graph-branch", null);
        } else {
            throw new IllegalArgumentException("You must specify a graph branch name");
        }

        if (line.hasOption("output-file")) {
            outputFilename = line.getOptionValue("output-file", null);
            if (!outputFilename.contains(".gexf") && outputFilename.contains(".pdf")
                    && outputFilename.contains(".svg") && outputFilename.contains(".gdf")) {
                throw new IllegalArgumentException(
                        "You must specify an output filename with an extension " + "of [.pdf|.svg|.gexf|gdf]");
            }
        } else {
            throw new IllegalArgumentException(
                    "You must specify an output filename with an extension " + "of [.pdf|.svg|.gexf|gdf]");
        }

    } catch (ParseException e) {
        printHelpExit(options);
        System.exit(1);
    }

    Mongo m = new Mongo();
    m.setWriteConcern(WriteConcern.SAFE);
    DB db = m.getDB(mongoDatabaseName);

    GraphCheckoutNamingScheme collectionNamer = new GraphCheckoutNamingScheme(graphName, graphBranch);
    DBCollection nodeCol = db.getCollection(collectionNamer.getNodeCollectionName());
    DBCollection edgeCol = db.getCollection(collectionNamer.getEdgeCollectionName());
    NodeDAO nodeDao = GraphDAOFactory.createDefaultNodeDAO(classLoader, m, db, nodeCol, edgeCol);
    EdgeDAO edgeDao = GraphDAOFactory.createDefaultEdgeDAO(classLoader, m, db, nodeCol, edgeCol);
    RevisionLog log = new RevisionLogDirectToMongoDbImpl(classLoader, m, db);

    MongoGraphToGephi exporter = new MongoGraphToGephi(nodeDao, edgeDao);
    exporter.exportGexf(new File(outputFilename));
    System.out.println("\n\nDone.");
}

From source file:uk.ac.ncl.aries.entanglement.WriteTestObjects.java

License:Apache License

public static void main(String[] args)
        throws UnknownHostException, JsonSerializerException, DbObjectMarshallerException {
    Mongo m = new Mongo();

    //    Mongo m = new Mongo( "localhost" );
    // or//w ww. ja  va2s.  c o  m
    //    Mongo m = new Mongo( "localhost" , 27017 );
    // or, to connect to a replica set, supply a seed list of members
    //    Mongo m = new Mongo(Arrays.asList(new ServerAddress("localhost", 27017),
    //                                          new ServerAddress("localhost", 27018),
    //                                          new ServerAddress("localhost", 27019)));

    m.setWriteConcern(WriteConcern.SAFE);

    DB db = m.getDB("aries-test");
    //    boolean auth = db.authenticate(myUserName, myPassword);

    DBCollection testCol = db.getCollection("testCollection");

    //    BasicDBObject newDoc = new BasicDBObject();
    //    newDoc.
    //    testCol.insert(newDoc);

    Node node = new Node();
    //    node.setNumericalId(3);
    node.setUid(UidGenerator.generateUid());
    //    node.setGraphUniqueId(UidGenerator.generateUid());

    //    node.getProperties().put("An_integer", 1);
    //    node.getProperties().put("A String", "Foo");

    Map<Integer, String> subMap = new HashMap<>();
    subMap.put(1, "one");
    subMap.put(2, "two");
    subMap.put(3, "three");
    //    node.getProperties().put("A map", subMap);
    DbObjectMarshaller marshaller = ObjectMarshallerFactory.create(WriteTestObjects.class.getClassLoader());
    DBObject dbObject = marshaller.serialize(node);
    testCol.insert(dbObject);

    System.out.println("Listing collections:");
    listCollections(db);

    System.out.println("\n\nFindOne:");
    findOne(testCol);

    System.out.println("\n\nCursor iteration:");
    cursorIterateAllDocs(testCol);

    System.out.println("\n\nDone.");
}

From source file:v7cr.InitDB.java

License:Open Source License

@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent e) {
    try {/*from   w  w  w.  ja va2  s  .c o  m*/
        Mongo db = new Mongo();

        ServletContext c = e.getServletContext();
        c.setAttribute(getClass().getName(), db);

        // check if the "roles" collection
        // exists, if not create it

        if (getDBCollection(c, "roles").findOne() == null) {
            String json = IOUtils.toString(getClass().getResourceAsStream("roles.json"), "UTF-8");
            List<DBObject> l = (List<DBObject>) JSON.parse(json);
            DBCollection roles = getDBCollection(c, "roles");
            for (DBObject r : l) {
                r.put("_version", 1);
                roles.save(r);
            }

        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:v7views.mongo.InitMongo.java

License:Open Source License

public void contextInitialized(ServletContextEvent sce) {

    try {/*w ww  .ja  v  a2s  . com*/
        BSONBackedObject conf = BSONBackedObjectLoader
                .parse(FileUtils.readFileToString(new File("conf/v7views.json"), "UTF-8"), null);
        sce.getServletContext().setAttribute("v7views.config", conf);

        Mongo mongo = new Mongo();
        sce.getServletContext().setAttribute("mongo", mongo);
    } catch (Exception e) {
        e.printStackTrace();
    }
}