Example usage for javax.json JsonReader read

List of usage examples for javax.json JsonReader read

Introduction

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

Prototype

JsonStructure read();

Source Link

Document

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

Usage

From source file:com.adobe.cq.wcm.core.components.Utils.java

/**
 * Provided a {@code model} object and an {@code expectedJsonResource} identifying a JSON file in the class path, this method will
 * test the JSON export of the model and compare it to the JSON object provided by the {@code expectedJsonResource}.
 *
 * @param model                the Sling Model
 * @param expectedJsonResource the class path resource providing the expected JSON object
 *///from  w  w  w  .j  a v a2  s . c  o  m
public static void testJSONExport(Object model, String expectedJsonResource) {
    Writer writer = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    PageModuleProvider pageModuleProvider = new PageModuleProvider();
    mapper.registerModule(pageModuleProvider.getModule());
    DefaultMethodSkippingModuleProvider defaultMethodSkippingModuleProvider = new DefaultMethodSkippingModuleProvider();
    mapper.registerModule(defaultMethodSkippingModuleProvider.getModule());
    try {
        mapper.writer().writeValue(writer, model);
    } catch (IOException e) {
        fail(String.format("Unable to generate JSON export for model %s: %s", model.getClass().getName(),
                e.getMessage()));
    }
    JsonReader outputReader = Json.createReader(IOUtils.toInputStream(writer.toString()));
    InputStream is = Thread.currentThread().getContextClassLoader().getClass()
            .getResourceAsStream(expectedJsonResource);
    if (is != null) {
        JsonReader expectedReader = Json.createReader(is);
        assertEquals(expectedReader.read(), outputReader.read());
    } else {
        fail("Unable to find test file " + expectedJsonResource + ".");
    }
    IOUtils.closeQuietly(is);
}

From source file:org.hyperledger.fabric_ca.sdk.MockHFCAClient.java

@Override
JsonObject httpPost(String url, String body, User admin) throws Exception {

    JsonObject response;/*ww  w  .  j  a  v a  2  s. c  o m*/

    if (httpPostResponse == null) {
        response = super.httpPost(url, body, admin);
    } else {
        JsonReader reader = Json.createReader(new StringReader(httpPostResponse));
        response = (JsonObject) reader.read();

        // TODO: HFCAClient could do with some minor refactoring to avoid duplicating this code here!!
        JsonObject result = response.getJsonObject("result");
        if (result == null) {
            EnrollmentException e = new EnrollmentException(format(
                    "POST request to %s failed request body %s " + "Body of response did not contain result",
                    url, body), new Exception());
            throw e;
        }
    }
    return response;
}

From source file:com.adobe.cq.wcm.core.components.internal.models.v1.ImageImplTest.java

protected void compareJSON(String expectedJson, String json) {
    JsonReader expected = Json.createReader(new StringReader(expectedJson));
    JsonReader actual = Json.createReader(new StringReader(json));
    assertEquals(expected.read(), actual.read());
}

From source file:org.hyperledger.fabric.sdk.MemberServicesFabricCAImpl.java

/**
 * Enroll the user with member service/*  ww  w  .j ava  2s . c o m*/
 *
 * @param req Enrollment request with the following fields: name, enrollmentSecret
 * @return enrollment
 */
