Example usage for org.json JSONWriter endObject

List of usage examples for org.json JSONWriter endObject

Introduction

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

Prototype

public JSONWriter endObject() throws JSONException 

Source Link

Document

End an object.

Usage

From source file:charitypledge.Pledge.java

public void JsonImport() {

    try {/*from w  w  w. j  a va2 s . c  o  m*/
        InputStream foo = new FileInputStream(JSONFile);
        JSONTokener t = new JSONTokener(foo);
        JSONObject jsonObj = new JSONObject(t);
        foo.close();
        JSONArray jsonList = jsonObj.getJSONArray("contributors");
        for (int i = 0; i < jsonList.length(); i++) {
            // loop array
            JSONObject objects = jsonList.getJSONObject(i);
            String nameField = objects.getString("name");
            String typeField = objects.getString("charity");
            String contributionField = objects.getString("contribution");
            // Add row to jTable
            loadPledgeTable(nameField, typeField, contributionField);
        }
    } catch (FileNotFoundException e) {
        JSONWriter jsonWriter;
        try {
            jsonWriter = new JSONWriter(new FileWriter(JSONFile));
            jsonWriter.object();
            jsonWriter.key("contributors");
            jsonWriter.array();
            jsonWriter.endArray();
            jsonWriter.endObject();
            //jsonWriter.close();
            tableRefresh();
        } catch (IOException f) {
            f.printStackTrace();
        } catch (JSONException g) {
            g.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:charitypledge.Pledge.java

public void JsonWrite(String[] args) {

    String[] values = args;//from w  w  w . j a  v  a2  s . co  m
    JSONObject obj = new JSONObject();
    JSONArray objArray = new JSONArray();
    try {
        if (args == null || values.length == 0) {
            throw new Exception("Noting to write to file");
        } else {
            String title = "";
            String value = "";

            for (int i = (values.length - 1); i >= 0; i--) {
                if ((i % 2) == 0) {
                    title = values[i];
                    obj.put(title, value);
                } else {
                    value = values[i];
                }
            }
            objArray.put(obj);
        }

        try {
            try {
                InputStream foo = new FileInputStream(JSONFile);
                JSONTokener t = new JSONTokener(foo);
                JSONObject json = new JSONObject(t);
                foo.close();
                FileWriter file = new FileWriter(JSONFile);
                json.append("contributors", obj);
                file.write(json.toString(5));
                file.close();
                tableRefresh();
            } catch (FileNotFoundException e) {
                JSONWriter jsonWriter;
                try {
                    jsonWriter = new JSONWriter(new FileWriter(JSONFile));
                    jsonWriter.object();
                    jsonWriter.key("contributors");
                    jsonWriter.array();
                    jsonWriter.endArray();
                    jsonWriter.endObject();
                    InputStream foo = new FileInputStream(JSONFile);
                    JSONTokener t = new JSONTokener(foo);
                    JSONObject json = new JSONObject(t);
                    foo.close();
                    FileWriter file = new FileWriter(JSONFile);
                    json.append("contributors", obj);
                    file.write(json.toString(5));
                    file.close();
                    tableRefresh();
                } catch (IOException f) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        int pic = JOptionPane.ERROR_MESSAGE;
        JOptionPane.showMessageDialog(null, e, "", pic);
    }
}

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 a  v a 2s  .  c  om
 *
 * @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:com.google.enterprise.connector.db.diffing.JsonDocument.java

public String toJson() {
    // JSON does not support custom serialization, so we have to find
    // the InputStreamFactory for the content and serialize it
    // ourselves. This could be cleaner if we supported toString on the
    // InputStreamFactory implementations, but that would mean less
    // control over when the LOB was materialized in memory.
    try {//from   www  . j ava2  s .c o  m
        StringWriter buffer = new StringWriter();
        JSONWriter writer = new JSONWriter(buffer);
        writer.object();
        for (String name : JSONObject.getNames(jsonObject)) {
            writer.key(name).value(toJson(name, jsonObject.get(name)));
        }
        writer.endObject();
        return buffer.toString();
    } catch (IOException e) {
        throw new SnapshotRepositoryRuntimeException("Error serializing document " + objectId, e);
    } catch (JSONException e) {
        throw new SnapshotRepositoryRuntimeException("Error serializing document " + objectId, e);
    }
}

From source file:org.everit.osgi.webconsole.configuration.Configurable.java

public void toJSON(final JSONWriter writer) {
    writer.object();/*w  w  w . j av a2  s  .com*/
    writer.key("name");
    writer.value(getDisplayedName());
    writer.key("description");
    writer.value(description);
    writer.key("bundleName");
    writer.value(bundleName);
    writer.key("location");
    writer.value(location);
    writer.key("pid");
    writer.value(pid);
    writer.key("factoryPid");
    writer.value(factoryPid);
    writer.key("boundBundleName");
    writer.value(boundBundleName);
    writer.endObject();
}

From source file:com.comcast.cqs.persistence.CQSMessagePartitionedCassandraPersistence.java

private String getMessageJSON(CQSMessage message) throws JSONException {

    Writer writer = new StringWriter();
    JSONWriter jw = new JSONWriter(writer);

    jw = jw.object();/*w ww.  j  a va  2s . co m*/
    jw.key("MessageId").value(message.getMessageId());
    jw.key("MD5OfBody").value(message.getMD5OfBody());
    jw.key("Body").value(message.getBody());

    if (message.getAttributes() == null) {
        message.setAttributes(new HashMap<String, String>());
    }

    if (!message.getAttributes().containsKey(CQSConstants.SENT_TIMESTAMP)) {
        message.getAttributes().put(CQSConstants.SENT_TIMESTAMP, "" + System.currentTimeMillis());
    }

    if (!message.getAttributes().containsKey(CQSConstants.APPROXIMATE_RECEIVE_COUNT)) {
        message.getAttributes().put(CQSConstants.APPROXIMATE_RECEIVE_COUNT, "0");
    }

    if (message.getAttributes() != null) {
        for (String key : message.getAttributes().keySet()) {
            String value = message.getAttributes().get(key);
            if (value == null || value.isEmpty()) {
                value = "";
            }
            jw.key(key).value(value);
        }
    }

    if (message.getMessageAttributes() != null && message.getMessageAttributes().size() > 0) {
        jw.key("MD5OfMessageAttributes").value(message.getMD5OfMessageAttributes());
        jw.key("MessageAttributes");
        jw.object();
        for (String key : message.getMessageAttributes().keySet()) {
            jw.key(key);
            jw.object();
            CQSMessageAttribute messageAttribute = message.getMessageAttributes().get(key);
            if (messageAttribute.getStringValue() != null) {
                jw.key("StringValue").value(messageAttribute.getStringValue());
            } else if (messageAttribute.getBinaryValue() != null) {
                jw.key("BinaryValue").value(messageAttribute.getBinaryValue());
            }
            jw.key("DataType").value(messageAttribute.getDataType());
            jw.endObject();
        }
        jw.endObject();
    }

    jw.endObject();

    return writer.toString();
}

From source file:org.qi4j.entitystore.sql.SQLEntityStoreMixin.java

protected void writeEntityState(DefaultEntityState state, Writer writer, String version)
        throws EntityStoreException {
    try {//from w ww.ja v a 2  s  .  c  o m
        JSONWriter json = new JSONWriter(writer);
        JSONWriter properties = json.object().key("identity").value(state.identity().identity())
                .key("application_version").value(application.version()).key("type")
                .value(state.entityDescriptor().entityType().type().name()).key("version").value(version)
                .key("modified").value(state.lastModified()).key("properties").object();
        EntityType entityType = state.entityDescriptor().entityType();
        for (PropertyType propertyType : entityType.properties()) {
            Object value = state.properties().get(propertyType.qualifiedName());
            json.key(propertyType.qualifiedName().name());
            if (value == null) {
                json.value(null);
            } else {
                propertyType.type().toJSON(value, json);
            }
        }

        JSONWriter associations = properties.endObject().key("associations").object();
        for (Map.Entry<QualifiedName, EntityReference> stateNameEntityReferenceEntry : state.associations()
                .entrySet()) {
            EntityReference value = stateNameEntityReferenceEntry.getValue();
            associations.key(stateNameEntityReferenceEntry.getKey().name())
                    .value(value != null ? value.identity() : null);
        }

        JSONWriter manyAssociations = associations.endObject().key("manyassociations").object();
        for (Map.Entry<QualifiedName, List<EntityReference>> stateNameListEntry : state.manyAssociations()
                .entrySet()) {
            JSONWriter assocs = manyAssociations.key(stateNameListEntry.getKey().name()).array();
            for (EntityReference entityReference : stateNameListEntry.getValue()) {
                assocs.value(entityReference.identity());
            }
            assocs.endArray();
        }

        JSONWriter namedAssociations = associations.endObject().key("namedassociations").object();
        for (Map.Entry<QualifiedName, Map<String, EntityReference>> stateNameListEntry : state
                .namedAssociations().entrySet()) {
            JSONWriter assocs = namedAssociations.key(stateNameListEntry.getKey().name()).object();
            Map<String, EntityReference> value = stateNameListEntry.getValue();
            for (Map.Entry<String, EntityReference> entry : value.entrySet()) {
                assocs.key(entry.getKey()).value(entry.getValue());
            }
            assocs.endObject();
        }
        manyAssociations.endObject().endObject();
    } catch (JSONException e) {
        throw new EntityStoreException("Could not store EntityState", e);
    }
}

From source file:org.everit.osgi.webconsole.configuration.DisplayedAttribute.java

private void optionsToJSON(final JSONWriter writer) {
    if (!options.isEmpty()) {
        writer.key("options");
        writer.object();//w  ww. j a v  a2  s  .c o  m
        for (String key : options.keySet()) {
            writer.key(key);
            writer.value(options.get(key));
        }
        writer.endObject();
    }
}

From source file:org.everit.osgi.webconsole.configuration.DisplayedAttribute.java

public void toJSON(final JSONWriter writer) {
    writer.object();//  w w w  . java  2s.  co  m
    writer.key("id");
    writer.value(id);
    writer.key("name");
    writer.value(name);
    writer.key("description");
    writer.value(description);
    writer.key("value");
    valueToJSON(writer);
    writer.key("type");
    typeToJSON(writer);
    writer.endObject();
}

From source file:org.everit.osgi.webconsole.configuration.DisplayedAttribute.java

private void typeToJSON(final JSONWriter writer) {
    writer.object();//from w w w. j a v  a 2  s  .c  om
    writer.key("baseType");
    writer.value(type);
    writer.key("maxOccurences");
    if (maxOccurences == Integer.MIN_VALUE || maxOccurences == Integer.MAX_VALUE) {
        writer.value("unbound");
    } else {
        writer.value(maxOccurences);
    }
    optionsToJSON(writer);
    writer.endObject();
}