Example usage for com.mongodb DBRef getId

List of usage examples for com.mongodb DBRef getId

Introduction

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

Prototype

public Object getId() 

Source Link

Document

Gets the _id of the referenced document

Usage

From source file:com.sonyericsson.jenkins.plugins.bfa.db.MongoDBKnowledgeBase.java

License:Open Source License

@Override
public Map<Integer, List<FailureCause>> getFailureCausesPerBuild(GraphFilterBuilder filter) {
    Map<Integer, List<FailureCause>> nbrOfFailureCausesPerBuild = new HashMap<Integer, List<FailureCause>>();
    DBObject matchFields = generateMatchFields(filter);
    DBObject match = new BasicDBObject("$match", matchFields);

    DBObject unwind = new BasicDBObject("$unwind", "$failureCauses");

    DBObject groupFields = new BasicDBObject("_id", "$buildNumber");
    groupFields.put("failureCauses", new BasicDBObject("$addToSet", "$failureCauses.failureCause"));
    DBObject group = new BasicDBObject("$group", groupFields);

    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1));

    AggregationOutput output;//from  ww  w  .j  a va  2 s  .  co m
    try {
        output = getStatisticsCollection().aggregate(match, unwind, group, sort);
        for (DBObject result : output.results()) {
            List<FailureCause> failureCauses = new ArrayList<FailureCause>();
            Integer buildNumber = (Integer) result.get("_id");
            BasicDBList failureCauseRefs = (BasicDBList) result.get("failureCauses");
            for (Object o : failureCauseRefs) {
                DBRef failureRef = (DBRef) o;
                String id = failureRef.getId().toString();
                FailureCause failureCause = getCause(id);
                failureCauses.add(failureCause);
            }

            nbrOfFailureCausesPerBuild.put(buildNumber, failureCauses);
        }
    } catch (Exception e) {
        logger.fine("Unable to count failure causes by build");
        e.printStackTrace();
    }

    return nbrOfFailureCausesPerBuild;
}

From source file:com.sonyericsson.jenkins.plugins.bfa.db.MongoDBKnowledgeBase.java

License:Open Source License

@Override
public List<FailureCauseTimeInterval> getFailureCausesPerTime(int intervalSize, GraphFilterBuilder filter,
        boolean byCategories) {
    List<FailureCauseTimeInterval> failureCauseIntervals = new ArrayList<FailureCauseTimeInterval>();
    Map<MultiKey, FailureCauseTimeInterval> categoryTable = new HashMap<MultiKey, FailureCauseTimeInterval>();

    DBObject matchFields = generateMatchFields(filter);
    DBObject match = new BasicDBObject("$match", matchFields);

    DBObject unwind = new BasicDBObject("$unwind", "$failureCauses");

    DBObject idFields = generateTimeGrouping(intervalSize);
    idFields.put("failureCause", "$failureCauses.failureCause");
    DBObject groupFields = new BasicDBObject();
    groupFields.put("_id", idFields);
    groupFields.put("number", new BasicDBObject("$sum", 1));
    DBObject group = new BasicDBObject("$group", groupFields);

    AggregationOutput output;/* w w  w .j a va  2  s.c o  m*/
    try {
        output = getStatisticsCollection().aggregate(match, unwind, group);
        for (DBObject result : output.results()) {
            int number = (Integer) result.get("number");

            TimePeriod period = generateTimePeriodFromResult(result, intervalSize);

            BasicDBObject groupedAttrs = (BasicDBObject) result.get("_id");
            DBRef failureRef = (DBRef) groupedAttrs.get("failureCause");
            String id = failureRef.getId().toString();
            FailureCause failureCause = getCause(id);

            if (byCategories) {
                if (failureCause.getCategories() != null) {
                    for (String category : failureCause.getCategories()) {
                        MultiKey multiKey = new MultiKey(category, period);
                        FailureCauseTimeInterval interval = categoryTable.get(multiKey);
                        if (interval == null) {
                            interval = new FailureCauseTimeInterval(period, category, number);
                            categoryTable.put(multiKey, interval);
                            failureCauseIntervals.add(interval);
                        } else {
                            interval.addNumber(number);
                        }
                    }
                }
            } else {
                FailureCauseTimeInterval timeInterval = new FailureCauseTimeInterval(period,
                        failureCause.getName(), failureCause.getId(), number);
                failureCauseIntervals.add(timeInterval);
            }
        }
    } catch (UnknownHostException e) {
        logger.fine("Unable to get failure causes by time");
        e.printStackTrace();
    } catch (AuthenticationException e) {
        logger.fine("Unable to get failure causes by time");
        e.printStackTrace();
    }

    return failureCauseIntervals;
}

