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.arangodb.internal.velocypack.VPackDocumentModule.java

@Override
public <C extends VPackParserSetupContext<C>> void setup(final C context) {
    context.registerDeserializer(ID, ValueType.CUSTOM, new VPackJsonDeserializer() {
        @Override/* w w  w.  jav a  2  s  .c  o m*/
        public void deserialize(final VPackSlice parent, final String attribute, final VPackSlice vpack,
                final StringBuilder json) throws VPackException {
            final String id;
            final long idLong = NumberUtil.toLong(vpack.getBuffer(), vpack.getStart() + 1,
                    vpack.getByteSize() - 1);
            final String collectionName = collectionCache.getCollectionName(idLong);
            if (collectionName != null) {
                final VPackSlice key = parent.get("_key");
                id = String.format("%s/%s", collectionName, key.getAsString());
            } else {
                id = null;
            }
            json.append(JSONValue.toJSONString(id));
        }
    });
}

From source file:com.conwet.silbops.model.basic.Value.java

@Override
public String toJSONString() {

    return JSONValue.toJSONString(toJSON());
}

From source file:com.turt2live.xmail.mail.attachment.MailMessageAttachment.java

@Override
public Object getSerializedContent() {
    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());/*  ww  w. java 2s. c  o  m*/
    }

    map.put("tags", tags);
    map.put("attachments", attachments);
    map.put("message_type", mtype.name());
    return JSONValue.toJSONString(map);
}

From source file:models.Document.java

/**
 * @param format The RDF serialization format to represent this document as
 * @return This documents, in the given RDF format
 *///ww w  .  j  a va  2s  .c  o m
public String as(final Format format) { // NOPMD
    final JsonLdConverter converter = new JsonLdConverter(format);
    final String json = JSONValue.toJSONString(JSONValue.parse(source));
    String result = "";
    try {
        result = converter.toRdf(json);
    } catch (BadURIException x) {
        Logger.error(x.getMessage(), x);
    }
    return result;
}

From source file:me.neatmonster.spacebukkit.PanelListener.java

/**
 * Interprets a raw command from the panel (multiple)
 * @param string input from panel//from  w w  w .  j av  a2 s.  c  o  m
 * @return result of the action
 * @throws InvalidArgumentsException Thrown when the wrong arguments are used by the panel
 * @throws UnhandledActionException Thrown when there is no handler for the action
 */
@SuppressWarnings("unchecked")
private static Object interpretm(final String string)
        throws InvalidArgumentsException, UnhandledActionException {
    final int indexOfMethod = string.indexOf("?method=");
    final int indexOfArguments = string.indexOf("&args=");
    final int indexOfKey = string.indexOf("&key=");
    final String methodString = string.substring(indexOfMethod + 8, indexOfArguments);
    final String argumentsString = string.substring(indexOfArguments + 6, indexOfKey);
    final List<Object> methods = (List<Object>) JSONValue.parse(methodString);
    final List<Object> arguments = (List<Object>) JSONValue.parse(argumentsString);
    final List<Object> result = (List<Object>) JSONValue.parse("[]");
    for (int i = 0; i < methods.size(); i++) {
        String argsString = arguments.toArray()[i].toString();
        List<Object> args = (List<Object>) JSONValue.parse(argsString);
        try {
            if (SpaceBukkit.getInstance().actionsManager.contains(methods.toArray()[i].toString()))
                result.add(SpaceBukkit.getInstance().actionsManager.execute(methods.toArray()[i].toString(),
                        args.toArray()));
            else {
                final RequestEvent event = new RequestEvent(methods.toArray()[i].toString(), args.toArray());
                Bukkit.getPluginManager().callEvent(event);
                result.add(JSONValue.toJSONString(event.getResult()));
            }
        } catch (final InvalidArgumentsException e) {
            result.add(null);
            e.printStackTrace();
        } catch (final UnhandledActionException e) {
            result.add(null);
            e.printStackTrace();
        }

    }
    return result;
}

From source file:com.valygard.aohruthless.utils.config.JsonConfiguration.java

/**
 * Writes a JSONArray to memory at a specified String key.
 * /*from   w w w .  j  a  v a  2s  .c o  m*/
 * @param key
 *            the String pathway
 * @param array
 *            the JSONArray
 * @return the JSONConfiguration instance
 */
@SuppressWarnings("unchecked")
public JsonConfiguration writeArray(String key, JSONArray array) {
    for (Object value : array) {
        if (value == null)
            continue;
        array.set(array.indexOf(value), JSONValue.toJSONString(value));
    }
    return writeObject(key, array);
}

From source file:me.neatmonster.spacertk.scheduler.Scheduler.java

/**
 * Saves all the queued jobs to the file
 */// w w  w . j  av  a  2 s .  co m
