Example usage for org.json JSONStringer toString

List of usage examples for org.json JSONStringer toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Return the JSON text.

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.jav  a2 s .co  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: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();/*www  . j  a va 2 s.c  o  m*/
    }
    creator.endArray().endObject();
    return creator.toString();
}

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

private static String infoToJson(PackageInstallInfo info) {
    String value = null;/*from  w w w .  j a  v a 2 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.android.launcher2.InstallShortcutReceiver.java

private static void addToInstallQueue(SharedPreferences sharedPrefs, PendingInstallShortcutInfo info) {
    synchronized (sLock) {
        try {/*from w w  w  . jav a2  s.co  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);
        }
    }
}

From source file:org.sc.probro.servlets.UserListServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/* w  ww. java  2 s .  c  om*/
        UserCredentials creds = new UserCredentials();
        String contentType = getContentType(request);
        String content = null;

        Broker broker = getBroker();

        String ontologyID = null;
        User[] users = broker.listUsers(creds, ontologyID);

        if (contentType.equals(CONTENT_TYPE_JSON)) {
            JSONStringer stringer = new JSONStringer();
            try {
                stringer.object();
                stringer.key("vals");

                BrokerData.stringJSONArray(stringer, users);

                stringer.endObject();

            } catch (JSONException e) {
                throw new BrokerException(e);
            }
            content = stringer.toString();

        } else if (contentType.equals(CONTENT_TYPE_HTML)) {
            StringWriter stringer = new StringWriter();
            PrintWriter writer = new PrintWriter(stringer);

            User t = new User();
            writer.println("<table>");
            writer.println(t.writeHTMLRowHeader());
            for (User user : users) {
                writer.println(user.writeHTMLObject(true));
            }
            writer.println("</table>");

            content = stringer.toString();
        }

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(contentType);
        response.getWriter().println(content);

    } catch (BrokerException e) {
        handleException(response, e);
    }
}

From source file:fr.mby.opa.picsimpl.service.BasicPictureFactory.java

protected void loadMetadata(final Picture picture, final BufferedInputStream stream) throws IOException {
    try {//from   www  . j a  va2  s  .  c  o  m
        stream.reset();
        final Metadata metadata = ImageMetadataReader.readMetadata(stream, false);

        // Process all metadatas
        final JSONStringer jsonStringer = new JSONStringer();
        // Start main object
        jsonStringer.object();

        final Iterator<Directory> dirIt = metadata.getDirectories().iterator();
        while (dirIt.hasNext()) {
            final Directory dir = dirIt.next();
            // Start Directory
            jsonStringer.key(dir.getName()).object();
            final Collection<Tag> dirTags = dir.getTags();
            for (final Tag tag : dirTags) {
                final int tagType = tag.getTagType();
                final String tagName = tag.getTagName();
                final String tagDesc = tag.getDescription();
                // Add Tag
                jsonStringer.key(tagName + "[" + tagType + "]").value(tagDesc);
            }

            // End Directory
            jsonStringer.endObject();
        }

        // End main object
        jsonStringer.endObject();

        final String jsonMetadata = jsonStringer.toString();
        picture.setJsonMetadata(jsonMetadata);

        // Process specific metadata

        // Times
        final Timestamp originalTime = this.findOriginalTime(metadata);
        picture.setOriginalTime(originalTime);

        picture.setCreationTime(new Timestamp(System.currentTimeMillis()));

    } catch (final ImageProcessingException e) {
        // Unable to process metadata
        BasicPictureFactory.LOG.warn("Unable to read metadata !", e);
    } catch (final JSONException e) {
        // Technical problem
        BasicPictureFactory.LOG.warn("Problem while converting Metadata to JSON !", e);
        throw new RuntimeException("Problem while converting Metadata to JSON !", e);
    }
}

From source file:org.sc.probro.servlets.OntologyListServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//www.j ava  2  s  .  c  o  m
        UserCredentials creds = new UserCredentials();
        String contentType = getContentType(request);
        String content = null;

        Broker broker = getBroker();
        Ontology[] onts = broker.listOntologies(creds);

        if (contentType.equals(CONTENT_TYPE_JSON)) {
            JSONStringer stringer = new JSONStringer();

            try {
                stringer.object();

                stringer.key("vals");
                BrokerData.stringJSONArray(stringer, onts);

                stringer.endObject();
            } catch (JSONException e) {
                throw new BrokerException(e);
            }

            content = stringer.toString();

        } else if (contentType.equals(CONTENT_TYPE_HTML)) {
            StringWriter stringer = new StringWriter();
            PrintWriter writer = new PrintWriter(stringer);

            Ontology t = new Ontology();
            writer.println("<table>");
            writer.println(t.writeHTMLRowHeader());
            for (Ontology ont : onts) {
                writer.println(ont.writeHTMLObject(true));
            }
            writer.println("</table>");

            content = stringer.toString();
        }

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(contentType);
        response.getWriter().println(content);

    } catch (BrokerException e) {
        handleException(response, e);
    }
}

From source file:de.ailis.midi4js.MessageReceiver.java

/**
 * @see javax.sound.midi.Receiver#send(javax.sound.midi.MidiMessage, long)
 *//*from  w  w w.  jav a 2 s.co m*/