From source file:com.streamsets.pipeline.stage.common.mongodb.MongoDBUtil.java

License:Apache License

@SuppressWarnings("unchecked")
private static Field jsonToField(Object object) throws IOException {
    if (object instanceof ObjectId) {
        String objectId = object.toString();
        return JsonUtil.jsonToField(objectId);
    } else if (object instanceof Binary) {
        byte[] data = ((Binary) object).getData();
        return JsonUtil.jsonToField(data);
    } else if (object instanceof BsonTimestamp) {
        int time = ((BsonTimestamp) object).getTime();
        Date date = new Date(time * 1000L);
        Map<String, Object> jsonMap = new LinkedHashMap<>();
        jsonMap.put(BSON_TS_TIME_T_FIELD, date);
        jsonMap.put(BSON_TS_ORDINAL_FIELD, ((BsonTimestamp) object).getInc());
        return JsonUtil.jsonToField(jsonMap);
    } else if (object instanceof List) {
        List jsonList = (List) object;
        List<Field> list = new ArrayList<>(jsonList.size());
        for (Object element : jsonList) {
            list.add(jsonToField(element));
        }/*from   w ww  . ja  va2 s . c o  m*/
        return Field.create(list);
    } else if (object instanceof Map) {
        Map<String, Object> jsonMap = (Map<String, Object>) object;
        Map<String, Field> map = new LinkedHashMap<>();
        for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
            map.put(entry.getKey(), jsonToField(entry.getValue()));
        }
        return Field.create(map);
    } else if (object instanceof com.mongodb.DBRef) {
        Map<String, Field> map = new LinkedHashMap<>();
        com.mongodb.DBRef ref = (com.mongodb.DBRef) object;
        map.put(REF, Field.create(ref.getCollectionName()));
        map.put(ID, Field.create(ref.getId().toString()));
        if (ref.getDatabaseName() != null) {
            map.put(DB, Field.create(ref.getDatabaseName()));
        }
        return Field.create(map);
    }
    return JsonUtil.jsonToField(object);
}

From source file:de.gwdg.europeanaqa.client.rest.DocumentTransformer.java

private Document resolveReference(DBRef ref, boolean withFieldRename) {
    String collection = ref.getCollectionName();
    ObjectId id = (ObjectId) ref.getId();
    return resolveReference(collection, id, withFieldRename);
    /*/*from   w w w .j  a v  a  2 s.  c om*/
    Document doc = mongoDb.getCollection(collection).find(Filters.eq("_id", ref.getId())).first();
    if (doc != null) {
       doc.remove("_id");
       doc.remove("className");
       transformLanguageStructure(doc);
       if (collection.equals("PhysicalThing") && withFieldRename) {
    doc.put("europeanaProxy", Arrays.asList(((Boolean)doc.get("europeanaProxy")).toString()));
       }
       if (withFieldRename)
    replaceKeys(doc);
       for (String key : subEntities.keySet()) {
    if (doc.containsKey(key)) {
       List<Document> subDocs = new ArrayList<Document>();
       List<DBRef> subRefs = (List<DBRef>) doc.get(key);
       for (DBRef subRef : subRefs) {
          subDocs.add(resolveReference(subRef, withFieldRename));
       }
       doc.remove(key);
       doc.put(subEntities.get(key), subDocs);
    }
       }
    }
    return doc;
    */
}

From source file:io.liveoak.mongo.RootMongoResource.java

License:Open Source License

