Example usage for org.json JSONTokener JSONTokener

List of usage examples for org.json JSONTokener JSONTokener

Introduction

In this page you can find the example usage for org.json JSONTokener JSONTokener.

Prototype

public JSONTokener(String s) 

Source Link

Document

Construct a JSONTokener from a string.

Usage

From source file:griffon.plugins.preferences.persistors.JsonPreferencesPersistor.java

@Nonnull
@SuppressWarnings("unchecked")
private JSONObject doRead(@Nonnull InputStream inputStream) throws IOException {
    if (inputStream.available() > 0) {
        return new JSONObject(new JSONTokener(inputStream));
    }/*from w w w . j  av  a2  s .c o m*/
    return new JSONObject();
}

From source file:org.everit.json.schema.ValidationExceptionTest.java

private JSONObject readFile(final String absPath) {
    return new JSONObject(new JSONTokener(getClass().getResourceAsStream(absPath)));
}

From source file:com.mattermost.service.Promise.java

void onResult(T r, String error) {
    MattermostApplication.handler.post(new Runnable() {
        @Override//from   w  w  w .ja  v  a 2s. c  o  m
        public void run() {
            try {
                if (busy != null) {
                    busy.dismiss();
                }
                busy = null;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    });

    result = r;

    if (error != null) {
        // lets parse...
        error = error.trim();
        if (error.startsWith("{") && error.endsWith("}")) {
            try {
                JSONTokener tokener = new JSONTokener(error);
                errorJson = (JSONObject) tokener.nextValue();
                if (errorJson.has("message")) {
                    this.error = errorJson.optString("message");
                }
            } catch (Exception ex) {
                // ignore...
                this.error = error;
            }
        } else {
            this.error = error;
        }
    }

    MattermostApplication.handler.post(new Runnable() {
        @Override
        public void run() {
            for (IResultListener<T> resultListener : next) {
                try {
                    resultListener.onResult(Promise.this);
                } catch (Exception ex) {
                    MattermostApplication.logError(ex);
                }
            }
        }
    });

}

From source file:com.github.caofangkun.bazelipse.command.IdeBuildInfo.java

/**
 * Constructs a map of label -> {@link IdeBuildInfo} from a list of files, parsing each files into
 * a {@link JSONObject} and then converting that {@link JSONObject} to an {@link IdeBuildInfo}
 * object./*w w w  .j  a v a 2 s . c o m*/
 */
static ImmutableMap<String, IdeBuildInfo> getInfo(List<String> files) throws IOException, InterruptedException {
    ImmutableMap.Builder<String, IdeBuildInfo> infos = ImmutableMap.builder();
    for (String s : files) {
        if (!s.isEmpty()) {
            IdeBuildInfo buildInfo = new IdeBuildInfo(new JSONObject(new JSONTokener(new FileInputStream(s))));
            infos.put(buildInfo.label, buildInfo);
        }
    }
    return infos.build();
}

From source file:com.android.launcher2.InstallShortcutReceiver.java

private static ArrayList<PendingInstallShortcutInfo> getAndClearInstallQueue(SharedPreferences sharedPrefs) {
    synchronized (sLock) {
        Set<String> strings = sharedPrefs.getStringSet(APPS_PENDING_INSTALL, null);
        if (strings == null) {
            return new ArrayList<PendingInstallShortcutInfo>();
        }//from  w  w  w.  j a  va2 s. c  o m
        ArrayList<PendingInstallShortcutInfo> infos = new ArrayList<PendingInstallShortcutInfo>();
        for (String json : strings) {
            try {
                JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
                Intent data = Intent.parseUri(object.getString(DATA_INTENT_KEY), 0);
                Intent launchIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);
                String name = object.getString(NAME_KEY);
                String iconBase64 = object.optString(ICON_KEY);
                String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY);
                String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY);
                if (iconBase64 != null && !iconBase64.isEmpty()) {
                    byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT);
                    Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length);
                    data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b);
                } else if (iconResourceName != null && !iconResourceName.isEmpty()) {
                    Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource();
                    iconResource.resourceName = iconResourceName;
                    iconResource.packageName = iconResourcePackageName;
                    data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
                }
                data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
                PendingInstallShortcutInfo info = new PendingInstallShortcutInfo(data, name, launchIntent);
                infos.add(info);
            } catch (org.json.JSONException e) {
                Log.d("InstallShortcutReceiver", "Exception reading shortcut to add: " + e);
            } catch (java.net.URISyntaxException e) {
                Log.d("InstallShortcutReceiver", "Exception reading shortcut to add: " + e);
            }
        }
        sharedPrefs.edit().putStringSet(APPS_PENDING_INSTALL, new HashSet<String>()).commit();
        return infos;
    }
}

