org.bson.BSON Java Examples

The following examples show how to use org.bson.BSON. 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: NonReactiveAggregateQueryProvider.java    From mongodb-aggregate-query-support with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the serialized value to be used for the given {@link ParameterBinding}.
 *
 * @param accessor - the accessor
 * @param binding  - the binding
 * @return - the value of the parameter
 */
@SuppressWarnings("Duplicates")
private String getParameterValueForBinding(ConvertingParameterAccessor accessor, ParameterBinding binding) {

  Object value = accessor.getBindableValue(binding.getParameterIndex());

  if (value instanceof String && binding.isQuoted()) {
    return (String) value;
  }
  else if (value instanceof byte[]) {

    String base64representation = Base64.encode((byte[]) value);
    if (!binding.isQuoted()) {
      return "{ '$binary' : '" + base64representation + "', '$type' : " + BSON.B_GENERAL + "}";
    }

    return base64representation;
  }

  return serialize(value);
}
 
Example #2
Source File: AggregateQueryProvider.java    From mongodb-aggregate-query-support with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the serialized value to be used for the given {@link ParameterBinding}.
 *
 * @param accessor - the accessor
 * @param binding  - the binding
 * @return - the value of the parameter
 */
@SuppressWarnings("Duplicates")
private String getParameterValueForBinding(ConvertingParameterAccessor accessor, ParameterBinding binding) {

  Object value = accessor.getBindableValue(binding.getParameterIndex());

  if (value instanceof String && binding.isQuoted()) {
    return (String) value;
  }
  else if (value instanceof byte[]) {

    String base64representation = Base64.encode((byte[]) value);
    if (!binding.isQuoted()) {
      return "{ '$binary' : '" + base64representation + "', '$type' : " + BSON.B_GENERAL + "}";
    }

    return base64representation;
  }

  return serialize(value);
}
 
Example #3
Source File: ExternalServiceHandler.java    From lumongo with Apache License 2.0 6 votes vote down vote up
@Override
public void store(StoreRequest request, StreamObserver<StoreResponse> responseObserver) {
	try {
		responseObserver.onNext(indexManger.storeDocument(request));
		responseObserver.onCompleted();
	}
	catch (Exception e) {
		log.error("Failed to store: <" + request.getUniqueId() + "> in index <" + request.getIndexName() + ">: " + e.getClass().getSimpleName() + ": ", e);
		Metadata m = new Metadata();
		m.put(MetaKeys.ERROR_KEY, e.getMessage());
		responseObserver.onError(new StatusRuntimeException(Status.UNKNOWN, m));

		if (request.hasResultDocument()) {
			try {
				if (request.getResultDocument().hasDocument()) {
					BasicBSONObject document = (BasicBSONObject) BSON.decode(request.getResultDocument().getDocument().toByteArray());
					log.error(document.toString());
				}
			}
			catch (Exception e2) {

			}
		}

	}
}
 
Example #4
Source File: MongoDocumentStorage.java    From lumongo with Apache License 2.0 5 votes vote down vote up
@Override
public Lumongo.ResultDocument getSourceDocument(String uniqueId, FetchType fetchType) throws Exception {
	if (!FetchType.NONE.equals(fetchType)) {
		MongoDatabase db = mongoClient.getDatabase(database);
		MongoCollection<Document> coll = db.getCollection(rawCollectionName);
		Document search = new Document(MongoConstants.StandardFields._ID, uniqueId);

		Document result = coll.find(search).first();

		if (null != result) {

			long timestamp = (long) result.remove(TIMESTAMP);

			ResultDocument.Builder dBuilder = ResultDocument.newBuilder();
			dBuilder.setUniqueId(uniqueId);
			dBuilder.setTimestamp(timestamp);

			if (result.containsKey(METADATA)) {
				Document metadata = (Document) result.remove(METADATA);
				for (String key : metadata.keySet()) {
					dBuilder.addMetadata(Metadata.newBuilder().setKey(key).setValue((String) metadata.get(key)));
				}
			}

			if (FetchType.FULL.equals(fetchType)) {
				BasicDBObject resultObj = new BasicDBObject();
				resultObj.putAll(result);

				ByteString document = ByteString.copyFrom(BSON.encode(resultObj));
				dBuilder.setDocument(document);

			}

			dBuilder.setIndexName(indexName);

			return dBuilder.build();
		}
	}
	return null;
}
 
