Example usage for javax.json JsonReader readObject

List of usage examples for javax.json JsonReader readObject

Introduction

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

Prototype

JsonObject readObject();

Source Link

Document

Returns a JSON object that is represented in the input source.

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();// w w  w.ja va2 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:ro.cs.products.landsat.LandsatSearch.java

public List<ProductDescriptor> execute() throws IOException {
    List<ProductDescriptor> results = new ArrayList<>();
    String queryUrl = getQuery();
    Logger.getRootLogger().info(queryUrl);
    try (CloseableHttpResponse response = NetUtils.openConnection(queryUrl, credentials)) {
        switch (response.getStatusLine().getStatusCode()) {
        case 200:
            String body = EntityUtils.toString(response.getEntity());
            final JsonReader jsonReader = Json.createReader(new StringReader(body));
            Logger.getRootLogger().debug("Parsing json response");
            JsonObject responseObj = jsonReader.readObject();
            JsonArray jsonArray = responseObj.getJsonArray("results");
            for (int i = 0; i < jsonArray.size(); i++) {
                LandsatProductDescriptor currentProduct = new LandsatProductDescriptor();
                JsonObject result = jsonArray.getJsonObject(i);
                currentProduct.setName(result.getString("scene_id"));
                currentProduct.setId(result.getString("sceneID"));
                currentProduct.setPath(String.valueOf(result.getInt("path")));
                currentProduct.setRow(String.valueOf(result.getInt("row")));
                currentProduct.setSensingDate(result.getString("acquisitionDate"));
                results.add(currentProduct);
            }//from  w  w w .  j a  v a2  s. c o  m

            break;
        case 401:
            Logger.getRootLogger().info("The supplied credentials are invalid!");
            break;
        default:
            Logger.getRootLogger().info("The request was not successful. Reason: %s",
                    response.getStatusLine().getReasonPhrase());
            break;
        }
    }
    Logger.getRootLogger().info("Query returned %s products", results.size());
    return results;
}

From source file:org.bsc.confluence.rest.AbstractRESTConfluenceService.java

protected JsonObject mapToObject(Response res) {
    final ResponseBody body = res.body();

    try (Reader r = body.charStream()) {

        final JsonReader rdr = Json.createReader(r);

        final JsonObject root = rdr.readObject();

        return root;

    } catch (IOException ex) {

        throw new Error(ex);
    }/*from w ww . j a  v  a2  s . c o  m*/
}

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

/**
 * Create a binary from a collection of uploaded parts
 * @param partition the partition//from  w ww  . j av a  2s. 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.bsc.confluence.rest.AbstractRESTConfluenceService.java

protected Stream<JsonObject> mapToStream(Response res) {

    final ResponseBody body = res.body();

    try (Reader r = body.charStream()) {

        final JsonReader rdr = Json.createReader(r);

        final JsonObject root = rdr.readObject();

        final Stream.Builder<JsonObject> stream = Stream.builder();

        // Check for Array
        if (root.containsKey("results")) {
            final JsonArray results = root.getJsonArray("results");

            if (results != null) {
                for (int ii = 0; ii < results.size(); ++ii)
                    stream.add(results.getJsonObject(ii));
            }/*w  w  w  .  ja  va  2 s  .c om*/
        } else {
            stream.add(root);
        }

        return stream.build();

    } catch (IOException | JsonParsingException e) {
        throw new Error(e);
    }

}

From source file:info.dolezel.jarss.rest.v1.ws.UnreadNotificationEndpoint.java

