Example usage for com.mongodb DBCollection save

List of usage examples for com.mongodb DBCollection save

Introduction

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

Prototype

public WriteResult save(final DBObject document) 

Source Link

Document

Update an existing document or insert a document depending on the parameter.

Usage

From source file:org.netbeans.modules.mongodb.ui.windows.collectionview.actions.EditSelectedDocumentAction.java

License:Open Source License

@Override
public void actionPerformed(ActionEvent e) {
    final DBObject document = getView().getResultTableSelectedDocument();
    final DBObject modifiedDocument = JsonUI.showEditor(Bundle.editDocumentTitle(), JSON.serialize(document));
    if (modifiedDocument != null) {
        try {//from w  ww .  jav a  2s  . com
            final DBCollection dbCollection = getView().getLookup().lookup(DBCollection.class);
            dbCollection.save(modifiedDocument);
            getView().refreshResults();
        } catch (MongoException ex) {
            DialogDisplayer.getDefault().notify(
                    new NotifyDescriptor.Message(ex.getLocalizedMessage(), NotifyDescriptor.ERROR_MESSAGE));
        }
    }
}

From source file:org.openspotlight.storage.mongodb.MongoStorageSessionImpl.java

License:Open Source License

@Override
public void persistNode(final DBObject reference, final StorageNode node)
        throws Exception, IllegalStateException {
    checkNotNull("reference", reference);
    checkNotNull("node", node);

    reference.put(LOCAL_ID, node.getKey().getCompositeKey().getKeyAsString());
    ensureIndexed(node.getPartition(), node.getType(), null, LOCAL_ID, null);

    final NodeKey uniqueId = node.getKey();
    final String parentId = uniqueId.getParentKeyAsString();
    if (parentId != null) {
        reference.put(PARENT_ID, parentId);
    }/*w  ww  .ja v  a  2 s . c  o  m*/
    final BasicDBObject key = new BasicDBObject();
    final List<String> keyNames = newArrayList();
    for (final SimpleKey keyEntry : uniqueId.getCompositeKey().getKeys()) {
        keyNames.add(keyEntry.getKeyName());
        key.put(keyEntry.getKeyName(), keyEntry.getValue() != null ? keyEntry.getValue() : NULL_VALUE);
        ensureIndexed(node.getPartition(), node.getType(), INDEXED, keyEntry.getKeyName(), null);
    }
    reference.put(ID, uniqueId.getKeyAsString());
    reference.put(KEY_NAMES, keyNames);
    reference.put(INDEXED, key);
    reference.put(NODE_TYPE, uniqueId.getCompositeKey().getNodeType());
    if (FlushMode.AUTO.equals(flushMode)) {
        final DBCollection col = getCachedCollection(node.getPartition(), node.getType());
        col.save(reference);
    } else {
        final Pair<StorageNode, DBObject> p = Pair.<StorageNode, DBObject>newPair(node, reference,
                Pair.PairEqualsMode.K1);
        if (!transientObjects.get(node.getPartition()).contains(p)) {
            transientObjects.put(node.getPartition(), p);
        }
    }
}

From source file:org.openspotlight.storage.mongodb.MongoStorageSessionImpl.java

License:Open Source License

@Override
public void persistLink(final StorageLink link) throws Exception, IllegalStateException {
    checkNotNull("link", link);

    createLinkReference(link);/*from   w  w  w.  ja  va 2 s .com*/
    if (flushMode.equals(FlushMode.AUTO)) {
        final DBObject nodeRef = createNodeReference(link.getSource());
        final DBCollection col = getCachedCollection(link.getSource().getPartition(),
                link.getSource().getType());
        col.save(nodeRef);
    }
}

From source file:org.openspotlight.storage.mongodb.MongoStorageSessionImpl.java

License:Open Source License

@Override
public void save(final Partition... partitions) throws Exception {

    for (final Partition partition : partitions) {
        for (final Pair<StorageNode, DBObject> p : transientObjects.get(partition)) {
            final StorageNode n = p.getK1();
            final DBCollection coll = getCachedCollection(partition, n.getType());
            coll.save(p.getK2());
        }//  w w  w . j ava 2 s.c o m
    }
    transientObjects.clear();
}

From source file:org.ossmeter.platform.MetricHistoryManager.java

License:Open Source License