From source file:uk.ac.imperial.presage2.web.export.DataExportServlet.java

/**
 * Takes a POST request with <code>query</code> parameter being a JSON table
 * specification and writes the resulting table back as the response. By
 * default we return a CSV file with the {@link CSVTableExporter}. Alternate
 * {@link TableExporter}s can be specified with the <code>format</code>
 * parameter.// ww  w  .  ja v a  2 s  . com
 * 
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logRequest(req);
    JSONObject query = null;
    try {
        query = new JSONObject(new JSONTokener(req.getParameter("query")));
        logger.info(query.toString());
    } catch (JSONException e) {
        logger.warn("Failed to parse postdata", e);
        resp.sendError(400, "Failed to parse postdata: " + e.getMessage());
        return;
    }
    try {
        Iterable<Iterable<String>> table = processRequest(query);
        TableExporter exporter = new CSVTableExporter();
        exporter.httpExportTable(table, resp);
    } catch (JSONException e) {
        logger.warn("Failed to process request", e);
        resp.sendError(400, "Failed to process request");
    }
}

From source file:org.gluu.oxpush2.u2f.v2.SoftwareDevice.java

public TokenResponse enroll(String jsonRequest, OxPush2Request oxPush2Request, Boolean isDeny)
        throws JSONException, IOException, U2FException {
    JSONObject request = (JSONObject) new JSONTokener(jsonRequest).nextValue();

    if (request.has("registerRequests")) {
        JSONArray registerRequestArray = request.getJSONArray("registerRequests");
        if (registerRequestArray.length() == 0) {
            throw new U2FException("Failed to get registration request!");
        }/*w  ww .  ja  v  a 2s . c  o m*/
        request = (JSONObject) registerRequestArray.get(0);
    }

    if (!request.getString(JSON_PROPERTY_VERSION).equals(SUPPORTED_U2F_VERSION)) {
        throw new U2FException("Unsupported U2F_V2 version!");
    }

    String version = request.getString(JSON_PROPERTY_VERSION);
    String appParam = request.getString(JSON_PROPERTY_APP_ID);
    String challenge = request.getString(JSON_PROPERTY_SERVER_CHALLENGE);
    String origin = oxPush2Request.getIssuer();

    EnrollmentResponse enrollmentResponse = u2fKey
            .register(new EnrollmentRequest(version, appParam, challenge, oxPush2Request));
    if (BuildConfig.DEBUG)
        Log.d(TAG, "Enrollment response: " + enrollmentResponse);

    JSONObject clientData = new JSONObject();
    if (isDeny) {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, REGISTER_CANCEL_TYPE);
    } else {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, REQUEST_TYPE_REGISTER);
    }
    clientData.put(JSON_PROPERTY_SERVER_CHALLENGE, challenge);
    clientData.put(JSON_PROPERTY_SERVER_ORIGIN, origin);

    String clientDataString = clientData.toString();
    byte[] resp = rawMessageCodec.encodeRegisterResponse(enrollmentResponse);

    String deviceType = getDeviceType();
    String versionName = getVersionName();

    DeviceData deviceData = new DeviceData();
    deviceData.setUuid(DeviceUuidManager.getDeviceUuid(context).toString());
    deviceData.setPushToken(PushNotificationManager.getRegistrationId(context));
    deviceData.setType(deviceType);
    deviceData.setPlatform("android");
    deviceData.setName(Build.MODEL);
    deviceData.setOsName(versionName);
    deviceData.setOsVersion(Build.VERSION.RELEASE);

    String deviceDataString = new Gson().toJson(deviceData);

    JSONObject response = new JSONObject();
    response.put("registrationData", Utils.base64UrlEncode(resp));
    response.put("clientData", Utils.base64UrlEncode(clientDataString.getBytes(Charset.forName("ASCII"))));
    response.put("deviceData", Utils.base64UrlEncode(deviceDataString.getBytes(Charset.forName("ASCII"))));

    TokenResponse tokenResponse = new TokenResponse();
    tokenResponse.setResponse(response.toString());
    tokenResponse.setChallenge(new String(challenge));
    tokenResponse.setKeyHandle(new String(enrollmentResponse.getKeyHandle()));

    return tokenResponse;
}

From source file:org.gluu.oxpush2.u2f.v2.SoftwareDevice.java

