Example usage for javax.json JsonReader close

List of usage examples for javax.json JsonReader close

Introduction

In this page you can find the example usage for javax.json JsonReader close.

Prototype

@Override
void close();

Source Link

Document

Closes this reader and frees any resources associated with the reader.

Usage

From source file:ufrj.pedroeusebio.biblioteca_pdf.Controller.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
    String json = "";
    if (br != null) {
        json = br.readLine();/*from   www . j  av  a 2  s.c  o  m*/
    }
    JsonReader reader = Json.createReader(new StringReader(json));
    JsonObject JSONObject = reader.readObject();
    reader.close();

    JsonObject innerObj;
    RespostaDTO dto = new RespostaDTO();
    BibliotecaDAO Biblioteca = new BibliotecaDAO();
    ArrayList<JSONArray> answer = new ArrayList<>();
    Biblioteca.setStrQuery("");
    String Query = "";
    try {
        if (!JSONObject.getString("patrimonio").isEmpty()) {
            System.out.println("entrei !!");
            dto.setPatrimonio(JSONObject.getString("patrimonio"));
            if (Biblioteca.getStrQuery().isEmpty()) {
                Query += "SELECT patrimonio FROM public.dadoscatalogo WHERE patrimonio='" + dto.getPatrimonio()
                        + "' ";
                Biblioteca.setStrQuery(Query);
            } else {
                Query += Biblioteca.QueryGenatator("patrimonio", dto.getPatrimonio(), null, "dadoscatalogo");
            }
        }
    } catch (Exception e) {
    }
    try {
        if (!JSONObject.getJsonObject("titulo").isEmpty()) {
            innerObj = JSONObject.getJsonObject("titulo");
            dto.setTitulo(innerObj.getString("texto"));
            if (Biblioteca.getStrQuery().isEmpty()) {
                Query += "SELECT patrimonio FROM public.dadoscatalogo WHERE titulo='" + dto.getTitulo() + "' ";
                Biblioteca.setStrQuery(Query);
            } else {
                Query += Biblioteca.QueryGenatator("titulo", dto.getTitulo(), innerObj.getString("mode"),
                        "dadoscatalogo");
            }
            ;
        }
    } catch (Exception e) {
    }
    try {
        if (!JSONObject.getJsonObject("autoria").isEmpty()) {
            innerObj = JSONObject.getJsonObject("autoria");
            dto.setAutoria(innerObj.getString("texto"));
            if (Biblioteca.getStrQuery().isEmpty()) {
                Query += "SELECT patrimonio FROM public.dadoscatalogo WHERE autoria='" + dto.getAutoria()
                        + "' ";
                Biblioteca.setStrQuery(Query);
            } else {
                Query += Biblioteca.QueryGenatator("autoria", dto.getAutoria(), innerObj.getString("mode"),
                        "dadoscatalogo");
            }
        }
    } catch (Exception e) {
    }
    try {
        if (!JSONObject.getJsonObject("veiculo").isEmpty()) {
            innerObj = JSONObject.getJsonObject("veiculo");
            dto.setVeiculo(innerObj.getString("texto"));
            if (Biblioteca.getStrQuery().isEmpty()) {
                Query += "SELECT patrimonio FROM public.dadoscatalogo WHERE veiculo='" + dto.getVeiculo()
                        + "' ";
                Biblioteca.setStrQuery(Query);
            } else {
                Query += Biblioteca.QueryGenatator("veiculo", dto.getAutoria(), innerObj.getString("mode"),
                        "dadoscatalogo");
            }
        }
    } catch (Exception e) {
    }
    try {
        if (!JSONObject.getJsonObject("datapublicacao").isEmpty()) {
            innerObj = JSONObject.getJsonObject("datapublicacao");
            dto.setData(innerObj.getString("texto"));
            if (Biblioteca.getStrQuery().isEmpty()) {
                Query += "SELECT patrimonio FROM public.dadoscatalogo WHERE data_publicacao='" + dto.getData()
                        + "' ";
                Biblioteca.setStrQuery(Query);
            } else {
                Query += Biblioteca.QueryGenatator("datapublicacao", dto.getData(), innerObj.getString("mode"),
                        "dadoscatalogo");
            }
        }
    } catch (Exception e) {
    }
    try {
        if (!JSONObject.getJsonObject("palchave").isEmpty()) {
            innerObj = JSONObject.getJsonObject("palchave");
            String[] parts = innerObj.getString("texto").replaceAll("\\s", "").split(";");
            for (int i = 0; i < parts.length; i++) {
                if (Biblioteca.getStrQuery().isEmpty()) {
                    Query += "SELECT patrimonio FROM public.palavras_chave WHERE palchave='" + parts[i] + "' ";
                    Biblioteca.setStrQuery(Query);
                } else if (!Biblioteca.getStrQuery().isEmpty()) {
                    Query += Biblioteca.QueryGenatator("palchave", parts[i], innerObj.getString("mode"),
                            "palavras_chave");
                }
            }
        }
    } catch (Exception e) {
    }
    try {
        if (JSONObject.getJsonObject("palchave").isEmpty()
                && JSONObject.getJsonObject("datapublicacao").isEmpty()
                && JSONObject.getJsonObject("veiculo").isEmpty()
                && JSONObject.getJsonObject("autoria").isEmpty() && JSONObject.getJsonObject("titulo").isEmpty()
                && JSONObject.getJsonObject("patrimonio").isEmpty()) {
            Query = "SELECT patrimonio FROM public.dadoscatalogo;";

        }
    } catch (Exception e) {

    }

    answer.addAll(Biblioteca.ExecuteQuery(Query));

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.print(answer);
    out.flush();

}

