Example usage for com.mongodb.util JSON serialize

List of usage examples for com.mongodb.util JSON serialize

Introduction

In this page you can find the example usage for com.mongodb.util JSON serialize.

Prototype

public static String serialize(final Object object) 

Source Link

Document

Serializes an object into its JSON form.

This method delegates serialization to JSONSerializers.getLegacy

Usage

From source file:org.mule.module.mongo.MongoCloudConnector.java

License:Open Source License

/**
 * Convert a BasicBSONList into Json.// w  w  w  . j a va2  s. c om
 * <p/>
 * {@sample.xml ../../../doc/mongo-connector.xml.sample mongo:mongoCollectionToJson}
 * 
 * @param input the input for this transformer
 * @return the converted string representation
 */
@Mime(MimeTypes.JSON)
@Transformer(sourceTypes = { MongoCollection.class })
public static String mongoCollectionToJson(final MongoCollection input) {
    return JSON.serialize(input);
}

From source file:org.mule.modules.morphia.MorphiaConnector.java

License:Open Source License

/**
 * Transform a Morphia object into JSON/*from  w  w  w .j  a  v a 2  s  .  c o  m*/
 * <p/>
 * {@sample.xml ../../../doc/mule-module-morphia.xml.sample morphia:object-to-json}
 *
 * @param object Object to transform
 * @param username the username to use in case authentication is required
 * @param password the password to use in case authentication is required, null
 *                 if no authentication is desired
 * @param host     The host of the Mongo server. If the host is part of a replica set then you can specify all the hosts
 *                 separated by comma.
 * @param port     The port of the Mongo server
 * @param database The database name of the Mongo server
 * @return A string containing JSON
 * @throws IOException if there is an exception
 * @throws ExecutionException if there is a connectivity problem
 */
@Processor
@Mime(MimeTypes.JSON)
public String objectToJson(@Optional @Default("#[payload]") Object object, @Optional String username,
        @Optional @Password String password, @Optional String host, @Optional Integer port,
        @Optional String database) throws IOException, ExecutionException {
    Datastore datastore = getDatastore(username, password, database, host, port);

    if (isListClass(object.getClass())) {
        if (((List) object).size() == 0) {
            throw new IllegalArgumentException("The list is empty");
        }
        if (datastore.getMapper().isMapped(((List) object).get(0).getClass())) {
            List originalList = (List) object;
            LinkedList<DBObject> dbObjectList = new LinkedList<DBObject>();
            for (Object innerObject : originalList) {
                dbObjectList.addLast(datastore.getMapper().toDBObject(innerObject));
            }
            return JSON.serialize(dbObjectList);
        } else if (((List) object).get(0) instanceof Key) {
            List originalList = (List) object;
            JsonFactory jsonFactory = new JsonFactory();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(outputStream);
            jsonGenerator.writeStartArray();
            for (Object innerObject : originalList) {
                Key keyObject = (Key) innerObject;
                ObjectId id = (ObjectId) keyObject.getId();
                jsonGenerator.writeString(id.toStringMongod());
            }
            jsonGenerator.writeEndArray();
            jsonGenerator.flush();
            return new String(outputStream.toByteArray());
        } else {
            throw new IllegalArgumentException(
                    ((List) object).get(0).getClass().getName() + " is not a Morphia-mapped type");
        }
    } else if (datastore.getMapper().isMapped(object.getClass())) {
        return JSON.serialize(datastore.getMapper().toDBObject(object));
    } else if (object instanceof Key) {
        JsonFactory jsonFactory = new JsonFactory();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(outputStream);
        Key keyObject = (Key) object;
        ObjectId id = (ObjectId) keyObject.getId();
        jsonGenerator.writeString(id.toStringMongod());
        jsonGenerator.flush();
        return new String(outputStream.toByteArray());
    } else {
        throw new IllegalArgumentException(object.getClass().getName() + " is not a Morphia-mapped type");
    }
}

From source file:org.netbeans.modules.mongodb.ui.components.QueryEditor.java

License:Open Source License

