Example usage for org.json.simple JSONValue toJSONString

List of usage examples for org.json.simple JSONValue toJSONString

Introduction

In this page you can find the example usage for org.json.simple JSONValue toJSONString.

Prototype

public static String toJSONString(Object value) 

Source Link

Usage

From source file:com.mobicage.rogerthat.plugins.friends.ActionScreenActivity.java

private void deliverResult(String requestId, Map<String, Object> result, Map<String, Object> error) {
    executeJS(false, "if (typeof rogerthat !== 'undefined') rogerthat._setResult('%s', %s, %s)", requestId,
            JSONValue.toJSONString(result), JSONValue.toJSONString(error));
}

From source file:com.mobicage.rogerthat.plugins.messaging.MessagingPlugin.java

public void startLocalFlow(final StartFlowRequest startFlow) {
    T.UI();/*w ww  .  j a  va  2s. c om*/
    FlowStartedRequestTO request = new FlowStartedRequestTO();
    request.thread_key = startFlow.thread_key;
    request.service = startFlow.service;
    request.static_flow_hash = startFlow.static_flow_hash;

    Map<String, Object> userInput = new HashMap<String, Object>();
    userInput.put("request", request.toJSONMap());
    userInput.put("func", "com.mobicage.api.messaging.jsmfr.flowStarted");

    Map<String, Object> tmpState = new HashMap<String, Object>();
    tmpState.put("message_flow_run_id", startFlow.message_flow_run_id);
    MessageFlowRun mfr = new MessageFlowRun();
    mfr.staticFlowHash = startFlow.static_flow_hash;
    mfr.state = JSONValue.toJSONString(tmpState);

    try {
        JsMfr.executeMfr(mfr, userInput, mMainService, false);
    } catch (EmptyStaticFlowException ex) {
        L.bug(ex);
    }
}

From source file:com.mobicage.rogerthat.plugins.messaging.MessagingPlugin.java

public void putSendMessageRequest(final String tmpKey, final SendMessageRequestTO request) {
    T.UI();/*  w w  w  . j av a 2s.com*/
    Configuration cfg = new Configuration();
    cfg.put(tmpKey, JSONValue.toJSONString(request.toJSONMap()));
    mConfigProvider.updateConfigurationNow(TRANSFER_PHOTO_UPLOAD_SEND_MESSAGE_CONFIGKEY, cfg);
}

From source file:com.mobicage.rogerthat.plugins.messaging.MessagingPlugin.java

