Example usage for com.mongodb.util JSON parse

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

Introduction

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

Prototype

public static Object parse(final String jsonString) 

Source Link

Document

Parses a JSON string and returns a corresponding Java object.

Usage

From source file:com.groupon.jenkins.mongo.MongoDataLoadRule.java

License:Open Source License

@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {
        @Override/*from www  .  ja  va 2 s.  com*/
        public void evaluate() throws Throwable {
            if (Jenkins.getInstance() == null || SetupConfig.get().getInjector() == null
                    || SetupConfig.get().getInjector().getInstance(Datastore.class) == null) {
                throw new IllegalStateException("Requires configured Jenkins and Mongo configurations");
            }

            DB db = SetupConfig.get().getInjector().getInstance(Datastore.class).getDB();

            //Load mongo data
            File homedir = Jenkins.getInstance().getRootDir();

            for (File fileOfData : homedir.listFiles()) {
                if (!fileOfData.getName().endsWith(".json"))
                    continue;

                String collectionName = fileOfData.getName().replaceAll("\\.json$", "");
                DBCollection collection = db.createCollection(collectionName, new BasicDBObject());

                String data = FileUtils.readFileToString(fileOfData);
                Object bsonObject = JSON.parse(data);
                if (bsonObject instanceof BasicDBList) {
                    BasicDBList basicDBList = (BasicDBList) bsonObject;
                    collection.insert(basicDBList.toArray(new DBObject[0]));
                } else {
                    collection.insert((DBObject) bsonObject);
                }

            }

            for (OrganizationContainer container : Jenkins.getInstance()
                    .getAllItems(OrganizationContainer.class)) {
                container.reloadItems();
            }

            base.evaluate();

            // Clean up mongo data
            for (String collectioName : db.getCollectionNames()) {
                db.getCollection(collectioName).drop();
            }
        }
    };
}

From source file:com.hangum.tadpole.mongodb.core.composite.result.MongodbResultComposite.java

License:Open Source License

/**
 * /*from   w ww  .jav a2 s  .  c  om*/
 */
private void find() {

    final Display display = getDisplay();
    // job
    Job job = new Job("SQL execute job") { //$NON-NLS-1$
        @Override
        public IStatus run(IProgressMonitor monitor) {
            monitor.beginTask("Starting JSON query...", IProgressMonitor.UNKNOWN); //$NON-NLS-1$

            try {
                // field               
                BasicDBObject basicFields = (BasicDBObject) JSON.parse(strBasicField);
                if (null == basicFields)
                    basicFields = new BasicDBObject();

                // search
                DBObject basicWhere = (DBObject) JSON.parse(strBasicFind);
                if (null == basicWhere)
                    basicWhere = new BasicDBObject();

                // sort
                BasicDBObject basicSort = (BasicDBObject) JSON.parse(strBasicSort);
                if (null == basicSort)
                    basicSort = new BasicDBObject();

                if (logger.isDebugEnabled()) {
                    logger.debug("############[text condition]#####################"); //$NON-NLS-1$
                    logger.debug("[Fields]" + strBasicField); //$NON-NLS-1$
                    logger.debug("[Find]" + strBasicFind); //$NON-NLS-1$
                    logger.debug("[Sort]" + strBasicSort); //$NON-NLS-1$
                    logger.debug("############[text condition]#####################"); //$NON-NLS-1$
                }
                monitor.setTaskName(basicWhere.toString());

                // console 
                sbConsoleErrorMsg.setLength(0);
                sbConsoleExecuteMsg.setLength(0);

                // 
                find(basicFields, basicWhere, basicSort, cntSkip, cntLimit);
            } catch (Exception e) {
                logger.error("find basic collection exception", e); //$NON-NLS-1$
                return new Status(Status.ERROR, Activator.PLUGIN_ID, "findBasic " + e.getMessage()); //$NON-NLS-1$
            } finally {
                monitor.done();
            }

            return Status.OK_STATUS;
        }
    };

    // job? event  ?.
    job.addJobChangeListener(new JobChangeAdapter() {
        public void done(IJobChangeEvent event) {

            final IJobChangeEvent jobEvent = event;

            display.asyncExec(new Runnable() {
                public void run() {
                    if (jobEvent.getResult().isOK()) {
                        setResult();
                    } else {
                        sbConsoleErrorMsg.append(jobEvent.getResult().getMessage());
                        appendMessage(jobEvent.getResult().getMessage());
                    }
                }
            }); // end display.asyncExec            
        } // end done
    }); // end job

    job.setName(userDB.getDisplay_name());
    job.setUser(true);
    job.schedule();
}

