Example usage for org.json.simple JSONValue parse

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

Introduction

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

Prototype

public static Object parse(String s) 

Source Link

Usage

From source file:mml.handler.get.MMLGetHandler.java

/**
 * Get a resource from the database if it already exists
 * @param db the collection name/* w  w  w  .  j a v  a 2s  .  c  om*/
 * @param docID the resource docID
 * @return the resource or null
 * @throws MMLException 
 */
public static AeseResource doGetResource(String db, String docID) throws MMLException {
    String res = null;
    JSONObject doc = null;
    AeseResource resource = null;
    try {
        res = Connector.getConnection().getFromDb(db, docID);
    } catch (Exception e) {
        throw new MMLException(e);
    }
    if (res != null)
        doc = (JSONObject) JSONValue.parse(res);
    if (doc != null) {
        String format = (String) doc.get(JSONKeys.FORMAT);
        if (format == null)
            throw new MMLException("doc missing format");
        String version1 = (String) doc.get(JSONKeys.VERSION1);
        resource = new AeseResource();
        if (version1 != null)
            resource.setVersion1(version1);
        if (doc.containsKey(JSONKeys.DESCRIPTION) && format.equals(Formats.TEXT))
            resource.setDescription((String) doc.get(JSONKeys.DESCRIPTION));
        resource.setFormat(format);
        resource.setContent((String) doc.get(JSONKeys.BODY));
    }
    return resource;
}

From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java

public static JSONObject pullNeutron(String host, String tenantId, String token) throws IOException {

    String url = String.format("http://%s:9696/v2.0/ports", host, tenantId);
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    String responseStr = sendGET(obj, con, "", token);
    JSONObject ports = (JSONObject) JSONValue.parse(responseStr);

    return ports;
}

From source file:com.teozcommunity.teozfrank.duelme.util.UpdateChecker.java

/**
 * Query the API to find the latest approved file's details.
 *///from  w  w  w.  ja va 2  s.  co m
public void query() {
    URL url = null;

    try {
        // Create the URL to query using the project's ID
        url = new URL(API_HOST + API_QUERY + projectID);
    } catch (MalformedURLException e) {
        // There was an error creating the URL

        e.printStackTrace();
        return;
    }

    try {
        // Open a connection and query the project
        URLConnection conn = url.openConnection();

        // Add the user-agent to identify the program
        conn.addRequestProperty("User-Agent", "ServerModsAPI-Example (by Gravity)");

        // Read the response of the query
        // The response will be in a JSON format, so only reading one line is necessary.
        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = reader.readLine();

        // Parse the array of files from the query's response
        JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() > 0) {
            // Get the newest file's details
            JSONObject latest = (JSONObject) array.get(array.size() - 1);

            // Get the version's title
            String versionName = (String) latest.get(API_NAME_VALUE);

            // Get the version's link
            String versionLink = (String) latest.get(API_LINK_VALUE);

            // Get the version's release type
            String versionType = (String) latest.get(API_RELEASE_TYPE_VALUE);

            // Get the version's file name
            String versionFileName = (String) latest.get(API_FILE_NAME_VALUE);

            // Get the version's game version
            String versionGameVersion = (String) latest.get(API_GAME_VERSION_VALUE);

            versionName = versionName.replaceAll("[a-zA-Z]", "");
            versionName = versionName.replaceAll(" ", "");

            String pluginVersion = plugin.getDescription().getVersion();

            pluginVersion = pluginVersion.replaceAll("Alpha", "");
            pluginVersion = pluginVersion.replaceAll("Beta", "");
            pluginVersion = pluginVersion.replaceAll("Release", "");
            pluginVersion = pluginVersion.replaceAll(" ", "");

            if (!versionName.equals(pluginVersion)) {
                this.updateAvailable = true;
                SendConsoleMessage.info("There is a new update available!");
                SendConsoleMessage.info("download it on bukkit dev " + ChatColor.YELLOW
                        + "http://dev.bukkit.org/bukkit-plugins/duelme/");
            } else {
                this.updateAvailable = false;
                SendConsoleMessage.info("plugin is up to date!");
            }

        } else {
            System.out.println("There are no files for this project");
        }
    } catch (IOException e) {
        // There was an error reading the query
        SendConsoleMessage.severe("There was an error checking for updates!");
        return;
    }
}

From source file:compare.handler.get.MetadataHandler.java

