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:me.neatmonster.spacertk.PanelListener.java

@Override
public void run() {
    if (mode == 0) {

        try {/*  w w w.j a v  a2s  .  c om*/
            serverSocket = new ServerSocket(SpaceRTK.getInstance().rPort, SO_BACKLOG,
                    SpaceRTK.getInstance().bindAddress);
            serverSocket.setSoTimeout(SO_TIMEOUT);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        while (!serverSocket.isClosed()) {
            try {
                final Socket clientSocket = serverSocket.accept();
                new PanelListener(clientSocket);
            } catch (SocketTimeoutException e) {
                // Do nothing.
            } catch (Exception e) {
                if (!e.getMessage().contains("socket closed"))
                    e.printStackTrace();
            }
        }
    } else {
        try {
            final BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String string = input.readLine();
            if (string == null) {
                return;
            }
            string = URLDecoder.decode(string, "UTF-8");
            string = string.substring(5, string.length() - 9);
            final PrintWriter output = new PrintWriter(socket.getOutputStream());
            if (string.startsWith("call") && string.contains("?method=") && string.contains("&args=")) {
                final String method = string.substring(12, string.indexOf("&args="));
                if (string.contains("&key=" + Utilities.crypt(method + SpaceRTK.getInstance().salt))) {
                    if (string.startsWith("call?method=DOWNLOAD_WORLD")) {
                        final boolean wasRunning = RemoteToolkit.isRunning();
                        if (wasRunning)
                            RemoteToolkit.hold();
                        final File file = new File(string.split("\"")[1] + ".zip");
                        ZIP.zip(file, new File(string.split("\"")[1]));
                        if (file.exists()) {
                            final FileInputStream fileInputStream = new FileInputStream(file);
                            final byte[] fileData = new byte[65536];
                            int length;
                            output.println("HTTP/1.1 200 OK");
                            output.println("Content-Type: application/force-download; name=" + file.getName());
                            output.println("Content-Transfer-Encoding: binary");
                            output.println("Content-Length:" + file.length());
                            output.println("Content-Disposition: attachment; filename=" + file.getName());
                            output.println("Expires: 0");
                            output.println("Cache-Control: no-cache, must-revalidate");
                            output.println("Pragma: no-cache");
                            while ((length = fileInputStream.read(fileData)) > 0)
                                output.print(new String(fileData, 0, length));
                            fileInputStream.close();
                        } else
                            output.println(Utilities.addHeader(null));
                        if (wasRunning)
                            RemoteToolkit.unhold();
                    } else {
                        final Object result = interpret(string);
                        if (result != null)
                            try {
                                output.println(Utilities.addHeader(JSONValue.toJSONString(result)));
                            } catch (OutOfMemoryError e) {
                                System.gc();
                                output.println(Utilities.addHeader(null));
                            }
                        else
                            output.println(Utilities.addHeader(null));
                    }
                } else
                    output.println(Utilities.addHeader("Incorrect Salt supplied. Access denied!"));
            } else if (string.startsWith("multiple") && string.contains("?method=")
                    && string.contains("&args=")) {
                final String method = string.substring(16, string.indexOf("&args="));
                if (string.contains("&key=" + Utilities.crypt(method + SpaceRTK.getInstance().salt))) {
                    final Object result = interpretm(string);
                    if (result != null)
                        try {
                            output.println(Utilities.addHeader(JSONValue.toJSONString(result)));
                        } catch (OutOfMemoryError e) {
                            System.gc();
                            output.println(Utilities.addHeader(null));
                        }
                    else
                        output.println(Utilities.addHeader(null));
                } else
                    output.println(Utilities.addHeader("Incorrect Salt supplied. Access denied!"));
            } else if (string.startsWith("ping"))
                output.println(Utilities.addHeader("Pong!"));
            else
                output.println(Utilities.addHeader(null));
            output.flush();
            input.close();
            output.close();
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
}

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

/** Tell's Hub DB about the results of the queue processing effort
 * Called after processing of the queue item and construction of the TrueCrypt volume is complete. 
 * Tells Hub where TrueCrypt volume is located, when processing finished, and any error reporting; sets status
 * Sets status='complete' or status='error' in fb_queue row for this queue item
 * Sets Completed=unixEpicTime in fb_queue row for this queue item
 * Sets results=ComplexJSONstring holding path, logs, messages.  That string would look like this:
 * <pre>//  w  w w  .  j  a va 2 s. c om
 * {
 *    "path": "/path/to/file/3DData1-2-11-35username.tc",
 *    "log": "",
 *    "messages": [
 *        "File 1102.obj was not found and not included in your zip file.",
 *        "Blah blah blah"
 *    ]
 * }
 * <pre>
 *
 * @param trueCryptFilename the full path name of the trueCrypt file (ie. /var/downloads/FBdata.tc)
 * @param size total size of TrueCrypt file
 * @param qid the queue id of the item that was processed
 * @param errors list of human-readable errors that were encountered (if nonzero, the status will be set to "error", otherwise status="complete".
 * @param logs list of detailed error information that was gathered (usually with Exception.getMessage()). 
 * @return true if successful
 */
boolean updateInstructionToCompleted(String trueCryptFilename, long size, long qid, ArrayList<String> errors,
        ArrayList<String> logs) {
    log.debug("InstructionQueueManager.updateInstructionToCompleted() called.");
    Session session = null;
    Transaction transaction = null;
    long unixEpicTime = System.currentTimeMillis() / 1000L;
    try {
        session = conf.openSession();
        transaction = session.beginTransaction();
        List<InstructionQueueItem> items = getPendingQueueItems(session, qid);
        String sizeString = (new Long(size)).toString();
        //LIKE THIS: jsonResultsString = "{\"path\":\""+trueCryptFilename+"\",\"log\":\"\",\"messages\":[\""+errorsString+"\"],\"size\":\""+sizeString+"\"}";
        Map resultsJSON = new LinkedHashMap();
        resultsJSON.put("path", trueCryptFilename);
        resultsJSON.put("size", sizeString);
        JSONArray messagesJSON = new JSONArray();
        JSONArray logsJSON = new JSONArray();
        for (String message : errors) {
            messagesJSON.add(message);
        }
        resultsJSON.put("messages", messagesJSON);
        for (String log : logs) {
            logsJSON.add(log);
        }
        resultsJSON.put("log", logsJSON);
        //LIKE THIS: jsonResultsString = resultsJSON.toString();...but toString() won't work...need toJSONString():
        String jsonResultsString = JSONValue.toJSONString(resultsJSON);
        if (items != null && items.size() >= 1) {
            InstructionQueueItem item = items.get(0);
            if (errors.isEmpty()) {
                item.setStatus("complete");
            } else {
                item.setStatus("error");
            }
            item.setResults(jsonResultsString);
            item.setCompleted(unixEpicTime);
            session.update(item);
            transaction.commit();
        }
        session.close();
        return true;
    } catch (Throwable t) {
        String errorString = "InstructionQueueManager caught a t in updateInstructionsToCompleted()"
                + 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:com.example.CcsClient.java

public static String createJsonMessage(Map map) {
    return JSONValue.toJSONString(map);
}

From source file:com.turt2live.xmail.engine.connection.PHPConnection2A.java

@Override
public List<Variable> convertMail(Mail mail) {
    if (mail == null) {
        return null;
    }/*ww  w . ja  v  a2 s  . com*/
    List<Variable> vars = new ArrayList<Variable>();
    Map<String, Object> map = new HashMap<String, Object>();

    map.put("to", mail.getTo());
    map.put("from", mail.getFrom());
    map.put("date", mail.getTimestamp());
    map.put("sent-from", mail.getServerSender());
    map.put("unread", !mail.isRead());
    List<String> tags = mail.getTags();

    // Convert attachments
    List<String> attachments = new ArrayList<String>();
    List<Attachment> lAtt = mail.getAttachments();
    for (Attachment a : lAtt) {
        attachments.add(a.toJson());
    }

    map.put("tags", tags);
    map.put("attachments", attachments);

    try {
        vars.add(new Variable("mail", URLEncoder.encode(JSONValue.toJSONString(map), "UTF-8")));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return vars;
}

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

/**
 * Create Delivery Receipt/* w  ww  . ja  v  a 2s.c  o m*/
        
 <message id="">
   <gcm xmlns="google:mobile:data">
   {
     "category":"com.example.yourapp", // to know which app sent it
     "data":
     {
 message_status":"MESSAGE_SENT_TO_DEVICE",
 original_message_id?:?m-1366082849205?,
 device_registration_id?: REGISTRATION_ID?,
 "message_sent_timestamp": "1430277821658"
     },
     "message_id":"dr2:m-1366082849205",
     "message_type":"receipt",
     "time_to_live": 0,
     "from":"gcm.googleapis.com"
   }
   </gcm>
 </message>
        
 * @param original
 * @param jsonObject
 * @return
 * @throws EntityFormatException
 */
private static Stanza createDeliveryReceiptMessageStanza(Stanza original, JSONObject jsonObject)
        throws EntityFormatException {

    Map<String, Object> message = new HashMap<>();
    message.put(JSON_MESSAGE_TYPE, JSON_RECEIPT);
    message.put(JSON_FROM, "gcm.googleapis.com");
    // TODO made up
    message.put(JSON_CATEGORY, "com.itsoninc.client");
    message.put(JSON_MESSAGE_ID, "dr2:" + jsonObject.get(JSON_MESSAGE_ID));
    Map<String, Object> data = new HashMap<>();
    data.put(JSON_MESSAGE_STATUS, JSON_MESSAGE_STATUS_SENT_TO_DEVICE);
    data.put(JSON_ORIGINAL_MESSAGE_ID, jsonObject.get(JSON_MESSAGE_ID));
    data.put(JSON_DEVICE_REG_ID, jsonObject.get(JSON_TO));
    data.put(JSON_SENT_TIMESTAMP, Long.toString(System.currentTimeMillis()));
    message.put("data", data);
    String payload = JSONValue.toJSONString(message);

    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();
}

From source file:au.org.paperminer.main.LocationFilter.java

/**
 *  Locate an existing locations by its Latitude & Longitude values.
 * //from  w w  w  .  j av a  2 s .  c om
 * @param req
 * @param resp
 */
private void findLatLongLocation(HttpServletRequest req, HttpServletResponse resp) {
    String lat = req.getParameter("lat");
    String lng = req.getParameter("lng");

    try {
        ArrayList<HashMap<String, String>> list = m_helper.locationsLikeLatLng(Float.valueOf(lat).floatValue(),
                Float.valueOf(lng).floatValue());
        m_logger.debug("locationFilter locn lookup: " + lat + ", " + lng + " -- List Size: " + list.size());

        resp.setContentType("text/json");
        PrintWriter pm = resp.getWriter();
        pm.write(JSONValue.toJSONString(list));
        pm.close();
    } catch (PaperMinerException ex) {
        m_logger.error("lookup failed", ex);
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e305");
    } catch (IOException ex) {
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e114");
    }
}

From source file:com.larryTheCoder.schematic.IslandBlock.java

/**
 * Sets this block's sign data/*from w  w  w . j a  va2  s  .c o m*/
 *
 * @param tileData
 */
public void setSign(Map<String, Tag> tileData) {
    signText = new ArrayList<>();
    List<String> text = new ArrayList<>();
    for (int i = 1; i < 5; i++) {
        String line = ((StringTag) tileData.get("Text" + String.valueOf(i))).getValue();
        // This value can actually be a string that says null sometimes.
        if (line.equalsIgnoreCase("null")) {
            line = "";
        }
        //System.out.println("DEBUG: line " + i + " = '"+ line + "' of length " + line.length());
        text.add(line);
    }

    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory = new ContainerFactory() {
        @Override
        public List creatArrayContainer() {
            return new LinkedList<>();
        }

        @Override
        public Map createObjectContainer() {
            return new LinkedHashMap<>();
        }

    };
    // This just removes all the JSON formatting and provides the raw text
    for (int line = 0; line < 4; line++) {
        String lineText = "";
        if (!text.get(line).equals("\"\"") && !text.get(line).isEmpty()) {
            //String lineText = text.get(line).replace("{\"extra\":[\"", "").replace("\"],\"text\":\"\"}", "");
            //Bukkit.getLogger().info("DEBUG: sign text = '" + text.get(line) + "'");
            if (text.get(line).startsWith("{")) {
                // JSON string
                try {

                    Map json = (Map) parser.parse(text.get(line), containerFactory);
                    List list = (List) json.get("extra");
                    //System.out.println("DEBUG1:" + JSONValue.toJSONString(list));
                    if (list != null) {
                        Iterator iter = list.iterator();
                        while (iter.hasNext()) {
                            Object next = iter.next();
                            String format = JSONValue.toJSONString(next);
                            //System.out.println("DEBUG2:" + format);
                            // This doesn't see right, but appears to be the easiest way to identify this string as JSON...
                            if (format.startsWith("{")) {
                                // JSON string
                                Map jsonFormat = (Map) parser.parse(format, containerFactory);
                                Iterator formatIter = jsonFormat.entrySet().iterator();
                                while (formatIter.hasNext()) {
                                    Map.Entry entry = (Map.Entry) formatIter.next();
                                    //System.out.println("DEBUG3:" + entry.getKey() + "=>" + entry.getValue());
                                    String key = entry.getKey().toString();
                                    String value = entry.getValue().toString();
                                    if (key.equalsIgnoreCase("color")) {
                                        try {
                                            lineText += TextFormat.valueOf(value.toUpperCase());
                                        } catch (Exception noColor) {
                                            Utils.ConsoleMsg("Unknown color " + value
                                                    + " in sign when pasting schematic, skipping...");
                                        }
                                    } else if (key.equalsIgnoreCase("text")) {
                                        lineText += value;
                                    } else // Formatting - usually the value is always true, but check just in case
                                    if (key.equalsIgnoreCase("obfuscated") && value.equalsIgnoreCase("true")) {
                                        lineText += TextFormat.OBFUSCATED;
                                    } else if (key.equalsIgnoreCase("underlined")
                                            && value.equalsIgnoreCase("true")) {
                                        lineText += TextFormat.UNDERLINE;
                                    } else {
                                        // The rest of the formats
                                        try {
                                            lineText += TextFormat.valueOf(key.toUpperCase());
                                        } catch (Exception noFormat) {
                                            // Ignore
                                            //System.out.println("DEBUG3:" + key + "=>" + value);
                                            Utils.ConsoleMsg("Unknown format " + value
                                                    + " in sign when pasting schematic, skipping...");
                                        }
                                    }
                                }
                            } else// This is unformatted text. It is included in "". A reset is required to clear
                            // any previous formatting
                            {
                                if (format.length() > 1) {
                                    lineText += TextFormat.RESET + format.substring(format.indexOf('"') + 1,
                                            format.lastIndexOf('"'));
                                }
                            }
                        }
                    } else {
                        // No extra tag
                        json = (Map) parser.parse(text.get(line), containerFactory);
                        String value = (String) json.get("text");
                        //System.out.println("DEBUG text only?:" + value);
                        lineText += value;
                    }
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else // This is unformatted text (not JSON). It is included in "".
            if (text.get(line).length() > 1) {
                try {
                    lineText = text.get(line).substring(text.get(line).indexOf('"') + 1,
                            text.get(line).lastIndexOf('"'));
                } catch (Exception e) {
                    //There may not be those "'s, so just use the raw line
                    lineText = text.get(line);
                }
            } else {
                // just in case it isn't - show the raw line
                lineText = text.get(line);
            }
            //Bukkit.getLogger().info("Line " + line + " is " + lineText);
        }
        signText.add(lineText);
    }
}

From source file:de.ncoder.studipsync.studip.jsoup.JsoupStudipAdapter.java

public void saveCookies() throws IOException {
    if (cookiesPath != null) {
        log.info("Save Cookies");
        if (Files.exists(cookiesPath)) {
            Files.delete(cookiesPath);
        }/*from   ww  w  .  j a  va  2s .  c  o  m*/
        try (Writer w = Files.newBufferedWriter(cookiesPath, Charset.defaultCharset())) {
            w.write(JSONValue.toJSONString(con.request().cookies()));
        }
    }
}

From source file:com.example.CcsClient.java

/**
 * Creates a JSON encoded ACK message for an upstream message received from
 * an application./*ww w .j  av a2 s  .c om*/
 *
 * @param to RegistrationId of the device who sent the upstream message.
 * @param messageId messageId of the upstream message to be acknowledged to
 * CCS.
 * @return JSON encoded ack.
 */
public static String createJsonAck(String to, String messageId) {
    Map<String, Object> message = new HashMap<String, Object>();
    message.put("message_type", "ack");
    message.put("to", to);
    message.put("message_id", messageId);
    return JSONValue.toJSONString(message);
}

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

/**
 * Create Draining Control Message//from  w w w .  j  a v  a  2 s .c o  m
        
 <message>
   <data:gcm xmlns:data="google:mobile:data">
   {
     "message_type":"control"
     "control_type":"CONNECTION_DRAINING"
   }
   </data:gcm>
 </message>
        
 * @param original
 * @param jsonObject
 * @return
 * @throws EntityFormatException
 */
private static Stanza createDrainingMessageStanza(Stanza original, JSONObject jsonObject)
        throws EntityFormatException {
    Map<String, Object> message = new HashMap<>();
    message.put(JSON_MESSAGE_TYPE, JSON_CONTROL);
    message.put(JSON_CONTROL_TYPE, "CONNECTION_DRAINING");
    String payload = JSONValue.toJSONString(message);

    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();
}