Example usage for javax.json JsonArrayBuilder add

List of usage examples for javax.json JsonArrayBuilder add

Introduction

In this page you can find the example usage for javax.json JsonArrayBuilder add.

Prototype

JsonArrayBuilder add(JsonArrayBuilder builder);

Source Link

Document

Adds a JsonArray from an array builder to the array.

Usage

From source file:assignment5.ProductServlet.java

/**
 * json format taken from//  ww  w.  j  a v  a  2s  .c o m
 * https://code.google.com/p/json-simple/wiki/EncodingExamples
 *
 * @param query
 * @param params
 * @return
 */
private String getResults(String query, String... params) {
    JsonArrayBuilder productArray = Json.createArrayBuilder();
    String numChanges = new String();
    try (Connection conn = credentials.getConnection()) {
        PreparedStatement pstmt = conn.prepareStatement(query);
        for (int i = 1; i <= params.length; i++) {
            pstmt.setString(i, params[i - 1]);
        }

        ResultSet rs = pstmt.executeQuery();

        while (rs.next()) {

            JsonObjectBuilder jsonobj = Json.createObjectBuilder().add("productID", rs.getInt("productID"))
                    .add("name", rs.getString("name")).add("description", rs.getString("description"))
                    .add("quantity", rs.getInt("quantity"));

            numChanges = jsonobj.build().toString();
            productArray.add(jsonobj);
        }

    } catch (SQLException ex) {
        Logger.getLogger(ProductServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (params.length == 0) {
        numChanges = productArray.build().toString();
    }
    return numChanges;
}

From source file:servlets.SampleServlet.java

private String getResults(String query, String... params) {
    JsonArrayBuilder productArray = Json.createArrayBuilder();
    String xxx = new String();
    try (Connection conn = Credentials.getConnection()) {
        PreparedStatement pstmt = conn.prepareStatement(query);
        for (int i = 1; i <= params.length; i++) {
            pstmt.setString(i, params[i - 1]);
        }//from w w  w. j a v a2s .  c o m
        ResultSet rs = pstmt.executeQuery();
        List list = new LinkedList();
        while (rs.next()) {
            JsonObjectBuilder jsonobj = Json.createObjectBuilder().add("productID", rs.getInt("productID"))
                    .add("Name", rs.getString("Name")).add("Description", rs.getString("Description"))
                    .add("Quantity", rs.getInt("Quantity"));

            xxx = jsonobj.build().toString();
            productArray.add(jsonobj);
        }
    } catch (SQLException ex) {
        Logger.getLogger(SampleServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (params.length == 0) {
        xxx = productArray.build().toString();
    }
    return xxx;
}

From source file:com.buffalokiwi.aerodrome.jet.products.JetAPIProduct.java

/**
 * Send shipping exceptions to jet /*from   w ww  .  j av a  2 s  .  c om*/
 * @param sku Sku 
 * @param nodes Filfillment nodes 
 * @return
 * @throws APIException
 * @throws JetException 
 */
@Override
public IJetAPIResponse sendPutProductShippingExceptions(final String sku, final List<FNodeShippingRec> nodes)
        throws APIException, JetException {
    checkSku(sku);

    if (nodes == null)
        throw new IllegalArgumentException("nodes cannot be null");

    APILog.info(LOG, "Sending", sku, "shipping exceptions");

    final JsonArrayBuilder b = Json.createArrayBuilder();
    for (final FNodeShippingRec node : nodes) {
        b.add(node.toJSON());
    }

    final JsonObjectBuilder o = Json.createObjectBuilder();
    o.add("fulfillment_nodes", b);

    final IJetAPIResponse response = put(config.getAddProductShipExceptionUrl(sku), o.build().toString(),
            getJSONHeaderBuilder().build());

    return response;
}

From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Post the given result to a election to the bulletin board
 * @param result /*from  ww w  .  j av  a2  s.  com*/
 * result to be posted to the bulletin board
 */
public void postResult(ElectionResult result) {
    Election election = result.getElection();
    ElectionTopic topic = election.getTopic();
    HashMap<String, Integer> optionResults = result.getOptionCount();
    //translate the ElectionResult object into a json String
    JsonObjectBuilder jBuilder = Json.createObjectBuilder();

    //TODO get email address from certificate 
    jBuilder.add("author", "alice@bfh.ch");

    JsonArrayBuilder resultBuilder = Json.createArrayBuilder();

    JsonObjectBuilder topicBuilder = Json.createObjectBuilder();

    topicBuilder.add("topic", topic.getTitle());
    topicBuilder.add("pick", topic.getPick());

    JsonArrayBuilder optionsBuilder = Json.createArrayBuilder();

    for (String option : topic.getOptions()) {
        JsonObjectBuilder optionBuilder = Json.createObjectBuilder();
        optionBuilder.add("optTitle", option);
        optionBuilder.add("count", optionResults.get(option));
        optionsBuilder.add(optionBuilder);
    }
    topicBuilder.add("options", optionsBuilder);

    resultBuilder.add(topicBuilder);

    jBuilder.add("result", resultBuilder);
    JsonArrayBuilder ballotsBuilder = Json.createArrayBuilder();
    for (Ballot ballot : result.getBallots()) {
        JsonObjectBuilder ballotBuilder = Json.createObjectBuilder();
        //Translate ballot object into a json string 
        JsonArrayBuilder ballotOptionsBuilder = Json.createArrayBuilder();
        for (String option : ballot.getSelectedOptions()) {
            ballotOptionsBuilder.add(option);
        }
        ballotBuilder.add("id", ballot.getId());
        ballotBuilder.add("e", ballotOptionsBuilder);
        ballotBuilder.add("valid", ballot.isValid());
        ballotBuilder.add("reason", ballot.getReason());

        ballotsBuilder.add(ballotBuilder);
    }

    jBuilder.add("ballots", ballotsBuilder);

    JsonObject model = jBuilder.build();

    //sign json string 
    SignatureController signController = new SignatureController();
    JsonObject signedModel = null;

    try {
        signedModel = signController.signJson(model);
    } catch (Exception ex) {
        Logger.getLogger(CommunicationController.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        //post JWS with the result to the bulletin board
        boolean requestOK = postJsonStringToURL(
                bulletinBoardUrl + "/elections/" + election.getId() + "/results", signedModel.toString(),
                false);
        if (requestOK) {
            System.out.println("Results posted!");
        } else {
            System.out.println("Was not able to post Results! Did not receive expected http 200 status.");
        }
    } catch (IOException ex) {
        System.out.println("Was not able to post Results! IOException");
    }

}

From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.exac.EXACResourceImplementation.java

@Override
public Result runProcess(SecureSession session, IRCTProcess process, Result result)
        throws ResourceInterfaceException {
    HttpClient client = createClient(session);
    try {/*  ww  w.  j a  v a  2 s  .c o  m*/
        ResultSet resultSetField = (ResultSet) process.getObjectValues().get("RESULTSET");
        String chromosomeColumn = process.getStringValues().get("CHROMOSOME");
        String positionColumn = process.getStringValues().get("POSITION");
        String referenceColumn = process.getStringValues().get("REFERENCE");
        String variantColumn = process.getStringValues().get("VARIANT");

        ResultSet rs = createResultSet(result, resultSetField);

        // Move to First
        resultSetField.first();
        // Loop through all rows and get the data needed for the bulk
        // request
        resultSetField.beforeFirst();
        JsonArrayBuilder jsonArray = Json.createArrayBuilder();
        while (resultSetField.next()) {

            String queryString = resultSetField.getString(chromosomeColumn);
            queryString += "-" + resultSetField.getString(positionColumn);
            queryString += "-" + resultSetField.getString(referenceColumn);
            queryString += "-" + resultSetField.getString(variantColumn);

            // Run the Bulk request(s)
            jsonArray.add(queryString);

        }

        HttpPost post = new HttpPost(this.resourceURL + "/rest/bulk/variant");

        // Set Header
        try {
            post.setEntity(new StringEntity(jsonArray.build().toString()));
            HttpResponse response = client.execute(post);
            JsonReader reader = Json.createReader(response.getEntity().getContent());
            JsonObject responseObject = reader.readObject();

            //Merge the results back into the result set
            resultSetField.beforeFirst();
            rs.first();
            while (resultSetField.next()) {
                rs.appendRow();
                //Copy the original data over
                for (Column column : resultSetField.getColumns()) {
                    rs.updateString(column.getName(), resultSetField.getString(column.getName()));
                }
                //Add the new data if it exists
                String queryString = resultSetField.getString(chromosomeColumn);
                queryString += "-" + resultSetField.getString(positionColumn);
                queryString += "-" + resultSetField.getString(referenceColumn);
                queryString += "-" + resultSetField.getString(variantColumn);

                if (responseObject.containsKey(queryString)) {
                    JsonObject varObject = responseObject.getJsonObject(queryString).getJsonObject("variant");
                    for (String newColumnString : this.exacColumns) {
                        String value = getValue(varObject, newColumnString);
                        if (value != null) {
                            rs.updateString(newColumnString, value.toString());
                        }
                    }
                }
            }

            result.setData(rs);
            result.setResultStatus(ResultStatus.COMPLETE);
        } catch (IOException | PersistableException e) {
            e.printStackTrace();
            result.setResultStatus(ResultStatus.ERROR);
            result.setMessage(e.getMessage());
        }

    } catch (ResultSetException e) {
        e.printStackTrace();
        result.setResultStatus(ResultStatus.ERROR);
        result.setMessage(e.getMessage());
    }

    return result;
}

From source file:prod.products.java

private String getResults(String query, String... params) {
    Boolean Result = false;
    JsonArrayBuilder pList = Json.createArrayBuilder();
    StringBuilder sb = new StringBuilder();
    try (Connection cn = credentials.getConnection()) {
        PreparedStatement pstmt = cn.prepareStatement(query);
        for (int i = 1; i <= params.length; i++) {
            pstmt.setString(i, params[i - 1]);
            Result = true;//from   ww  w . j a  v  a2 s .c om
        }
        ResultSet rs = pstmt.executeQuery();

        if (Result == false) {
            while (rs.next()) {
                JsonObjectBuilder productBuilder = Json.createObjectBuilder();
                productBuilder.add("productId", rs.getInt("product_id"))
                        .add("name", rs.getString("product_name"))
                        .add("description", rs.getString("product_description"))
                        .add("quantity", rs.getInt("quantity"));
                pList.add(productBuilder);
            }
        } else {
            while (rs.next()) {
                JsonObject jsonObt = Json.createObjectBuilder().add("productId", rs.getInt("product_id"))
                        .add("name", rs.getString("product_name"))
                        .add("description", rs.getString("product_description"))
                        .add("quantity", rs.getInt("quantity")).build();
                return jsonObt.toString();
            }
        }

    } catch (SQLException ex) {
        Logger.getLogger(products.class.getName()).log(Level.SEVERE, null, ex);
    }
    return pList.build().toString();
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@GET
@Produces(MediaType.APPLICATION_JSON)/*from  ww w.j  av  a  2s.  co  m*/
@Path("tree")
public Response getFeedsTree(@Context SecurityContext securityContext) {
    EntityManager em;
    User user = (User) securityContext.getUserPrincipal();
    JsonArrayBuilder jsonBuilder;
    List<FeedCategory> fcs;
    List<Feed> rootFeeds;

    em = HibernateUtil.getEntityManager();

    jsonBuilder = Json.createArrayBuilder();

    try {
        fcs = em.createQuery("select fc from FeedCategory fc where fc.user = :user order by fc.name asc")
                .setParameter("user", user).getResultList();

        for (FeedCategory fc : fcs) {
            JsonObjectBuilder obj = getFeedCategory(em, fc);
            jsonBuilder.add(obj);
        }

        rootFeeds = em.createQuery(
                "select f from Feed f where f.user = :user and f.feedCategory is null order by f.name asc")
                .setParameter("user", user).getResultList();
        for (Feed feed : rootFeeds) {
            JsonObjectBuilder obj = getFeed(em, feed);
            jsonBuilder.add(obj);
        }

        return Response.ok(jsonBuilder.build().toString()).build();
    } finally {
        em.close();
    }
}

From source file:io.bibleget.HTTPCaller.java

public int isValidBook(String book) {
    try {//from w ww. j  av a2 s .  c  om
        JsonArrayBuilder biblebooksBldr = Json.createArrayBuilder();
        BibleGetDB bibleGetDB;
        bibleGetDB = BibleGetDB.getInstance();
        for (int i = 0; i < 73; i++) {
            String usrprop = bibleGetDB.getMetaData("BIBLEBOOKS" + Integer.toString(i));
            //System.out.println("value of BIBLEBOOKS"+Integer.toString(i)+": "+usrprop);                
            JsonReader jsonReader = Json.createReader(new StringReader(usrprop));
            JsonArray jsbooks = jsonReader.readArray();
            biblebooksBldr.add(jsbooks);
        }
        JsonArray biblebooks = biblebooksBldr.build();
        if (!biblebooks.isEmpty()) {
            return idxOf(book, biblebooks);
        }
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(HTTPCaller.class.getName()).log(Level.SEVERE, null, ex);
    }
    return -1;
}

From source file:no.sintef.jarfter.PostgresqlInteractor.java

public JsonObject selectAllTransfomations(String filter_uri) throws JarfterException {
    checkConnection();//from w  w  w .j a va2 s. co  m

    String table = "transformations";
    String uri = "uri";
    String name = "name";
    String metadata = "metadata";
    String clojure = "clojure";
    JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
    try {
        PreparedStatement st = conn.prepareStatement("SELECT " + uri + ", " + name + ", " + metadata + ", "
                + clojure + " FROM transformations WHERE uri ~ ?;");
        if (filter_uri == null) {
            st.setString(1, ".*");
        } else {
            st.setString(1, filter_uri);
        }
        log("selectAllTransfomations - calling executeQuery");
        ResultSet rs = st.executeQuery();
        while (rs.next()) {
            JsonObjectBuilder job = Json.createObjectBuilder();
            job.add(uri, rs.getString(uri));
            job.add(name, rs.getString(name));
            job.add(metadata, rs.getString(metadata));
            job.add(clojure, rs.getString(clojure));
            jsonArrayBuilder.add(job.build());
        }

        rs.close();
        st.close();
    } catch (SQLException sqle) {
        log("selectAllTransformations - got SQLException");
        error(sqle);
        throw new JarfterException(JarfterException.Error.SQL_UNKNOWN_ERROR, sqle.getLocalizedMessage());
    }
    return Json.createObjectBuilder().add(table, jsonArrayBuilder.build()).build();
}

From source file:csg.files.CSGFiles.java

public void saveProjectsData(AppDataComponent courseData, AppDataComponent projectData, String filePath)
        throws IOException {

    CourseData courseDataManager = (CourseData) courseData;
    ProjectData projectDataManager = (ProjectData) projectData;

    ObservableList<Student> students = projectDataManager.getStudents();

    JsonArrayBuilder studentArrayBuilder = Json.createArrayBuilder();
    JsonArrayBuilder teamArrayBuilder = Json.createArrayBuilder();
    ObservableList<Team> teams = projectDataManager.getTeams();

    for (Team team : teams) {
        for (Student student : students) {
            if (student.getTeam().equals(team.getName())) {
                studentArrayBuilder.add(student.getFirstName() + " " + student.getLastName());
            }//from  ww w.  j ava 2 s.co m
        }
        JsonArray studentArray = studentArrayBuilder.build();
        JsonObject teamsJson = Json.createObjectBuilder().add(JSON_NAME, team.getName())
                .add(JSON_STUDENTS, studentArray).add(JSON_LINK, team.getLink()).build();
        teamArrayBuilder.add(teamsJson);
    }
    JsonArray teamArray = teamArrayBuilder.build();

    CSGWorkspace workspace = (CSGWorkspace) app.getWorkspaceComponent();
    JsonArrayBuilder courseJsonBuilder = Json.createArrayBuilder();
    JsonObject coursesJson = Json.createObjectBuilder()
            .add(JSON_SEMESTER, courseDataManager.getSemester() + " " + courseDataManager.getYear())
            .add(JSON_PROJECTS, teamArray).build();
    courseJsonBuilder.add(coursesJson);

    JsonArray courseJsonArr = courseJsonBuilder.build();

    JsonObject dataManagerJSO = Json.createObjectBuilder().add(JSON_WORK, courseJsonArr).build();

    // AND NOW OUTPUT IT TO A JSON FILE WITH PRETTY PRINTING
    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
    StringWriter sw = new StringWriter();
    JsonWriter jsonWriter = writerFactory.createWriter(sw);
    jsonWriter.writeObject(dataManagerJSO);
    jsonWriter.close();

    // INIT THE WRITER
    OutputStream os = new FileOutputStream(filePath);
    JsonWriter jsonFileWriter = Json.createWriter(os);
    jsonFileWriter.writeObject(dataManagerJSO);
    String prettyPrinted = sw.toString();
    PrintWriter pw = new PrintWriter(filePath);
    pw.write(prettyPrinted);
    pw.close();
}