@Override
protected MongoObjectResource getResource(DBRef dbRef, boolean byReference) throws ResourceProcessingException {
    if (dbRef != null) {
        if (dbRef.getDB() == null) {
            throw new ResourceProcessingException("Invalid Reference. Reference Database is null.");
        }/*  w w  w. ja  va 2s  . c o  m*/
        if (dbRef.getDB().getName() != db().getName()) {
            throw new ResourceProcessingException(
                    "LiveOak only supports MongoResource objects within the same database.");
        }

        String collectionName = dbRef.getRef();
        if (!db().collectionExists(collectionName)) {
            throw new ResourceProcessingException(
                    "Cannot find collection specified in a reference. No collection named '" + collectionName
                            + "' found");
        }

        MongoCollectionResource mongoCollectionResource = new MongoCollectionResource(this, collectionName);

        if (byReference) {

            MongoObjectResource mongoObjectResource = new MongoBaseObjectResource(mongoCollectionResource,
                    dbRef.getId());

            return mongoObjectResource;
        } else {
            DBObject referencedObject = dbRef.fetch();
            if (referencedObject == null) {
                throw new ResourceProcessingException(
                        "Cannot find referenced resource. No resource in collection '" + collectionName
                                + "' with id '" + dbRef.getId() + "'");
            }
            return new MongoBaseObjectResource(mongoCollectionResource, referencedObject);
        }
    } else {
        throw new ResourceProcessingException("Invalid Reference. Reference cannot be null.");
    }
}

From source file:net.vz.mongodb.jackson.internal.stream.DBEncoderBsonGenerator.java

License:Apache License

@Override
protected void _writeSimpleObject(Object value) throws IOException, JsonGenerationException {
    if (value instanceof Date) {
        writeDateTime((Date) value);
    } else if (value instanceof Calendar) {
        writeDateTime(((Calendar) value).getTime());
    } else if (value instanceof ObjectId) {
        writeObjectId(ObjectIdConvertor.convert((ObjectId) value));
    } else if (value instanceof DBRef) {
        DBRef dbRef = (DBRef) value;
        writeStartObject();//from ww w.  ja va2 s .com
        writeFieldName("$ref");
        writeString(dbRef.getRef());
        writeFieldName("$id");
        writeObject(dbRef.getId());
        if (dbRef.getDB() != null) {
            writeFieldName("$db");
            writeString(dbRef.getDB().getName());
        }
        writeEndObject();
    } else {
        super._writeSimpleObject(value);
    }
}

From source file:org.codinjutsu.tools.mongo.view.model.JsonTreeUtils.java

License:Apache License

private static void processDBRef(JsonTreeNode parentNode, DBRef dbRef) {
    parentNode//from  w  w  w .  j  ava  2 s. c  o m
            .add(new JsonTreeNode(MongoKeyValueDescriptor.createDescriptor("$ref", dbRef.getCollectionName())));
    parentNode.add(new JsonTreeNode(MongoKeyValueDescriptor.createDescriptor("$id", dbRef.getId())));
    parentNode.add(new JsonTreeNode(MongoKeyValueDescriptor.createDescriptor("$db", dbRef.getDatabaseName())));
}

From source file:org.grails.datastore.mapping.mongo.engine.MongoEntityPersister.java

License:Apache License

/**
 * Implementors who want to support one-to-many associations embedded should implement this method
 *
 * @param association The association/*from  w  ww . j a  va2s  .com*/
 * @param ea
 * @param nativeEntry
 * @return A list of keys loaded from the embedded instance
 */
@Override
protected List loadEmbeddedCollectionKeys(Association association, EntityAccess ea, DBObject nativeEntry) {
    if (nativeEntry != null) {

        Object entry = nativeEntry.get(getPropertyKey(association));
        List keys = new ArrayList();
        if (entry instanceof List) {
            List entries = (List) entry;
            for (Object o : entries) {
                if (o instanceof DBRef) {
                    DBRef dbref = (DBRef) o;
                    keys.add(dbref.getId());
                } else if (o != null) {
                    keys.add(o);
                } else {
                    keys.add(null);
                }
            }
        }
        return keys;
    }
    return super.loadEmbeddedCollectionKeys(association, ea, nativeEntry);
}

From source file:org.grails.datastore.mapping.mongo.engine.MongoEntityPersister.java

License:Apache License

private Object getIdentifierForKey(Object key) {
    Object id = key;//from  ww  w  . j  av a 2  s .  c  om
    if (key instanceof DBRef) {
        DBRef ref = (DBRef) key;
        id = ref.getId();
    }
    return id;
}

From source file:org.mongodb.morphia.mapping.Mapper.java

License:Open Source License

public <T> Key<T> refToKey(final DBRef ref) {
    return ref == null ? null : new Key<T>(ref.getCollectionName(), ref.getId());
}