public void setTransferCompleted(final String parentMessageKey, final String messageKey, String resultUrl) {
    T.BIZZ();//ww w .j a  va 2 s. co m
    if (isTmpKey(messageKey)) {
        Configuration cfg = mConfigProvider.getConfiguration(TRANSFER_PHOTO_UPLOAD_SEND_MESSAGE_CONFIGKEY);

        String serializedMessageRequest = cfg.get(messageKey, "");
        if ("".equals(serializedMessageRequest)) {
            L.bug("Could not find SendMessageRequestTO " + messageKey);
        } else {
            transferQueueDelete(messageKey);
            @SuppressWarnings("unchecked")
            Map<String, Object> jsonMap = (Map<String, Object>) JSONValue.parse(serializedMessageRequest);
            SendMessageRequestTO request;
            try {
                request = new SendMessageRequestTO(jsonMap);
            } catch (IncompleteMessageException e1) {
                L.bug(e1);
                return;
            }

            String tmpDownloadUrlHash = attachmentDownloadUrlHash(request.attachments[0].download_url);
            String downloadUrlHash = attachmentDownloadUrlHash(resultUrl);
            String tmpMessageKey = messageKey.replace(MessagingPlugin.TMP_KEY_PREFIX, "");
            File attachmentsDir;
            try {
                attachmentsDir = attachmentsDir(parentMessageKey == null ? tmpMessageKey : parentMessageKey,
                        tmpMessageKey);
            } catch (IOException e) {
                L.d("Unable to create attachment directory", e);
                UIUtils.showAlertDialog(mMainService, "", R.string.unable_to_read_write_sd_card);
                return;
            }

            File tmpAttachmentFile = new File(attachmentsDir, tmpDownloadUrlHash);
            File dstAttachmentFile = new File(attachmentsDir, downloadUrlHash);
            tmpAttachmentFile.renameTo(dstAttachmentFile);

            File tmpThumbnailFile = new File(tmpAttachmentFile.getAbsoluteFile() + ".thumb");
            if (tmpThumbnailFile.exists()) {
                File dstThumbnailFile = new File(dstAttachmentFile.getAbsoluteFile() + ".thumb");
                tmpThumbnailFile.renameTo(dstThumbnailFile);
            }

            request.attachments[0].download_url = resultUrl;

            final FriendsPlugin friendsPlugin = mMainService.getPlugin(FriendsPlugin.class);
            try {
                SendMessageWizardActivity.sendMessage(request, parentMessageKey, messageKey, friendsPlugin,
                        this, mMainService);
            } catch (Exception e) {
                L.bug("Failed to send message after transfer was complete", e);
            }
        }

    } else {
        Message message = mStore.getFullMessageByKey(messageKey);
        if (message != null && message.form != null) {
            if (Widget.TYPE_PHOTO_UPLOAD.equals(message.form.get("type"))) {
                final SubmitPhotoUploadFormRequestTO request = new SubmitPhotoUploadFormRequestTO();
                request.timestamp = message.members[0].acked_timestamp;
                request.button_id = message.members[0].button_id;
                request.message_key = messageKey;
                request.parent_message_key = parentMessageKey;
                if (Message.POSITIVE.equals(request.button_id)) {
                    request.result = new UnicodeWidgetResultTO();
                    request.result.value = resultUrl;
                }
                boolean isSentByJSMFR = (message.flags & FLAG_SENT_BY_JSMFR) == FLAG_SENT_BY_JSMFR;

                transferQueueDelete(messageKey);
                if (UIUtils.getTopActivity(mMainService) instanceof ServiceMessageDetailActivity) {
                    // Send an Intent to ServiceMessageDetailActivity so it can hide the processing dialog
                    final Intent iSubmitPhotoUploadForm = new Intent(
                            ServiceMessageDetailActivity.class.getName());
                    iSubmitPhotoUploadForm.putExtra("threadKey",
                            parentMessageKey == null ? messageKey : parentMessageKey);
                    iSubmitPhotoUploadForm.putExtra("message_key", messageKey);
                    iSubmitPhotoUploadForm.setAction(MessagingPlugin.MESSAGE_SUBMIT_PHOTO_UPLOAD);
                    if (isSentByJSMFR) {
                        iSubmitPhotoUploadForm.putExtra("submitToJSMFR",
                                JSONValue.toJSONString(request.toJSONMap()));
                    }
                    mMainService.sendBroadcast(iSubmitPhotoUploadForm);
                    L.d("------------------------------------------------------------");
                    L.d("ServiceMessageDetailActivity on top");
                    L.d("------------------------------------------------------------");
                } else {
                    L.d("------------------------------------------------------------");
                    L.d("ServiceMessageDetailActivity NOT on top");
                    L.d("------------------------------------------------------------");

                    if (isSentByJSMFR) {
                        mMainService.postOnUIHandler(new SafeRunnable() {
                            @Override
                            protected void safeRun() throws Exception {
                                // TODO read from db
                                JSONObject json = jsmfrTransferCompletedLoad();
                                // TODO add current message
                                JSONObject transfer = new JSONObject();
                                try {
                                    transfer.put("threadKey",
                                            parentMessageKey == null ? messageKey : parentMessageKey);
                                    transfer.put("submitToJSMFR", JSONValue.toJSONString(request.toJSONMap()));
                                    json.put(messageKey, transfer);
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                // TODO save to db
                                jsmfrTransferCompletedSave(json);

                                String n_message = mMainService
                                        .getString(R.string.transfer_complete_notification);
                                String title = mMainService
                                        .getString(R.string.transfer_complete_notification_title);
                                int notificationId = R.integer.transfer_complete_continue;
                                boolean withSound = false;
                                boolean withVibration = true;
                                boolean withLight = false;
                                boolean autoCancel = false;
                                int icon = R.drawable.notification_icon;
                                int notificationNumber = 0;
                                Bundle b = new Bundle();
                                b.putString("threadKey",
                                        parentMessageKey == null ? messageKey : parentMessageKey);
                                b.putString("message_key", messageKey);
                                b.putBoolean("submitToJSMFR", true);
                                String tickerText = null;
                                long timestamp = mMainService.currentTimeMillis();

                                UIUtils.doNotification(mMainService, title, n_message, notificationId,
                                        MainActivity.ACTION_NOTIFICATION_PHOTO_UPLOAD_DONE, withSound,
                                        withVibration, withLight, autoCancel, icon, notificationNumber, b,
                                        tickerText, timestamp);
                            }
                        });
                    }
                }

                if (!isSentByJSMFR) {
                    try {
                        Rpc.submitPhotoUploadForm(new ResponseHandler<SubmitPhotoUploadFormResponseTO>(),
                                request);
                    } catch (Exception e) {
                        L.e("Sending the submitPhotoUploadForm failed.", e);
                    }
                }
            }
        }
    }
}

From source file:com.mobicage.rpc.config.LookAndFeelConstants.java

public static void saveDynamicLookAndFeel(Context context, LookAndFeelTO request) {
    try {/* w ww.jav a2 s.  c  o m*/
        setup(context, request);
        File file = lookAndFeelSettingsFile(context);
        if (request == null) {
            if (file.exists()) {
                Boolean fileDeleted = file.delete();
                L.d("settings.json deleted:" + fileDeleted);
            }
        } else {
            SystemUtils.writeStringToFile(file, JSONValue.toJSONString(request.toJSONMap()));
        }
    } catch (Exception e) {
        L.bug("Failed to saveDynamicLookAndFeel", e);
        setup(context, null);
    }
}

From source file:net.xpresstek.zroster.web.UploadController.java

public void upload() {
    progress = 0;//from ww  w . ja va2 s. c  o  m
    HashMap hm = new HashMap();
    hm.put("user", getDb_user());
    hm.put("password", getDb_pass());
    List l1 = new LinkedList();

    ShiftController sc = ShiftControllerConverter.getController();
    List<Shift> shifts = sc.getItemsFromTwoWeeks();
    progress = 10;
    for (Shift s : shifts) {

        if (s.getEmployeeObject() != null && s.getPositionObject() != null && s.getStart() != null
                && s.getEnd() != null) {
            Map map = new HashMap();
            map.put("employee", s.getEmployeeObject().getName());
            map.put("position", s.getPositionObject().getName());
            map.put("start", DateUtils.DateToString(s.getStart()));
            map.put("end", DateUtils.DateToString(s.getEnd()));
            l1.add(map);
        }
    }
    progress = 20;
    hm.put("data", JSONValue.toJSONString(l1));
    progress = 50;
    try {
        response = HttpUtil.sendPost(hm, getUrl());
        progress = 100;
    } catch (Exception ex) {
        Logger.getLogger(UploadController.class.getName()).log(Level.SEVERE, null, ex);
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Upload Failed", "Upload Failed"));
        error = true;
    } finally {
        url = null;
        db_user = null;
        db_pass = null;
        error = false;
    }
}

From source file:nl.utwente.bigdata.spouts.WorldcupDataJsonSpout.java

@Override
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
    try {// ww w  .  j a v a  2 s .c o m
        System.out.println("Reading worldcup-data");
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(getClass().getClassLoader().getResourceAsStream("worldcup-games.json")));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null)
            sb.append(line);
        JSONParser parser = new JSONParser();
        JSONArray collection = (JSONArray) parser.parse(sb.toString());
        Iterator iter = collection.iterator();
        while (iter.hasNext()) {
            JSONObject entry = (JSONObject) iter.next();
            matches.add(JSONValue.toJSONString(entry));
            //    System.out.println(JSONValue.toJSONString( entry ));
        }
        reader.close();
        System.out.println("Reading done");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    _collector = collector;
    _rand = new Random();
}

