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:lv.semti.morphology.attributes.AttributeValues.java

public String toJSON() {
     return JSONValue.toJSONString(attributes);
 }

From source file:com.ikanow.aleph2.analytics.storm.services.RemoteStormController.java

/**
 * Submits a job to the remote storm cluster.  Sends the input jar to the server and then
 * submits the supplied topology w/ the given job_name.
 * /*from w  w  w  . j  av a  2 s . c o m*/
 */
@Override
public CompletableFuture<BasicMessageBean> submitJob(String job_name, String input_jar_location,
        StormTopology topology, Map<String, Object> config_override) {
    final CompletableFuture<BasicMessageBean> future = new CompletableFuture<BasicMessageBean>();
    logger.info("Submitting job: " + job_name + " jar: " + input_jar_location);
    logger.info("submitting jar");

    final String remote_jar_location = StormSubmitter.submitJar(remote_config, input_jar_location);
    //      final String json_conf = JSONValue.toJSONString(ImmutableMap.builder()
    //               .putAll(remote_config)
    //               .putAll(config_override)
    //            .build());
    final String json_conf = JSONValue.toJSONString(mergeMaps(Arrays.asList(remote_config, config_override)));
    logger.info("submitting topology");
    try {
        synchronized (client) {
            client.submitTopology(job_name, remote_jar_location, json_conf, topology);
        }
        //verify job was assigned some executors
        final TopologyInfo info = getJobStats(job_name);
        logger.info("submitted job received: " + info.get_executors_size() + " executors");
        if (info.get_executors_size() == 0) {
            logger.info("received 0 executors, killing job, reporting failure");
            //no executors were available for this job, stop the job, throw an error
            stopJob(job_name);

            future.complete(ErrorUtils.buildErrorMessage(this, "submitJob",
                    "No executors were assigned to this job, typically this is because too many jobs are currently running, kill some other jobs and resubmit."));
            return future;
        }
    } catch (Exception ex) {
        logger.info(ErrorUtils.getLongForm("Error submitting job: " + job_name + ": {0}", ex));
        return FutureUtils.returnError(ex);
    }

    future.complete(
            ErrorUtils.buildSuccessMessage(this, "submitJob", "Submitted job successfully: " + job_name));
    return future;
}

From source file:backtype.storm.utils.Utils.java

public static String to_json(Object m) {
    // return JSON.toJSONString(m);
    return JSONValue.toJSONString(m);
}

From source file:edu.pitt.dbmi.facebase.hd.InstructionQueueManager.java

/** Tell's Hub DB how much data is being packaged
 * Writes the value (in bytes) of the size of the files requests to the "results" column in the database in JSON format. 
 * Tells the Hub DB how big (and therefore how long to process) the requested data is. 
 *
 * @param session the Hibernate session object
 * @param qid the id of the QueueItem (and the row in the table) being processed
 * @return true if successful// w  w w .  j  a v a2  s . c o m
 */
boolean updateInstructionSize(long size, long qid) {
    log.debug("InstructionQueueManager.updateInstructionSize() called.");
    Session session = null;
    Transaction transaction = null;
    try {
        session = conf.openSession();
        transaction = session.beginTransaction();
        List<InstructionQueueItem> items = getPendingQueueItems(session, qid);
        String sizeString = (new Long(size)).toString();
        Map resultsJSON = new LinkedHashMap();
        resultsJSON.put("size", sizeString);
        String jsonResultsString = JSONValue.toJSONString(resultsJSON);
        if (items != null && items.size() >= 1) {
            InstructionQueueItem item = items.get(0);
            item.setResults(jsonResultsString);
            session.update(item);
            transaction.commit();
        }
        session.close();
        return true;
    } catch (Throwable t) {
        String errorString = "InstructionQueueManager caught a t in updateInstructionSize(): " + t.toString();
        String logString = t.getMessage();
        edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString);
        log.error(errorString, t);
        handleThrowable(t, session, transaction);
    }
    return false;
}

From source file:mensajes.SmackCcsClient.java