public Enrollment enroll(EnrollmentRequest req) throws EnrollmentException {

    logger.debug(String.format("[MemberServicesFabricCAImpl.enroll] [%s]", req));
    if (req == null) {
        throw new RuntimeException("req is not set");
    }
    final String user = req.getEnrollmentID();
    final String secret = req.getEnrollmentSecret();
    if (StringUtil.isNullOrEmpty(user)) {
        throw new RuntimeException("req.enrollmentID is not set");
    }
    if (StringUtil.isNullOrEmpty(secret)) {
        throw new RuntimeException("req.enrollmentSecret is not set");
    }

    logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys...");

    try {
        // generate ECDSA keys: signing and encryption keys
        KeyPair signingKeyPair = cryptoPrimitives.ecdsaKeyGen();
        logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys...done!");
        //  KeyPair encryptionKeyPair = cryptoPrimitives.ecdsaKeyGen();

        PKCS10CertificationRequest csr = cryptoPrimitives.generateCertificationRequest(user, signingKeyPair);
        String pem = cryptoPrimitives.certificationRequestToPEM(csr);
        JsonObjectBuilder factory = Json.createObjectBuilder();
        factory.add("certificate_request", pem);
        JsonObject postObject = factory.build();
        StringWriter stringWriter = new StringWriter();

        JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter));

        jsonWriter.writeObject(postObject);

        jsonWriter.close();

        String str = stringWriter.toString();

        logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys...done!");

        String responseBody = httpPost(url + COP_ENROLLMENBASE, str,
                new UsernamePasswordCredentials(user, secret));

        logger.debug("response" + responseBody);

        JsonReader reader = Json.createReader(new StringReader(responseBody));
        JsonObject jsonst = (JsonObject) reader.read();
        String result = jsonst.getString("result");
        boolean success = jsonst.getBoolean("success");
        logger.debug(String.format("[MemberServicesFabricCAImpl] enroll success:[%s], result:[%s]", success,
                result));

        if (!success) {
            EnrollmentException e = new EnrollmentException("COP Failed response success is false. " + result,
                    new Exception());
            logger.error(e.getMessage());
            throw e;
        }

        Base64.Decoder b64dec = Base64.getDecoder();
        String signedPem = new String(b64dec.decode(result.getBytes()));
        logger.info(String.format("[MemberServicesFabricCAImpl] enroll returned pem:[%s]", signedPem));

        Enrollment enrollment = new Enrollment();
        enrollment.setKey(signingKeyPair);
        enrollment.setPublicKey(Hex.toHexString(signingKeyPair.getPublic().getEncoded()));
        enrollment.setCert(signedPem);
        return enrollment;

    } catch (Exception e) {
        EnrollmentException ee = new EnrollmentException(String.format("Failed to enroll user %s ", user), e);
        logger.error(ee.getMessage(), ee);
        throw ee;
    }

}

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 w w . j  av  a  2 s  .c  om*/
    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:com.adobe.cq.wcm.core.components.extension.contentfragment.internal.models.v1.ContentFragmentImplTest.java