/**
 * Handle a request to get some metadata for a document
 * @param request the http request/*from   www  . j  a  v  a2 s  . c  o m*/
 * @param response the response
 * @param urn the current urn (ignored)
 * @throws CompareException if the resource could not be found
 */
public void handle(HttpServletRequest request, HttpServletResponse response, String urn)
        throws CompareException {
    try {
        Connection conn = Connector.getConnection();
        docid = request.getParameter(Params.DOCID);
        if (docid != null && docid.length() > 0) {
            String res = conn.getFromDb(Database.METADATA, docid);
            JSONObject jObj1 = null;
            if (res != null) {
                jObj1 = (JSONObject) JSONValue.parse(res);
                if (jObj1.containsKey(metadataKey)) {
                    metadataValue = (String) jObj1.get(metadataKey);
                    saved = true;
                }
            }
            if (metadataValue == null)
                getMetadataFromCortex(conn);
            saveToMetadata(jObj1, conn);
        } else
            metadataValue = "";
        response.setContentType("text/plain");
        response.getWriter().write(metadataValue);
    } catch (Exception e) {
        throw new CompareException(e);
    }
}

From source file:com.p000ison.dev.simpleclans2.updater.bamboo.BambooBuild.java

private static JSONObject parseJSON(Reader reader) {
    Object parse = JSONValue.parse(reader);

    if (!(parse instanceof JSONObject)) {
        Logging.debug(Level.SEVERE, "Failed at reading the update info! Please contact the developers!");
    }/*from ww  w.  j  a  va  2s  .  c om*/

    return (JSONObject) parse;
}

From source file:eu.hansolo.accs.RestClient.java

public void putLocation(final Location LOCATION) {
    JSONObject jsonObject = getLocation(LOCATION.name);
    final String OID = ((JSONObject) JSONValue.parse(jsonObject.get("_id").toString())).get("$oid").toString();
    URIBuilder builder = new URIBuilder();
    builder.setScheme("https").setHost("api.mlab.com").setPort(443)
            .setPath(String.join("/", DbCollection.LOCATIONS.REST_URL, OID))
            //.setParameter("u", "true")
            .setParameter("apiKey", MLAB_API_KEY);
    putSpecific(builder, LOCATION);//  w w w .ja v  a 2s  . c om
    updateLocations();
}

From source file:eu.wordnice.wnconsole.WNCListener.java

