List of usage examples for com.mongodb BasicDBObject get
public Object get(final String key)
From source file:org.slc.sli.ingestion.transformation.IsCorrectQuery.java
License:Apache License
private boolean matches(Query arg) { String queryKey;//from w w w. j a va 2s . c o m String argKey; for (String key : query.getQueryObject().keySet()) { queryKey = query.getQueryObject().get(key).getClass().getSimpleName(); argKey = arg.getQueryObject().get(key).getClass().getSimpleName(); if (!queryKey.equals(argKey)) { return false; } else if (queryKey.equals("BasicDBObject")) { BasicDBObject queryObj = (BasicDBObject) query.getQueryObject().get(key); BasicDBObject argObj = (BasicDBObject) arg.getQueryObject().get(key); // System.out.println(key); // System.out.print("\t"+queryObj); // System.out.println(" "+argObj); for (String key2 : queryObj.keySet()) { if (queryObj.get(key2).getClass() != argObj.get(key2).getClass()) { return false; } else if (key2.equals("$in")) { List<?> queryVal = (List<?>) queryObj.get(key2); List<?> argVal = (List<?>) argObj.get(key2); if (queryVal.size() != argVal.size()) { return false; } for (int i = 0; i < queryVal.size(); ++i) { if (!(queryVal.get(i).equals(argVal.get(i)))) { return false; } } return true; } } } else if (!query.getQueryObject().get(key).equals(arg.getQueryObject().get(key))) { return false; } } return true; }
From source file:org.socialhistoryservices.pid.database.dao.HandleDaoImpl.java
License:Open Source License
/** * Retrieves a list of HandleValues from the resultset and casts each to the domain model Handle. * * @param handle The pid/* ww w . j av a2 s . c o m*/ * @return The handle documents */ private List<Handle> getHandleValueByData(BasicDBObject handle) { final BasicDBList results = (BasicDBList) handle.get("handles"); final Iterator<Object> iterator = results.iterator(); final List<Handle> handles = new ArrayList<Handle>(); while (iterator.hasNext()) { HandleValue value = handleStorage.getHandleValue((BasicDBObject) iterator.next()); handles.add(Handle.cast((String) handle.get("handle"), value)); } return handles; }
From source file:org.springframework.data.mongodb.microbenchmark.MongoResultsWriter.java
License:Apache License
@Override public void write(Collection<RunResult> results) { Date now = new Date(); StandardEnvironment env = new StandardEnvironment(); String projectVersion = env.getProperty("project.version", "unknown"); String gitBranch = env.getProperty("git.branch", "unknown"); String gitDirty = env.getProperty("git.dirty", "no"); String gitCommitId = env.getProperty("git.commit.id", "unknown"); MongoClientURI uri = new MongoClientURI(this.uri); MongoClient client = new MongoClient(uri); String dbName = StringUtils.hasText(uri.getDatabase()) ? uri.getDatabase() : "spring-data-mongodb-benchmarks"; MongoDatabase db = client.getDatabase(dbName); for (BasicDBObject dbo : (List<BasicDBObject>) JSON.parse(ResultsWriter.jsonifyResults(results))) { String collectionName = extractClass(dbo.get("benchmark").toString()); Document sink = new Document(); sink.append("_version", projectVersion); sink.append("_branch", gitBranch); sink.append("_commit", gitCommitId); sink.append("_dirty", gitDirty); sink.append("_method", extractBenchmarkName(dbo.get("benchmark").toString())); sink.append("_date", now); sink.append("_snapshot", projectVersion.toLowerCase().contains("snapshot")); sink.putAll(dbo);/* w w w . ja va 2 s .com*/ db.getCollection(collectionName).insertOne(fixDocumentKeys(sink)); } client.close(); }
From source file:org.springframework.integration.mongodb.metadata.MongoDbMetadataStore.java
License:Apache License
/** * If the specified key is not already associated with a value, associate it with the given value. * This is equivalent to//from w ww . j av a 2s .c o m * <pre> {@code * if (!map.containsKey(key)) * return map.put(key, value); * else * return map.get(key); * }</pre> * except that the action is performed atomically. * <p> * Performs the {@code stored} JavaScript function. * @param key the metadata entry key * @param value the metadata entry value to store * @return null if successful, the old value otherwise. * @see java.util.concurrent.ConcurrentMap#putIfAbsent(Object, Object) * @see ScriptOperations#call(String, Object...) */ @Override public String putIfAbsent(String key, String value) { Assert.hasText(key, "'key' must not be empty."); Assert.hasText(value, "'value' must not be empty."); if (!this.scriptInitialized) { synchronized (this) { if (!this.scriptInitialized) { this.scriptOperations .register(new NamedMongoScript(PUT_IF_ABSENT_SCRIPT_NAME, PUT_IF_ABSENT_FUNCTION)); this.scriptInitialized = true; } } } BasicDBObject result = (BasicDBObject) this.scriptOperations.call(PUT_IF_ABSENT_SCRIPT_NAME, this.collectionName, key, value); return (result == null) ? null : (String) result.get(VALUE); }
From source file:org.teiid.translator.mongodb.MongoDBExecutionFactory.java
License:Open Source License
/** * @param field/*from ww w. ja va 2 s. co m*/ * @param expectedClass * @return * @throws TranslatorException */ public Object retrieveValue(Object value, Class<?> expectedClass, DB mongoDB, String fqn, String colName) throws TranslatorException { if (value == null) { return null; } if (value.getClass().equals(expectedClass)) { return value; } if (value instanceof DBRef) { Object obj = ((DBRef) value).getId(); if (obj instanceof BasicDBObject) { BasicDBObject bdb = (BasicDBObject) obj; return bdb.get(colName); } return obj; } else if (value instanceof java.util.Date && expectedClass.equals(java.sql.Date.class)) { return new java.sql.Date(((java.util.Date) value).getTime()); } else if (value instanceof java.util.Date && expectedClass.equals(java.sql.Timestamp.class)) { return new java.sql.Timestamp(((java.util.Date) value).getTime()); } else if (value instanceof java.util.Date && expectedClass.equals(java.sql.Time.class)) { return new java.sql.Time(((java.util.Date) value).getTime()); } else if (value instanceof String && expectedClass.equals(BigDecimal.class)) { return new BigDecimal((String) value); } else if (value instanceof String && expectedClass.equals(BigInteger.class)) { return new BigInteger((String) value); } else if (value instanceof String && expectedClass.equals(Character.class)) { return new Character(((String) value).charAt(0)); } else if (value instanceof String && expectedClass.equals(BinaryType.class)) { return new BinaryType(((String) value).getBytes()); } else if (value instanceof String && expectedClass.equals(Blob.class)) { GridFS gfs = new GridFS(mongoDB, fqn); final GridFSDBFile resource = gfs.findOne((String) value); if (resource == null) { return null; } return new BlobImpl(new InputStreamFactory() { @Override public InputStream getInputStream() throws IOException { return resource.getInputStream(); } }); } else if (value instanceof String && expectedClass.equals(Clob.class)) { GridFS gfs = new GridFS(mongoDB, fqn); final GridFSDBFile resource = gfs.findOne((String) value); if (resource == null) { return null; } return new ClobImpl(new InputStreamFactory() { @Override public InputStream getInputStream() throws IOException { return resource.getInputStream(); } }, -1); } else if (value instanceof String && expectedClass.equals(SQLXML.class)) { GridFS gfs = new GridFS(mongoDB, fqn); final GridFSDBFile resource = gfs.findOne((String) value); if (resource == null) { return null; } return new SQLXMLImpl(new InputStreamFactory() { @Override public InputStream getInputStream() throws IOException { return resource.getInputStream(); } }); } else if (value instanceof BasicDBList) { BasicDBList arrayValues = (BasicDBList) value; //array if (expectedClass.isArray() && !(arrayValues.get(0) instanceof BasicDBObject)) { Class arrayType = expectedClass.getComponentType(); Object array = Array.newInstance(arrayType, arrayValues.size()); for (int i = 0; i < arrayValues.size(); i++) { Object arrayItem = retrieveValue(arrayValues.get(i), arrayType, mongoDB, fqn, colName); Array.set(array, i, arrayItem); } value = array; } } else if (value instanceof org.bson.types.ObjectId) { org.bson.types.ObjectId id = (org.bson.types.ObjectId) value; value = id.toStringBabble(); } else { Transform transform = DataTypeManager.getTransform(value.getClass(), expectedClass); if (transform != null) { try { value = transform.transform(value, expectedClass); } catch (TransformationException e) { throw new TranslatorException(e); } } } return value; }
From source file:org.teiid.translator.mongodb.MongoDBMetadataProcessor.java
License:Open Source License
private Table addTable(MetadataFactory metadataFactory, String tableName, BasicDBObject row) { if (metadataFactory.getSchema().getTable(tableName) != null) { Table t = metadataFactory.getSchema().getTable(tableName); return t; }/*from w w w .ja va 2 s . c o m*/ Table table = metadataFactory.addTable(tableName); table.setSupportsUpdate(true); for (String columnKey : row.keySet()) { Object value = row.get(columnKey); Column column = addColumn(metadataFactory, table, columnKey, value); if (column != null) { column.setUpdatable(true); } } return table; }
From source file:org.teiid.translator.mongodb.MongoDBMetadataProcessor.java
License:Open Source License
private Column addColumn(MetadataFactory metadataFactory, Table table, String columnKey, Object value) { Column column = null;/*w ww. ja v a 2 s . co m*/ if (columnKey.equals(ID)) { if (value instanceof BasicDBObject) { BasicDBObject compositeKey = (BasicDBObject) value; for (String key : compositeKey.keySet()) { column = addColumn(metadataFactory, table, key, compositeKey.get(key)); column.setUpdatable(true); } } } if (!columnKey.equals(ID) && value instanceof BasicDBObject) { // embedded doc - one to one Table childTable = addTable(metadataFactory, columnKey, (BasicDBObject) value); childTable.setProperty(MERGE, table.getName()); childTable.setProperty(ASSOSIATION, MergeDetails.Association.ONE.name()); } else if (value instanceof BasicDBList) { // embedded doc, list one to many if (((BasicDBList) value).get(0) instanceof BasicDBObject) { Table childTable = addTable(metadataFactory, columnKey, (BasicDBObject) ((BasicDBList) value).get(0)); childTable.setProperty(MERGE, table.getName()); childTable.setProperty(ASSOSIATION, MergeDetails.Association.MANY.name()); } else { column = metadataFactory.addColumn(columnKey, TypeFacility.RUNTIME_NAMES.OBJECT + "[]", table); //$NON-NLS-1$ column.setSearchType(SearchType.Unsearchable); } } else if (value instanceof DBRef) { Object obj = ((DBRef) value).getId(); column = addColumn(metadataFactory, table, columnKey, obj); String ref = ((DBRef) value).getRef(); metadataFactory.addForiegnKey("FK_" + columnKey, Arrays.asList(columnKey), ref, table); //$NON-NLS-1$ } else { column = metadataFactory.addColumn(columnKey, getDataType(value), table); } // create a PK out of _id if (columnKey.equals(ID)) { if (value instanceof BasicDBObject) { BasicDBObject compositeKey = (BasicDBObject) value; ArrayList<String> columns = new ArrayList<String>(); for (String key : compositeKey.keySet()) { columns.add(key); } metadataFactory.addPrimaryKey("PK0", columns, table); //$NON-NLS-1$ } else { metadataFactory.addPrimaryKey("PK0", Arrays.asList(ID), table); //$NON-NLS-1$ } } return column; }
From source file:org.teiid.translator.mongodb.MongoDBSelectVisitor.java
License:Open Source License
@Override public void visit(DerivedColumn obj) { Expression teiidExpression = obj.getExpression(); String alias = getAlias(obj.getAlias()); this.processingDerivedColumn = true; append(teiidExpression);//from www. j a v a 2s . co m Object mongoExpression = this.onGoingExpression.pop(); ColumnDetail exprDetails = this.expressionMap.get(mongoExpression); if (exprDetails == null) { exprDetails = new ColumnDetail(); exprDetails.addProjectedName(alias); this.expressionMap.put(mongoExpression, exprDetails); } // the the expression is already part of group by then the projection should be $_id.{name} this.selectColumns.add(alias); if (exprDetails.partOfGroupBy) { BasicDBObject id = this.groupByProjections.get("_id"); //$NON-NLS-1$ this.project.append(alias, id.get(exprDetails.getProjectedName())); exprDetails.addProjectedName(alias); this.selectColumnReferences.add(alias); } else { exprDetails.addProjectedName(alias); exprDetails.partOfProject = true; if (teiidExpression instanceof ColumnReference) { String elementName = getColumnName((ColumnReference) obj.getExpression()); this.selectColumnReferences.add(elementName); // the the expression is already part of group by then the projection should be $_id.{name} if (this.command.isDistinct() || this.groupByProjections.get(alias) != null) { // this is DISTINCT case this.project.append(alias, "$_id." + alias); //$NON-NLS-1$ // if group by does not exist then build the group root id based on distinct this.group.put(alias, mongoExpression); } else { this.project.append(alias, mongoExpression); } } else { implicitProject(teiidExpression, mongoExpression, exprDetails, alias); // what user sees as project this.selectColumnReferences.add(alias); } } this.processingDerivedColumn = false; }
From source file:org.teiid.translator.mongodb.MongoDBUpdateExecution.java
License:Open Source License
private void buildUpdate(MongoDocument doc, DBCollection collection, BasicDBObject row, List<String> parentKeys, int level, RowInfo rowInfo, List<WriteResult> executionResults, UpdateOperation operation) throws TranslatorException { String parentKeyName = parentKeys.get(level); boolean top = parentKeyName.equals(doc.getTargetDocument().getQualifiedName(false)); Object parentBlock = row.get(top ? "_id" : parentKeyName); //$NON-NLS-1$ // the parent-child must have been one-2-one relationship if (parentBlock == null) { parentBlock = rowInfo.PK;// w ww.j av a 2s. c o m } String mergeTableName = doc.getTable().getName(); if (parentKeys.size() != (level + 1)) { mergeTableName = parentKeys.get(level + 1); } if (parentBlock instanceof BasicDBList) { // so parent is an array document BasicDBList parentRows = (BasicDBList) parentBlock; //parentRows = (BasicDBList)((BasicDBObject)parentRows.get(0)).get("_id"); //$NON-NLS-1$ for (int i = 0; i < parentRows.size(); i++) { RowInfo info = RowInfo.build(parentKeyName, mergeTableName, parentRows.get(i), i, rowInfo); if (parentKeys.size() == (level + 1)) { String aliasDocumentName = doc.getQualifiedName(false).replace('.', '_'); BasicDBList dataRows = (BasicDBList) row.get(aliasDocumentName); if (dataRows != null && dataRows.size() > i) { operation.execute(doc, collection, row, (DBObject) dataRows.get(i), info, executionResults); } } else { buildUpdate(doc, collection, row, parentKeys, level + 1, info, executionResults, operation); } } } else { // here the _id is same as parent RowInfo info = RowInfo.build(parentKeyName, mergeTableName, parentBlock, -1, rowInfo); if (parentKeys.size() == (level + 1)) { //Leaf, no more down String aliasDocumentName = doc.getQualifiedName(false).replace('.', '_'); DBObject dataRows = (DBObject) row.get(aliasDocumentName); if (dataRows != null) { operation.execute(doc, collection, row, dataRows, info, executionResults); } } else { buildUpdate(doc, collection, row, parentKeys, level + 1, info, executionResults, operation); } } }
From source file:org.unitedid.shibboleth.attribute.resolver.provider.dataConnector.MongoDbDataConnector.java
License:Apache License
/** * Process the result from the query and return a list of resolved attributes * * @param result the result from the query * @return a list of resolved attributes * @throws AttributeResolutionException if an error occurs when reading the mongo db result */// w ww . j a v a 2 s.c om protected Map<String, BaseAttribute> processCollectionResult(DBObject result) throws AttributeResolutionException { Map<String, BaseAttribute> attributes = new HashMap<String, BaseAttribute>(); try { MongoDbKeyAttributeMapper keyAttributeMapper; BaseAttribute attribute; if (result != null) { for (String keyName : result.keySet()) { log.debug("Processing mongodb key: {} class: {}", keyName, result.get(keyName).getClass()); List<MongoDbKeyAttributeMapper> keyChildMap = null; keyAttributeMapper = keyAttributeMap.get(keyName); attribute = getAttribute(attributes, keyAttributeMapper, keyName); if (keyAttributeMapper != null) { keyChildMap = keyAttributeMapper.getChildKeyAttributeMaps(); } if (keyChildMap != null && keyChildMap.size() > 0) { BasicDBObject dataMap = (BasicDBObject) result.get(keyName); for (MongoDbKeyAttributeMapper map : keyChildMap) { attribute = getAttribute(attributes, map, map.getAttributeName()); attribute.getValues().add(dataMap.get(map.getMongoKey())); attributes.put(attribute.getId(), attribute); } } else if (result.get(keyName) instanceof com.mongodb.BasicDBList) { log.debug("Processing BasicDBList for {}.", keyName); BasicDBList res = (BasicDBList) result.get(keyName); List<String> resultList = new ArrayList<String>(); for (Object s : res) { if (s instanceof BasicDBObject) { log.error("BasicDBObjects in embedded lists not supported"); continue; } resultList.add((String) s); } attribute.getValues().addAll(resultList); attributes.put(attribute.getId(), attribute); } else { attribute.getValues().add(result.get(keyName)); attributes.put(attribute.getId(), attribute); } } } } catch (MongoException e) { log.error("Problem processing result {}:", getId(), e); throw new AttributeResolutionException("Problem processing result " + getId() + ":", e); } log.debug("MongoDb data connector {} attribute result: {}", getId(), attributes.keySet()); return attributes; }