@Test
public void testJSONExport() throws IOException {
    ContentFragmentImpl fragment = (ContentFragmentImpl) getTestContentFragment(CF_TEXT_ONLY);
    Writer writer = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.writerWithView(ContentFragmentImpl.class).writeValue(writer, fragment);
    JsonReader jsonReaderOutput = Json.createReader(IOUtils.toInputStream(writer.toString()));
    JsonReader jsonReaderExpected = Json.createReader(Thread.currentThread().getContextClassLoader().getClass()
            .getResourceAsStream("/contentfragment/test-expected-content-export.json"));
    assertEquals(jsonReaderExpected.read(), jsonReaderOutput.read());
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

/**
 * Return information on the Fabric Certificate Authority.
 * No credentials are needed for this API.
 *
 * @return {@link HFCAInfo}// www . j a  v a  2 s.c o  m
 * @throws InfoException
 * @throws InvalidArgumentException
 */

public HFCAInfo info() throws InfoException, InvalidArgumentException {

    logger.debug(format("info url:%s", url));
    if (cryptoSuite == null) {
        throw new InvalidArgumentException("Crypto primitives not set.");
    }

    setUpSSL();

    try {

        JsonObjectBuilder factory = Json.createObjectBuilder();

        if (caName != null) {
            factory.add(HFCAClient.FABRIC_CA_REQPROP, caName);
        }
        JsonObject body = factory.build();

        String responseBody = httpPost(url + HFCA_INFO, body.toString(), (UsernamePasswordCredentials) null);

        logger.debug("response:" + responseBody);

        JsonReader reader = Json.createReader(new StringReader(responseBody));
        JsonObject jsonst = (JsonObject) reader.read();

        boolean success = jsonst.getBoolean("success");
        logger.debug(format("[HFCAClient] enroll success:[%s]", success));

        if (!success) {
            throw new EnrollmentException(format("FabricCA failed info %s", url));
        }

        JsonObject result = jsonst.getJsonObject("result");
        if (result == null) {
            throw new InfoException(
                    format("FabricCA info error  - response did not contain a result url %s", url));
        }

        String caName = result.getString("CAName");
        String caChain = result.getString("CAChain");
        String version = null;
        if (result.containsKey("Version")) {
            version = result.getString("Version");
        }
        String issuerPublicKey = null;
        if (result.containsKey("IssuerPublicKey")) {
            issuerPublicKey = result.getString("IssuerPublicKey");
        }
        String issuerRevocationPublicKey = null;
        if (result.containsKey("IssuerRevocationPublicKey")) {
            issuerRevocationPublicKey = result.getString("IssuerRevocationPublicKey");
        }

        logger.info(format("CA Name: %s, Version: %s, issuerPublicKey: %s, issuerRevocationPublicKey: %s",
                caName, caChain, issuerPublicKey, issuerRevocationPublicKey));
        return new HFCAInfo(caName, caChain, version, issuerPublicKey, issuerRevocationPublicKey);

    } catch (Exception e) {
        InfoException ee = new InfoException(format("Url:%s, Failed to get info", url), e);
        logger.error(e.getMessage(), e);
        throw ee;
    }

}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

JsonObject getResult(HttpResponse response, String body, String type)
        throws HTTPException, ParseException, IOException {

    int respStatusCode = response.getStatusLine().getStatusCode();
    HttpEntity entity = response.getEntity();
    logger.trace(format("response status %d, HttpEntity %s ", respStatusCode, "" + entity));
    String responseBody = entity != null ? EntityUtils.toString(entity) : null;
    logger.trace(format("responseBody: %s ", responseBody));

    // If the status code in the response is greater or equal to the status code set in the client object then an exception will
    // be thrown, otherwise, we continue to read the response and return any error code that is less than 'statusCode'
    if (respStatusCode >= statusCode) {
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s. Response: %s", type, url, body, responseBody),
                respStatusCode);//from   w ww .  j a  v a2 s.com
        logger.error(e.getMessage());
        throw e;
    }
    if (responseBody == null) {

        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s with null response body returned.", type, url,
                        body),
                respStatusCode);
        logger.error(e.getMessage());
        throw e;

    }

    logger.debug("Status: " + respStatusCode);

    JsonReader reader = Json.createReader(new StringReader(responseBody));
    JsonObject jobj = (JsonObject) reader.read();

    JsonObjectBuilder job = Json.createObjectBuilder();
    job.add("statusCode", respStatusCode);

    JsonArray errors = jobj.getJsonArray("errors");
    // If the status code is greater than or equal to 400 but less than or equal to the client status code setting,
    // then encountered an error and we return back the status code, and log the error rather than throwing an exception.
    if (respStatusCode < statusCode && respStatusCode >= 400) {
        if (errors != null && !errors.isEmpty()) {
            JsonObject jo = errors.getJsonObject(0);
            String errorMsg = format(
                    "[HTTP Status Code: %d] - %s request to %s failed request body %s error message: [Error Code %d] - %s",
                    respStatusCode, type, url, body, jo.getInt("code"), jo.getString("message"));
            logger.error(errorMsg);
        }
        return job.build();
    }
    if (errors != null && !errors.isEmpty()) {
        JsonObject jo = errors.getJsonObject(0);
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s error message: [Error Code %d] - %s", type, url,
                        body, jo.getInt("code"), jo.getString("message")),
                respStatusCode);
        throw e;
    }

    boolean success = jobj.getBoolean("success");
    if (!success) {
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s Body of response did not contain success", type,
                        url, body),
                respStatusCode);
        logger.error(e.getMessage());
        throw e;
    }

    JsonObject result = jobj.getJsonObject("result");
    if (result == null) {
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s " + "Body of response did not contain result",
                        type, url, body),
                respStatusCode);
        logger.error(e.getMessage());
        throw e;
    }

    JsonArray messages = jobj.getJsonArray("messages");
    if (messages != null && !messages.isEmpty()) {
        JsonObject jo = messages.getJsonObject(0);
        String message = format(
                "%s request to %s failed request body %s response message: [Error Code %d] - %s", type, url,
                body, jo.getInt("code"), jo.getString("message"));
        logger.info(message);
    }

    // Construct JSON object that contains the result and HTTP status code
    for (Entry<String, JsonValue> entry : result.entrySet()) {
        job.add(entry.getKey(), entry.getValue());
    }
    job.add("statusCode", respStatusCode);
    result = job.build();

    logger.debug(format("%s %s, body:%s result: %s", type, url, body, "" + result));
    return result;
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

/**
 * Enroll the user with member service//from  w w  w .j a v  a 2 s  .  c om
 *
 * @param user   Identity name to enroll
 * @param secret Secret returned via registration
 * @param req    Enrollment request with the following fields: hosts, profile, csr, label, keypair
 * @return enrollment
 * @throws EnrollmentException
 * @throws InvalidArgumentException
 */

