Example usage for org.json JSONStringer JSONStringer

List of usage examples for org.json JSONStringer JSONStringer

Introduction

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

Prototype

public JSONStringer() 

Source Link

Document

Make a fresh JSONStringer.

Usage

From source file:io.github.runassudo.launchert.InstallShortcutReceiver.java

private static void addToInstallQueue(SharedPreferences sharedPrefs, PendingInstallShortcutInfo info) {
    synchronized (sLock) {
        try {//from w w  w  .  j a v a  2  s.  c o  m
            JSONStringer json = new JSONStringer().object().key(DATA_INTENT_KEY).value(info.data.toUri(0))
                    .key(LAUNCH_INTENT_KEY).value(info.launchIntent.toUri(0)).key(NAME_KEY).value(info.name);
            if (info.icon != null) {
                byte[] iconByteArray = ItemInfo.flattenBitmap(info.icon);
                json = json.key(ICON_KEY)
                        .value(Base64.encodeToString(iconByteArray, 0, iconByteArray.length, Base64.DEFAULT));
            }
            if (info.iconResource != null) {
                json = json.key(ICON_RESOURCE_NAME_KEY).value(info.iconResource.resourceName);
                json = json.key(ICON_RESOURCE_PACKAGE_NAME_KEY).value(info.iconResource.packageName);
            }
            json = json.endObject();
            SharedPreferences.Editor editor = sharedPrefs.edit();
            if (DBG)
                Log.d(TAG, "Adding to APPS_PENDING_INSTALL: " + json);
            addToStringSet(sharedPrefs, editor, APPS_PENDING_INSTALL, json.toString());
            editor.commit();
        } catch (org.json.JSONException e) {
            Log.d(TAG, "Exception when adding shortcut: " + e);
        }
    }
}

From source file:com.bedatadriven.rebar.sync.server.JpaUpdateBuilder.java

