Example usage for org.json JSONWriter key

List of usage examples for org.json JSONWriter key

Introduction

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

Prototype

public JSONWriter key(String string) throws JSONException 

Source Link

Document

Append a key.

Usage

From source file:tap.formatter.JSONFormat.java

/**
 * Formats in JSON and writes the given {@link TAPColumn} in the given output.
 * /*from   ww w  .j a  v  a2 s .  co m*/
 * @param tapCol         The column metadata to format/write in JSON.
 * @param out            The stream in which the formatted column metadata must be written.
 * 
 * @throws IOException      If there is an error while writing the field metadata.
 * @throws JSONException   If there is an error while formatting something in JSON format.
 * @throws TAPException      If there is any other error (by default: never happen).
 */
protected void writeFieldMeta(TAPColumn tapCol, JSONWriter out)
        throws IOException, TAPException, JSONException {
    // {
    out.object();

    // "name": "..."
    out.key("name").value(tapCol.getADQLName());

    // "description": "..." (if any)
    if (tapCol.getDescription() != null && tapCol.getDescription().trim().length() > 0)
        out.key("description").value(tapCol.getDescription());

    // "datatype": "..."
    VotType votType = new VotType(tapCol.getDatatype());
    out.key("datatype").value(votType.datatype);

    // "arraysize": "..." (if any)
    if (votType.arraysize != null)
        out.key("arraysize").value(votType.arraysize);

    // "xtype": "..." (if any)
    if (votType.xtype != null)
        out.key("xtype").value(votType.xtype);

    // "unit": "..." (if any)
    if (tapCol.getUnit() != null && tapCol.getUnit().length() > 0)
        out.key("unit").value(tapCol.getUnit());

    // "ucd": "..." (if any)
    if (tapCol.getUcd() != null && tapCol.getUcd().length() > 0)
        out.key("ucd").value(tapCol.getUcd());

    // "utype": "..." (if any)
    if (tapCol.getUtype() != null && tapCol.getUtype().length() > 0)
        out.key("utype").value(tapCol.getUtype());

    // }
    out.endObject();
}

From source file:charitypledge.Pledge.java

public void JsonImport() {

    try {// w ww . j a v  a2 s .co  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  a 2 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 ww.java 2 s .  c o 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: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  ww w . ja v  a  2s  .c om
        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  a v a 2s.c  o m*/
    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:de.jaetzold.philips.hue.HueLightBulb.java

private List<JSONObject> stateChange(String param, Object value) {
    if (value == null) {
        throw new IllegalArgumentException("A value of null is not allowed for any of the lights states");
    }//  w w  w.  ja v a 2 s  . c o  m
    final JSONObject stateTransaction = stateTransactionJson.get();
    if (stateTransaction == null) {
        JSONWriter json = JO();
        if (transitionTime != null) {
            json = json.key("transitiontime").value(transitionTime);
        }
        return bridge.checkedSuccessRequest(PUT, "/lights/" + getId() + "/state", json.key(param).value(value));
    } else {
        stateTransaction.put(param, value);
        return null;
    }
}

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();//from   ww  w. ja v  a  2 s  . c om
    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 w  w.j av a2 s. c  om
        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();// www.j  a v  a2  s.c o  m
        for (String key : options.keySet()) {
            writer.key(key);
            writer.value(options.get(key));
        }
        writer.endObject();
    }
}