From source file:com.hangum.tadpole.mongodb.core.composite.result.MongodbResultComposite.java

License:Open Source License

/**
 * error console/*from  www. j  a va  2 s . com*/
 */
public void consoleError() {
    DBObject dbObject = (DBObject) JSON.parse(sbConsoleErrorMsg.toString());
    FindOneDetailDialog dlg = new FindOneDetailDialog(null, userDB,
            collectionName + " " + Messages.MongodbResultComposite_25, dbObject);
    dlg.open();
}

From source file:com.hangum.tadpole.mongodb.core.composite.result.MongodbResultComposite.java

License:Open Source License

/**
 * execute plan console//  w  w w.j  a  v a  2  s.  co  m
 */
public void consoleExecutePlan() {
    DBObject dbObject = (DBObject) JSON.parse(sbConsoleExecuteMsg.toString());
    FindOneDetailDialog dlg = new FindOneDetailDialog(null, userDB,
            collectionName + " " + Messages.MongodbResultComposite_26, dbObject);
    dlg.open();
}

From source file:com.hangum.tadpole.mongodb.core.dialogs.collection.FindAndModifyDialog.java

License:Open Source License

@Override
protected void okPressed() {
    if (!MessageDialog.openConfirm(null, "Confirm", "Are you want to execute?"))
        return;// ww w  .ja va  2 s  . c o m
    DBObject objQuery = null;
    DBObject objFields = null;
    DBObject objSort = null;
    DBObject objUpdate = null;

    try {
        objQuery = "".equals(textQuery.getText()) ? null : (DBObject) JSON.parse(textQuery.getText());
    } catch (Exception e) {
        textQuery.setFocus();
        MessageDialog.openError(null, "Error",
                e.getMessage() + PublicTadpoleDefine.LINE_SEPARATOR + "{Query} is error.");
        return;
    }

    try {
        objFields = "".equals(textFields.getText()) ? null : (DBObject) JSON.parse(textFields.getText());
    } catch (Exception e) {
        textFields.setFocus();
        MessageDialog.openError(null, "Error",
                e.getMessage() + PublicTadpoleDefine.LINE_SEPARATOR + "{Field} is error.");
        return;
    }

    try {
        objSort = "".equals(textSort.getText()) ? null : (DBObject) JSON.parse(textSort.getText());
    } catch (Exception e) {
        textSort.setFocus();
        MessageDialog.openError(null, "Error",
                e.getMessage() + PublicTadpoleDefine.LINE_SEPARATOR + "{Sort} is error.");
        return;
    }

    try {
        objUpdate = "".equals(textUpdate.getText()) ? null : (DBObject) JSON.parse(textUpdate.getText());
    } catch (Exception e) {
        textUpdate.setFocus();
        MessageDialog.openError(null, "Error",
                e.getMessage() + PublicTadpoleDefine.LINE_SEPARATOR + "{Update} is error.");
        return;
    }

    try {
        DBObject retDBObj = MongoDBQuery.findAndModify(userDB, collName, objQuery, objSort, objFields,
                btnRemove.getSelection(), objUpdate, btnReturnNew.getSelection(), btnUpsert.getSelection());
        if (null != retDBObj) {
            FindOneDetailDialog resultViewDialog = new FindOneDetailDialog(null, userDB,
                    "Update Result Message", retDBObj);
            resultViewDialog.open();
        } else
            MessageDialog.openInformation(null, "Result", "Result message is null");

    } catch (Exception e) {
        logger.error("mongodb FindAndModify", e); //$NON-NLS-1$
        Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); //$NON-NLS-1$
        ExceptionDetailsErrorDialog.openError(null, "Error", "FindAndModify Exception", errStatus); //$NON-NLS-1$ //$NON-NLS-2$
    }
}