public JpaUpdateBuilder() {
    json = new JSONStringer();
    try {//from  w  w w.  j a va  2  s  .c  om
        json.array();
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    context = new UnitMapping();
}

From source file:hu.bme.iit.quiz.endpoint.IndexEndpoint.java

private String createGatheringQuizzesUpdateString() {
    JSONStringer creator = new JSONStringer();
    creator.object().key("type").value("QUIZZESUPDATE").key("quizzes").array();
    for (String key : quizzesInGatheringPhase.keySet()) {
        QuizPresentation quizPresentation = quizzesInGatheringPhase.get(key);
        creator.object().key("username").value(quizPresentation.getOwner().getLogin()).key("quizname")
                .value(quizPresentation.getQuiz().getName()).key("presenationID")
                .value(quizPresentation.getId()).key("started").value(quizPresentation.getStarted())
                .endObject();/*from  w  w w. j  av  a  2 s.c  o m*/
    }
    creator.endArray().endObject();
    return creator.toString();
}

From source file:util.JSONManager.java

public static String createFlow(String dpid, String name, String cookie, String priority, String ingressPort,
        String active, String outport) throws JSONException {
    /*//  w  w w  .ja  va2  s.c o  m
        Primero se crean los objetos JSON para configurar los flujos.
        Luego se convierten en String.
    */
    String flow = new JSONStringer().object().key("switch").value(dpid).key("name").value(name).key("cookie")
            .value(cookie).key("priority").value(priority).key("ingress-port").value(ingressPort).key("active")
            .value(active).key("actions").value("output=" + outport).endObject().toString();

    return flow;
}

From source file:util.JSONManager.java

public static String deleteRequest(String name) throws JSONException {
    String flowname = new JSONStringer().object().key("name").value(name).endObject().toString();
    return flowname;
}

From source file:de.jaetzold.philips.hue.HueBridge.java

/**
 * Attempt to verify the given username is allowed to access the bridge instance.
 * If the username is not allowed (or not given, meaning <code>null</code>) and <code>waitForGrant</code> is <code>true</code>,
 * the method then waits for up to 30 seconds to be granted access to the bridge. This would be done by pressing the bridges button.
 * If authentication succeeds, the username for which it succeeded is then saved and the method returns <code>true</code>.
 *
 * <p>See <a href="http://developers.meethue.com/4_configurationapi.html#41_create_user">Philips hue API, Section 4.1</a> for further reference.</p>
 *
 * @see #authenticate(boolean)/*from   w w  w .j av  a  2 s.co  m*/
 *
 * @param usernameToTry a username to authenticate with or null if a new one should be generated by the bridge if access is granted through pressing the hardware button.
 * @param waitForGrant if true, this method blocks for up to 30 seconds or until access to the bridge is allowed, whichever comes first.
 *
 * @return true, if this bridge API instance has now a username that is verified to be allowed to access the bridge device.
 */
public boolean authenticate(String usernameToTry, boolean waitForGrant) {
    if (usernameToTry != null && !usernameToTry.matches("\\s*[-\\w]{10,40}\\s*")) {
        throw new IllegalArgumentException(
                "A username must be 10-40 characters long and may only contain the characters -,_,a-b,A-B,0-9");
    }

    if (!isAuthenticated() || !equalEnough(username, usernameToTry)) {
        // if we have an usernameToTry then check that first whether it already exists
        // I just don't get why a "create new user" request for an existing user results in the same 101 error as when the user does not exist.
        // But for this reason this additional preliminary request is necessary.
        if (!equalEnough(null, usernameToTry)) {
            try {
                completeSync(usernameToTry);
                authenticated = true;
            } catch (HueCommException e) {
                e.printStackTrace();
            }
        }

        if (!isAuthenticated()) {
            long start = System.currentTimeMillis();
            int waitSeconds = 30;
            do {
                JSONObject response = new JSONObject();
                try {
                    final JSONWriter jsonWriter = new JSONStringer().object().key("devicetype")
                            .value(deviceType);
                    if (usernameToTry != null && usernameToTry.trim().length() >= 10) {
                        jsonWriter.key("username").value(usernameToTry.trim());
                    }
                    // use comm directly here because the user is not currently set
                    response = comm.request(POST, "api", jsonWriter.endObject().toString()).get(0);
                } catch (IOException e) {
                    log.log(Level.WARNING, "IOException on create user request", e);
                }
                final JSONObject success = response.optJSONObject("success");
                if (success != null && success.has("username")) {
                    username = success.getString("username");
                    authenticated = true;
                    waitForGrant = false;
                } else {
                    final JSONObject error = response.optJSONObject("error");
                    if (error != null && error.has("type")) {
                        if (error.getInt("type") != 101) {
                            log.warning("Got unexpected error on create user: " + error);
                            waitForGrant = false;
                        }
                    }
                }
                if (waitForGrant) {
                    if (System.currentTimeMillis() - start > waitSeconds * 1000) {
                        waitForGrant = false;
                    } else {
                        try {
                            Thread.sleep(900 + Math.round(Math.random() * 100));
                        } catch (InterruptedException e) {
                        }
                    }
                }
            } while (waitForGrant);
        }
    }

    if (isAuthenticated() && !initialSyncDone) {
        completeSync(username);
    }

    return isAuthenticated();
}

From source file:de.jaetzold.philips.hue.HueBridge.java

/**
 * Helper method to shorten creation of a JSONObject String.
 * @return A JSONStringer with an object already 'open' and auto-object-end on a call to toString()
 *///  w  ww . j  av  a 2  s . c  om
private static JSONStringer JO() {
    return new JSONStringer() {
        {
            object();
        }

        @Override
        public String toString() {
            return writer.toString() + (mode != 'd' ? "}" : "");
        }
    };
}

From source file:com.android.launcher4.compat.PackageInstallerCompatV16.java

private static String infoToJson(PackageInstallInfo info) {
    String value = null;/*from w  w  w  .  j  a  va2  s.  c o  m*/
    try {
        JSONStringer json = new JSONStringer().object().key(KEY_STATE).value(info.state).key(KEY_PROGRESS)
                .value(info.progress).endObject();
        value = json.toString();
    } catch (JSONException e) {
        Log.e(TAG, "failed to serialize app state update", e);
    }
    return value;
}

From source file:com.commonsware.android.vidtry.URLHistory.java

void save(Writer out) throws JSONException, IOException {
    JSONStringer json = new JSONStringer().object();

    for (HistoryItem h : spareCopy) {
        h.emit(json);/*www .j ava2s. com*/
    }

    out.write(json.endObject().toString());
}

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

private static void addToInstallQueue(SharedPreferences sharedPrefs, PendingInstallShortcutInfo info) {
    synchronized (sLock) {
        try {/*from  w  w  w  .ja v a 2s  .  c  o  m*/
            JSONStringer json = new JSONStringer().object().key(DATA_INTENT_KEY).value(info.data.toUri(0))
                    .key(LAUNCH_INTENT_KEY).value(info.launchIntent.toUri(0)).key(NAME_KEY).value(info.name);
            if (info.icon != null) {
                byte[] iconByteArray = ItemInfo.flattenBitmap(info.icon);
                json = json.key(ICON_KEY)
                        .value(Base64.encodeToString(iconByteArray, 0, iconByteArray.length, Base64.DEFAULT));
            }
            if (info.iconResource != null) {
                json = json.key(ICON_RESOURCE_NAME_KEY).value(info.iconResource.resourceName);
                json = json.key(ICON_RESOURCE_PACKAGE_NAME_KEY).value(info.iconResource.packageName);
            }
            json = json.endObject();
            SharedPreferences.Editor editor = sharedPrefs.edit();
            addToStringSet(sharedPrefs, editor, APPS_PENDING_INSTALL, json.toString());
            editor.commit();
        } catch (org.json.JSONException e) {
            Log.d("InstallShortcutReceiver", "Exception when adding shortcut: " + e);
        }
    }
}