@SuppressWarnings("unchecked")
@Override//from   ww w  .j a  v a  2 s .  c o m
public void handle(Thread thr_cur, HIO hio) {
    try {
        if (hio.PATH == null || !hio.PATH.equals("/") || hio.GET == null) {
            try {
                WNCUtils.writeHeaders(hio, "200 OK", 2);
                hio.out.write(new byte[] { '{', '}' });
            } catch (Throwable t) {
            }
            try {
                hio.close();
            } catch (Throwable t2) {
            }
            return;
        }

        // <String, JSONObject or JSONArray or primitive>
        Map<String, Object> settings = new Map<String, Object>();

        // <String, Map<String, Object>>
        Map<String, Object> args = new Map<String, Object>();
        int i = 0;
        for (; i < hio.GET.size(); i++) {
            String name = hio.GET.getNameI(i);
            String svalue = hio.GET.getI(i);
            if (svalue == null || name == null) {
                continue;
            }
            name = name.trim();
            svalue = svalue.trim();
            if (svalue.length() == 0 || name.length() == 0) {
                continue;
            }
            try {
                Object value = JSONValue.parse(svalue);
                if (value instanceof JSONObject) {
                    value = WNCUtils.sortObject((JSONObject) value);
                    if (name.equals("settings")) {
                        settings.addAll((Map<String, Object>) value);
                    }
                    args.addWC(name, value);
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }

        Map<String, Object> out_complet = new Map<String, Object>();

        WNCStore store = new WNCStore();

        for (i = 0; i < args.size(); i++) {
            String arg_name = args.getNameI(i);
            Object value = args.getI(i);

            if (!(value instanceof Map)) {
                continue;
            }

            try {
                Long.parseLong(arg_name);
            } catch (Throwable t) {
                continue;
            }

            Map<String, Object> out = new Map<String, Object>();
            Map<String, Object> cur = (Map<String, Object>) value;

            store.players = null;
            store.plugins = null;
            store.worlds = null;

            Set<String> unh = null;

            int i2 = 0;
            for (; i2 < cur.size(); i2++) {
                String key = cur.getNameI(i2);
                Object val = cur.getI(i2);

                /*** 153 EXTEND AREA ***/

                if (eu.wordnice.wnconsole.hio.WNCHIO_Player.handleHIO(this.wnc, store, out, key, val))
                    continue;
                if (eu.wordnice.wnconsole.hio.WNCHIO_World.handleHIO(this.wnc, store, out, key, val))
                    continue;
                if (eu.wordnice.wnconsole.hio.WNCHIO_Plugin.handleHIO(this.wnc, store, out, key, val))
                    continue;
                if (eu.wordnice.wnconsole.hio.WNCHIO_File.handleHIO(this.wnc, store, out, key, val))
                    continue;

                /*** 177 ENDIF EXTEND AREA ***/

                if (unh == null) {
                    unh = new Set<String>();
                }
                unh.addWC(key);
            }
            if (unh != null) {
                out.addWC("unhandled", unh);
            }
            out_complet.addWC(arg_name, out);
        }
        /*
         * DONE! Lets them know what we did (not)
         */
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            out_complet.toJsonString(baos);
            byte[] response = baos.toByteArray();
            WNCUtils.writeHeaders(hio, "200 OK", response.length);
            hio.out.write(response);
        } catch (Throwable t) {
        }
        try {
            hio.close();
        } catch (Throwable t2) {
        }
    } catch (Throwable et) {
        this.wnc.init.getLogger().severe("Error occured while executing instructions... Details:");
        et.printStackTrace();
        try {
            WNCUtils.writeHeaders(hio, "200 OK", 2);
            hio.out.write(new byte[] { '{', '}' });
        } catch (Throwable t) {
        }
        try {
            hio.close();
        } catch (Throwable t2) {
        }
        return;
    }
}

From source file:com.domsplace.DomsCommandsXenforoAddon.Threads.XenforoUpdateThread.java

@Override
public void run() {
    debug("THREAD STARTED");
    long start = getNow();
    while (start + TIMEOUT <= getNow() && player == null) {
    }/*w ww  .j a va  2s  . c om*/
    this.stopThread();
    this.deregister();
    if (player == null)
        return;

    boolean alreadyActivated = false;
    boolean isActivated = false;

    try {
        String x = player.getSavedVariable("xenforo");
        alreadyActivated = x.equalsIgnoreCase("yes");
    } catch (Exception e) {
    }

    try {
        String url = XenforoManager.XENFORO_MANAGER.yml.getString("xenforo.root", "") + APPEND;
        if (url.equals(APPEND))
            return;

        String encodedData = "name=" + encode("username") + "&value=" + encode(this.player.getPlayer())
                + "&_xfResponseType=json";
        //String rawData = "name=username";
        String type = "application/x-www-form-urlencoded; charset=UTF-8";
        //String encodedData = URLEncoder.encode(rawData, "ISO-8859-1"); 
        URL u = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", type);
        conn.setRequestProperty("Content-Length", String.valueOf(encodedData.length()));
        conn.setRequestProperty("User-Agent", USER_AGENT);
        conn.setRequestProperty("Referer", XenforoManager.XENFORO_MANAGER.yml.getString("xenforo.root", ""));
        conn.setUseCaches(false);

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(encodedData);
        wr.flush();

        InputStream in = conn.getInputStream();
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();

        String inputStr;
        while ((inputStr = streamReader.readLine()) != null)
            responseStrBuilder.append(inputStr);

        String out = responseStrBuilder.toString();
        JSONObject o = (JSONObject) JSONValue.parse(out);
        try {
            isActivated = o.get("_redirectMessage").toString().equalsIgnoreCase("ok");
        } catch (NullPointerException e) {
            isActivated = true;
        }
        debug("GOT: " + isActivated);
    } catch (Exception e) {
        if (DebugMode)
            e.printStackTrace();
        return;
    }

    player.setSavedVariable("xenforo", (isActivated ? "yes" : "no"));
    player.save();

    if (isActivated && !alreadyActivated) {
        runCommands(XenforoManager.XENFORO_MANAGER.yml.getStringList("commands.onRegistered"));
    }

    if (!isActivated && alreadyActivated) {
        runCommands(XenforoManager.XENFORO_MANAGER.yml.getStringList("commands.onDeRegistered"));
    }
}

From source file:com.alvexcore.repo.documents.generation.ExportDataListToXlsx.java

protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    Map<String, Object> model = new HashMap<String, Object>();

    final String FOLDER_NAME = "datalists-exports";
    final String XLS_SHEET_NAME = "DataList";
    // Parse the JSON, if supplied
    JSONObject json = null;//  ww  w .ja v a  2 s  .co m
    String contentType = req.getContentType();
    if (contentType != null && contentType.indexOf(';') != -1) {
        contentType = contentType.substring(0, contentType.indexOf(';'));
    }
    if (MimetypeMap.MIMETYPE_JSON.equals(contentType)) {
        try {
            json = (JSONObject) JSONValue.parse(req.getContent().getContent());
        } catch (Exception e) {
            status.setCode(500);
            model.put("message", "Invalid JSON");
            return model;
        }
    }

    String siteName;
    String fileName;
    JSONArray rows;

    try {
        siteName = (String) json.get("site");
        fileName = (String) json.get("fileName");
        rows = (JSONArray) json.get("rows");
    } catch (Exception e) {
        status.setCode(500);
        model.put("message", "Mandatory fields were not provided");
        return model;
    }

    fileName += ".xlsx";

    SiteInfo site = siteService.getSite(siteName);

    NodeRef container = siteService.getContainer(siteName, "documentLibrary");
    if (container == null)
        container = siteService.createContainer(siteName, "documentLibrary", null, null);

    NodeRef folder = getChildByName(container, FOLDER_NAME);

    if (folder == null) {
        Map<QName, Serializable> properties = new HashMap<QName, Serializable>(11);
        properties.put(ContentModel.PROP_NAME, FOLDER_NAME);

        folder = nodeService.createNode(container, ContentModel.ASSOC_CONTAINS,
                QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, FOLDER_NAME),
                ContentModel.TYPE_FOLDER, properties).getChildRef();
    }

    NodeRef file = getChildByName(folder, fileName);
    if (file == null) {
        Map<QName, Serializable> properties = new HashMap<QName, Serializable>(11);
        properties.put(ContentModel.PROP_NAME, fileName);

        file = nodeService.createNode(folder, ContentModel.ASSOC_CONTAINS,
                QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, fileName), ContentModel.TYPE_CONTENT,
                properties).getChildRef();
    }

    Workbook wb;

    try {
        wb = createXlsx(rows, XLS_SHEET_NAME);
    } catch (Exception e) {
        status.setCode(500);
        model.put("message", "Can not create file");
        return model;
    }

    try {
        ContentWriter writer = contentService.getWriter(file, ContentModel.PROP_CONTENT, true);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        wb.write(baos);
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        writer.setMimetype(MimetypeMap.MIMETYPE_EXCEL);
        writer.putContent(bais);
    } catch (Exception e) {
        status.setCode(500);
        model.put("message", "Can not save file");
        return model;
    }

    model.put("nodeRef", file.toString());
    model.put("name", fileName);
    status.setCode(200);
    return model;
}