public static void saveJobs() {
    final File file = new File(SpaceModule.MAIN_DIRECTORY, "jobs.yml");
    if (!file.exists())
        try {
            file.createNewFile();
        } catch (final IOException e) {
            e.printStackTrace();
        }
    final YamlConfiguration configuration = YamlConfiguration.loadConfiguration(file);
    for (final String jobName : jobs.keySet()) {
        final Job job = jobs.get(jobName);
        final String actionName = job.actionName;
        final List<Object> actionArguments = Arrays.asList(job.actionArguments);
        final String timeType = job.timeType;
        final String timeArgument = job.timeArgument;
        configuration.set(jobName + ".TimeType", timeType);
        configuration.set(jobName + ".TimeArgument", timeArgument);
        configuration.set(jobName + ".ActionName", actionName);
        configuration.set(jobName + ".ActionArguments", JSONValue.toJSONString(actionArguments)
                .replace("[[", "[").replace("],[", ",").replace("]]", "]"));
    }
    try {
        configuration.save(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:admin.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w  w  w  .ja va  2 s.  c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    response.setContentType("application/json;charset=UTF-8");
    String id = "";
    String nama = "";
    String email = "";
    String link = "";
    String admin = "";
    String icw = "";
    try {
        JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
        id = userAccount.get("id").toString();
        nama = userAccount.get("name").toString();
        email = userAccount.get("email").toString();
        link = userAccount.get("link").toString();
        admin = userAccount.get("admin").toString();
        icw = userAccount.get("icw").toString();
    } catch (Exception ex1) {
    }
    if (admin.equalsIgnoreCase("Y")) {
        try (PrintWriter out = response.getWriter()) {
            Vector dataPosisi = new Vector();
            dataPosisi.addElement("Menteri");
            dataPosisi.addElement("Pejabat Setingkat Menteri");
            dataPosisi.addElement("Duta Besar");
            JSONArray obj1 = new JSONArray();
            for (int i = 0; i < dataPosisi.size(); i++) {
                String FilterKey = "", FilterValue = "";
                String key = "posisi",
                        keyValue = dataPosisi.get(i).toString().toLowerCase().replaceAll(" ", "");
                String table = "posisi";
                DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
                //Filter linkFilter = new FilterPredicate(FilterKey, FilterOperator.EQUAL, FilterValue);
                Key AlasanStarCalonKey = KeyFactory.createKey(key, keyValue);
                Query query = new Query(table, AlasanStarCalonKey);
                PreparedQuery pq = datastore.prepare(query);
                JSONArray obj11 = new JSONArray();
                getData(obj11, table, key, keyValue, dataPosisi.get(i).toString(),
                        Query.SortDirection.ASCENDING);
                LinkedHashMap record = new LinkedHashMap();
                record.put("posisi", keyValue);
                record.put("nama", dataPosisi.get(i).toString());
                record.put("child", obj11);
                obj1.add(record);
            }
            out.print(JSONValue.toJSONString(obj1));
            out.flush();
        }
    }
}

From source file:com.jgoetsch.eventtrader.source.ApeStreamingMsgSource.java

protected HttpUriRequest createCommandRequest(String cmd, Map<String, Object> params) {
    Map<String, Object> cmdParams = new LinkedHashMap<String, Object>();
    cmdParams.put("cmd", cmd);
    cmdParams.put("chl", challenge++);
    if (params != null) {
        cmdParams.put("params", params);
    }/* ww  w  .jav  a  2  s. co m*/
    if (sessid != null) {
        cmdParams.put("sessid", sessid);
    }
    List<Object> cmdJson = new LinkedList<Object>();
    cmdJson.add(cmdParams);

    HttpPost req = new HttpPost(getUrl());
    req.addHeader("X-Requested-With", "XMLHttpRequest");
    try {
        String jsonCmd = JSONValue.toJSONString(cmdJson);
        req.setEntity(new StringEntity(jsonCmd, "application/x-www-form-urlencoded", "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        log.error("Error encoding request entity", e);
    }
    return req;
}

From source file:com.framework.testcase.testrail.APIClient.java

private Object sendRequest(String method, String uri, Object data) throws MalformedURLException, IOException {
    URL url = new URL(this.m_url + uri);

    // Create the connection object and set the required HTTP method
    // (GET/POST) and headers (content type and basic auth).
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("Content-Type", "application/json");

    String auth = getAuthorization(this.m_user, this.m_password);
    conn.addRequestProperty("Authorization", "Basic " + auth);

    if (method.equalsIgnoreCase("POST")) {
        // Add the POST arguments, if any. We just serialize the passed
        // data object (i.e. a dictionary) and then add it to the
        // request body.
        if (data != null) {
            byte[] block = JSONValue.toJSONString(data).getBytes("UTF-8");

            conn.setDoOutput(true);// w  w w .  j  a  va  2 s  . c  o  m
            OutputStream ostream = conn.getOutputStream();
            ostream.write(block);
            ostream.flush();
        }
    }

    // Execute the actual web request (if it wasn't already initiated
    // by getOutputStream above) and record any occurred errors (we use
    // the error stream in this case).
    int status = 0;
    try {
        status = conn.getResponseCode();
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
        System.err.println("the request is timeout from the server ,we quite the test");

    } catch (SSLHandshakeException ex) {
        ex.printStackTrace();
        System.err.println("the request is  Remote host closed connection during handshake");
    }

    InputStream istream;
    if (status != 200) {
        istream = conn.getErrorStream();
        if (istream == null) {

            new Exception("TestRail API return HTTP " + status + " (No additional error message received)");

        }
    } else {
        istream = conn.getInputStream();
    }

    // Read the response body, if any, and deserialize it from JSON.
    String text = "";
    if (istream != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(istream, "UTF-8"));

        String line;
        while ((line = reader.readLine()) != null) {
            text += line;
            text += System.getProperty("line.separator");
        }

        reader.close();
    }

    Object result;
    if (text != "") {
        result = JSONValue.parse(text);
    } else {
        result = new JSONObject();
    }

    // Check for any occurred errors and add additional details to
    // the exception message, if any (e.g. the error message returned
    // by TestRail).
    if (status != 200) {
        String error = "No additional error message received";
        if (result != null && result instanceof JSONObject) {
            JSONObject obj = (JSONObject) result;
            if (obj.containsKey("error")) {
                error = '"' + (String) obj.get("error") + '"';
            }
        }

        new Exception("TestRail API returned HTTP " + status + "(" + error + ")");
    }

    return result;
}