Example usage for javax.json JsonArrayBuilder build

List of usage examples for javax.json JsonArrayBuilder build

Introduction

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

Prototype

JsonArray build();

Source Link

Document

Returns the current array.

Usage

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());
        }// ww w. j  ava  2 s.c o 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("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:io.bibleget.BibleGetDB.java

public JsonObject getOptions() {
    if (instance.connect()) {
        try {/*from w  w w  .ja  va2  s.c  om*/
            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: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// www  .  ja v  a 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);
}