com.mongodb.DBRef Java Examples

The following examples show how to use com.mongodb.DBRef. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InternalValidator.java    From scava with Eclipse Public License 2.0 8 votes vote down vote up
private Map<String, Float> readDistanceScores(String startingObject, Set<String> others) {
	Map<String, Float> result = new HashMap<String, Float>();
	Query query = new org.springframework.data.mongodb.core.query.Query();
	query.addCriteria(Criteria.where("type.name").is(_SIMILARITY_METHOD).orOperator(
			Criteria.where("fromArtifact.$id").is(new ObjectId(startingObject)),
			Criteria.where("toArtifact.$id").is(new ObjectId(startingObject))));
	DBCollection dbCollection = mongoTemplate.getCollection("relation");
	DBCursor cursor = dbCollection.find(query.getQueryObject());
	List<DBObject> list = cursor.toArray();
	for (DBObject dbObject : list) {
		String toArtifact = ((DBRef) dbObject.get("toArtifact")).getId().toString();
		String fromArtifact = ((DBRef) dbObject.get("fromArtifact")).getId().toString();
		double value = ((double) dbObject.get("value"));
		if (toArtifact.equals(startingObject)) {
			if (others.contains(fromArtifact))
				result.put(fromArtifact, (float) (1 - value));
		} else if (others.contains(toArtifact))
			result.put(toArtifact, (float) (1 - value));
	}
	return result;
}
 
Example #2
Source File: EntityDataController.java    From restfiddle with Apache License 2.0 6 votes vote down vote up
private void dbRefToRelation(DBObject dbObject) {
if (dbObject == null) {
    return;
}
if (dbObject.containsField("_id")) 
    dbObject.put("_id", ((ObjectId) dbObject.get("_id")).toHexString());
for (String key : dbObject.keySet()) {
    Object obj = dbObject.get(key);
    if (obj instanceof DBRef) {
	DBRef ref = (DBRef) obj;
	dbObject.put(key, dbRefToRel(ref));
    } else if (obj instanceof DBObject) {
	dbRefToRelation((DBObject) obj);
    }
}

   }
 
Example #3
Source File: MapReference.java    From morphia with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void readFromSingleCollection(final String collection, final List<Object> collectionIds) {

    try (MongoCursor<T> cursor = (MongoCursor<T>) getDatastore().find(collection)
                                                                .filter(in("_id", collectionIds)).iterator()) {
        final Map<Object, T> idMap = new HashMap<>();
        while (cursor.hasNext()) {
            final T entity = cursor.next();
            idMap.put(getDatastore().getMapper().getId(entity), entity);
        }

        for (final Entry<String, Object> entry : ids.entrySet()) {
            final Object id = entry.getValue();
            final T value = idMap.get(id instanceof DBRef ? ((DBRef) id).getId() : id);
            if (value != null) {
                values.put(entry.getKey(), value);
            }
        }
    }
}
 
Example #4
Source File: CollectionReference.java    From morphia with Apache License 2.0 6 votes vote down vote up
private List<Object> mapIds(final List list, final Map<Object, Object> idMap) {
    final List<Object> values = new ArrayList<>(asList(new Object[list.size()]));
    for (int i = 0; i < list.size(); i++) {
        final Object id = list.get(i);

        final Object value;
        if (id instanceof List) {
            value = mapIds((List) id, idMap);
        } else {
            value = idMap.get(id instanceof DBRef ? ((DBRef) id).getId() : id);
        }
        if (value != null) {
            values.set(i, value);
        }
    }

    return values;
}
 
Example #5
Source File: EntitySessionController.java    From restfiddle with Apache License 2.0 6 votes vote down vote up
private void dbRefToRelation(DBObject dbObject) {
if (dbObject == null) {
    return;
}
if (dbObject.containsField("_id")) 
    dbObject.put("_id", ((ObjectId) dbObject.get("_id")).toHexString());
for (String key : dbObject.keySet()) {
    Object obj = dbObject.get(key);
    if (obj instanceof DBRef) {
	DBRef ref = (DBRef) obj;
	dbObject.put(key, dbRefToRel(ref));
    } else if (obj instanceof DBObject) {
	dbRefToRelation((DBObject) obj);
    }
}

   }
 
