Example usage for com.mongodb.client MongoCollection insertOne

List of usage examples for com.mongodb.client MongoCollection insertOne

Introduction

In this page you can find the example usage for com.mongodb.client MongoCollection insertOne.

Prototype

void insertOne(TDocument document);

Source Link

Document

Inserts the provided document.

Usage

From source file:org.auraframework.test.perf.util.PerfResultsUtil.java

License:Apache License

public static void writeToDb(PerfExecutorTestCase test, String testName, String dbURI, PerfMetrics metrics,
        String traceLog) {//from w  w  w.  j  a  va 2 s . c  o m
    try {
        MongoClient mongo = getMongoClient(dbURI);
        if (mongo != null) {
            LOG.info("Writing perf results into mongo db at: " + mongo.getAddress());
            MongoDatabase db = mongo.getDatabase("performance");
            MongoCollection<Document> runs = db.getCollection("testRun");
            JSONObject json = metrics.toJSONObject();
            Document doc = Document.parse(json.toString());

            doc.append("timeline", traceLog);
            doc.append("testName", testName);
            doc.append("transaction", Document.parse((metrics.getMetricsServiceTransaction()).toString()));
            doc.append("commonMetrics", Document.parse((metrics.getCommonMetrics()).toString()));
            doc.append("customMetrics", Document.parse((metrics.getCustomMetrics()).toString()));
            doc.append("run", RUN_TIME);
            runs.insertOne(doc);
            exportToCsv(test, doc);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.bananaforscale.cormac.dao.document.DocumentDataServiceImpl.java

License:Apache License

/**
 * Saves a document to the collection. If the specified database and
 * collection do not exist they will be created.
 *
 * @param databaseName the database//  w ww .  j  a  v a 2 s. c o  m
 * @param collectionName the collection
 * @param content the JSON payload
 * @return the document identifier
 * @throws DatasourceException
 * @throws DeserializeException
 * @throws IllegalArgumentException
 */
@Override
public String add(String databaseName, String collectionName, String content)
        throws DatasourceException, DeserializeException, IllegalArgumentException {
    try {
        if (!validInputForAddOrUpdate(databaseName, collectionName, "temp", content)) {
            throw new IllegalArgumentException();
        }
        MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
        MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName);
        Document document = Document.parse(content);
        collection.insertOne(document);
        return document.get("_id").toString();
    } catch (IllegalArgumentException | ClassCastException | JSONParseException ex) {
        logger.error("The JSON payload is invalid", ex);
        throw new DeserializeException("The JSON payload is invalid");
    } catch (MongoException ex) {
        logger.error("An error occured while adding the document", ex);
        throw new DatasourceException("An error occured while adding the document");
    }
}

From source file:org.codinjutsu.tools.nosql.mongo.logic.SingleMongoClient.java

License:Apache License

public void update(ServerConfiguration configuration, SingleMongoCollection singleMongoCollection,
        Document mongoDocument) {
    MongoClient mongo = null;/*from   w  w  w .j a  v a  2  s  .  c  o  m*/
    try {
        String databaseName = singleMongoCollection.getDatabaseName();
        mongo = createMongoClient(configuration);

        MongoDatabase database = mongo.getDatabase(databaseName);
        MongoCollection<Document> collection = database.getCollection(singleMongoCollection.getName());

        final Object id = mongoDocument.get("_id");
        if (id == null) {
            collection.insertOne(mongoDocument);
        } else {
            collection.replaceOne(Filters.eq("_id", id), mongoDocument);
        }
    } catch (UnknownHostException ex) {
        throw new ConfigurationException(ex);
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}

From source file:org.eclipse.leshan.server.californium.impl.LeshanServer.java

License:Open Source License

private void observeResource(final Client client) {
    // ObserveRequest request = new ObserveRequest("2050/0/0");
    String contentFormatParam = "TLV";
    ContentFormat contentFormat = contentFormatParam != null
            ? ContentFormat.fromName(contentFormatParam.toUpperCase())
            : null;//from   w w  w  .  j  a  v  a 2s  .c  om
    ObserveRequest request = new ObserveRequest(contentFormat, "/3/0/13");
    // ObserveRequest request = new ObserveRequest(contentFormat, "/2050/0/0");
    ObserveResponse cResponse = null;
    try {

        long i = 50000L;
        cResponse = this.send(client, request, i);

    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    LOG.debug("cResponse : " + cResponse);

    Observation observation = cResponse.getObservation();

    observationRegistry.addListener(new ObservationRegistryListener() {

        @Override
        public void newObservation(Observation observation) {
            // TODO Auto-generated method stub

        }

        @Override
        public void cancelled(Observation observation) {
            LOG.debug("Observation Cancelled ....");

        }

        @Override
        public void newValue(Observation observation, ObserveResponse response) {
            // writeToFile(observation, mostRecentValue,timestampedValues );
            // TODO Auto-generated method stub
            if (client.getRegistrationId().equals(observation.getRegistrationId())) {

                // initialize("document");

                /*
                 * try { publishMesssage(); } catch (Exception e1) { // TODO Auto-generated catch block
                 * e1.printStackTrace(); }
                 */

                // ********Saving into database**************************
                Gson gson = new Gson();
                // List<TimestampedLwM2mNode> obresp = response.getTimestampedLwM2mNode();
                JsonObject jsonObject = new JsonParser().parse(gson.toJson(response.getContent()))
                        .getAsJsonObject();

                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                java.util.Date date = new java.util.Date();
                String timestamp = dateFormat.format(date);

                try {

                    MongoClient mongoClient = new MongoClient(mongoDBAdd, mongoDBPort);
                    MongoDatabase database = mongoClient.getDatabase("qolsys");
                    MongoCollection<Document> collection = database.getCollection("events");
                    String event = jsonObject.get("value").getAsString().trim();
                    Document document = new Document();
                    document.put("client_ep", client.getEndpoint());
                    document.put("event", event);
                    document.put("timestamp", timestamp);
                    collection.insertOne(document);
                    json = document.toJson();
                    sendToBroker(topic, json);
                    mongoClient.close();
                    producer.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println(e.getClass().getName() + ": " + e.getMessage());
                    System.exit(0);
                }

                // ******************************************************

                LOG.debug("recent observation ...." + observation);
            }
        }

        // *************************************************************

        /*
         * private static Producer<Integer, String> producer; private static final String topic = "mytopic";
         */

        @SuppressWarnings("deprecation")
        public void sendToBroker(String topic, String msg) {

            Properties producerProps = new Properties();
            producerProps.put("metadata.broker.list", kafkaBroker1Add + ":" + kafkaBroker1Port);
            producerProps.put("serializer.class", "kafka.serializer.StringEncoder");
            producerProps.put("request.required.acks", "1");
            ProducerConfig producerConfig = new ProducerConfig(producerProps);
            producer = new Producer<Integer, String>(producerConfig);
            KeyedMessage<Integer, String> keyedMsg = new KeyedMessage<Integer, String>(topic, msg);
            producer.send(keyedMsg);

        }

    });

}

From source file:org.graylog2.fongo.SeedingFongoRule.java

License:Open Source License

public void insertSeed(String seed) throws IOException {
    final byte[] bytes = Resources.toByteArray(Resources.getResource(seed));
    final Map<String, Object> map = objectMapper.readValue(bytes, MAP_TYPE);

    for (String collectionName : map.keySet()) {
        @SuppressWarnings("unchecked")
        final List<Map<String, Object>> documents = (List<Map<String, Object>>) map.get(collectionName);
        final MongoCollection<Document> indexSets = getDatabase().getCollection(collectionName);

        for (Map<String, Object> document : documents) {
            final Document parsedDocument = Document.parse(objectMapper.writeValueAsString(document));
            LOG.debug("Inserting parsed document: \n{}", parsedDocument.toJson(new JsonWriterSettings(true)));
            indexSets.insertOne(parsedDocument);
        }/*from  ww  w . j av  a  2 s.  co  m*/
    }
}

From source file:org.helm.rest.MongoDB.java

public long SaveRecord(String table, long id, Map<String, String> data) {
    MongoCollection coll = db.getCollection(table);

    Document doc = new Document();
    for (String k : data.keySet()) {
        String v = data.get(k);/*from  w w  w . java  2 s . co m*/
        if (v != null)
            doc.append(k, new org.bson.BsonString(v));
        else
            doc.append(k, new org.bson.BsonNull());
    }

    if (id > 0) {
        Document where = new Document("id", new BsonInt64(id));
        coll.findOneAndUpdate(where, new Document("$set", doc));
    } else {
        id = GetMaxID(table) + 1;
        doc.append("id", new BsonInt64(id));
        coll.insertOne(doc);
    }

    return id;
}

From source file:org.iotivity.cloud.accountserver.db.MongoDB.java

License:Open Source License

/**
 * API for inserting a record into DB table. the record will not be inserted
 * if duplicated one.//from w  w  w  .  j a  va  2 s.  com
 * 
 * @param tableName
 *            table name to be inserted
 * @param doc
 *            document to be inserted
 */
public Boolean insertRecord(String tableName, Document doc) {

    if (tableName == null || doc == null)
        return false;

    MongoCollection<Document> collection = db.getCollection(tableName);

    try {

        if (collection.find(doc).first() == null) {

            collection.insertOne(doc);

        } else {

            Log.w("DB insert failed due to duplecated one.");
            return false;
        }

    } catch (Exception e) {

        e.printStackTrace();
        return false;
    }

    showRecord(tableName);

    return true;
}

From source file:org.iotivity.cloud.accountserver.db.MongoDB.java

License:Open Source License

/**
 * API for inserting a record into DB table. the record will be replaced if
 * duplicated one./*from  ww w.ja  v  a 2  s .c o  m*/
 * 
 * @param tableName
 *            table name to be inserted
 * @param filter
 *            document filter
 * @param doc
 *            document to be inserted
 * @return returns true if the record is inserted and replaced successfully,
 *         or returns false
 */
public Boolean insertAndReplaceRecord(String tableName, Document filter, Document doc) {

    if (tableName == null || filter == null || doc == null)
        return false;

    MongoCollection<Document> collection = db.getCollection(tableName);

    try {

        if (collection.findOneAndReplace(filter, doc) == null) {

            collection.insertOne(doc);
        }

    } catch (Exception e) {

        e.printStackTrace();
        return false;
    }

    showRecord(tableName);

    return true;
}

From source file:org.iotivity.cloud.rdserver.MongoDB.java

License:Open Source License

/**
 * API for storing information of published resources
 *
 * @param publishPayloadFormat/*  w w w .jav a  2  s. c  o  m*/
 *            information of published resources to store in collection
 * @param tablename
 *            collection name
 */
public void createResource(PublishPayloadFormat publishPayloadFormat, String tablename) {
    ArrayList<Document> docList = createDocuments(publishPayloadFormat);
    Iterator<Document> docIter = docList.iterator();

    MongoCollection<Document> collection = db.getCollection(tablename);

    while (docIter.hasNext()) {
        Document doc = docIter.next();

        if (collection.findOneAndReplace(
                Filters.and(Filters.eq(Constants.RS_DEVICE_ID, doc.get(Constants.RS_DEVICE_ID)),
                        Filters.eq(Constants.RS_INS, doc.get(Constants.RS_INS))),
                doc) == null) {

            collection.insertOne(doc);
        }
    }
}

From source file:org.jaqpot.core.db.entitymanager.MongoDBEntityManager.java

License:Open Source License

@Override
public void persist(JaqpotEntity entity) {
    MongoDatabase db = mongoClient.getDatabase(database);
    String entityJSON = serializer.write(entity);
    MongoCollection collection = db.getCollection(collectionNames.get(entity.getClass()));
    Document entityBSON = Document.parse(entityJSON);
    try {//from  w w  w.  j  av  a  2 s .co m
        collection.insertOne(entityBSON);
    } catch (final MongoWriteException ex) {
        String errorMessage = "Entity with ID " + entity.getId()
                + " is already registered and will not be overwritten!";
        LOG.log(Level.FINE, errorMessage, ex);
        throw ex;
    }
}