Example usage for org.json JSONWriter endArray

List of usage examples for org.json JSONWriter endArray

Introduction

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

Prototype

public JSONWriter endArray() throws JSONException 

Source Link

Document

End an 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  ww  . ja va 2 s.c o m*/
        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();/*from  w  ww.  j a v  a2 s .co m*/
    configManager.configAdminStream().forEach((confAdmin) -> {
        jsonWriter.object();
        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();/* w ww  . j a  va 2s .c om*/
    configManager.lookupConfigurations(configAdminPid)
            .forEach((configurable) -> configurable.toJSON(jsonWriter));
    jsonWriter.endArray();
}

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 {/* w  w  w.  jav a  2  s . 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.gatein.management.rest.providers.JsonResourceProvider.java

@Override
public void writeTo(Resource resource, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {
    PrintWriter printWriter = new PrintWriter(entityStream);
    try {/*  w  ww  .ja va  2s.co m*/
        JSONWriter writer = new JSONWriter(printWriter);
        writer.object().key("description").value(resource.getDescription());
        writer.key("children").array();
        for (Child child : resource.getChildren()) {
            writeChild(child, writer);
        }
        writer.endArray();
        if (resource.getOperations() != null) {
            writer.key("operations").array();
            for (Operation operation : resource.getOperations()) {
                writeOperation(operation, writer);
            }
            writer.endArray();
        }
        writer.endObject();

        printWriter.flush();
    } catch (JSONException e) {
        throw new IOException("Exception writing json result.", e);
    } finally {
        printWriter.close();
    }
}

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();/*  w  w  w. j av  a 2  s.  co  m*/
    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 ww  .j  a v  a2s . c o  m
 * @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.
 * //from   ww w .jav a2  s  .  c o m
 * @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   w ww.j  a va  2 s.  com
        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;// w  w  w  . j a v a 2s  .  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);
    }
}