From source file:oncue.backingstore.RedisBackingStore.java

/**
 * Persist a job as a hash in Redis/*from w  w w.  ja  v a  2 s .co  m*/
 * 
 * @param job
 *            is the {@linkplain Job} to persist
 * @param queueName
 *            is the name of the queue to push the job onto
 * @param redis
 *            is a connection to Redis
 */
public static void persistJob(Job job, String queueName, Jedis redis) {

    // Persist the job in a transaction
    Transaction transaction = redis.multi();

    // Create a map describing the job
    String jobKey = String.format(JOB_KEY, job.getId());
    transaction.hset(jobKey, JOB_ENQUEUED_AT, job.getEnqueuedAt().toString());

    if (job.getStartedAt() != null)
        transaction.hset(jobKey, JOB_STARTED_AT, job.getStartedAt().toString());

    if (job.getCompletedAt() != null)
        transaction.hset(jobKey, JOB_COMPLETED_AT, job.getCompletedAt().toString());

    transaction.hset(jobKey, JOB_WORKER_TYPE, job.getWorkerType());
    transaction.hset(jobKey, JOB_RERUN_STATUS, Boolean.toString(job.isRerun()));

    if (job.getParams() != null)
        transaction.hset(jobKey, JOB_PARAMS, JSONValue.toJSONString(job.getParams()));

    if (job.getState() != null)
        transaction.hset(jobKey, JOB_STATE, job.getState().toString());

    transaction.hset(jobKey, JOB_PROGRESS, String.valueOf(job.getProgress()));

    if (job.getErrorMessage() != null)
        transaction.hset(jobKey, JOB_ERROR_MESSAGE, job.getErrorMessage());

    // Add the job to the specified queue
    transaction.lpush(queueName, Long.toString(job.getId()));

    // Exec the transaction
    transaction.exec();
}

