Example usage for org.json JSONObject toString

List of usage examples for org.json JSONObject toString

Introduction

In this page you can find the example usage for org.json JSONObject toString.

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONObject.

Usage

From source file:com.cloverstudio.spika.couchdb.ConnectionHandler.java

public static String getError(JSONObject jsonObject) {

    String error = "Unknown Spika Error: ";

    if (jsonObject.has("message")) {
        try {/*from   ww  w  .ja v a 2  s .co  m*/
            error = jsonObject.getString("message");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        error += jsonObject.toString();
    }
    return error;
}

From source file:com.microsoft.activitytracker.Classes.Utils.java

/**
 * Formats the date and then creates a json object using the activity information
 * and returns it in string form to be inserted directly into the body of a request
 * @param subject the string from the subject edittext
 * @param date the date that was entered in the date picker
 * @param notes the string from the notes edittext
 * @return returns the activity in a json string
 *//*from ww w  .  j  ava  2  s  . c om*/
public static String getSerializedCheckIn(String subject, Date date, String notes) {
    JSONObject checkin = new JSONObject();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

    try {
        checkin.put("Subject", subject);
        checkin.put("ActualEnd", format.format(date));
        checkin.put("Description", notes);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return checkin.toString();
}

From source file:org.enderstone.server.packet.status.PacketInRequest.java

@Override
public void onRecieve(NetworkManager networkManager) {
    int protocol = networkManager.latestHandshakePacket.getProtocol();
    if (!Main.SUPPORTED_PROTOCOLS.contains(protocol)) {
        protocol = Main.DEFAULT_PROTOCOL;
    }/*from  ww  w .  ja v a  2 s  . co m*/
    JSONObject json = new JSONObject();
    json.put("version", new JSONObject().put("name", Main.PROTOCOL_VERSION).put("protocol", protocol));
    json.put("players", new JSONObject().put("max", Main.getInstance().maxPlayers).put("online",
            Main.getInstance().playerCount));
    json.put("description", Main.getInstance().motd);

    if (Main.getInstance().FAVICON != null) {
        json.put("favicon", Main.getInstance().FAVICON);
    }

    networkManager.sendPacket(new PacketOutResponse(json.toString()));
}

From source file:org.LexGrid.lexevs.metabrowser.helper.ChildPagingJsonConverter.java

public String buildChildrenNodes(MetaTreeNode focusNode) {
    JSONObject json = new JSONObject();
    try {/* w ww  .ja v a 2s  .com*/
        json.put(NODES, buildChildren(focusNode, 1, SUBCHILDREN_LEVELS));
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    return json.toString();
}

From source file:org.LexGrid.lexevs.metabrowser.helper.ChildPagingJsonConverter.java

public String buildChildrenNodes(MetaTreeNode focusNode, int page) {
    JSONObject json = new JSONObject();
    try {/*from  w  w w .  j  a v  a2  s. c  o m*/
        json.put(NODES, buildChildren(focusNode, page, SUBCHILDREN_LEVELS));
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    return json.toString();
}

From source file:com.umeng.community.example.CommunityApplication.java

@Override
public void onCreate() {
    super.onCreate();
    PlatformConfig.setWeixin("wx96110a1e3af63a39", "c60e3d3ff109a5d17013df272df99199");
    //RENREN?????
    //?//from ww  w. ja  v a  2  s .  c  om
    PlatformConfig.setSinaWeibo("275392174", "d96fb6b323c60a42ed9f74bfab1b4f7a");
    PlatformConfig.setQQZone("1104606393", "X4BAsJAVKtkDQ1zQ");
    PushAgent.getInstance(this).setDebugMode(true);
    PushAgent.getInstance(this).setMessageHandler(new UmengMessageHandler() {
        @Override
        public void dealWithNotificationMessage(Context arg0, UMessage msg) {
            // ,????
            super.dealWithNotificationMessage(arg0, msg);
            Log.e("", "### ???");
        }
    });
    PushAgent.getInstance(this).setNotificationClickHandler(new UHandler() {
        @Override
        public void handleMessage(Context context, UMessage uMessage) {
            com.umeng.comm.core.utils.Log.d("notifi", "getting message");
            try {
                JSONObject jsonObject = uMessage.getRaw();
                String feedid = "";
                if (jsonObject != null) {
                    com.umeng.comm.core.utils.Log.d("json", jsonObject.toString());
                    JSONObject extra = uMessage.getRaw().optJSONObject("extra");
                    feedid = extra.optString(Constants.FEED_ID);
                }
                Class myclass = Class.forName(uMessage.activity);
                Intent intent = new Intent(context, myclass);
                Bundle bundle = new Bundle();
                bundle.putString(Constants.FEED_ID, feedid);
                intent.putExtras(bundle);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            } catch (Exception e) {
                com.umeng.comm.core.utils.Log.d("class", e.getMessage());
            }
        }
    });
}

From source file:edu.ucsd.ccdb.cil.xml2json.XML2JsonUtil.java

public String xml2Json(String xml) throws Exception {
    String jsonPrettyPrintString = "";
    try {/*from   w w w . ja  va 2 s.c om*/
        JSONObject xmlJSONObj = XML.toJSONObject(xml);
        jsonPrettyPrintString = xmlJSONObj.toString();
        //System.out.println(jsonPrettyPrintString);
    } catch (JSONException je) {
        System.out.println(je.toString());
    }
    return jsonPrettyPrintString;
}

From source file:io.bitfactory.mobileclimatemonitor.SlackReporter.java

@Background
protected void sendValuesToSlack() {

    if (temperatureValue == 0) {
        return;//from www  .  j av a  2  s .  c o m
    }

    if (humidityValue == 0) {
        return;
    }

    try {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("text",
                Helper.formatTemperature(temperatureValue) + "\n" + Helper.formatHumidity(humidityValue));
        jsonObject.put("channel", slackChannel);
        jsonObject.put("username", slackSenderName);
        jsonObject.put("icon_emoji", ":cubimal_chick:");

        MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

        Request request = new Request.Builder().url(new URL(slackWebhookUrl))
                .post(RequestBody.create(MEDIA_TYPE_JSON, jsonObject.toString())).build();

        new OkHttpClient().newCall(request).execute();

    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }

    temperatureValue = 0;
    humidityValue = 0;
}

From source file:org.apache.giraph.graph.BspServiceWorker.java

@Override
public void setup() {
    // Unless doing a restart, prepare for computation:
    // 1. Start superstep INPUT_SUPERSTEP (no computation)
    // 2. Wait until the INPUT_SPLIT_ALL_READY_PATH node has been created
    // 3. Process input splits until there are no more.
    // 4. Wait until the INPUT_SPLIT_ALL_DONE_PATH node has been created
    // 5. Wait for superstep INPUT_SUPERSTEP to complete.
    if (getRestartedSuperstep() != UNSET_SUPERSTEP) {
        setCachedSuperstep(getRestartedSuperstep());
        return;/*from w  w w .j  a  va 2  s  . c  o m*/
    }

    JSONObject jobState = getJobState();
    if (jobState != null) {
        try {
            if ((ApplicationState
                    .valueOf(jobState.getString(JSONOBJ_STATE_KEY)) == ApplicationState.START_SUPERSTEP)
                    && jobState.getLong(JSONOBJ_SUPERSTEP_KEY) == getSuperstep()) {
                if (LOG.isInfoEnabled()) {
                    LOG.info("setup: Restarting from an automated " + "checkpointed superstep " + getSuperstep()
                            + ", attempt " + getApplicationAttempt());
                }
                setRestartedSuperstep(getSuperstep());
                return;
            }
        } catch (JSONException e) {
            throw new RuntimeException("setup: Failed to get key-values from " + jobState.toString(), e);
        }
    }

    // Add the partitions for that this worker owns
    Collection<? extends PartitionOwner> masterSetPartitionOwners = startSuperstep();
    workerGraphPartitioner.updatePartitionOwners(getWorkerInfo(), masterSetPartitionOwners, getPartitionMap());

    commService.setup();

    // Ensure the InputSplits are ready for processing before processing
    while (true) {
        Stat inputSplitsReadyStat;
        try {
            inputSplitsReadyStat = getZkExt().exists(inputSplitsAllReadyPath, true);
        } catch (KeeperException e) {
            throw new IllegalStateException("setup: KeeperException waiting on input splits", e);
        } catch (InterruptedException e) {
            throw new IllegalStateException("setup: InterruptedException waiting on input splits", e);
        }
        if (inputSplitsReadyStat != null) {
            break;
        }
        getInputSplitsAllReadyEvent().waitForever();
        getInputSplitsAllReadyEvent().reset();
    }

    getContext().progress();

    try {
        VertexEdgeCount vertexEdgeCount = loadVertices();
        if (LOG.isInfoEnabled()) {
            LOG.info("setup: Finally loaded a total of " + vertexEdgeCount);
        }
    } catch (IOException e) {
        throw new IllegalStateException("setup: loadVertices failed due to " + "IOException", e);
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("setup: loadVertices failed due to " + "ClassNotFoundException", e);
    } catch (InterruptedException e) {
        throw new IllegalStateException("setup: loadVertices failed due to " + "InterruptedException", e);
    } catch (InstantiationException e) {
        throw new IllegalStateException("setup: loadVertices failed due to " + "InstantiationException", e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException("setup: loadVertices failed due to " + "IllegalAccessException", e);
    } catch (KeeperException e) {
        throw new IllegalStateException("setup: loadVertices failed due to " + "KeeperException", e);
    }
    getContext().progress();

    // Workers wait for each other to finish, coordinated by master
    String workerDonePath = inputSplitsDonePath + "/" + getWorkerInfo().getHostnameId();
    try {
        getZkExt().createExt(workerDonePath, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, true);
    } catch (KeeperException e) {
        throw new IllegalStateException("setup: KeeperException creating worker done splits", e);
    } catch (InterruptedException e) {
        throw new IllegalStateException("setup: InterruptedException creating worker done splits", e);
    }
    while (true) {
        Stat inputSplitsDoneStat;
        try {
            inputSplitsDoneStat = getZkExt().exists(inputSplitsAllDonePath, true);
        } catch (KeeperException e) {
            throw new IllegalStateException("setup: KeeperException waiting on worker done splits", e);
        } catch (InterruptedException e) {
            throw new IllegalStateException("setup: InterruptedException waiting on worker " + "done splits",
                    e);
        }
        if (inputSplitsDoneStat != null) {
            break;
        }
        getInputSplitsAllDoneEvent().waitForever();
        getInputSplitsAllDoneEvent().reset();
    }

    // At this point all vertices have been sent to their destinations.
    // Move them to the worker, creating creating the empty partitions
    movePartitionsToWorker(commService);
    for (PartitionOwner partitionOwner : masterSetPartitionOwners) {
        if (partitionOwner.getWorkerInfo().equals(getWorkerInfo())
                && !getPartitionMap().containsKey(partitionOwner.getPartitionId())) {
            Partition<I, V, E, M> partition = new Partition<I, V, E, M>(getConfiguration(),
                    partitionOwner.getPartitionId());
            getPartitionMap().put(partitionOwner.getPartitionId(), partition);
        }
    }

    // Generate the partition stats for the input superstep and process
    // if necessary
    List<PartitionStats> partitionStatsList = new ArrayList<PartitionStats>();
    for (Partition<I, V, E, M> partition : getPartitionMap().values()) {
        PartitionStats partitionStats = new PartitionStats(partition.getPartitionId(),
                partition.getVertices().size(), 0, partition.getEdgeCount());
        partitionStatsList.add(partitionStats);
    }
    workerGraphPartitioner.finalizePartitionStats(partitionStatsList, workerPartitionMap);

    finishSuperstep(partitionStatsList);
}

From source file:org.apache.giraph.graph.BspServiceWorker.java

@Override
public boolean finishSuperstep(List<PartitionStats> partitionStatsList) {
    // This barrier blocks until success (or the master signals it to
    // restart)./*from w  w w .ja v a  2  s  .  c  o  m*/
    //
    // Master will coordinate the barriers and aggregate "doneness" of all
    // the vertices.  Each worker will:
    // 1. Flush the unsent messages
    // 2. Execute user postSuperstep() if necessary.
    // 3. Save aggregator values that are in use.
    // 4. Report the statistics (vertices, edges, messages, etc.)
    //    of this worker
    // 5. Let the master know it is finished.
    // 6. Wait for the master's global stats, and check if done
    long workerSentMessages = 0;
    try {
        commService.flush();
        workerSentMessages = commService.resetMessageCount();
    } catch (IOException e) {
        throw new IllegalStateException("finishSuperstep: flush failed", e);
    }

    if (getSuperstep() != INPUT_SUPERSTEP) {
        getWorkerContext().postSuperstep();
        getContext().progress();
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("finishSuperstep: Superstep " + getSuperstep() + " " + MemoryUtils.getRuntimeMemoryStats());
    }

    JSONArray aggregatorValueArray = marshalAggregatorValues(getSuperstep());
    Collection<PartitionStats> finalizedPartitionStats = workerGraphPartitioner
            .finalizePartitionStats(partitionStatsList, workerPartitionMap);
    List<PartitionStats> finalizedPartitionStatsList = new ArrayList<PartitionStats>(finalizedPartitionStats);
    byte[] partitionStatsBytes = WritableUtils.writeListToByteArray(finalizedPartitionStatsList);
    JSONObject workerFinishedInfoObj = new JSONObject();
    try {
        workerFinishedInfoObj.put(JSONOBJ_AGGREGATOR_VALUE_ARRAY_KEY, aggregatorValueArray);
        workerFinishedInfoObj.put(JSONOBJ_PARTITION_STATS_KEY, Base64.encodeBytes(partitionStatsBytes));
        workerFinishedInfoObj.put(JSONOBJ_NUM_MESSAGES_KEY, workerSentMessages);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    String finishedWorkerPath = getWorkerFinishedPath(getApplicationAttempt(), getSuperstep()) + "/"
            + getHostnamePartitionId();
    try {
        getZkExt().createExt(finishedWorkerPath, workerFinishedInfoObj.toString().getBytes(),
                Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, true);
    } catch (KeeperException.NodeExistsException e) {
        LOG.warn("finishSuperstep: finished worker path " + finishedWorkerPath + " already exists!");
    } catch (KeeperException e) {
        throw new IllegalStateException("Creating " + finishedWorkerPath + " failed with KeeperException", e);
    } catch (InterruptedException e) {
        throw new IllegalStateException("Creating " + finishedWorkerPath + " failed with InterruptedException",
                e);
    }
    getContext().setStatus("finishSuperstep: (waiting for rest " + "of workers) "
            + getGraphMapper().getMapFunctions().toString() + " - Attempt=" + getApplicationAttempt()
            + ", Superstep=" + getSuperstep());

    String superstepFinishedNode = getSuperstepFinishedPath(getApplicationAttempt(), getSuperstep());
    try {
        while (getZkExt().exists(superstepFinishedNode, true) == null) {
            getSuperstepFinishedEvent().waitForever();
            getSuperstepFinishedEvent().reset();
        }
    } catch (KeeperException e) {
        throw new IllegalStateException("finishSuperstep: Failed while waiting for master to "
                + "signal completion of superstep " + getSuperstep(), e);
    } catch (InterruptedException e) {
        throw new IllegalStateException("finishSuperstep: Failed while waiting for master to "
                + "signal completion of superstep " + getSuperstep(), e);
    }
    GlobalStats globalStats = new GlobalStats();
    WritableUtils.readFieldsFromZnode(getZkExt(), superstepFinishedNode, false, null, globalStats);
    if (LOG.isInfoEnabled()) {
        LOG.info(
                "finishSuperstep: Completed superstep " + getSuperstep() + " with global stats " + globalStats);
    }
    incrCachedSuperstep();
    getContext()
            .setStatus("finishSuperstep: (all workers done) " + getGraphMapper().getMapFunctions().toString()
                    + " - Attempt=" + getApplicationAttempt() + ", Superstep=" + getSuperstep());
    getGraphMapper().getGraphState().setNumEdges(globalStats.getEdgeCount())
            .setNumVertices(globalStats.getVertexCount());
    return globalStats.getHaltComputation();
}