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:com.seniorproject.semanticweb.services.WebServices.java

public String prepareFacetedSearchResult(ArrayList<String> data, String category) throws FileNotFoundException {
    JsonArrayBuilder out = Json.createArrayBuilder();
    JsonObjectBuilder resultObject = Json.createObjectBuilder();
    for (String line : data) {
        List<String> matchList = new ArrayList<>();
        Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
        Matcher regexMatcher = regex.matcher(line);
        while (regexMatcher.find()) {
            matchList.add(regexMatcher.group());
        }//  ww w  .  j  a  v a 2  s .co  m
        if (matchList.size() >= 2) {
            try (BufferedReader br = new BufferedReader(new FileReader(servletContext
                    .getRealPath("/WEB-INF/classes/hadoop/modified_isValueOfQuery/modified_isValueOfQuery_"
                            + category + ".txt")))) {
                String sCurrentLine;
                while ((sCurrentLine = br.readLine()) != null) {
                    if (matchList.get(0).equalsIgnoreCase(sCurrentLine)) {
                        matchList.set(0, "is " + matchList.get(0) + " of");
                        break;
                    }
                }
                resultObject.add("value", matchList.get(0));
                if (matchList.size() >= 2) {
                    resultObject.add("head", matchList.get(1).replace("\"", ""));
                } else {
                    resultObject.add("head", matchList.get(0).replace("\"", ""));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            ;
        }
        out.add(resultObject);
    }
    return out.build().toString();
}

From source file:io.hops.hopsworks.api.jobs.JobService.java

/**
 * Get the log information related to a job. The return value is a JSON
 * object, with format logset=[{"time":"JOB
 * EXECUTION TIME"}, {"log":"INFORMATION LOG"}, {"err":"ERROR LOG"}]
 * <p>//  ww  w  .j a va2 s  .c o  m
 * @param jobId
 * @param sc
 * @param req
 * @return
 */
@GET
@Path("/{jobId}/showlog")
@Produces(MediaType.APPLICATION_JSON)
@AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST })
public Response getLogInformation(@PathParam("jobId") int jobId, @Context SecurityContext sc,
        @Context HttpServletRequest req) {

    JsonObjectBuilder builder = Json.createObjectBuilder();
    JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
    List<Execution> executionHistory = exeFacade.findbyProjectAndJobId(project, jobId);
    JsonObjectBuilder arrayObjectBuilder;
    if (executionHistory != null && !executionHistory.isEmpty()) {
        for (Execution e : executionHistory) {
            arrayObjectBuilder = Json.createObjectBuilder();
            arrayObjectBuilder.add("jobId", e.getJob().getId());
            arrayObjectBuilder.add("appId", e.getAppId() == null ? "" : e.getAppId());
            arrayObjectBuilder.add("time", e.getSubmissionTime().toString());
            arrayBuilder.add(arrayObjectBuilder);
        }
    } else {
        arrayObjectBuilder = Json.createObjectBuilder();
        arrayObjectBuilder.add("jobId", "");
        arrayObjectBuilder.add("appId", "");
        arrayObjectBuilder.add("time", "Not available");
        arrayObjectBuilder.add("log", "No log available");
        arrayObjectBuilder.add("err", "No log available");
        arrayBuilder.add(arrayObjectBuilder);
    }
    builder.add("logset", arrayBuilder);

    return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(builder.build()).build();
}

From source file:com.seniorproject.semanticweb.services.WebServices.java