From source file:org.trellisldp.http.MultipartUploader.java

/**
 * Create a binary from a collection of uploaded parts
 * @param partition the partition/*from ww  w  . ja va  2  s . c om*/
 * @param id the identifier
 * @param input the input value
 * @return a response
 *
 * <p>Note: The structure should be like this:</p>
 * <pre>{
 *   "1": "somehash",
 *   "2": "otherhash",
 *   "3": "anotherhash"
 * }</pre>
 */
@POST
@Timed
@Consumes("application/json")
public Response createBinary(@PathParam("partition") final String partition, @PathParam("id") final String id,
        final InputStream input) {

    final JsonReader reader = Json.createReader(input);
    final JsonObject obj = reader.readObject();
    reader.close();
    final Map<Integer, String> partDigests = obj.keySet().stream()
            .collect(toMap(Integer::parseInt, obj::getString));

    return binaryService.getResolverForPartition(partition)
            .filter(BinaryService.Resolver::supportsMultipartUpload).filter(svc -> svc.uploadSessionExists(id))
            .map(svc -> svc.completeUpload(id, partDigests)).map(upload -> {
                try (final TrellisDataset dataset = TrellisDataset.createDataset()) {
                    final IRI identifier = rdf.createIRI(TRELLIS_PREFIX + upload.getPath());

                    // Add Audit quads
                    audit.creation(identifier, upload.getSession()).stream()
                            .map(skolemizeQuads(resourceService, upload.getBaseUrl()))
                            .forEachOrdered(dataset::add);
                    dataset.add(rdf.createQuad(PreferServerManaged, identifier, type, NonRDFSource));
                    dataset.add(rdf.createQuad(PreferServerManaged, identifier, DC.hasPart,
                            upload.getBinary().getIdentifier()));
                    dataset.add(rdf.createQuad(PreferServerManaged, upload.getBinary().getIdentifier(),
                            DC.format, rdf.createLiteral(
                                    upload.getBinary().getMimeType().orElse(APPLICATION_OCTET_STREAM))));
                    upload.getBinary().getSize()
                            .ifPresent(size -> dataset
                                    .add(rdf.createQuad(PreferServerManaged, upload.getBinary().getIdentifier(),
                                            DC.extent, rdf.createLiteral(size.toString(), XSD.long_))));

                    if (resourceService.put(identifier, dataset.asDataset())) {
                        return created(create(upload.getBaseUrl() + upload.getPath())).build();
                    }
                }
                LOGGER.error("Could not persist data");
                return serverError().entity("Could not persist data internally").build();
            }).orElseThrow(NotFoundException::new);
}