Example #6
Source File: PongoFactory.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
public Pongo resolveReference(Object ref) {
	if (ref instanceof DBRef) {
		DBRef dbRef = (DBRef) ref;
	
		String fullyQualifiedId = dbRef.getDB().getName() + "." + dbRef.getRef() + "." + dbRef.getId().toString();
		Pongo pongo = (Pongo) cache.get(fullyQualifiedId);
		if (pongo == null) {
			DBObject dbObject = dbRef.getDB().getCollection(dbRef.getRef()).findOne(new BasicDBObject("_id", dbRef.getId()));
			if (dbObject != null) {
				pongo = createPongo(dbObject, dbRef.getDB().getCollection(dbRef.getRef()));
			}
		}
		return pongo;
	}
	else {
		return null;
	}
}
 
Example #7
Source File: AggregateQueryProvider.java    From mongodb-aggregate-query-support with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("Duplicates")
@Override
protected void bindDriverSpecificTypes(List<ParameterBinding> bindings, Object value) {
  if (value instanceof DBRef) {

    DBRef dbref = (DBRef) value;
    potentiallyAddBinding(dbref.getCollectionName(), bindings);
    potentiallyAddBinding(dbref.getId().toString(), bindings);

  }
  else if (value instanceof DBObject) {

    DBObject dbo = (DBObject) value;

    for (String field : dbo.keySet()) {
      // replace @ params on lhs
      collectParameterReferencesIntoBindings(bindings, field);
      // replace ? params on RHS
      collectParameterReferencesIntoBindings(bindings, dbo.get(field));
    }
  }
}
 
Example #8
Source File: InternalValidator.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private Map<String, Float> readDistanceScores(String object) {
	Map<String, Float> result = new HashMap<String, Float>();
	Query query = new org.springframework.data.mongodb.core.query.Query();
	query.addCriteria(Criteria.where("type.name").is(_SIMILARITY_METHOD).orOperator(
			Criteria.where("fromArtifact.$id").is(new ObjectId(object)),
			Criteria.where("toArtifact.$id").is(new ObjectId(object))));
	DBCollection dbCollection = mongoTemplate.getCollection("relation");
	DBCursor cursor = dbCollection.find(query.getQueryObject());
	List<DBObject> list = cursor.toArray();
	for (DBObject dbObject : list) {
		String toArtifact = ((DBRef) dbObject.get("toArtifact")).getId().toString();
		String fromArtifact = ((DBRef) dbObject.get("fromArtifact")).getId().toString();
		double value = ((double) dbObject.get("value"));
		if (toArtifact.equals(object))
			result.put(fromArtifact, (float) (1 - value));
		else
			result.put(toArtifact, (float) (1 - value));
	}
	return result;
}
 
Example #9
Source File: ClaraClulsterCalulator.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private Map<String, Float> readDistanceScores(String object) {
	Map<String, Float> result = new HashMap<String, Float>();
	Query query = new org.springframework.data.mongodb.core.query.Query();
	query.addCriteria(Criteria.where("type.name").is(sm.getSimilarityName()).orOperator(
			Criteria.where("fromArtifact.$id").is(new ObjectId(object)),
			Criteria.where("toArtifact.$id").is(new ObjectId(object))));
	DBCollection dbCollection = mongoTemplate.getCollection("relation");
	DBCursor cursor = dbCollection.find(query.getQueryObject());
	List<DBObject> list = cursor.toArray();
	for (DBObject dbObject : list) {
		String toArtifact = ((DBRef) dbObject.get("toArtifact")).getId().toString();
		String fromArtifact = ((DBRef) dbObject.get("fromArtifact")).getId().toString();
		double value = ((double) dbObject.get("value"));
		if (toArtifact.equals(object))
			result.put(fromArtifact, (float) (1 - value));
		else
			result.put(toArtifact, (float) (1 - value));
	}
	return result;
}
 
Example #10
Source File: KmeansClulsterCalulator.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private Map<String, Float> readDistanceScores(String object) {
	Map<String, Float> result = new HashMap<String, Float>();
	Query query = new org.springframework.data.mongodb.core.query.Query();
	query.addCriteria(Criteria.where("type.name").is(sm.getSimilarityName())
			.orOperator(Criteria.where("fromArtifact.$id").is(new ObjectId(object)), 
					    Criteria.where("toArtifact.$id").is(new ObjectId(object))));
	DBCollection dbCollection = mongoTemplate.getCollection("relation");
    DBCursor cursor = dbCollection.find(query.getQueryObject());
    List<DBObject> list = cursor.toArray();
    for (DBObject dbObject : list) {
		String toArtifact = ((DBRef)dbObject.get("toArtifact")).getId().toString();
		String fromArtifact = ((DBRef)dbObject.get("fromArtifact")).getId().toString();
		double value = ((double)dbObject.get("value"));
		if (toArtifact.equals(object))  
			result.put(fromArtifact, (float) (1 - value));
		else 
			result.put(toArtifact, (float) (1 - value));
	}
	return result;
}
 