private void setEditorValue(JEditorPane editor, DBObject value) {
    final String text = value != null ? Json.prettify(JSON.serialize(value)) : "{}";
    editor.setText(text);/* ww  w. j  a  v a2  s .  co  m*/
}

From source file:org.netbeans.modules.mongodb.ui.native_tools.MongoDumpOptionsPanel.java

License:Open Source License

private void editQueryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editQueryButtonActionPerformed
    final DBObject dbObject = JsonUI.showEditor(Bundle.queryEditorTitle(), queryField.getText());
    if (dbObject != null) {
        queryField.setText(JSON.serialize(dbObject));
    }/*  ww w.  j  a va 2s. com*/
}

From source file:org.netbeans.modules.mongodb.ui.native_tools.MongoRestoreOptionsPanel.java

License:Open Source License

private void editFilterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editFilterButtonActionPerformed
    final DBObject dbObject = JsonUI.showEditor(Bundle.filterEditorTitle(), filterField.getText());
    if (dbObject != null) {
        filterField.setText(JSON.serialize(dbObject));
    }/*w w w.  j  ava  2s. com*/
}

From source file:org.netbeans.modules.mongodb.ui.windows.collectionview.actions.CopyDocumentToClipboardAction.java

License:Open Source License

@Override
public StringSelection convertToStringSelection(DBObject dbObject) {
    return new StringSelection(JSON.serialize(dbObject));
}

From source file:org.netbeans.modules.mongodb.ui.windows.collectionview.actions.CopyValueToClipboardAction.java

License:Open Source License

private String convertToString(Object value) {
    if (value instanceof Map) {
        return JSON.serialize(new BasicDBObject((Map) value));
    }//from   www.  jav a2 s  . c  om
    return value.toString();
}

From source file:org.netbeans.modules.mongodb.ui.windows.collectionview.actions.EditSelectedDocumentAction.java

License:Open Source License

@Override
public void actionPerformed(ActionEvent e) {
    final DBObject document = getView().getResultTableSelectedDocument();
    final DBObject modifiedDocument = JsonUI.showEditor(Bundle.editDocumentTitle(), JSON.serialize(document));
    if (modifiedDocument != null) {
        try {/*from w  ww . j a v a 2  s.  co m*/
            final DBCollection dbCollection = getView().getLookup().lookup(DBCollection.class);
            dbCollection.save(modifiedDocument);
            getView().refreshResults();
        } catch (MongoException ex) {
            DialogDisplayer.getDefault().notify(
                    new NotifyDescriptor.Message(ex.getLocalizedMessage(), NotifyDescriptor.ERROR_MESSAGE));
        }
    }
}

From source file:org.netbeans.modules.mongodb.util.Exporter.java

License:Open Source License

private void export(Writer writer) {
    final PrintWriter output = new PrintWriter(writer);
    final DBCollection collection = db.getCollection(properties.getCollection());
    final DBCursor cursor = collection.find(properties.getCriteria(), properties.getProjection());
    if (properties.getSort() != null) {
        cursor.sort(properties.getSort());
    }/*  w w  w .  ja va2 s  .c  om*/
    if (properties.isJsonArray()) {
        output.print("[");
    }
    boolean first = true;
    for (DBObject document : cursor) {
        if (Thread.interrupted()) {
            return;
        }
        if (first) {
            first = false;
        } else if (properties.isJsonArray()) {
            output.print(",");
        }
        final String json = JSON.serialize(document);
        output.print(json);
        if (properties.isJsonArray() == false) {
            output.println();
        }
        output.flush();
    }
    if (properties.isJsonArray()) {
        output.println("]");
    }
    output.flush();
}

From source file:org.pentaho.di.trans.steps.mongodbupdate.MongoDbUpdate.java