From source file:org.apache.eagle.app.environment.impl.StormSubmitter.java

/**
 * Submits a topology to run on the cluster. A topology runs forever or until
 * explicitly killed./*  w  w w .  j  av a2 s  .  co  m*/
 *
 *
 * @param name the name of the storm.
 * @param stormConf the topology-specific configuration. See {@link Config}.
 * @param topology the processing to execute.
 * @param opts to manipulate the starting of the topology
 * @param progressListener to track the progress of the jar upload process
 * @throws AlreadyAliveException if a topology with this name is already running
 * @throws InvalidTopologyException if an invalid topology was submitted
 */
public static void submitTopology(String name, Map stormConf, StormTopology topology, SubmitOptions opts,
        ProgressListener progressListener) throws AlreadyAliveException, InvalidTopologyException {
    if (!Utils.isValidConf(stormConf)) {
        throw new IllegalArgumentException("Storm conf is not valid. Must be json-serializable");
    }
    stormConf = new HashMap(stormConf);
    stormConf.putAll(Utils.readCommandLineOpts());
    Map conf = Utils.readStormConfig();
    conf.putAll(stormConf);
    try {
        String serConf = JSONValue.toJSONString(stormConf);
        if (localNimbus != null) {
            LOG.info("Submitting topology " + name + " in local mode");
            localNimbus.submitTopology(name, null, serConf, topology);
        } else {
            NimbusClient client = NimbusClient.getConfiguredClient(conf);
            if (topologyNameExists(conf, name)) {
                throw new RuntimeException("Topology with name `" + name + "` already exists on cluster");
            }
            submitJar(conf, progressListener);
            try {
                LOG.info("Submitting topology " + name + " in distributed mode with conf " + serConf);
                if (opts != null) {
                    client.getClient().submitTopologyWithOpts(name, submittedJar, serConf, topology, opts);
                } else {
                    // this is for backwards compatibility
                    client.getClient().submitTopology(name, submittedJar, serConf, topology);
                }
            } catch (InvalidTopologyException e) {
                LOG.warn("Topology submission exception: " + e.get_msg());
                throw e;
            } catch (AlreadyAliveException e) {
                LOG.warn("Topology already alive exception", e);
                throw e;
            } finally {
                client.close();
            }
        }
        LOG.info("Finished submitting topology: " + name);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.falcon.metadata.LineageRecorder.java

/**
 * this method is invoked from with in the workflow.
 *
 * @param lineageMetadata metadata to persist
 * @param lineageFile file to serialize the metadata
 * @throws IOException/*from w ww.  j  a  v  a2 s  .c  o  m*/
 * @throws FalconException
 */
protected void persistLineageMetadata(Map<String, String> lineageMetadata, String lineageFile)
        throws IOException, FalconException {
    OutputStream out = null;
    Path file = new Path(lineageFile);
    try {
        FileSystem fs = HadoopClientFactory.get().createFileSystem(file.toUri(), getConf());
        out = fs.create(file);

        // making sure falcon can read this file
        FsPermission permission = new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL);
        fs.setPermission(file, permission);

        out.write(JSONValue.toJSONString(lineageMetadata).getBytes());
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ignore) {
                // ignore
            }
        }
    }
}