/**
 * Creates a JSON encoded GCM message.//from   ww  w .  jav a2s.c om
 *
 * @param to RegistrationId of the target device (Required).
 * @param messageId Unique messageId for which CCS sends an
 *         "ack/nack" (Required).
 * @param payload Message content intended for the application. (Optional).
 * @param collapseKey GCM collapse_key parameter (Optional).
 * @param timeToLive GCM time_to_live parameter (Optional).
 * @param delayWhileIdle GCM delay_while_idle parameter (Optional).
 * @return JSON encoded GCM message.
 */
public static String createJsonMessage(String to, String messageId, Map<String, String> payload,
        String collapseKey, Long timeToLive, Boolean delayWhileIdle) {
    Map<String, Object> message = new HashMap<String, Object>();
    message.put("to", to);
    if (collapseKey != null) {
        message.put("collapse_key", collapseKey);
    }
    if (timeToLive != null) {
        message.put("time_to_live", timeToLive);
    }
    if (delayWhileIdle != null && delayWhileIdle) {
        message.put("delay_while_idle", true);
    }
    message.put("message_id", messageId);
    message.put("data", payload);
    return JSONValue.toJSONString(message);
}

From source file:kms.prolog.comms.TransportServlet.java

/** 
 * Prolog typically deals with HTTP POST for RESTful communication
 * Therefore we use the doPost to implement a RESTful web service
 * for contacting the chosen web service to receive the chosen data
 * Prolog sends JSON { transport: "moduleId", queryPayload="relevant parameters" }
 * This method:/*www  . j a  va  2 s .  c  o  m*/
 * 1. Looks up module id in RDBMS in order to find external web service location
 *    to retrieve data from
 * 2. Acts as a SOAP client to retrieve data from this service
 * --> For first web service 
 *     a.Create and generate web service WSDL
 *     b.Use wsimport to generate necessary stubs
 *     c.Import stubs to project
 *     d.Use WSDL as generic wsdl for people to implement other web services
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //       logger.log(Level.INFO, "Inside the transport servlet");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        ServletInputStream inputStream = request.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder requestStringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            requestStringBuilder.append(line + "\n");
        }
        inputStream.close();
        PrologRESTClient restClient = new PrologRESTClient();
        JSONParser jsonParser = new JSONParser();
        ContainerFactory jsonContainerFactory = getJsonContainerFactory();
        try {
            //              out.print(requestStringBuilder.toString());
            Map<String, Object> jsonMap = (Map<String, Object>) jsonParser
                    .parse(requestStringBuilder.toString(), jsonContainerFactory);
            String transportId = (String) jsonMap.get(TRANSPORT_PARAMETER_ID);
            Object queryObject = (Object) jsonMap.get(TRANSPORT_PARAMETER_QUERY);
            String query = null;
            if (queryObject instanceof String) {
                query = (String) queryObject;
            } else if (queryObject instanceof Map) {
                query = JSONValue.toJSONString(queryObject);
            }
            if (transportId != null) {
                TransportServiceImpl transportService = getTransportModuleWebService(transportId);
                if (transportService != null) {
                    String result = (String) transportService.transport(query);
                    out.print(result);
                } else {
                    throw new TransportException(
                            "Transport Servlet could not locate transport web service with transportId: "
                                    + transportId);
                }
            } else {
                throw new TransportException("Transport Servlet not supplied with transportId");
            }
        } catch (ParseException e) {
            //log and put something in response
            logger.log(Level.SEVERE, "", e);
        } catch (ServiceException e) {
            //log and put something in response
            logger.log(Level.SEVERE, "", e);
        } catch (IOException e) {
            //log and put something in response
            logger.log(Level.SEVERE, "", e);
            throw (e);
        } catch (TransportException e) {
            logger.log(Level.SEVERE, "", e);
        }
    } finally {
        out.close();
    }
    processRequest(request, response);
}

From source file:com.github.nukesparrow.htmlunit.DebuggingWebConnection.java

public String asJSON() {
    try {// ww w .  ja v  a2s. co m
        StringBuilder b = new StringBuilder();
        b.append('[');
        for (final Object e : events.toArray()) {
            if (b.length() > 1)
                b.append(",\n");
            synchronized (e) {
                b.append(JSONValue.toJSONString(e));
            }
        }
        b.append(']');
        return b.toString();
        //return JSONValue.toJSONString(events.toArray());
    } catch (RuntimeException ex) {
        synchronized (events) {
            LOG.log(Level.SEVERE, "Unable to convert to JSON: " + String.valueOf(events), ex);
        }
        return null;
    }
}