Example #5
Source File: MDbResultSetMetaData.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private int doGetColumnType( int index ) throws OdaException
{
    FieldMetaData columnMD = getColumnMetaData( index );
    if( columnMD == null )         // unknown
           return BSON.STRING;        // use default data type
    
    if( columnMD.hasDocumentDataType() ) 
        return columnMD.getPreferredNativeDataType( m_isAutoFlattening );

    // a child field from a nested document
       if( columnMD.isDescendantOfArrayField() )
       {
           // If Flatten Nested Collections data set property == "false", i.e.
           // nested array's field values will be concatenated into a single String value in a result set column,
           // flattening of nested array of array (with scalar values) is not supported either, and 
           // will be concatenated into a single String value as well.
           if( ! m_isAutoFlattening || columnMD.isArrayOfScalarValues() )
               return BSON.STRING;

           // flattening of nested collection is supported for only one such field in a document,
           // and is tracked in containing DocumentsMetaData
           String arrayAncestorName = columnMD.getArrayAncestorName();
           if( arrayAncestorName != null && ! isFlattenableNestedField( columnMD ) )
               return BSON.STRING;
       }
       else if( columnMD.isArrayOfScalarValues() ) // top-level array of scalar values
       {
           // if no flattening, or already flattening another field,
           // this array of scalar values will be concatenated to a String value
           if( ! m_isAutoFlattening )
               return BSON.STRING;
           String flattenableFieldName = m_docsMetaData.getFlattenableFieldName();
           if( flattenableFieldName != null && 
                   ! flattenableFieldName.equals( columnMD.getFullName() ))
               return BSON.STRING;
       }
    
    // return own native data type
    return columnMD.getPreferredNativeDataType( m_isAutoFlattening );
}
 
Example #6
Source File: MDbMetaData.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
private void addDataType( Object fieldValue )
     {
         // add the data type of given fieldValue to existing set, if exists;
         // the same named field set in a different doc may have a different data type 
         byte nativeBSonDataTypeCode = Bytes.getType( fieldValue );
         if( m_nativeDataTypes == null )
             m_nativeDataTypes = new HashSet<Integer>(2);
if ( nativeBSonDataTypeCode == -1 )
{
	if ( fieldValue instanceof Document )
	{
		nativeBSonDataTypeCode = Bytes.OBJECT;
	}
}
         m_nativeDataTypes.add( Integer.valueOf( nativeBSonDataTypeCode ) );

         // check if field value contains a document,
         // iteratively get field document's nested metadata
         if( nativeBSonDataTypeCode == BSON.ARRAY )
         {
             if( fieldValue instanceof java.util.List )
             {
                 java.util.List<?> listOfObjects = (java.util.List<?>)fieldValue;
                 if( listOfObjects.size() > 0 )
                 {
                     // use first element in array to determine metadata
                     addDataType( listOfObjects.get(0) );    // handles nested arrays
                     return;
                 }
             }
         }

         Object fieldObjValue = 
                 ResultDataHandler.fetchFieldDocument( fieldValue, nativeBSonDataTypeCode );
         
         if( fieldObjValue != null ) // contains nested document
         {
             if( m_childDocMetaData == null )
                 m_childDocMetaData = sm_factory.new DocumentsMetaData();
             m_childDocMetaData.addDocumentMetaData( fieldObjValue, this );
         }
     }
 
Example #7
Source File: ResultDataHandler.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
static Object fetchFieldDocument( Object fieldValue )
{
    return fetchFieldDocument( fieldValue, BSON.UNDEFINED );
}
 
Example #8
Source File: MongoIdConverter.java    From secure-data-service with Apache License 2.0 3 votes vote down vote up
/**
 * Converts the given UUID into a Binary object that represents the underlying byte array in
 * Mongo. This is recommended by the mongo docs
 * to store UUIDs.
 *
 * @param uid
 *            The object's UUID
 * @return a Binary representation of the given UUID.
 */

public static Binary convertUUIDtoBinary(UUID uuid) {

    ByteBuffer buff = ByteBuffer.allocate(16);
    buff.putLong(uuid.getMostSignificantBits());
    buff.putLong(uuid.getLeastSignificantBits());
    byte[] arr = buff.array();

    Binary binary = new Binary(BSON.B_UUID, arr);

    return binary;
}
 
Example #9
Source File: MongoIdConverter.java    From secure-data-service with Apache License 2.0 3 votes vote down vote up
/**
 * Converts the given UUID into a Binary object that represents the underlying byte array in
 * Mongo. This is recommended by the mongo docs to store UUIDs.
 * 
 * @param uid
 *            The object's UUID
 * @return a Binary representation of the given UUID.
 */

public static Binary convertUUIDtoBinary(UUID uuid) {
    
    ByteBuffer buff = ByteBuffer.allocate(16);
    buff.putLong(uuid.getMostSignificantBits());
    buff.putLong(uuid.getLeastSignificantBits());
    byte[] arr = buff.array();
    
    Binary binary = new Binary(BSON.B_UUID, arr);
    
    return binary;
}