From source file:cs.rsa.ts14dist.appserver.RabbitMQRPCConnector.java

@Override
public JSONObject sendHighPriorityRequestAndBlockUntilReply(JSONObject payload) throws IOException {
    String response = null;//  w  w w. j a v a 2 s .  c  om
    String corrId = UUID.randomUUID().toString();

    BasicProperties props = new BasicProperties.Builder().correlationId(corrId)
            .replyTo(replyHighPriorityQueueName).build();

    String message = payload.toJSONString();

    logger.trace("Send request: " + message);
    channelHighPriority.basicPublish("", requestHighPriorityQueueName, props, message.getBytes());

    while (true) {
        QueueingConsumer.Delivery delivery = null;
        try {
            delivery = consumerHighPriority.nextDelivery();
        } catch (ShutdownSignalException e) {
            logger.error("ShutdownException: " + e.getMessage());
            e.printStackTrace();
        } catch (ConsumerCancelledException e) {
            logger.error("ConsumerCancelledException: " + e.getMessage());
            e.printStackTrace();
        } catch (InterruptedException e) {
            logger.error("InterruptedException: " + e.getMessage());
            e.printStackTrace();
        }
        if (delivery.getProperties().getCorrelationId().equals(corrId)) {
            response = new String(delivery.getBody(), "UTF-8");
            logger.trace("Retrieved reply: " + response);
            break;
        }
    }

    JSONObject reply = (JSONObject) JSONValue.parse(response);
    return reply;
}