Example usage for org.json JSONWriter array

List of usage examples for org.json JSONWriter array

Introduction

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

Prototype

public JSONWriter array() throws JSONException 

Source Link

Document

Begin appending a new array.

Usage

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

private void getConfigForm(final HttpServletResponse resp, final String pid, final String factoryPid,
        final String location, final String configAdminPid) {
    try {/*from  w w w  . j  a v  a2 s  . c  om*/
        JSONWriter writer = new JSONWriter(resp.getWriter());
        writer.array();
        configManager.getConfigForm(pid, factoryPid, location, configAdminPid)
                .forEach((attr) -> attr.toJSON(writer));
        writer.endArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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

private void listConfigAdminServices(final Writer writer) {
    JSONWriter jsonWriter = new JSONWriter(writer);
    jsonWriter.array();
    configManager.configAdminStream().forEach((confAdmin) -> {
        jsonWriter.object();//from  w w  w.j a v a2  s .  c  o  m
        jsonWriter.key("pid");
        jsonWriter.value(confAdmin.getProperty("service.pid"));
        jsonWriter.key("description");
        jsonWriter.value(confAdmin.getProperty("service.description"));
        jsonWriter.key("bundleId");
        jsonWriter.value(confAdmin.getBundle().getBundleId());
        jsonWriter.endObject();
    });
    jsonWriter.endArray();
}

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

private void listManagedServices(final String configAdminPid, final Writer writer) {
    JSONWriter jsonWriter = new JSONWriter(writer);
    jsonWriter.array();
    configManager.lookupConfigurations(configAdminPid)
            .forEach((configurable) -> configurable.toJSON(jsonWriter));
    jsonWriter.endArray();//www .  j  a  va  2  s  .c o m
}

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

private void printServiceSuggestions(final HttpServletResponse resp, final String configAdminPid,
        final String pid, final String attributeId, final String ldapQuery) {
    try {//from  w ww  . j  av a 2s  .  c  o m
        JSONWriter writer = new JSONWriter(resp.getWriter());
        List<ServiceSuggestion> suggestions;
        try {
            suggestions = configManager.getServiceSuggestions(configAdminPid, pid, attributeId, ldapQuery);
            writer.array();
            for (ServiceSuggestion suggestion : suggestions) {
                suggestion.toJSON(writer);
            }
            writer.endArray();
        } catch (InvalidSyntaxException e) {
            // resp.setStatus(403);
            writer.object();
            writer.key("error");
            writer.value("invalid query: " + e.getMessage());
            writer.endObject();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.araqne.confdb.file.Exporter.java

public void exportData(OutputStream os) throws IOException {
    if (os == null)
        throw new IllegalArgumentException("export output stream cannot be null");

    logger.debug("araqne confdb: start export data");
    db.lock();/*from  w  ww .j ava2 s .com*/
    try {
        OutputStreamWriter writer = new OutputStreamWriter(os, Charset.forName("utf-8"));
        JSONWriter jw = new JSONWriter(writer);

        jw.object();

        jw.key("metadata");
        jw.object();
        jw.key("version").value(1);
        jw.key("date").value(sdf.format(new Date()));
        jw.endObject();

        jw.key("collections");
        jw.object();

        for (String name : db.getCollectionNames()) {
            ConfigCollection col = db.getCollection(name);

            // collection name
            jw.key(name);

            // typed doc list
            jw.array();

            jw.value("list");

            // doc list begin
            jw.array();

            ConfigIterator it = col.findAll();
            try {
                while (it.hasNext()) {
                    Object doc = it.next().getDocument();
                    jw.value(insertType(doc));
                }
            } finally {
                it.close();
            }

            // end of doc list
            jw.endArray();

            // end of typed list
            jw.endArray();
        }

        // end of collection
        jw.endObject();

        // end of master doc
        jw.endObject();
        writer.flush();
        logger.debug("araqne confdb: export complete");
    } catch (JSONException e) {
        throw new IOException(e);
    } finally {
        db.unlock();
    }
}

From source file:tap.formatter.JSONFormat.java

/**
 * Write the whole metadata part of the JSON file.
 * //from  w  w  w .j  a va  2s  . c om
 * @param result      Result to write later (but it contains also metadata that was extracted from the result itself).
 * @param out         Output stream in which the metadata must be written.
 * @param execReport   Execution report (which contains the metadata extracted/guessed from the ADQL query).
 * @param thread      Thread which has asked for this formatting (it must be used in order to test the {@link Thread#isInterrupted()} flag and so interrupt everything if need).
 * 
 * @return   All the written metadata.
 * 
 * @throws IOException            If there is an error while writing something in the output stream.
 * @throws InterruptedException      If the thread has been interrupted.
 * @throws JSONException         If there is an error while formatting something in JSON.
 * @throws TAPException            If any other error occurs.
 * 
 * @see #getValidColMeta(DBColumn, TAPColumn)
 */
protected DBColumn[] writeMetadata(TableIterator result, JSONWriter out, TAPExecutionReport execReport,
        Thread thread) throws IOException, TAPException, InterruptedException, JSONException {
    out.array();

    // Get the metadata extracted/guesses from the ADQL query:
    DBColumn[] columnsFromQuery = execReport.resultingColumns;

    // Get the metadata extracted from the result:
    TAPColumn[] columnsFromResult = result.getMetadata();

    int indField = 0;
    if (columnsFromQuery != null) {

        // For each column:
        for (DBColumn field : columnsFromQuery) {

            // Try to build/get appropriate metadata for this field/column:
            TAPColumn colFromResult = (columnsFromResult != null && indField < columnsFromResult.length)
                    ? columnsFromResult[indField]
                    : null;
            TAPColumn tapCol = getValidColMeta(field, colFromResult);

            // Ensure these metadata are well returned at the end of this function:
            columnsFromQuery[indField] = tapCol;

            // Write the field/column metadata in the JSON output:
            writeFieldMeta(tapCol, out);
            indField++;
        }
    }

    out.endArray();
    return columnsFromQuery;
}

From source file:tap.formatter.JSONFormat.java

/**
 * Write the whole data part of the JSON file.
 * /*w  ww. jav a 2 s .  c om*/
 * @param result         Result to write.   
 * @param selectedColumns   All columns' metadata.
 * @param out            Output stream in which the data must be written.
 * @param execReport      Execution report (which contains the maximum allowed number of records to output).
 * @param thread         Thread which has asked for this formatting (it must be used in order to test the {@link Thread#isInterrupted()} flag and so interrupt everything if need).
 * 
 * @throws IOException            If there is an error while writing something in the output stream.
 * @throws InterruptedException      If the thread has been interrupted.
 * @throws JSONException         If there is an error while formatting something in JSON.
 * @throws TAPException            If any other error occurs.
 */
protected void writeData(TableIterator result, DBColumn[] selectedColumns, JSONWriter out,
        TAPExecutionReport execReport, Thread thread)
        throws IOException, TAPException, InterruptedException, JSONException {
    // [
    out.array();

    execReport.nbRows = 0;
    while (result.nextRow()) {
        // Stop right now the formatting if the job has been aborted/canceled/interrupted:
        if (thread.isInterrupted())
            throw new InterruptedException();

        // Deal with OVERFLOW, if needed:
        if (execReport.parameters.getMaxRec() > 0 && execReport.nbRows >= execReport.parameters.getMaxRec())
            break;

        // [
        out.array();
        int indCol = 0;
        while (result.hasNextCol())
            // ...
            writeFieldValue(result.nextCol(), selectedColumns[indCol++], out);
        // ]
        out.endArray();
        execReport.nbRows++;
    }

    // ]
    out.endArray();
}

From source file:charitypledge.Pledge.java

public void JsonImport() {

    try {//from   ww w . ja  va  2 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   ww  w  . j  av a 2  s . c  om
    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:org.everit.osgi.webconsole.configuration.DisplayedAttribute.java

private void valueToJSON(final JSONWriter writer) {
    writer.array();
    for (String value : Optional.ofNullable(this.value).orElse(new String[0])) {
        if (type.equals("boolean")) {
            writer.value(value.equals("true"));
        } else {//from  ww w .jav a2s.  co  m
            writer.value(value);
        }
    }
    writer.endArray();
}