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:ch.simas.jtoggl.JToggl.java

/**
 * All users in the workspace with the given id.
 * //from  ww w  .  java  2 s .com
 * @param workspaceId
 *            id of the workspace
 * @return all users
 */
public List<User> getWorkspaceUsers(long workspaceId) {
    Client client = prepareClient();
    String url = WORKSPACES_USERS.replace(PLACEHOLDER, String.valueOf(workspaceId));
    WebResource webResource = client.resource(url);

    String response = webResource.get(String.class);
    JSONArray data = (JSONArray) JSONValue.parse(response);

    List<User> users = new ArrayList<User>();
    if (data != null) {
        for (Object obj : data) {
            JSONObject entryObject = (JSONObject) obj;
            users.add(new User(entryObject.toJSONString()));
        }
    }
    return users;
}

From source file:com.dsh105.commodus.data.Updater.java

private boolean read() {
    try {//from   w  ww .  j av  a 2s.c o m
        final URLConnection conn = this.url.openConnection();
        conn.setConnectTimeout(5000);

        if (this.apiKey != null) {
            conn.addRequestProperty("X-API-Key", this.apiKey);
        }
        conn.addRequestProperty("User-Agent", "Updater (by Gravity)");

        conn.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            this.plugin.getLogger()
                    .warning("The updater could not find any files for the project id " + this.id);
            this.result = UpdateResult.FAIL_BADID;
            return false;
        }

        this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE);
        this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE);
        this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE);
        this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1))
                .get(Updater.VERSION_VALUE);

        return true;
    } catch (final IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            this.plugin.getLogger()
                    .warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
            this.plugin.getLogger().warning("Please double-check your configuration to ensure it is correct.");
            this.result = UpdateResult.FAIL_APIKEY;
        } else {
            this.plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating.");
            this.plugin.getLogger().warning(
                    "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
            this.result = UpdateResult.FAIL_DBO;
        }
        e.printStackTrace();
        return false;
    }
}

From source file:com.bchalk.GVCallback.callback.GVCommunicator.java