From source file:com.mobicage.rogerthat.registration.RegistrationWizard2.java

@SuppressWarnings("unchecked")
@Override//  www.j a  va  2  s .  com
public void writePickle(DataOutput out) throws IOException {
    T.UI();
    super.writePickle(out);
    boolean set = mCredentials != null;
    out.writeBoolean(set);
    if (set) {
        out.writeInt(mCredentials.getPickleClassVersion());
        mCredentials.writePickle(out);
    }
    set = mEmail != null;
    out.writeBoolean(set);
    if (set)
        out.writeUTF(mEmail);
    out.writeLong(mTimestamp);
    out.writeUTF(mRegistrationId);
    out.writeBoolean(mInGoogleAuthenticationProcess);
    out.writeUTF(mInstallationId);
    out.writeUTF(mDeviceId);
    set = mBeaconRegions != null;
    out.writeBoolean(set);
    if (set)
        out.writeUTF(JSONValue.toJSONString(mBeaconRegions.toJSONMap()));
    set = mDetectedBeacons != null;
    out.writeBoolean(set);
    if (set) {
        JSONArray db1 = new JSONArray();
        for (String db : mDetectedBeacons) {
            db1.add(db);
        }
        out.writeUTF(JSONValue.toJSONString(db1));
    }
}

From source file:br.com.ulife.googlexmpp.SmackCcsClient.java

/**
 * Creates a JSON encoded GCM message./*from w  ww .ja va  2s. co  m*/
 *
 * @param to RegistrationId of the target device (Required).
 * @param messageId Unique messageId for which CCS will send an "ack/nack"
 * (Required).
 * @param payload Message content intended for the application. (Optional).
 * @param collapseKey GCM collapse_key parameter (Optional).
 * @param timeToLive GCM time_to_live parameter (Optional).
 * @param delayWhileIdle GCM delay_while_idle parameter (Optional).
 * @return JSON encoded GCM message.
 */
public static String createJsonMessage(String to, String messageId, Map payload, String collapseKey,
        Long timeToLive, Boolean delayWhileIdle) {
    Map message = new HashMap();
    message.put("to", to);
    if (collapseKey != null) {
        message.put("collapse_key", collapseKey);
    }
    if (timeToLive != null) {
        message.put("time_to_live", timeToLive);
    }
    if (delayWhileIdle != null && delayWhileIdle) {
        message.put("delay_while_idle", true);
    }
    message.put("message_id", messageId);
    message.put("data", payload);
    return JSONValue.toJSONString(message);
}

From source file:com.jql.gcmccsmock.GCMMessageHandler.java

/**
 * Create Ack Message//from   w  w  w .j  a  v  a  2 s .  c om
        
 <message id="">
   <gcm xmlns="google:mobile:data">
   {
     "from":"REGID",
     "message_id":"m-1366082849205"
     "message_type":"ack"
   }
   </gcm>
 </message>
        
 * @param original
 * @param jsonObject
 * @return
 * @throws EntityFormatException
 */
private static Stanza createAckMessageStanza(Stanza original, JSONObject jsonObject)
        throws EntityFormatException {
    Map<String, Object> message = new HashMap<>();
    message.put(JSON_MESSAGE_TYPE, JSON_ACK);
    message.put(JSON_FROM, jsonObject.get(JSON_TO));
    message.put(JSON_MESSAGE_ID, jsonObject.get(JSON_MESSAGE_ID));
    String payload = JSONValue.toJSONString(message);

    // no from & to
    StanzaBuilder builder = new StanzaBuilder("message");
    builder.addAttribute("id",
            original.getAttributeValue("id") == null ? "" : original.getAttributeValue("id"));
    GCMMessage.Builder gcmMessageBuilder = new GCMMessage.Builder();
    gcmMessageBuilder.addText(payload);
    builder.addPreparedElement(gcmMessageBuilder.build());
    return builder.build();
}