Example #11
Source File: NonReactiveAggregateQueryProvider.java    From mongodb-aggregate-query-support with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("Duplicates")
@Override
protected void bindDriverSpecificTypes(List<ParameterBinding> bindings, Object value) {
  if (value instanceof DBRef) {

    DBRef dbref = (DBRef) value;
    potentiallyAddBinding(dbref.getCollectionName(), bindings);
    potentiallyAddBinding(dbref.getId().toString(), bindings);

  }
  else if (value instanceof DBObject) {

    DBObject dbo = (DBObject) value;

    for (String field : dbo.keySet()) {
      // replace @ params on lhs
      collectParameterReferencesIntoBindings(bindings, field);
      // replace ? params on RHS
      collectParameterReferencesIntoBindings(bindings, dbo.get(field));
    }
  }
}
 
Example #12
Source File: ReferenceUtil.java    From bugu-mongo with Apache License 2.0 5 votes vote down vote up
public static String fromDbReference(Ref ref, Object value){
    String result;
    if(ref.reduced()){
        result = value.toString();
    }else{
        DBRef dbRef = (DBRef)value;
        result = dbRef.getId().toString();
    }
    return result;
}
 
Example #13
Source File: ReferenceUtil.java    From bugu-mongo with Apache License 2.0 5 votes vote down vote up
public static String fromDbReference(RefList refList, Object value){
    String result;
    if(refList.reduced()){
        result = value.toString();
    }else{
        DBRef dbRef = (DBRef)value;
        result = dbRef.getId().toString();
    }
    return result;
}
 
Example #14
Source File: CollectionReference.java    From morphia with Apache License 2.0 5 votes vote down vote up
static void collate(final MappedClass valueType, final Map<String, List<Object>> collections,
                    final Object o) {
    final String collectionName;
    final Object id;
    if (o instanceof DBRef) {
        final DBRef dbRef = (DBRef) o;
        collectionName = dbRef.getCollectionName();
        id = dbRef.getId();
    } else {
        collectionName = valueType.getCollectionName();
        id = o;
    }

    register(collections, collectionName).add(id);
}
 
Example #15
Source File: EntityDataController.java    From restfiddle with Apache License 2.0 5 votes vote down vote up
private void relationToDBRef(DBObject dbObject, String projectId) {
for (String key : dbObject.keySet()) {
    Object obj = dbObject.get(key);
    if (obj instanceof DBObject) {
	DBObject doc = (DBObject) obj;
	if (doc.containsField("_rel")) {
	    DBObject relation = (DBObject) doc.get("_rel");
	    dbObject.put(key, new DBRef(projectId + "_" + (String) relation.get("entity"), new ObjectId((String) relation.get("_id"))));
	} else {
	    relationToDBRef(doc, projectId);
	}
    }
}
   }
 
Example #16
Source File: SingleReference.java    From morphia with Apache License 2.0 5 votes vote down vote up
Query<?> buildQuery() {
    final Query<?> query;
    if (id instanceof DBRef) {
        final Class<?> clazz = getDatastore()
                                   .getMapper()
                                   .getClassFromCollection(((DBRef) id).getCollectionName());
        query = getDatastore().find(clazz)
                              .filter(eq("_id", ((DBRef) id).getId()));
    } else {
        query = getDatastore().find(mappedClass.getType())
                              .filter(eq("_id", id));
    }
    return query;
}
 
Example #17
Source File: AdvancedDatastore.java    From morphia with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a reference to the entity (using the current DB -can be null-, the collectionName, and id)
 *
 * @param <T>    The type of the entity
 * @param entity the entity to create a DBRef for
 * @return the DBRef for the entity
 */
@Deprecated(since = "2.0", forRemoval = true)
default <T> DBRef createRef(T entity)  {
    final Object id = getMapper().getId(entity);
    if (id == null) {
        throw new MappingException("Could not get id for " + entity.getClass().getName());
    }
    return createRef(entity.getClass(), id);
}
 
