Java Code Examples for com.mongodb.util.JSON#serialize()

The following examples show how to use com.mongodb.util.JSON#serialize() . 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: RascalMetricsTest.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private JSONArray getJSONArrayFromDump(File dump) {
	try {
		JSONArray result = new JSONArray(); 
		InputStream is = new FileInputStream(dump);
		BSONDecoder decoder = new BasicBSONDecoder();

		while(is.available() > 0) {
			BSONObject obj = decoder.readObject(is);
			if(obj == null) {
				break;
			}
			else {
				JSONObject json = new JSONObject(JSON.serialize(obj));
				result.put(json);
			}
		}
		is.close();
		return result;
	}
	catch(IOException e) {
		System.out.println("We got an error when parsing a BSON file: " + e);
		return null;
	}
}
 
Example 2
Source File: RascalMetricsTest.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private JSONArray getJSONArrayFromDB(String db, String col) {
	try {
		JSONArray result = new JSONArray(); 
		DBCollection collection = mongo.getDB(db).getCollectionFromString(col);
		DBCursor cursor = collection.find();

		while(cursor.hasNext()) {
			DBObject obj = cursor.next();
			JSONObject json = new JSONObject(JSON.serialize(obj));
			result.put(json);
		}
		return result;
	}
	catch(Exception e) {
		System.out.println("We got an error when creating a JSONArray: " + e);
		return null;
	}
}
 
Example 3
Source File: FeedResource.java    From hvdf with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{feed}/{channel}/data")
public String pushToChannel(
        @PathParam("feed") String feedId,
        @PathParam("channel") String channelId,
        @QueryParam("sample") JSONParam sample ) {

    // Find the correct channel implementation
	Channel channel = channelService.getChannel(feedId, channelId);
	    	
    // push it to the channel correct
	DBObject sampleObj = sample.toDBObject();
	
	BasicDBList sid = new BasicDBList();
	channel.pushSample(sampleObj, sampleObj instanceof BasicDBList, sid);
    
    // return the ID
    return JSON.serialize(sid);
}
 
Example 4
Source File: MongoDBEntityStoreMixin.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public Reader get( EntityReference entityReference )
    throws EntityStoreException
{
    MongoCursor<Document> cursor = db.getCollection( collectionName )
                                     .find( byIdentity( entityReference ) )
                                     .limit( 1 ).iterator();
    if( !cursor.hasNext() )
    {
        throw new EntityNotFoundException( entityReference );
    }
    Document bsonState = (Document) cursor.next().get( STATE_COLUMN );
    String jsonState = JSON.serialize( bsonState );
    return new StringReader( jsonState );
}
 
Example 5
Source File: ItemsMetadata.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public void save() {

    try {
      if (!itemsMetadataFile.exists()) {
        itemsMetadataFile.getParentFile().mkdirs();
        itemsMetadataFile.createNewFile();
      }
      try (PrintWriter writer = new PrintWriter(itemsMetadataFile)) {
        String content = JSON.serialize(itemsMetadata);
        writer.print(content);
      }
    } catch (IOException e) {
      log.error("Exception writing metadata file", e);
    }
  }
 
Example 6
Source File: QueryProperties.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public String serialize()
{
    Map<String, Object> definedPropsMap = copyNonDefaultProperties( getPropertiesMap() );

    // convert property values not serializable by BSON serializer
    externalizePropValues( definedPropsMap );

    return JSON.serialize( definedPropsMap );
}
 