From source file:org.opendaylight.eman.impl.EmanSNMPBinding.java

public String getEoAttrSNMP(String deviceIP, String attribute) {
    LOG.info("EmanSNMPBinding.getEoAttrSNMP: ");

    /* To do: generalize targetURL
        research using Java binding to make reference to 'local' ODL API
     *///from ww  w. ja  v a2  s .c  o  m
    String targetUrl = "http://localhost:8181/restconf/operations/snmp:snmp-get";
    String bodyString = buildSNMPGetBody(deviceIP, attribute);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    String result = null;

    try {
        /* invoke ODL SNMP API */
        HttpPost httpPost = new HttpPost(targetUrl);
        httpPost.addHeader("Authorization", "Basic " + encodedAuthStr);

        StringEntity inputBody = new StringEntity(bodyString);
        inputBody.setContentType(CONTENTTYPE_JSON);
        httpPost.setEntity(inputBody);

        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity responseEntity = httpResponse.getEntity();
        LOG.info("EmanSNMPBinding.getEoAttrSNMP: Response Status: " + httpResponse.getStatusLine().toString());
        InputStream in = responseEntity.getContent();

        /* Parse response from ODL SNMP API */
        JsonReader rdr = Json.createReader(in);
        JsonObject obj = rdr.readObject();
        JsonObject output = obj.getJsonObject("output");
        JsonArray results = output.getJsonArray("results");
        JsonObject pwr = results.getJsonObject(0);
        String oid = pwr.getString("oid");
        result = pwr.getString("value");
        rdr.close();

        LOG.info("EmanSNMPBinding.getEoAttrSNMP: oid: " + oid + " value " + result);
    } catch (Exception ex) {
        LOG.info("Error: " + ex.getMessage(), ex);
    } finally {
        try {
            httpClient.close();
        } catch (IOException ex) {
            LOG.info("Error: " + ex.getMessage(), ex);
        }
    }
    return (result);
}

From source file:DesignGUI.java