@Override
public void send(final MidiMessage message, final long timeStamp) {
    try {
        final JSONStringer json = new JSONStringer();
        json.object();
        json.key("status").value(message.getStatus());
        json.key("message");
        json.array();
        final byte[] data = message.getMessage();
        final int max = Math.min(data.length, message.getLength());
        for (int i = 0; i < max; i++)
            json.value(data[i] & 0xff);
        json.endArray();
        if (message instanceof ShortMessage)
            processShortMessage((ShortMessage) message, json);
        else if (message instanceof MetaMessage)
            processMetaMessage((MetaMessage) message, json);
        else if (message instanceof SysexMessage)
            processSysexMessage((SysexMessage) message, json);
        json.endObject();
        this.applet.execJSMethod("messageReceived", System.identityHashCode(this), json.toString(), timeStamp);
    } catch (final JSONException e) {
        throw new RuntimeException(e.toString(), e);
    }
}

From source file:com.google.blockly.android.control.BlocklyEvent.java

public String toJsonString() throws JSONException {
    JSONStringer out = new JSONStringer();
    out.object();//  w  w w . j  a  va2s.c  o  m
    out.key(JSON_TYPE);
    out.value(getTypeName());
    if (!TextUtils.isEmpty(mBlockId)) {
        out.key(JSON_BLOCK_ID);
        out.value(mBlockId);
    }
    if (!TextUtils.isEmpty(mGroupId)) {
        out.key(JSON_GROUP_ID);
        out.value(mGroupId);
    }
    writeJsonAttributes(out);
    // Workspace id is not included to reduce size over network.
    out.endObject();
    return out.toString();
}

From source file:org.jwebsocket.plugins.sharedobjects.SharedObjectsPlugIn.java

@Override
public void processToken(PlugInResponse aResponse, WebSocketConnector aConnector, Token aToken) {
    String lType = aToken.getType();
    String lNS = aToken.getNS();//w  w  w. ja  v a 2  s .c o m
    String lID = aToken.getString("id");
    String lDataType = aToken.getString("datatype");
    String lValue = aToken.getString("value");

    if (lType != null && (lNS == null || lNS.equals(NS_SHARED_OBJECTS))) {

        Token lResponse = getServer().createResponse(aToken);

        // create
        if (lType.equals("create")) {
            if (log.isDebugEnabled()) {
                log.debug("Processing 'create'...");
            }
            if (!isDataTypeValid(lDataType, aConnector, lResponse)) {
                return;
            }
            if (alreadyExists(lID, aConnector, lResponse)) {
                return;
            }
            sharedObjects.put(lID, string2Object(lDataType, lValue));

            Token lBCT = new Token(lNS, "event");
            lBCT.put("name", "created");
            lBCT.put("id", lID);
            lBCT.put("datatype", lDataType);
            lBCT.put("value", lValue);
            getServer().broadcastToken(aConnector, lBCT);

            // destroy
        } else if (lType.equals("destroy")) {
            if (log.isDebugEnabled()) {
                log.debug("Processing 'destroy'...");
            }
            if (!doesContain(lID, aConnector, lResponse)) {
                return;
            }
            sharedObjects.remove(lID);

            Token lBCT = new Token(lNS, "event");
            lBCT.put("name", "destroyed");
            lBCT.put("id", lID);
            getServer().broadcastToken(aConnector, lBCT);

            // get
        } else if (lType.equals("get")) {
            if (log.isDebugEnabled()) {
                log.debug("Processing 'get'...");
            }
            if (!doesContain(lID, aConnector, lResponse)) {
                return;
            }
            Object lObj = sharedObjects.get(lID);
            lResponse.put("id", lID);
            lResponse.put("result", lObj.toString());

            // put
        } else if (lType.equals("update")) {
            if (log.isDebugEnabled()) {
                log.debug("Processing 'update'...");
            }
            if (!isDataTypeValid(lDataType, aConnector, lResponse)) {
                return;
            }
            sharedObjects.put(lID, string2Object(lDataType, lValue));
            Token lBCT = new Token(lNS, "event");
            lBCT.put("name", "updated");
            lBCT.put("id", lID);
            lBCT.put("datatype", lDataType);
            lBCT.put("value", lValue);
            getServer().broadcastToken(aConnector, lBCT);

            // init
        } else if (lType.equals("init")) {
            if (log.isDebugEnabled()) {
                log.debug("Processing 'init'...");
            }
            Token lBCT = new Token(lNS, "event");
            lBCT.put("name", "init");

            String lData = null;
            try {
                JSONStringer jsonStringer = new JSONStringer();
                // start main object
                jsonStringer.object();
                // iterate through all items (fields) of the token
                Iterator<String> lIterator = sharedObjects.getKeys().iterator();
                while (lIterator.hasNext()) {
                    String lKey = lIterator.next();
                    Object lVal = sharedObjects.get(lKey);
                    if (lVal instanceof Collection) {
                        jsonStringer.key(lKey).array();
                        for (Object item : (Collection) lVal) {
                            jsonStringer.value(item);
                        }
                        jsonStringer.endArray();
                    } else {
                        jsonStringer.key(lKey).value(lVal);
                    }
                }
                // end main object
                jsonStringer.endObject();
                lData = jsonStringer.toString();
            } catch (JSONException ex) {
                log.error(ex.getClass().getSimpleName() + ": " + ex.getMessage());
            }
            lBCT.put("value", lData);
            getServer().sendToken(aConnector, lBCT);

        } else {
            log.warn("Invalid command " + lType + " received...");
            lResponse.put("code", -1);
            lResponse.put("msg", "invalid type '" + lType + "'");
        }

        getServer().sendToken(aConnector, lResponse);
    }

}