Example 7
Source File: MongoService.java    From BLELocalization with MIT License 4 votes vote down vote up
public void sendCSV(Object obj, HttpServletRequest request, HttpServletResponse response) throws IOException {
	// TODO Auto-generated method stub
	boolean gzip = false;
	if (request != null) {
		String acceptedEncodings = request.getHeader("accept-encoding");
		gzip = acceptedEncodings != null && acceptedEncodings.indexOf("gzip") != -1;
	}
	response.setCharacterEncoding("UTF-8");
	response.setContentType("text/plain");
	
	if (obj instanceof WriteResult) {
		String error = ((WriteResult) obj).getError();
		if (error != null) {
			obj = error;
		} else {
			obj = "OK";
		}
	}
	
	OutputStream os = null;
	try {
		String json = JSON.serialize(obj);
		ByteArrayInputStream in = new ByteArrayInputStream(json.getBytes("utf-8"));
		List<Sample> samples = DataUtils.readJSONSamples(in);
		byte data[] = Sample.samplesToCSVString(samples).getBytes("UTF-8");
		
		os = response.getOutputStream();
		if (gzip && data.length >= 860) {
			response.setHeader("Content-Encoding", "gzip");
			GZIPOutputStream gzos = new GZIPOutputStream(os);
			gzos.write(data);
			gzos.finish();
			gzos.close();
		} else {
			os.write(data);
		}
	} catch (Exception e) {
		e.printStackTrace();
		response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
	} finally {
		if (os != null) {
			os.close();
		}
	}
}
 
Example 8
Source File: MapDBObject.java    From gameserver with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
	return JSON.serialize(this.delegateMap);
}
 
Example 9
Source File: MongoDbInput.java    From pentaho-mongodb-plugin with Apache License 2.0 4 votes vote down vote up
@Override public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException {
  try {
    if ( meta.getExecuteForEachIncomingRow() && m_currentInputRowDrivingQuery == null ) {
      m_currentInputRowDrivingQuery = getRow();

      if ( m_currentInputRowDrivingQuery == null ) {
        // no more input, no more queries to make
        setOutputDone();
        return false;
      }

      if ( !first ) {
        initQuery();
      }
    }

    if ( first ) {
      data.outputRowMeta = new RowMeta();
      meta.getFields( data.outputRowMeta, getStepname(), null, null, MongoDbInput.this );

      initQuery();
      first = false;

      data.init();
    }

    boolean
        hasNext =
        ( ( meta.getQueryIsPipeline() ? data.m_pipelineResult.hasNext() : data.cursor.hasNext() ) && !isStopped() );
    if ( hasNext ) {
      DBObject nextDoc = null;
      Object[] row = null;
      if ( meta.getQueryIsPipeline() ) {
        nextDoc = data.m_pipelineResult.next();
      } else {
        nextDoc = data.cursor.next();
      }

      if ( !meta.getQueryIsPipeline() && !m_serverDetermined ) {
        ServerAddress s = data.cursor.getServerAddress();
        if ( s != null ) {
          m_serverDetermined = true;
          logBasic(
              BaseMessages.getString( PKG, "MongoDbInput.Message.QueryPulledDataFrom", s.toString() ) ); //$NON-NLS-1$
        }
      }

      if ( meta.getOutputJson() || meta.getMongoFields() == null || meta.getMongoFields().size() == 0 ) {
        String json = JSON.serialize( nextDoc );
        row = RowDataUtil.allocateRowData( data.outputRowMeta.size() );
        int index = 0;

        row[index++] = json;
        putRow( data.outputRowMeta, row );
      } else {
        Object[][] outputRows = data.mongoDocumentToKettle( nextDoc, MongoDbInput.this );

        // there may be more than one row if the paths contain an array
        // unwind
        for ( int i = 0; i < outputRows.length; i++ ) {
          putRow( data.outputRowMeta, outputRows[i] );
        }
      }
    } else {
      if ( !meta.getExecuteForEachIncomingRow() ) {
        setOutputDone();

        return false;
      } else {
        m_currentInputRowDrivingQuery = null; // finished with this row
      }
    }

    return true;
  } catch ( Exception e ) {
    if ( e instanceof KettleException ) {
      throw (KettleException) e;
    } else {
      throw new KettleException( e ); //$NON-NLS-1$
    }
  }
}
 
Example 10
Source File: ExtractorImpl.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
private String toJSON(Entity record) {
    return JSON.serialize(record.getBody());
}