Example #18
Source File: EntitySessionController.java    From restfiddle with Apache License 2.0 4 votes vote down vote up
private DBObject dbRefToRel(DBRef obj){
return new BasicDBObject().append("_rel",new BasicDBObject().append("entity", ((String) obj.getId()).split("_")[1]).append("_id", ((ObjectId)obj.getId()).toHexString()));
   }
 
Example #19
Source File: Pongo.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
public DBRef createDBRef() {
	if (!isReferencable()) throw new IllegalStateException("Attempted to create DBRef for non-referenceable object " + this);
	return new DBRef(getPongoCollection().getDbCollection().getDB(), getPongoCollection().getName(), getId());
}
 
Example #20
Source File: EntityAuthService.java    From restfiddle with Apache License 2.0 4 votes vote down vote up
public JSONObject authorize(String projectId, String authToken, String... roles) {

JSONObject response = new JSONObject();
if(authToken == null){
    return response.put(SUCCESS, false).put("msg", UNAUTHORIZED);
}

List<String> roleList = Arrays.asList(roles);

DBCollection dbCollection = mongoTemplate.getCollection(ENTITY_AUTH);

BasicDBObject queryObject = new BasicDBObject();
queryObject.append("_id", new ObjectId(authToken));

DBObject authData = dbCollection.findOne(queryObject);

if(authData != null && projectId.equals(authData.get("projectId"))) {
    DBRef userRef = (DBRef)authData.get("user");
    DBObject user = mongoTemplate.getCollection(userRef.getCollectionName()).findOne(userRef.getId());
    
    DBObject roleObj = null;
    if(user.containsField("role")){
	DBRef roleRef = (DBRef)user.get("role");
	roleObj = mongoTemplate.getCollection(roleRef.getCollectionName()).findOne(roleRef.getId());
    }
    
    if((roleObj != null && roleList.contains(roleObj.get("name"))) || roleList.contains("USER")){
	response.put(SUCCESS, true);
	response.put("user", userRef);
	
	authData.put("expireAt", new Date(System.currentTimeMillis() + 3600 * 1000));
	dbCollection.save(authData);
    } else {
	response.put(SUCCESS, false).put("msg", UNAUTHORIZED);
    }
} else {
    response.put(SUCCESS, false).put("msg", UNAUTHORIZED);
}

return response;
   }
 
Example #21
Source File: EntityDataController.java    From restfiddle with Apache License 2.0 4 votes vote down vote up
private DBObject dbRefToRel(DBRef obj){
return new BasicDBObject().append("_rel",new BasicDBObject().append("entity", (obj.toString()).split("_")[1]).append("_id", ((ObjectId)obj.getId()).toHexString()));
   }
 
Example #22
Source File: ReferenceUtil.java    From bugu-mongo with Apache License 2.0 4 votes vote down vote up
private static DBRef toDBRef(Class<?> clazz, String idStr){
    String name = MapperUtil.getEntityName(clazz);
    Object dbId = IdUtil.toDbId(clazz, idStr);
    return new DBRef(name, dbId);
}
 
Example #23
Source File: MongoQuery.java    From MongoDB-Plugin with Apache License 2.0 4 votes vote down vote up
public MongoQuery join(String key, String collectionName, String id) {
    DBRef ref = new DBRef(collectionName, new ObjectId(id));
    document.append(key, ref);
    return this;
}
 
Example #24
Source File: AdvancedDatastore.java    From morphia with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a reference to the entity (using the current DB -can be null-, the collectionName, and id)
 *
 * @param clazz The type of the entity
 * @param id    The ID value of the entity
 * @param <T>   The type of the entity
 * @param <V>   The type of the ID value
 * @return the DBRef for the entity
 */
@Deprecated(since = "2.0", forRemoval = true)
default <T, V> DBRef createRef(Class<T> clazz, V id) {
    if (id == null) {
        throw new MappingException("Could not get id for " + clazz.getName());
    }
    return new DBRef(getMapper().getCollection(clazz).getNamespace().getCollectionName(), id);
}
 
Example #25
Source File: MappedField.java    From morphia with Apache License 2.0 2 votes vote down vote up
/**
 * @return true if this field is a reference to a foreign document
 * @see Reference
 * @see Key
 * @see DBRef
 */
public boolean isReference() {
    return hasAnnotation(Reference.class) || Key.class == getType() || DBRef.class == getType();
}