From source file:com.hangum.tadpole.mongodb.core.editors.group.MongoDBGroupEditor.java

License:Open Source License

private void search() throws Exception {
    final DBCollection dbCol = MongoDBQuery.findCollection(userDB, initColName);

    final DBObject dbObjectKey = (DBObject) JSON.parse(textKeys.getText());
    final DBObject dbObjectInitial = (DBObject) JSON.parse(textInitialValue.getText());
    final DBObject dbObjectCondition = (DBObject) JSON.parse(textQuery.getText());

    final String strReductFunction = textReduceFunction.getText();
    final String strFinalize = textFinalizeFunction.getText();

    // search job
    Job job = new Job("Group Search job") { //$NON-NLS-1$
        @Override//from  www .ja va2s .c om
        public IStatus run(IProgressMonitor monitor) {
            monitor.beginTask("Starting JSON query...", IProgressMonitor.UNKNOWN); //$NON-NLS-1$
            try {
                resultDBObject = dbCol.group(dbObjectKey, dbObjectCondition, dbObjectInitial, strReductFunction,
                        strFinalize);

            } catch (Exception e) {
                logger.error("Group exception", e); //$NON-NLS-1$
                return new Status(Status.WARNING, Activator.PLUGIN_ID, "Group " + e.getMessage()); //$NON-NLS-1$
            } finally {
                monitor.done();
            }

            return Status.OK_STATUS;
        }
    };

    // job? event  ?.
    job.addJobChangeListener(new JobChangeAdapter() {
        public void done(IJobChangeEvent event) {

            final IJobChangeEvent jobEvent = event;
            getSite().getShell().getDisplay().asyncExec(new Runnable() {
                public void run() {
                    if (jobEvent.getResult().isOK()) {
                        try {
                            compositeResult.refreshDBView(resultDBObject, 0);
                            compositeResult.setResult();
                        } catch (Exception e) {
                            logger.error("MapReduce Error", e); //$NON-NLS-1$
                            Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(),
                                    e); //$NON-NLS-1$
                            ExceptionDetailsErrorDialog.openError(null, "Error", "MapReduce execute exception", //$NON-NLS-1$//$NON-NLS-2$
                                    errStatus);
                        }
                    } else {
                        //                     compositeResult.errorView(jobEvent.getResult().getMessage());
                    }
                }
            }); // end display.asyncExec            
        } // end done
    }); // end job

    job.setName(userDB.getDisplay_name());
    job.setUser(true);
    job.schedule();

}

From source file:com.hangum.tadpole.mongodb.core.editors.main.MongoDBTableEditor.java

License:Open Source License

/**
 *  //from  ww w .  j a  v a  2 s  .co  m
 */
public void findBasic() {
    final String strBasicField = textBasicField.getText().trim();
    final String strBasicFind = textBasicFind.getText().trim();
    final String strBasicSort = textBasicSort.getText().trim();
    final int cntSkip = getCntSkip();
    final int cntLimit = getCntLimit();

    // job
    Job job = new Job("SQL execute job") { //$NON-NLS-1$
        @Override
        public IStatus run(IProgressMonitor monitor) {
            monitor.beginTask("Starting JSON query...", IProgressMonitor.UNKNOWN); //$NON-NLS-1$

            try {
                // field               
                BasicDBObject basicFields = (BasicDBObject) JSON.parse(strBasicField);
                if (null == basicFields)
                    basicFields = new BasicDBObject();

                // search
                DBObject basicWhere = (DBObject) JSON.parse(strBasicFind);
                if (null == basicWhere)
                    basicWhere = new BasicDBObject();

                // sort
                BasicDBObject basicSort = (BasicDBObject) JSON.parse(strBasicSort);
                if (null == basicSort)
                    basicSort = new BasicDBObject();

                if (logger.isDebugEnabled()) {
                    logger.debug("############[text condition]#####################"); //$NON-NLS-1$
                    logger.debug("[Fields]" + strBasicField); //$NON-NLS-1$
                    logger.debug("[Find]" + strBasicFind); //$NON-NLS-1$
                    logger.debug("[Sort]" + strBasicSort); //$NON-NLS-1$
                    logger.debug("############[text condition]#####################"); //$NON-NLS-1$
                }
                monitor.setTaskName(basicWhere.toString());

                // console 
                sbConsoleMsg.setLength(0);
                // 
                find(basicFields, basicWhere, basicSort, cntSkip, cntLimit);
            } catch (Exception e) {
                logger.error("find basic collection exception", e); //$NON-NLS-1$
                return new Status(Status.WARNING, Activator.PLUGIN_ID, "findBasic " + e.getMessage()); //$NON-NLS-1$
            } finally {
                monitor.done();
            }

            return Status.OK_STATUS;
        }
    };

    // job? event  ?.
    job.addJobChangeListener(new JobChangeAdapter() {
        public void done(IJobChangeEvent event) {

            final IJobChangeEvent jobEvent = event;
            getSite().getShell().getDisplay().asyncExec(new Runnable() {
                public void run() {
                    if (jobEvent.getResult().isOK()) {
                        compositeResult.setResult(txtCnt, mapColumns, listTrees, sourceDataList);
                    } else {
                        sbConsoleMsg.append(jobEvent.getResult().getMessage());
                        compositeResult.appendMessage(jobEvent.getResult().getMessage());
                    }
                }
            }); // end display.asyncExec            
        } // end done
    }); // end job

    job.setName(userDB.getDisplay_name());
    job.setUser(true);
    job.schedule();
}