public String prepareResultDetail(ArrayList<String> data, String category) throws FileNotFoundException {
    JsonArrayBuilder out = Json.createArrayBuilder();
    JsonObjectBuilder resultObject = Json.createObjectBuilder();
    for (String line : data) {
        List<String> matchList = new ArrayList<>();
        Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
        Matcher regexMatcher = regex.matcher(line);
        while (regexMatcher.find()) {
            matchList.add(regexMatcher.group());
        }//from ww w .jav  a  2s  .  c  om
        if (matchList.size() >= 2) {
            try (BufferedReader br = new BufferedReader(new FileReader(servletContext
                    .getRealPath("/WEB-INF/classes/hadoop/modified_isValueOfQuery/modified_isValueOfQuery_"
                            + category + ".txt")))) {

                String sCurrentLine;

                while ((sCurrentLine = br.readLine()) != null) {

                    if (matchList.get(0).equalsIgnoreCase(sCurrentLine)) {
                        matchList.set(0, "is " + matchList.get(0) + " of");
                        break;
                    }
                }
                resultObject.add("name", matchList.get(0));
                resultObject.add("label", matchList.get(1).replace("\"", ""));

                if (matchList.size() >= 3) {
                    resultObject.add("url",
                            convertToNoPrefix(matchList.get(2)).replace("<", "").replace(">", ""));
                } else {
                    resultObject.add("url",
                            convertToNoPrefix(matchList.get(1)).replace("<", "").replace(">", ""));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            ;
        }
        out.add(resultObject);
    }
    return out.build().toString();
}

From source file:csg.files.CSGFiles.java

public void saveCourseData(AppDataComponent courseData, String filePath) throws IOException {
    CourseData courseDataManager = (CourseData) courseData;
    JsonArrayBuilder courseArrayBuilder = Json.createArrayBuilder();
    JsonArray courseArray = courseArrayBuilder.build();

    CSGWorkspace workspace = (CSGWorkspace) app.getWorkspaceComponent();
    JsonObject courseJson = Json.createObjectBuilder().add(JSON_SUBJECT, courseDataManager.getSubject())
            .add(JSON_NUMBER, courseDataManager.getNumber()).add(JSON_SEMESTER, courseDataManager.getSemester())
            .add(JSON_YEAR, courseDataManager.getYear()).add(JSON_TITLE, courseDataManager.getTitle())
            .add(JSON_INSTRUCTORNAME, courseDataManager.getInsName())
            .add(JSON_INSTRUCTORHOME, courseDataManager.getInsHome())
            .add(JSON_BANNER, courseDataManager.getBannerLink())
            .add(JSON_LEFTFOOTER, courseDataManager.getLeftFooterLink())
            .add(JSON_RIGHTFOOTER, courseDataManager.getRightFooterLink())
            .add(JSON_STYLESHEET, courseDataManager.getStyleSheet()).build();

    ObservableList<CourseTemplate> templates = courseDataManager.getTemplates();

    for (CourseTemplate template : templates) {
        JsonObject cJson = Json.createObjectBuilder().add(JSON_USE, template.isUse().getValue())
                .add(JSON_NAVBAR, template.getNavbarTitle()).add(JSON_FILENAME, template.getFileName())
                .add(JSON_SCRIPT, template.getScript()).build();
        courseArrayBuilder.add(cJson);
    }/* w  w w. j a v  a2s  .c om*/
    courseArray = courseArrayBuilder.build();

    JsonObject dataManagerJSO = Json.createObjectBuilder().add(JSON_COURSE, courseJson)
            .add(JSON_COURSETEMPLATE, courseArray).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();
}

From source file:io.bibleget.BibleGetDB.java

public JsonObject getOptions() {
    if (instance.connect()) {
        try {/*  w w w  .  j ava 2  s .  com*/
            JsonObjectBuilder myOptionsTable;
            JsonArrayBuilder myRows;
            try (Statement stmt = instance.conn.createStatement();
                    ResultSet rsOps = stmt.executeQuery("SELECT * FROM OPTIONS")) {
                Iterator itColNames = colNames.iterator();
                Iterator itDataTypes = colDataTypes.iterator();
                myOptionsTable = Json.createObjectBuilder();
                myRows = Json.createArrayBuilder();
                while (rsOps.next()) {
                    //System.out.println("Getting a row from the table.");
                    JsonObjectBuilder thisRow = Json.createObjectBuilder();
                    while (itColNames.hasNext() && itDataTypes.hasNext()) {
                        String colName = (String) itColNames.next();
                        Class dataType = (Class) itDataTypes.next();
                        if (dataType == String.class) {
                            thisRow.add(colName, rsOps.getString(colName));
                        }
                        if (dataType == Integer.class) {
                            thisRow.add(colName, rsOps.getInt(colName));
                        }
                        if (dataType == Boolean.class) {
                            thisRow.add(colName, rsOps.getBoolean(colName));
                        }
                        //System.out.println(colName + " <" + dataType + ">");
                    }
                    thisRow.build();
                    myRows.add(thisRow);
                }
                rsOps.close();
                stmt.close();
                instance.disconnect();
                myRows.build();
                return myOptionsTable.add("rows", myRows).build();
            }
        } catch (SQLException ex) {
            Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
    return null;
}

From source file:org.kuali.student.ap.coursesearch.service.impl.CourseDetailsViewHelperServiceImpl.java

/**
 * @see org.kuali.student.ap.coursesearch.service.CourseDetailsViewHelperService#createAddSectionEvent(String, String, String, String, java.util.List, javax.json.JsonObjectBuilder)
 *//*from  w  w w. j a  v  a  2s  .  co m*/
@Override
public JsonObjectBuilder createAddSectionEvent(String termId, String courseOfferingCode,
        String courseOfferingId, String formatOfferingId, List<ActivityOfferingDetailsWrapper> activities,
        JsonObjectBuilder eventList) {
    JsonObjectBuilder addEvent = Json.createObjectBuilder();
    addEvent.add("courseOfferingId", courseOfferingId);
    addEvent.add("termId", termId.replace(".", "-"));
    addEvent.add("courseOfferingCode", courseOfferingCode);
    addEvent.add("formatOfferingId", formatOfferingId);
    addEvent.add("uid", UUID.randomUUID().toString());

    // Create json array of activity to add and add it to event
    String regGroupCode = "";
    JsonArrayBuilder activityEvents = Json.createArrayBuilder();
    for (ActivityOfferingDetailsWrapper activity : activities) {
        JsonObjectBuilder activityEvent = Json.createObjectBuilder();
        String instructor = "";
        String days = "";
        String time = "";
        String location = "";
        String classUrl = "";

        // activities in the reg group will have the same reg group code.
        regGroupCode = activity.getRegGroupCode();

        // if activity value is null use empty string
        if (activity.getInstructorName() != null)
            instructor = activity.getInstructorName();
        if (activity.getDays() != null)
            days = activity.getDays();
        if (activity.getTime() != null)
            time = activity.getTime();
        if (activity.getLocation() != null)
            location = activity.getLocation();
        if (activity.getClassUrl() != null)
            classUrl = activity.getClassUrl();

        // Add data to json for activity
        activityEvent.add("activityOfferingId", activity.getActivityOfferingId());
        activityEvent.add("activityFormatName", activity.getActivityFormatName());
        activityEvent.add("activityOfferingCode", activity.getActivityOfferingCode());

        activityEvent.add("instructor", instructor);
        activityEvent.add("days", days);
        activityEvent.add("time", time);
        activityEvent.add("location", location);
        activityEvent.add("currentEnrollment", activity.getCurrentEnrollment());
        activityEvent.add("maxEnrollment", activity.getMaxEnrollment());
        activityEvent.add("honors", activity.isHonors());
        activityEvent.add("classUrl", classUrl);
        JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();

        activityEvent.add("activityOfferingRequisites", activity.isHasActivityOfferingRequisites());
        activityEvents.add(activityEvent);
    }
    addEvent.add("activities", activityEvents);
    addEvent.add("regGroupCode", regGroupCode);

    eventList.add("COURSE_SECTION_ADDED", addEvent);
    return eventList;
}

From source file:de.pangaea.fixo3.xml.ProcessXmlFiles.java

private void run() throws FileNotFoundException, SAXException, IOException, ParserConfigurationException,
        XPathExpressionException {
    // src/test/resources/, src/main/resources/files
    File folder = new File("src/main/resources/files");
    File[] files = folder.listFiles(new FileFilter() {

        @Override/*  w w w . j  a  va 2 s.com*/
        public boolean accept(File pathname) {
            if (pathname.getName().endsWith(".xml"))
                return true;

            return false;
        }
    });

    JsonArrayBuilder json = Json.createArrayBuilder();

    Document doc;
    String deviceLabel, deviceComment, deviceImage;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    final Map<String, String> prefixToNS = new HashMap<>();
    prefixToNS.put(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
    prefixToNS.put(XMLConstants.XMLNS_ATTRIBUTE, XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
    prefixToNS.put("sml", "http://www.opengis.net/sensorml/2.0");
    prefixToNS.put("gml", "http://www.opengis.net/gml/3.2");
    prefixToNS.put("gmd", "http://www.isotc211.org/2005/gmd");

    XPath x = XPathFactory.newInstance().newXPath();
    x.setNamespaceContext(new NamespaceContext() {
        @Override
        public String getNamespaceURI(String prefix) {
            Objects.requireNonNull(prefix, "Namespace prefix cannot be null");
            final String uri = prefixToNS.get(prefix);
            if (uri == null) {
                throw new IllegalArgumentException("Undeclared namespace prefix: " + prefix);
            }
            return uri;
        }

        @Override
        public String getPrefix(String namespaceURI) {
            throw new UnsupportedOperationException();
        }

        @Override
        public Iterator<?> getPrefixes(String namespaceURI) {
            throw new UnsupportedOperationException();
        }
    });

    XPathExpression exGmlName = x.compile("/sml:PhysicalSystem/gml:name");
    XPathExpression exGmlDescription = x.compile("/sml:PhysicalSystem/gml:description");
    XPathExpression exGmdUrl = x.compile(
            "/sml:PhysicalSystem/sml:documentation/sml:DocumentList/sml:document/gmd:CI_OnlineResource/gmd:linkage/gmd:URL");
    XPathExpression exTerm = x
            .compile("/sml:PhysicalSystem/sml:classification/sml:ClassifierList/sml:classifier/sml:Term");

    int m = 0;
    int n = 0;

    for (File file : files) {
        log.info(file.getName());
        doc = dbf.newDocumentBuilder().parse(new FileInputStream(file));

        deviceLabel = exGmlName.evaluate(doc).trim();
        deviceComment = exGmlDescription.evaluate(doc).trim();
        deviceImage = exGmdUrl.evaluate(doc).trim();
        NodeList terms = (NodeList) exTerm.evaluate(doc, XPathConstants.NODESET);

        JsonObjectBuilder jobDevice = Json.createObjectBuilder();

        jobDevice.add("name", toUri(deviceLabel));
        jobDevice.add("label", deviceLabel);
        jobDevice.add("comment", toAscii(deviceComment));
        jobDevice.add("image", deviceImage);

        JsonArrayBuilder jabSubClasses = Json.createArrayBuilder();

        for (int i = 0; i < terms.getLength(); i++) {
            Node term = terms.item(i);
            NodeList attributes = term.getChildNodes();

            String attributeLabel = null;
            String attributeValue = null;

            for (int j = 0; j < attributes.getLength(); j++) {
                Node attribute = attributes.item(j);
                String attributeName = attribute.getNodeName();

                if (attributeName.equals("sml:label")) {
                    attributeLabel = attribute.getTextContent();
                } else if (attributeName.equals("sml:value")) {
                    attributeValue = attribute.getTextContent();
                }
            }

            if (attributeLabel == null || attributeValue == null) {
                throw new RuntimeException("Attribute label or value cannot be null [attributeLabel = "
                        + attributeLabel + "; attributeValue = " + attributeValue + "]");
            }

            if (attributeLabel.equals("model")) {
                continue;
            }

            if (attributeLabel.equals("manufacturer")) {
                jobDevice.add("manufacturer", attributeValue);
                continue;
            }

            n++;

            Quantity quantity = getQuantity(attributeValue);

            if (quantity == null) {
                continue;
            }

            m++;

            JsonObjectBuilder jobSubClass = Json.createObjectBuilder();
            JsonObjectBuilder jobCapability = Json.createObjectBuilder();
            JsonObjectBuilder jobQuantity = Json.createObjectBuilder();

            String quantityLabel = getQuantityLabel(attributeLabel);
            String capabilityLabel = deviceLabel + " " + quantityLabel;

            jobCapability.add("label", capabilityLabel);

            jobQuantity.add("label", quantity.getLabel());

            if (quantity.getValue() != null) {
                jobQuantity.add("value", quantity.getValue());
            } else if (quantity.getMinValue() != null && quantity.getMaxValue() != null) {
                jobQuantity.add("minValue", quantity.getMinValue());
                jobQuantity.add("maxValue", quantity.getMaxValue());
            } else {
                throw new RuntimeException(
                        "Failed to determine quantity value [attributeValue = " + attributeValue + "]");
            }

            jobQuantity.add("unitCode", quantity.getUnitCode());
            jobQuantity.add("type", toUri(quantityLabel));

            jobCapability.add("quantity", jobQuantity);
            jobSubClass.add("capability", jobCapability);

            jabSubClasses.add(jobSubClass);
        }

        jobDevice.add("subClasses", jabSubClasses);

        json.add(jobDevice);
    }

    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);

    JsonWriterFactory jsonWriterFactory = Json.createWriterFactory(properties);
    JsonWriter jsonWriter = jsonWriterFactory.createWriter(new FileWriter(new File(jsonFileName)));
    jsonWriter.write(json.build());
    jsonWriter.close();

    System.out.println("Fraction of characteristics included: " + m + "/" + n);
}