private void parseStackExchange(String jsonStr) {
    JsonReader reader = null;
    StringBuilder content = new StringBuilder();

    this.jEditorPane_areaShow.setContentType("text/html");

    content.append("<html></body>");
    try {//  ww  w . ja  va  2s.c o  m
        reader = Json.createReader(new StringReader(jsonStr));
        JsonObject jsonObject = reader.readObject();
        reader.close();
        JsonArray array = jsonObject.getJsonArray("items");
        for (JsonObject result : array.getValuesAs(JsonObject.class)) {

            JsonObject ownerObject = result.getJsonObject("owner");
            //   int ownerReputation = ownerObject.getInt("reputation");
            //  System.out.println("Reputation:"+ownerReputation);
            int viewCount = result.getInt("view_count");
            content.append("<br>View Count :" + viewCount + "<br>");

            int answerCount = result.getInt("answer_count");
            content.append("Answer Count :" + answerCount + "<br>");

            String title = result.getString("title");
            content.append("Title: <FONT COLOR=green>" + title + "</FONT>.<br>");

            String link = result.getString("link");

            content.append("URL :<a href=");
            content.append("'link'>" + link);
            content.append("</a>.<br>");

            //  String body = result.getString("body"); 
            //  content.append("Body:"+body);

            /* JsonArray tagsArray = result.getJsonArray("tags");
             StringBuilder tagBuilder = new StringBuilder();
             int i = 1;
             for(JsonValue tag : tagsArray){
            tagBuilder.append(tag.toString());
            if(i < tagsArray.size())
                tagBuilder.append(",");
            i++;
             }
            content.append("Tags: "+tagBuilder.toString());*/
        }

        content.append("</body></html>");
        this.jEditorPane_areaShow.setText(content.toString());
        System.out.println(content.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fr.ortolang.diffusion.runtime.engine.task.ImportReferentialEntityTask.java

private String extractField(String jsonContent, String fieldName) {
    String fieldValue = null;//  w w w  .  ja  v a2 s  .  c om
    StringReader reader = new StringReader(jsonContent);
    JsonReader jsonReader = Json.createReader(reader);
    try {
        JsonObject jsonObj = jsonReader.readObject();
        fieldValue = jsonObj.getString(fieldName);
    } catch (IllegalStateException | NullPointerException | ClassCastException | JsonException e) {
        LOGGER.log(Level.WARNING, "No property '" + fieldName + "' in json object", e);
    } finally {
        jsonReader.close();
        reader.close();
    }

    return fieldValue;
}

From source file:com.oncore.calorders.rest.service.extension.OrderHistoryFacadeRESTExtension.java

/**
 * Creates an order, containing the ordered products and related services.
 *
 * @param orderjson The order, represented as a JSON string
 * @throws DataAccessException//from  w w w  .j  ava  2s . c  o m
 */
@POST
@Path("createOrder")
@Consumes({ MediaType.APPLICATION_JSON })
public void createOrder(String orderjson) throws DataAccessException {

    try {
        JsonReader reader = Json.createReader(new StringReader(orderjson));
        JsonObject orderObject = reader.readObject();
        reader.close();

        OrderHistory order = new OrderHistory();

        order.setUpdateTs(new Date());
        order.setUpdateUserId(orderObject.getString("updateUserId", null));
        order.setCreateTs(new Date());
        order.setCreateUserId(orderObject.getString("createUserId", null));

        OrdStatusCd ordStatusCd = this.ordStatusCdFacadeREST.find(orderObject.getString("orderStatusCd", null));

        if (ordStatusCd == null) {
            throw new DataAccessException(ErrorCode.DATAACCESSERROR.toString());
        } else {
            order.setOrdStatusCd(ordStatusCd);
        }

        Party party = this.partyFacadeRESTExtension.find(Integer.valueOf(orderObject.getString("partyUid")));

        if (party == null) {
            throw new DataAccessException(ErrorCode.DATAACCESSERROR.toString());
        } else {
            order.setPtyUidFk(party);

            order.setDepUidFk(
                    party.getGroupPartyAssocCollection().iterator().next().getGrpUidFk().getDepUidFk());
        }

        order.setOrderProductAssocCollection(new ArrayList<OrderProductAssoc>());

        JsonArray productList = orderObject.getJsonArray("products");

        for (int i = 0; i < productList.size(); i++) {
            JsonObject productObject = productList.getJsonObject(i);
            OrderProductAssoc orderProductAssoc = new OrderProductAssoc();

            Product product = this.productFacadeRESTExtension.find(productObject.getInt("prdUid"));

            orderProductAssoc.setPrdUidFk(product);
            orderProductAssoc.setOrdUidFk(order);
            orderProductAssoc.setUpdateTs(new Date());
            orderProductAssoc.setUpdateUserId(productObject.getString("updateUserId", null));
            orderProductAssoc.setCreateTs(new Date());
            orderProductAssoc.setCreateUserId(productObject.getString("createUserId", null));
            orderProductAssoc.setOpaQuantity(productObject.getInt("quantity"));
            orderProductAssoc.setOpaPrice(product.getPrdCntrUnitPrice()
                    .multiply(BigDecimal.valueOf(productObject.getInt("quantity"))));

            order.getOrderProductAssocCollection().add(orderProductAssoc);
        }

        super.create(order);
    } catch (Exception ex) {
        Logger.error(LOG, FormatHelper.getStackTrace(ex));
        throw new DataAccessException(ex, ErrorCode.DATAACCESSERROR);
    }

}

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

@Override
public Result runQuery(SecureSession session, Query qep, Result result) throws ResourceInterfaceException {
    // TODO Auto-generated method stub
    HttpClient client = createClient(session);
    result.setResultStatus(ResultStatus.CREATED);

    // Check Clause
    if (qep.getClauses().size() != 1) {
        result.setResultStatus(ResultStatus.ERROR);
        result.setMessage("Wrong number of clauses");
        return result;
    }//from w ww . j av a 2  s . c  o m
    ClauseAbstract clause = qep.getClauses().values().iterator().next();

    if (!(clause instanceof WhereClause)) {
        result.setResultStatus(ResultStatus.ERROR);
        result.setMessage("Clause is not a where Clause");
        return result;
    }

    WhereClause whereClause = (WhereClause) clause;
    // Create Query
    String urlString = null;

    // BY ENSEMBL
    if (whereClause.getPredicateType().getName().equals("ENSEMBL")) {
        urlString = resourceURL + "/rest" + getResourcePathFromPUI(whereClause.getField().getPui()) + "/"
                + whereClause.getStringValues().get("ENSEMBLID");

    } else if (whereClause.getPredicateType().getName().equals("QUERY")) {
        // BY QUERY
        String[] resourcePath = getResourcePathFromPUI(whereClause.getField().getPui()).split("/");
        String service = "";
        if (resourcePath.length >= 3) {
            service = "&service=" + resourcePath[2];
        }

        urlString = resourceURL + "/rest/awesome?query=" + whereClause.getStringValues().get("QUERY") + service;
    } else if (whereClause.getPredicateType().getName().equals("REGION")) {
        // BY REGION
        urlString = resourceURL + "/rest" + getResourcePathFromPUI(whereClause.getField().getPui()) + "/"
                + whereClause.getStringValues().get("CHROMOSOME") + "-"
                + whereClause.getStringValues().get("START");
        if (whereClause.getStringValues().containsKey("STOP")) {
            urlString += "-" + whereClause.getStringValues().get("STOP");
        }

    } else if (whereClause.getPredicateType().getName().equals("VARIANT")) {
        // BY VARIANT
        urlString = resourceURL + "/rest" + getResourcePathFromPUI(whereClause.getField().getPui()) + "/"
                + whereClause.getStringValues().get("CHROMOSOME") + "-"
                + whereClause.getStringValues().get("POSITION") + "-"
                + whereClause.getStringValues().get("REFERENCE") + "-"
                + whereClause.getStringValues().get("VARIANT");
    }
    // Run Query
    if (urlString == null) {
        result.setResultStatus(ResultStatus.ERROR);
        result.setMessage("Unknown predicate");
        return result;
    }

    HttpGet get = new HttpGet(urlString);
    try {
        HttpResponse response = client.execute(get);
        JsonReader reader = Json.createReader(response.getEntity().getContent());
        JsonStructure results = reader.read();
        if (results.getValueType().equals(ValueType.ARRAY)) {
            result = convertJsonArrayToResultSet((JsonArray) results, result);
        } else {
            result = convertJsonObjectToResultSet((JsonObject) results, result);
        }
        reader.close();
        result.setResultStatus(ResultStatus.COMPLETE);
    } catch (IOException e) {
        result.setResultStatus(ResultStatus.ERROR);
        result.setMessage(e.getMessage());
    }

    // Format Results

    return result;
}

From source file:csg.files.CSGFiles.java

private JsonObject loadJSONFile(String jsonFilePath) throws IOException {
    InputStream is = new FileInputStream(jsonFilePath);
    JsonReader jsonReader = Json.createReader(is);
    JsonObject json = jsonReader.readObject();
    jsonReader.close();
    is.close();//from ww  w . j av  a  2 s  .  c  om
    return json;
}

From source file:de.pksoftware.springstrap.cms.util.CmsUtils.java

public static String getModelProperty(CmsModel model, String path, String defaultValue)
        throws InvalidPathException {
    if (null == model) {
        return defaultValue;
    }//from  w  ww. java2  s .c  o m

    Pattern pattern = Pattern.compile("^(\\/\\w+)+$");
    Matcher matcher = pattern.matcher(path);

    if (!matcher.matches()) {
        throw new RuntimeException(
                "Path must start with /, must not end with / and must only contain letters and numbers.");
    }

    String value = defaultValue;

    logger.info("Trying to get " + model.getModelName() + ">" + path);

    String data = model.getData();

    String[] pathParts = path.split("\\/");
    int partsLength = pathParts.length;

    JsonReader jsonReader = Json.createReader(new StringReader(data));
    JsonObject jsonObject = jsonReader.readObject();

    boolean pointerIsArray = false;
    Object pointer = jsonObject;

    for (int i = 1; i < partsLength; i++) {
        String pathPart = pathParts[i];
        logger.info("Testing property: " + pathPart);
        JsonValue jsonValue = null;
        Assert.notNull(pointer);
        if (pointerIsArray) {
            if (!NumberUtils.isNumber(pathPart)) {
                throw new InvalidPathException("Path element '" + pathPart + "' should be numeric.");
            }
            jsonValue = ((JsonArray) pointer).get(Integer.parseInt(pathPart));
        } else {
            jsonValue = ((JsonObject) pointer).get(pathPart);
        }

        if (null == jsonValue) {
            logger.info(model.getModelName() + " has no property: " + path);

            break;
        }

        JsonValue.ValueType valueType = jsonValue.getValueType();
        if (i < partsLength - 1) {
            //Must be Object or Array
            if (valueType == JsonValue.ValueType.ARRAY) {
                logger.info(pathPart + " is an array.");
                pointer = (JsonArray) jsonValue;
                pointerIsArray = true;
            } else if (valueType == JsonValue.ValueType.OBJECT) {
                logger.info(pathPart + " is an object.");
                pointer = (JsonObject) jsonValue;
                pointerIsArray = false;
            } else {
                throw new InvalidPathException("Path element '" + pathPart
                        + "' should be a be an object or array, but " + valueType.toString() + " found.");
            }
        } else {
            if (valueType == JsonValue.ValueType.STRING) {
                logger.info(pathPart + " is an string.");
                value = ((JsonString) jsonValue).getString();
                break;
            } else {
                throw new InvalidPathException("Path element '" + pathPart + "' should be a string, but "
                        + valueType.toString() + " found.");
            }
        }
    }

    jsonReader.close();

    return value;
}

From source file:org.owasp.dependencycheck.analyzer.NodePackageAnalyzer.java

@Override
protected void analyzeFileType(Dependency dependency, Engine engine) throws AnalysisException {
    final File file = dependency.getActualFile();
    JsonReader jsonReader;
    try {//w  ww.j ava2s . c o m
        jsonReader = Json.createReader(FileUtils.openInputStream(file));
    } catch (IOException e) {
        throw new AnalysisException("Problem occurred while reading dependency file.", e);
    }
    try {
        final JsonObject json = jsonReader.readObject();
        final EvidenceCollection productEvidence = dependency.getProductEvidence();
        final EvidenceCollection vendorEvidence = dependency.getVendorEvidence();
        if (json.containsKey("name")) {
            final Object value = json.get("name");
            if (value instanceof JsonString) {
                final String valueString = ((JsonString) value).getString();
                productEvidence.addEvidence(PACKAGE_JSON, "name", valueString, Confidence.HIGHEST);
                vendorEvidence.addEvidence(PACKAGE_JSON, "name_project",
                        String.format("%s_project", valueString), Confidence.LOW);
            } else {
                LOGGER.warn("JSON value not string as expected: {}", value);
            }
        }
        addToEvidence(json, productEvidence, "description");
        addToEvidence(json, vendorEvidence, "author");
        addToEvidence(json, dependency.getVersionEvidence(), "version");
        dependency.setDisplayFileName(String.format("%s/%s", file.getParentFile().getName(), file.getName()));
    } catch (JsonException e) {
        LOGGER.warn("Failed to parse package.json file.", e);
    } finally {
        jsonReader.close();
    }
}