public Enrollment enroll(String user, String secret, EnrollmentRequest req)
        throws EnrollmentException, InvalidArgumentException {

    logger.debug(format("url:%s enroll user: %s", url, user));

    if (Utils.isNullOrEmpty(user)) {
        throw new InvalidArgumentException("enrollment user is not set");
    }
    if (Utils.isNullOrEmpty(secret)) {
        throw new InvalidArgumentException("enrollment secret is not set");
    }

    if (cryptoSuite == null) {
        throw new InvalidArgumentException("Crypto primitives not set.");
    }

    setUpSSL();

    try {
        String pem = req.getCsr();
        KeyPair keypair = req.getKeyPair();
        if (null != pem && keypair == null) {
            throw new InvalidArgumentException(
                    "If certificate signing request is supplied the key pair needs to be supplied too.");
        }
        if (keypair == null) {
            logger.debug("[HFCAClient.enroll] Generating keys...");

            // generate ECDSA keys: signing and encryption keys
            keypair = cryptoSuite.keyGen();

            logger.debug("[HFCAClient.enroll] Generating keys...done!");
        }

        if (pem == null) {
            String csr = cryptoSuite.generateCertificationRequest(user, keypair);
            req.setCSR(csr);
        }

        if (caName != null && !caName.isEmpty()) {
            req.setCAName(caName);
        }
        String body = req.toJson();

        String responseBody = httpPost(url + HFCA_ENROLL, body, new UsernamePasswordCredentials(user, secret));

        logger.debug("response:" + responseBody);

        JsonReader reader = Json.createReader(new StringReader(responseBody));
        JsonObject jsonst = (JsonObject) reader.read();

        boolean success = jsonst.getBoolean("success");
        logger.debug(format("[HFCAClient] enroll success:[%s]", success));

        if (!success) {
            throw new EnrollmentException(
                    format("FabricCA failed enrollment for user %s response success is false.", user));
        }

        JsonObject result = jsonst.getJsonObject("result");
        if (result == null) {
            throw new EnrollmentException(
                    format("FabricCA failed enrollment for user %s - response did not contain a result", user));
        }

        Base64.Decoder b64dec = Base64.getDecoder();

        String signedPem = new String(b64dec.decode(result.getString("Cert").getBytes(UTF_8)));
        logger.debug(format("[HFCAClient] enroll returned pem:[%s]", signedPem));

        JsonArray messages = jsonst.getJsonArray("messages");
        if (messages != null && !messages.isEmpty()) {
            JsonObject jo = messages.getJsonObject(0);
            String message = format("Enroll request response message [code %d]: %s", jo.getInt("code"),
                    jo.getString("message"));
            logger.info(message);
        }
        logger.debug("Enrollment done.");

        return new X509Enrollment(keypair, signedPem);

    } catch (EnrollmentException ee) {
        logger.error(format("url:%s, user:%s  error:%s", url, user, ee.getMessage()), ee);
        throw ee;

    } catch (Exception e) {
        EnrollmentException ee = new EnrollmentException(format("Url:%s, Failed to enroll user %s ", url, user),
                e);
        logger.error(e.getMessage(), e);
        throw ee;
    }

}

From source file:org.apache.johnzon.maven.plugin.ExampleToModelMojo.java

private void generate(final JsonReaderFactory readerFactory, final File source, final Writer writer,
        final String javaName) throws MojoExecutionException {
    JsonReader reader = null;
    try {/* w ww .  j a  va2s.  co  m*/
        reader = readerFactory.createReader(new FileReader(source));
        final JsonStructure structure = reader.read();
        if (JsonArray.class.isInstance(structure) || !JsonObject.class.isInstance(structure)) { // quite redundant for now but to avoid surprises in future
            throw new MojoExecutionException(
                    "This plugin doesn't support array generation, generate the model (generic) and handle arrays in your code");
        }

        final JsonObject object = JsonObject.class.cast(structure);
        final Collection<String> imports = new TreeSet<String>();

        // while we browse the example tree just store imports as well, avoids a 2 passes processing duplicating imports logic
        final StringWriter memBuffer = new StringWriter();
        generateFieldsAndMethods(memBuffer, object, "    ", imports);

        if (header != null) {
            writer.write(header);
            writer.write('\n');
        }

        writer.write("package " + packageBase + ";\n\n");

        if (!imports.isEmpty()) {
            for (final String imp : imports) {
                writer.write("import " + imp + ";\n");
            }
            writer.write('\n');
        }

        writer.write("public class " + javaName + " {\n");
        writer.write(memBuffer.toString());
        writer.write("}\n");
    } catch (final IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}