public void store(Project project, Date date, IHistoricalMetricProvider provider) {
    DB db = platform.getMetricsRepository(project).getDb();

    DBCollection collection = db.getCollection(provider.getCollectionName());

    MetricProviderContext context = new MetricProviderContext(platform,
            new OssmeterLoggerFactory().makeNewLoggerInstance(provider.getIdentifier()));
    context.setDate(date);// w  w w.  ja  v  a  2  s . com
    provider.setMetricProviderContext(context);
    Pongo metric = provider.measure(project);
    DBObject dbObject = metric.getDbObject();

    dbObject.put("__date", date.toString());
    dbObject.put("__datetime", date.toJavaDate());
    collection.save(dbObject);
}

From source file:org.semispace.semimeter.dao.mongo.SemiMeterDaoMongo.java

License:Apache License

private void deleteOldMinutes(long before24h, long before180min, long before15min) {
    Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(before24h);//  w  w w  .j  a  v  a 2s  .c  o m
    cal.set(Calendar.MILLISECOND, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MINUTE, 0);
    long targetHour = cal.getTimeInMillis();

    DBCollection meterCollection = mongoTemplate.getCollection("meter");
    DBCursor result = meterCollection.find(new BasicDBObject(), new BasicDBObject("_id", 1));
    while (result.hasNext()) {
        DBObject doc = result.next();

        try {
            //start a new "session" for each document. not sure if this actually helps anything consistency-wise
            meterCollection.getDB().requestStart();

            //and fetch actual object (result only contains _id's)
            doc = meterCollection.findOne(doc); // TODO Double check

            log.trace("cleaning document : {}", doc);
            DBObject day = (DBObject) doc.get("day");
            //log.trace("day: {}", day);
            DBObject hours = (DBObject) day.get("hours");
            //log.trace("hours: {}", hours);
            Set<String> hrSet = new HashSet<String>();
            hrSet.addAll(hours.keySet());
            boolean docChanged = false;

            if (hrSet.isEmpty()) {
                log.trace("no hours in document, remove it: {}", doc);
                meterCollection.remove(new BasicDBObject("_id", doc.get("_id")), WriteConcern.UNACKNOWLEDGED);
            } else {
                for (String h : hrSet) {
                    long hourmillis = Long.valueOf(h);
                    log.trace("checking hour: {}", hourmillis);
                    if (hourmillis < targetHour) {
                        if (log.isTraceEnabled()) {
                            log.trace("removing hour " + h + " because it is older than target" + targetHour);
                        }
                        docChanged = true;
                        DBObject obj = (DBObject) hours.get(h);
                        day.put("count", (Integer) day.get("count") - (Integer) obj.get("count"));
                        hours.removeField(h);
                    } else if (hourmillis == targetHour) {
                        log.trace("current hour is targetHour, check minutes");
                        DBObject currentHour = (DBObject) hours.get(h);
                        DBObject minutes = (DBObject) currentHour.get("minutes");
                        Set<String> keys = new HashSet<String>();
                        keys.addAll(minutes.keySet());
                        for (String m : keys) {
                            long minutemillis = Long.valueOf(m);
                            log.trace("checking minute: {}", minutemillis);
                            if (minutemillis < before24h) {
                                if (log.isTraceEnabled()) {
                                    log.trace("removing minute " + minutemillis + " because it is older than "
                                            + before24h);
                                }

                                docChanged = true;
                                DBObject obj = (DBObject) minutes.get(m);
                                DBObject hourObj = (DBObject) hours.get(h);
                                day.put("count", (Integer) day.get("count") - (Integer) obj.get("count"));
                                hourObj.put("count",
                                        (Integer) hourObj.get("count") - (Integer) obj.get("count"));
                                minutes.removeField(m);
                            }
                        }
                        if (minutes.keySet().isEmpty()) {
                            log.trace("no more minutes, removing hour {}", h);
                            hours.removeField(h);
                            docChanged = true;
                        }
                    }
                }
            }

            docChanged |= updateTrendCounters(doc, before180min, before15min);

            if (docChanged) {
                meterCollection.save(doc);
            }
        } finally {
            meterCollection.getDB().requestDone();
        }
    }
}

From source file:org.sipfoundry.sipxconfig.admin.commserver.imdb.ReplicationManagerImpl.java

License:Contributor Agreement License

/**
 * Replicate a Location. That means just register a location in Mongo node DB
 * and register the tunnels./*  w w  w  .  jav a2s  .  co m*/
 */