public TokenResponse sign(String jsonRequest, String origin, Boolean isDeny)
        throws JSONException, IOException, U2FException {
    if (BuildConfig.DEBUG)
        Log.d(TAG, "Starting to process sign request: " + jsonRequest);
    JSONObject request = (JSONObject) new JSONTokener(jsonRequest).nextValue();

    JSONArray authenticateRequestArray = null;
    if (request.has("authenticateRequests")) {
        authenticateRequestArray = request.getJSONArray("authenticateRequests");
        if (authenticateRequestArray.length() == 0) {
            throw new U2FException("Failed to get authentication request!");
        }/*from   w  w w .j a va  2s  .  c  om*/
    } else {
        authenticateRequestArray = new JSONArray();
        authenticateRequestArray.put(request);
    }

    Log.i(TAG, "Found " + authenticateRequestArray.length() + " authentication requests");

    AuthenticateResponse authenticateResponse = null;
    String authenticatedChallenge = null;
    JSONObject authRequest = null;
    for (int i = 0; i < authenticateRequestArray.length(); i++) {
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Process authentication request: " + authRequest);
        authRequest = (JSONObject) authenticateRequestArray.get(i);

        if (!authRequest.getString(JSON_PROPERTY_VERSION).equals(SUPPORTED_U2F_VERSION)) {
            throw new U2FException("Unsupported U2F_V2 version!");
        }

        String version = authRequest.getString(JSON_PROPERTY_VERSION);
        String appParam = authRequest.getString(JSON_PROPERTY_APP_ID);
        String challenge = authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE);
        byte[] keyHandle = Base64.decode(authRequest.getString(JSON_PROPERTY_KEY_HANDLE),
                Base64.URL_SAFE | Base64.NO_WRAP);

        authenticateResponse = u2fKey.authenticate(new AuthenticateRequest(version,
                AuthenticateRequest.USER_PRESENCE_SIGN, challenge, appParam, keyHandle));
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Authentication response: " + authenticateResponse);
        if (authenticateResponse != null) {
            authenticatedChallenge = challenge;
            break;
        }
    }

    if (authenticateResponse == null) {
        return null;
    }

    JSONObject clientData = new JSONObject();
    if (isDeny) {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, AUTHENTICATE_CANCEL_TYPE);
    } else {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, REQUEST_TYPE_AUTHENTICATE);
    }
    clientData.put(JSON_PROPERTY_SERVER_CHALLENGE, authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE));
    clientData.put(JSON_PROPERTY_SERVER_ORIGIN, origin);

    String keyHandle = authRequest.getString(JSON_PROPERTY_KEY_HANDLE);
    String clientDataString = clientData.toString();
    byte[] resp = rawMessageCodec.encodeAuthenticateResponse(authenticateResponse);

    JSONObject response = new JSONObject();
    response.put("signatureData", Utils.base64UrlEncode(resp));
    response.put("clientData", Utils.base64UrlEncode(clientDataString.getBytes(Charset.forName("ASCII"))));
    response.put("keyHandle", keyHandle);

    TokenResponse tokenResponse = new TokenResponse();
    tokenResponse.setResponse(response.toString());
    tokenResponse.setChallenge(authenticatedChallenge);
    tokenResponse.setKeyHandle(keyHandle);

    return tokenResponse;
}

From source file:com.xgf.inspection.qrcode.google.zxing.client.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException {

    CharSequence contents = HttpHelper.downloadViaHttp(
            "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;//from   ww  w  .  j  av a 2 s . co m
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>(authorsArray.length());
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

    } catch (JSONException e) {
        throw new IOException(e.toString());
    }

    Collection<String> newTexts = new ArrayList<String>();

    if (title != null && title.length() > 0) {
        newTexts.add(title);
    }

    if (authors != null && !authors.isEmpty()) {
        boolean first = true;
        StringBuilder authorsText = new StringBuilder();
        for (String author : authors) {
            if (first) {
                first = false;
            } else {
                authorsText.append(", ");
            }
            authorsText.append(author);
        }
        newTexts.add(authorsText.toString());
    }

    if (pages != null && pages.length() > 0) {
        newTexts.add(pages + "pp.");
    }

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}

From source file:org.official.json.CookieList.java

/**
 * Convert a cookie list into a JSONObject. A cookie list is a sequence
 * of name/value pairs. The names are separated from the values by '='.
 * The pairs are separated by ';'. The names and the values
 * will be unescaped, possibly converting '+' and '%' sequences.
 *
 * To add a cookie to a cooklist,/*from   ww w. j ava2 s .  com*/
 * cookielistJSONObject.put(cookieJSONObject.getString("name"),
 *     cookieJSONObject.getString("value"));
 * @param string  A cookie list string
 * @return A JSONObject
 * @throws JSONException
 */
public static JSONObject toJSONObject(String string) throws JSONException {
    JSONObject jo = new JSONObject();
    JSONTokener x = new JSONTokener(string);
    while (x.more()) {
        String name = Cookie.unescape(x.nextTo('='));
        x.next('=');
        jo.put(name, Cookie.unescape(x.nextTo(';')));
        x.next();
    }
    return jo;
}