public boolean verifyPhone(String number, long phoneId, int verificationCode) {
    if (!isLoggedIn()) {
        if (!login()) {
            return false;
        }// w  w  w  .  j  a  v  a 2s  .c om
    }
    try {
        HttpPost post = new HttpPost(BASE + "/voice/call/verifyForwarding");
        List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();

        data.add(new BasicNameValuePair("_rnr_se", myToken));
        data.add(new BasicNameValuePair("code", String.valueOf(verificationCode)));
        data.add(new BasicNameValuePair("forwardingNumber", number));
        data.add(new BasicNameValuePair("phoneId", String.valueOf(phoneId)));
        data.add(new BasicNameValuePair("subscriberNumber", "undefined"));

        post.setEntity(new UrlEncodedFormEntity(data));

        HttpResponse response = myClient.execute(post);
        String rsp = getContent(response.getEntity());
        JSONObject val = (JSONObject) JSONValue.parse(rsp);
        return (Boolean) val.get("ok");
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.treasure_data.client.bulkimport.BulkImportClientAdaptorImpl.java

private void doCreateSession(CreateSessionRequest request, CreateSessionResult result) throws ClientException {
    request.setCredentials(client.getTreasureDataCredentials());
    validator.validateCredentials(client, request);

    String jsonData = null;//ww  w.j  a  va2 s.co  m
    int code = 0;
    String message = null;
    try {
        conn = createConnection();

        // send request
        String path = String.format(HttpURL.V3_CREATE, HttpConnectionImpl.e(request.getSessionName()),
                HttpConnectionImpl.e(request.getDatabaseName()), HttpConnectionImpl.e(request.getTableName()));
        Map<String, String> header = new HashMap<String, String>();
        setUserAgentHeader(header);
        Map<String, String> params = null;
        conn.doPostRequest(request, path, header, params);

        // receive response code
        code = conn.getResponseCode();
        message = conn.getResponseMessage();
        if (code != HttpURLConnection.HTTP_OK) {
            String errMessage = conn.getErrorMessage();
            LOG.severe(HttpClientException.toMessage("Create session failed", message, code));
            LOG.severe(errMessage);
            throw new HttpClientException("Create session failed", message + ", detail = " + errMessage, code);
        }

        // receive response body
        jsonData = conn.getResponseBody();
        validator.validateJSONData(jsonData);
    } catch (IOException e) {
        LOG.throwing(getClass().getName(), "createSession", e);
        LOG.severe(HttpClientException.toMessage(e.getMessage(), message, code));
        throw new HttpClientException("Create session failed", message, code, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // parse JSON data {"name":"sess01"}
    @SuppressWarnings({ "unchecked", "rawtypes" })
    Map map = (Map<String, String>) JSONValue.parse(jsonData);
    validator.validateJavaObject(jsonData, map);

    result.set(request.getSession());
}

From source file:bbdn.lti2.LTI2Servlet.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void handleResultRequest(HttpServletRequest request, HttpServletResponse response, String sourcedid)
        throws java.io.IOException {
    IMSJSONRequest jsonRequest = null;//w w  w .  j  a  va 2s  . c om
    String retval = null;
    if ("GET".equals(request.getMethod())) {
        String grade = (String) PERSIST.get("grade");
        String comment = (String) PERSIST.get("comment");

        Map jsonResponse = new TreeMap();
        Map resultScore = new TreeMap();

        jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.RESULT_CONTEXT);
        jsonResponse.put(LTI2Constants.TYPE, StandardServices.RESULT_TYPE);
        resultScore.put(LTI2Constants.TYPE, LTI2Constants.GRADE_TYPE_DECIMAL);
        jsonResponse.put(LTI2Constants.COMMENT, grade);
        resultScore.put(LTI2Constants.VALUE, comment);
        jsonResponse.put(LTI2Constants.RESULTSCORE, resultScore);
        response.setContentType(StandardServices.RESULT_FORMAT);
        response.setStatus(HttpServletResponse.SC_OK);
        String jsonText = JSONValue.toJSONString(jsonResponse);
        M_log.debug(jsonText);
        PrintWriter out = response.getWriter();
        out.println(jsonText);
        return;
    } else if ("PUT".equals(request.getMethod())) {
        retval = "Error parsing input data";
        try {
            jsonRequest = new IMSJSONRequest(request);
            // System.out.println(jsonRequest.getPostBody());
            JSONObject requestData = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
            String comment = (String) requestData.get(LTI2Constants.COMMENT);
            JSONObject resultScore = (JSONObject) requestData.get(LTI2Constants.RESULTSCORE);
            String sGrade = (String) resultScore.get(LTI2Constants.VALUE);
            Double dGrade = new Double(sGrade);

            PERSIST.put("comment", comment);
            PERSIST.put("grade", dGrade + "");
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        } catch (Exception e) {
            retval = "Error: " + e.getMessage();
        }
    } else {
        retval = "Unsupported operation:" + request.getMethod();
    }

    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    doErrorJSON(request, response, jsonRequest, (String) retval, null);
}

From source file:gov.nih.nci.rembrandt.web.ajax.DynamicReportGenerator.java

public String processAnnotation(String key) {
    String s = "";

    Object o = JSONValue.parse(key);
    JSONObject obj = (JSONObject) o;//  ww w .  j a  v  a  2 s  . c  om
    String kt = obj.get("keyType") != null ? (String) obj.get("keyType") : "";
    String k = obj.get("key") != null ? (String) obj.get("key") : "";
    String aurl = System.getProperty("rembrandt.annotations.links." + kt) != null
            ? ((String) System.getProperty("rembrandt.annotations.links." + kt) + k)
            : "";
    return aurl;
}

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

public void registerDevice() {
    T.UI();//w  w w  .  j a v a  2 s .co  m
    final HttpClient httpClient = HTTPUtil.getHttpClient();
    final String email = mWizard.getEmail();
    final String tosAge = mWizard.getTOSAge();
    final String pushNotifcationsEnabled = mWizard.getPushNotificationEnabled();
    final String timestamp = "" + mWizard.getTimestamp();
    final String deviceId = mWizard.getDeviceId();
    final String registrationId = mWizard.getRegistrationId();
    // Make call to Rogerthat
    String message = getString(R.string.activating);
    final ProgressDialog progressDialog = UIUtils.showProgressDialog(mActivity, null, message, true, false);
    final SafeRunnable showErrorDialog = new SafeRunnable() {
        @Override
        protected void safeRun() throws Exception {
            T.UI();
            progressDialog.dismiss();
            UIUtils.showErrorPleaseRetryDialog(mActivity);
        }
    };

    runOnWorker(new SafeRunnable() {
        @Override
        protected void safeRun() throws Exception {
            T.REGISTRATION();
            String version = "3";
            String signature = SecurityUtils.sha256(version + " " + email + " " + timestamp + " " + deviceId
                    + " " + registrationId + " " + CloudConstants.REGISTRATION_MAIN_SIGNATURE);

            HttpPost httppost = HTTPUtil.getHttpPost(mActivity,
                    CloudConstants.REGISTRATION_REGISTER_DEVICE_URL);
            try {
                List<NameValuePair> nameValuePairs = HTTPUtil.getRegistrationFormParams(mActivity);
                nameValuePairs.add(new BasicNameValuePair("version", version));
                nameValuePairs.add(new BasicNameValuePair("registration_time", timestamp));
                nameValuePairs.add(new BasicNameValuePair("device_id", deviceId));
                nameValuePairs.add(new BasicNameValuePair("registration_id", registrationId));
                nameValuePairs.add(new BasicNameValuePair("signature", signature));
                nameValuePairs.add(new BasicNameValuePair("email", email));
                nameValuePairs.add(new BasicNameValuePair("tos_age", tosAge));
                nameValuePairs
                        .add(new BasicNameValuePair("push_notifications_enabled", pushNotifcationsEnabled));
                nameValuePairs.add(new BasicNameValuePair("GCM_registration_id", getGCMRegistrationId()));
                nameValuePairs.add(new BasicNameValuePair("hardware_model", SystemPlugin.getDeviceModelName()));
                TelephonyManager telephonyManager = (TelephonyManager) mService
                        .getSystemService(Context.TELEPHONY_SERVICE);
                if (telephonyManager != null) {
                    nameValuePairs.add(
                            new BasicNameValuePair("sim_carrier_name", telephonyManager.getSimOperatorName()));
                }

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpClient.execute(httppost);

                int statusCode = response.getStatusLine().getStatusCode();
                HttpEntity entity = response.getEntity();

                if (entity == null) {
                    runOnUI(showErrorDialog);
                    return;
                }

                @SuppressWarnings("unchecked")
                final Map<String, Object> responseMap = (Map<String, Object>) JSONValue
                        .parse(new InputStreamReader(entity.getContent()));

                if (statusCode != 200 || responseMap == null) {
                    if (statusCode == 500 && responseMap != null) {
                        final String errorMessage = (String) responseMap.get("error");
                        if (errorMessage != null) {
                            runOnUI(new SafeRunnable() {
                                @Override
                                protected void safeRun() throws Exception {
                                    T.UI();
                                    progressDialog.dismiss();
                                    UIUtils.showDialog(mActivity, null, errorMessage);
                                }
                            });
                            return;
                        }
                    }
                    runOnUI(showErrorDialog);
                    return;
                }
                JSONObject account = (JSONObject) responseMap.get("account");
                setAgeAndGenderSet((Boolean) responseMap.get("age_and_gender_set"));

                final RegistrationInfo info = new RegistrationInfo(email,
                        new Credentials((String) account.get("account"), (String) account.get("password")));
                runOnUI(new SafeRunnable() {
                    @Override
                    protected void safeRun() throws Exception {
                        T.UI();
                        mWizard.setEmail(email);
                        mWizard.save();
                        tryConnect(progressDialog, 1, getString(R.string.registration_establish_connection,
                                email, getString(R.string.app_name)) + " ", info);
                    }
                });

            } catch (Exception e) {
                L.d(e);
                runOnUI(showErrorDialog);
            }
        }
    });
}

From source file:at.nonblocking.cliwix.cli.CliwixCliClient.java

private static JSONObject uploadFile(String serverUrl, String path, File file) {
    if (debug)/*w w  w  .ja v  a 2 s.c  o m*/
        console.println("Uploading file to: " + path);

    Response response = null;
    try {
        response = postHandler.post(serverUrl, path, new FileInputStream(file), file.length(),
                CONTENT_TYPE.UPLOAD, file.getName(), new ProgressCallbackConsoleImpl(console), cookieManager);
    } catch (IOException e) {
        if (debug)
            console.printStacktrace(e);
        console.printlnError("Error: File not found. " + file.getAbsolutePath());
        console.exit(EXIT_STATUS_FAIL);
        return null;
    }

    handleError(response);

    JSONObject obj = null;
    try {
        String exportResult = response.getResponseAsString();
        if (debug)
            console.println("Received: " + exportResult);
        return (JSONObject) JSONValue.parse(exportResult);
    } catch (IOException e) {
        if (debug)
            console.printStacktrace(e);
        console.printlnError("Error: " + e.getMessage());
        console.exit(EXIT_STATUS_FAIL);
    } finally {
        response.disconnect();
    }

    return null;
}

From source file:bammerbom.ultimatecore.bukkit.UltimateUpdater.java

/**
 * Make a connection to the BukkitDev API and request the newest file's
 * details.//  ww  w  .ja v  a 2  s. c  o m
 *
 * @return true if successful.
 */
private boolean read() {
    try {
        final URLConnection conn = this.url.openConnection();
        conn.setConnectTimeout(5000);

        conn.addRequestProperty("User-Agent", UltimateUpdater.USER_AGENT);

        conn.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.isEmpty()) {
            r.log("No updates found.");
            this.result = UpdateResult.FAIL_BADID;
            return false;
        }

        UltimateUpdater.versionName = (String) ((Map) array.get(array.size() - 1))
                .get(UltimateUpdater.TITLE_VALUE);
        this.versionLink = (String) ((Map) array.get(array.size() - 1)).get(UltimateUpdater.LINK_VALUE);
        this.versionType = (String) ((Map) array.get(array.size() - 1)).get(UltimateUpdater.TYPE_VALUE);
        this.versionGameVersion = (String) ((Map) array.get(array.size() - 1))
                .get(UltimateUpdater.VERSION_VALUE);

        return true;
    } catch (final IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            r.log("Invalid API key.");
            this.result = UpdateResult.FAIL_APIKEY;
        } else {
            r.log("Could not connect to bukkit.org, update check failed. "
                    + (e.getCause() != null ? "(" + e.getCause() + ")" : ""));
            this.result = UpdateResult.FAIL_DBO;
        }
        return false;
    }
}

From source file:ca.inverse.sogo.engine.source.SOGoUtilities.java

/**
 * //w ww .j a v a 2 s.  c om
 * @param source
 * @param context
 * @param log
 * @return
 */
public static TimeZone getUserTimeZone(SOGoSyncSource source, SyncContext context, FunambolLogger log) {
    String tz;

    tz = null;

    try {
        ResultSet rs;
        Statement s;

        // We first fetch the user's time zone
        s = source.getDBConnection().createStatement();
        rs = s.executeQuery("SELECT c_defaults FROM sogo_user_profile WHERE c_uid = '"
                + context.getPrincipal().getUsername() + "'");

        if (rs.next()) {
            String data;
            Object o;

            data = rs.getString(1);
            o = null;

            try {
                JSONObject json;

                json = (JSONObject) JSONValue.parse(data);

                try {
                    o = json.get("SOGoTimeZone");
                } catch (Exception nfe) {
                    o = json.get("TimeZone");
                }

            } catch (Exception pe) {
                log.error("Exception occured in getUserTimeZone(): " + pe.toString(), pe);
            }

            if (o != null) {
                tz = o.toString();
            }
        }

        rs.close();
        s.close();

    } catch (Exception e) {
        log.error("Exception occured in getUserTimeZone(): " + e.toString(), e);
    }

    if (tz == null) {
        log.info("No timezone defined in SOGo for user: " + context.getPrincipal().getUsername());
        return TimeZone.getTimeZone("GMT");
    }

    return TimeZone.getTimeZone(tz);
}