From source file:com.hangum.tadpole.mongodb.core.editors.mapreduce.MapReduceEditor.java

License:Open Source License

/**
 * execute map reduce//from w  w  w . jav  a 2 s  .  c  o m
 */
private void executeMapReduce() throws Exception {
    String strMap = textMap.getText();
    String strReduce = textReduce.getText();
    String strFinilize = textFinalize.getText();
    String strOutputTarget = textOutputTarget.getText();
    MapReduceCommand.OutputType outputType = (MapReduceCommand.OutputType) comboOutputType
            .getData(comboOutputType.getText());

    DBObject dbQuery = null;
    if (!"".equals(textQuery.getText()))
        dbQuery = (DBObject) JSON.parse(textQuery.getText());

    DBObject dbSort = null;
    if (!"".equals(textSort.getText()))
        dbSort = (DBObject) JSON.parse(textSort.getText());

    //  .
    DBCollection dbCol = MongoDBQuery.findCollection(userDB, initColName);
    MapReduceCommand mrCmd = new MapReduceCommand(dbCol, strMap, strReduce, strOutputTarget, outputType,
            dbQuery);
    if (!"".equals(strFinilize))
        mrCmd.setFinalize(strFinilize);
    if (dbSort != null)
        mrCmd.setSort(dbSort);
    if (getLimit() > 0)
        mrCmd.setLimit(getLimit());
    if (btnJsMode.getSelection())
        mrCmd.addExtraOption("jsMode", true);

    final BasicDBObject searchObj = (BasicDBObject) mrCmd.toDBObject();
    if (btnSharded.getSelection())
        ((BasicDBObject) searchObj.get("out")).put("sharded", true);
    if (btnNoneAtomic.getSelection())
        ((BasicDBObject) searchObj.get("out")).put("nonAtomic", true);

    goMapReduce(dbCol, searchObj, outputType);
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * Execute command/*from   ww w. j av  a 2s  .  c  o m*/
 * 
 * @param userDB
 * @param cmd
 * @return
 * @throws Exception
 */
public static CommandResult runCommand(UserDBDAO userDB, String cmd) throws Exception {
    DB mongoDB = MongoConnectionManager.getInstance(userDB);

    DBObject cmdObj = (DBObject) JSON.parse(cmd);
    return mongoDB.command(cmdObj);
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * collection ?.//  w w  w  . j a v a 2s . c o  m
 * 
 * @param userDB
 * @param colName
 * @param jsonStr
 * @throws Exception
 */
public static void createCollection(UserDBDAO userDB, String colName, String jsonStr) throws Exception {
    DB mongoDB = MongoConnectionManager.getInstance(userDB);

    DBObject dbObject = (DBObject) JSON.parse(jsonStr);
    mongoDB.createCollection(colName, dbObject);
}