@OnWebSocketMessage
public void onMessage(Session session, String text) {
    EntityManager em = null;//from w  w  w  . j a v a 2s. co m
    EntityTransaction tx = null;
    try {
        JsonReader reader;
        JsonObject object;
        Token token;

        em = HibernateUtil.getEntityManager();
        tx = em.getTransaction();

        tx.begin();

        reader = Json.createReader(new StringReader(text));
        object = reader.readObject();

        token = Token.loadToken(em, object.getString("token"));
        if (token == null) {
            tx.rollback();

            Logger.getLogger(UnreadNotificationEndpoint.class.getName()).log(Level.WARNING,
                    "Invalid token provided over WebSocket");
            session.close();
        } else {
            synchronized (sessions) {
                sessions.put(session, token.getUser());
            }
            synchronized (userSessions) {
                userSessions.put(token.getUser(), session);
            }
        }

        tx.commit();
    } catch (Exception ex) {
        if (tx != null)
            tx.rollback();

        Logger.getLogger(UnreadNotificationEndpoint.class.getName()).log(Level.SEVERE,
                "Error processing incoming WebSocket message", ex);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:fr.ortolang.diffusion.client.cmd.CheckBagCommand.java

private int parseACLLevel(Path aclFile) throws IOException {
    JsonReader reader = Json.createReader(Files.newInputStream(aclFile));
    String name = reader.readObject().getString("template");
    return Template.findTemplateByName(name).getLevel();
}

From source file:com.amazon.alexa.avs.auth.companionservice.CompanionServiceClient.java

JsonObject callService(String path, Map<String, String> parameters) throws IOException {
    HttpURLConnection con = null;
    InputStream response = null;/*from  ww  w. j a  v  a2 s.  c om*/
    try {
        String queryString = mapToQueryString(parameters);
        URL obj = new URL(deviceConfig.getCompanionServiceInfo().getServiceUrl(), path + queryString);
        con = (HttpURLConnection) obj.openConnection();

        if (con instanceof HttpsURLConnection) {
            ((HttpsURLConnection) con).setSSLSocketFactory(pinnedSSLSocketFactory);
        }

        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestMethod("GET");

        if ((con.getResponseCode() >= 200) || (con.getResponseCode() < 300)) {
            response = con.getInputStream();
        }

        if (response != null) {
            String responsestring = IOUtils.toString(response);
            JsonReader reader = Json
                    .createReader(new ByteArrayInputStream(responsestring.getBytes(StandardCharsets.UTF_8)));
            IOUtils.closeQuietly(response);
            return reader.readObject();
        }
        return Json.createObjectBuilder().build();
    } catch (IOException e) {
        if (con != null) {
            response = con.getErrorStream();

            if (response != null) {
                String responsestring = IOUtils.toString(response);
                JsonReader reader = Json.createReader(
                        new ByteArrayInputStream(responsestring.getBytes(StandardCharsets.UTF_8)));
                JsonObject error = reader.readObject();

                String errorName = error.getString("error", null);
                String errorMessage = error.getString("message", null);

                if (!StringUtils.isBlank(errorName) && !StringUtils.isBlank(errorMessage)) {
                    throw new RemoteServiceException(errorName + ": " + errorMessage);
                }
            }
        }
        throw e;
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response);
        }
    }
}

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 {/*from  w w  w . j a  v a  2 s.co 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();
    }
}

From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.i2b2transmart.I2B2TranSMARTResourceImplementation.java

@Override
public List<Entity> getPathRelationship(Entity path, OntologyRelationship relationship, SecureSession session)
        throws ResourceInterfaceException {
    List<Entity> returns = super.getPathRelationship(path, relationship, session);

    // Get the counts from the tranSMART server
    try {// w ww. ja v a 2  s .com
        HttpClient client = createClient(session);
        String basePath = path.getPui();
        String[] pathComponents = basePath.split("/");

        if (pathComponents.length > 3) {
            String myPath = "\\";
            for (String pathComponent : Arrays.copyOfRange(pathComponents, 3, pathComponents.length)) {
                myPath += "\\" + pathComponent;
            }
            basePath = pathComponents[0] + "/" + pathComponents[1] + "/" + pathComponents[2];

            HttpPost post = new HttpPost(this.transmartURL + "/chart/childConceptPatientCounts");
            List<NameValuePair> formParameters = new ArrayList<NameValuePair>();
            formParameters.add(new BasicNameValuePair("charttype", "childconceptpatientcounts"));
            formParameters.add(new BasicNameValuePair("concept_key", myPath + "\\"));
            formParameters.add(new BasicNameValuePair("concept_level", ""));

            post.setEntity(new UrlEncodedFormEntity(formParameters));

            HttpResponse response = client.execute(post);

            JsonReader jsonReader = Json.createReader(response.getEntity().getContent());

            JsonObject counts = jsonReader.readObject().getJsonObject("counts");

            for (Entity singleReturn : returns) {
                String singleReturnMyPath = convertPUItoI2B2Path(singleReturn.getPui());

                if (counts.containsKey(singleReturnMyPath)) {
                    singleReturn.getCounts().put("count", counts.getInt(singleReturnMyPath));
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return returns;
}