@Override
public boolean replicateLocation(Location location) {
    boolean success = false;
    try {
        if (location.isRegistered()) {
            DBCollection nodeCollection = m_imdb.getDb().getCollection(MongoConstants.NODE_COLLECTION);
            DBObject search = new BasicDBObject();
            search.put(ID, location.getId());
            DBCursor cursor = nodeCollection.find(search);
            DBObject node = new BasicDBObject();
            if (cursor.hasNext()) {
                node = cursor.next();
            }
            node.put(ID, location.getId());
            node.put(IP, location.getAddress());
            node.put(DESCRIPTION, location.getName());
            node.put(MASTER, location.isPrimary());
            nodeCollection.save(node);
        }
        registerTunnels(location);
        success = true;
        m_auditLogContext.logReplicationMongo(LOCATION_REGISTRATION, location);
    } catch (Exception e) {
        m_auditLogContext.logReplicationMongoFailed(LOCATION_REGISTRATION, location, e);
        throw new UserException("Cannot register location in mongo db: " + e);
    }
    return success;
}

From source file:org.sipfoundry.sipxconfig.admin.commserver.imdb.ReplicationManagerImpl.java

License:Contributor Agreement License

@Override
public void registerTunnels(Location location) {
    DBCollection registrarNode = m_imdb.getDb().getCollection(MongoConstants.STUNNEL_COLLECTION);
    registrarNode.drop();/*from   w  w  w . ja  va2  s  . c  om*/

    Location[] locations = m_locationsManager.getLocations();
    if (locations.length > 1) {
        for (int i = 0; i < locations.length; i++) {
            List<Location> otherLocations = new ArrayList<Location>(Arrays.asList(locations));
            otherLocations.remove(locations[i]);

            for (TunnelProvider tunnelProvider : m_tunnelManager.getTunnelProviders()) {
                List<RemoteOutgoingTunnel> tunnels = (List<RemoteOutgoingTunnel>) tunnelProvider
                        .getClientSideTunnels(otherLocations, location);
                for (RemoteOutgoingTunnel tunnel : tunnels) {
                    DBObject search = new BasicDBObject();
                    search.put(ID, tunnel.getName());
                    DBObject server = registrarNode.findOne(search);
                    if (server == null) {
                        server = new BasicDBObject();
                        server.put(ID, tunnel.getName());
                    }
                    server.put(SERVER, "localhost:" + tunnel.getLocalhostPort());
                    server.put(INTERNAL_ADDRESS, tunnel.getRemoteMachineAddress());
                    Location loc = m_locationsManager.getLocationByAddress(tunnel.getRemoteMachineAddress());
                    server.put(ENABLED, loc.isRegistered());
                    registrarNode.save(server);
                }
            }
        }
        DBObject timestamp = new BasicDBObject();
        timestamp.put(ID, "timestamp");
        timestamp.put(TIMESTAMP, new Long(System.currentTimeMillis() / 1000).toString());
        registrarNode.save(timestamp);
    }
}

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

License:Apache License

protected Object saveDBObject(String collectionName, final DBObject dbDoc) {

    if (dbDoc.keySet().isEmpty()) {
        return null;
    }/*from   w ww. ja  va 2  s  . c  om*/

    //TODO: Need to move this to more central place
    if (dbDoc.containsField("_id")) {
        if (dbDoc.get("_id") instanceof String) {
            ObjectId oid = convertIdValue(this.mongoConverter, dbDoc.get("_id"));
            if (oid != null) {
                dbDoc.put("_id", oid);
            }
        }
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("save DBObject containing fields: " + dbDoc.keySet());
    }
    return execute(collectionName, new CollectionCallback<Object>() {
        public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            if (writeConcern == null) {
                collection.save(dbDoc);
            } else {
                collection.save(dbDoc, writeConcern);
            }
            return dbDoc.get(ID);
        }
    });
}

From source file:org.springframework.data.mongodb.core.MongoTemplate.java

License:Apache License

protected Object saveDBObject(final String collectionName, final DBObject dbDoc, final Class<?> entityClass) {

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Saving DBObject containing fields: {}", dbDoc.keySet());
    }//from   w ww . j  ava2  s  .  co m

    return execute(collectionName, new CollectionCallback<Object>() {
        public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.SAVE, collectionName,
                    entityClass, dbDoc, null);
            WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
            WriteResult writeResult = writeConcernToUse == null ? collection.save(dbDoc)
                    : collection.save(dbDoc, writeConcernToUse);
            handleAnyWriteResultErrors(writeResult, dbDoc, MongoActionOperation.SAVE);
            return dbDoc.get(ID_FIELD);
        }
    });
}