License:Open Source License

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    Object[] row = getRow();// w  w w.  j  av  a  2  s. c o  m

    if (row == null) {
        setOutputDone();
        return false;
    }
    if (first) {
        first = false;
        data.fieldNumber = meta.getFieldNames().length;
        data.fieldIndexes = new int[data.fieldNumber];
        for (int i = 0; i < data.fieldNumber; i++) {
            data.fieldIndexes[i] = getInputRowMeta().indexOfValue(meta.getFieldNames()[i]);
            if (data.fieldIndexes[i] < 0) {
                logError(BaseMessages.getString(PKG, "MongoDbUpdate.Log.CanNotFindField",
                        meta.getFieldNames()[i]));
                throw new KettleException(BaseMessages.getString(PKG, "MongoDbUpdate.Log.CanNotFindField",
                        meta.getFieldNames()[i]));
            }
        }
    }
    String firstPrefix;
    String secondPrefix;
    boolean noContainer = false;
    if (meta.getContainerObjectName() == null)
        meta.setContinerObjectName("");
    if (meta.getContainerObjectName().length() == 0) {
        firstPrefix = "";
        secondPrefix = "";
        meta.setArrayFlag(false);
        noContainer = true;
    } else {
        firstPrefix = meta.getContainerObjectName() + ".";
        secondPrefix = meta.getContainerObjectName() + (meta.getArrayFlag() ? ".$." : ".");
    }
    DBObject globalQueryObj = new BasicDBObject();
    globalQueryObj.putAll(data.primaryQuery);
    DBObject queryObj = new BasicDBObject();
    DBObject updateInnerObj = new BasicDBObject();
    DBObject rowImageObj = new BasicDBObject();
    for (int i = 0; i < data.fieldNumber; i++) {
        String fieldvalue = getInputRowMeta().getString(row, data.fieldIndexes[i]);
        switch (meta.getTrimType()) {
        case 0:
            break;
        case 1:
            fieldvalue = Const.ltrim(fieldvalue);
            break;
        case 2:
            fieldvalue = Const.rtrim(fieldvalue);
            break;
        case 3:
            fieldvalue = Const.trim(fieldvalue);
            break;
        }
        if (meta.getKeyFieldFlags()[i]) {
            queryObj.put(firstPrefix + meta.getJSONNames()[i], fieldvalue);
        } else {
            updateInnerObj.put(secondPrefix + meta.getJSONNames()[i], fieldvalue);
        }
        rowImageObj.put(meta.getJSONNames()[i], fieldvalue);
    }
    globalQueryObj.putAll(queryObj);
    boolean insert = false;
    if (meta.getInsertIfNotPresentFlag() && (data.collection.count(globalQueryObj) == 0)) {
        insert = true;
    }
    if (insert) {
        if (noContainer) {
            data.collection.insert(rowImageObj);
            if (getLogLevel().isDebug()) {
                logDebug(BaseMessages.getString(PKG, "MongoDbUpdate.Log.DocumentInsert",
                        JSON.serialize(rowImageObj)));
            }
        } else if (meta.getArrayFlag()) {
            DBObject updateObj = new BasicDBObject();
            updateObj.put("$push", new BasicDBObject(meta.getContainerObjectName(), rowImageObj));
            data.collection.updateMulti(data.primaryQuery, updateObj);
            if (getLogLevel().isDebug()) {
                logDebug(BaseMessages.getString(PKG, "MongoDbUpdate.Log.DocumentPushed",
                        JSON.serialize(data.primaryQuery), JSON.serialize(updateObj)));
            }
        } else {
            DBObject updateObj = new BasicDBObject();
            updateObj.put("$set", new BasicDBObject(meta.getContainerObjectName(), rowImageObj));
            data.collection.updateMulti(data.primaryQuery, updateObj);
            if (getLogLevel().isDebug()) {
                logDebug(BaseMessages.getString(PKG, "MongoDbUpdate.Log.InsertIntoDocument"),
                        JSON.serialize(data.primaryQuery), JSON.serialize(updateObj));
            }
        }

    } else {
        DBObject updateObj = new BasicDBObject();
        updateObj.put("$set", updateInnerObj);
        data.collection.updateMulti(globalQueryObj, updateObj);
        if (getLogLevel().isDebug()) {
            logDebug(BaseMessages.getString(PKG, "MongoDbUpdate.Log.DocumentUpdated",
                    JSON.serialize(globalQueryObj), JSON.serialize(updateObj)));
        }
    }
    putRow(getInputRowMeta(), row);
    return true;
}