Example usage for javax.json JsonObject getBoolean

List of usage examples for javax.json JsonObject getBoolean

Introduction

In this page you can find the example usage for javax.json JsonObject getBoolean.

Prototype

boolean getBoolean(String name);

Source Link

Document

Returns the boolean value of the associated mapping for the specified name.

Usage

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

/**
 * Enroll the user with member service//from w  w w. j  a va 2  s.c  om
 *
 * @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:io.bitgrillr.gocddockerexecplugin.DockerExecPluginTest.java

@Test
public void handleExecuteFailure() throws Exception {
    UnitTestUtils.mockJobConsoleLogger();
    PowerMockito.mockStatic(DockerUtils.class);
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.pullImage(anyString());/*w w  w .  j a v a  2s  . c  o  m*/
    when(DockerUtils.createContainer(anyString(), anyString(), anyMap())).thenReturn("123");
    when(DockerUtils.getContainerUid(anyString())).thenReturn("4:5");
    when(DockerUtils.execCommand(anyString(), any(), anyString(), any())).thenAnswer(i -> {
        if (i.getArgument(2).equals("chown")) {
            return 0;
        } else {
            return 1;
        }
    });
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.removeContainer(anyString());
    PowerMockito.mockStatic(SystemHelper.class);
    when(SystemHelper.getSystemUid()).thenReturn("7:8");

    DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, "execute");
    JsonObject requestBody = Json.createObjectBuilder()
            .add("config",
                    Json.createObjectBuilder()
                            .add("IMAGE", Json.createObjectBuilder().add("value", "ubuntu:latest").build())
                            .add("COMMAND", Json.createObjectBuilder().add("value", "ls").build())
                            .add("ARGUMENTS", Json.createObjectBuilder().build()).build())
            .add("context", Json.createObjectBuilder().add("workingDirectory", "pipelines/test")
                    .add("environmentVariables", Json.createObjectBuilder().build()).build())
            .build();
    request.setRequestBody(requestBody.toString());
    final GoPluginApiResponse response = new DockerExecPlugin().handle(request);

    assertEquals("Expected 2xx response", DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE,
            response.responseCode());
    final JsonObject responseBody = Json.createReader(new StringReader(response.responseBody())).readObject();
    assertEquals("Expected failure", Boolean.FALSE, responseBody.getBoolean("success"));
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.execCommand("123", "root", "chown", "-R", "4:5", ".");
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.execCommand("123", "root", "chown", "-R", "7:8", ".");
}

From source file:io.bitgrillr.gocddockerexecplugin.DockerExecPluginTest.java

@Test
public void handleExecute() throws Exception {
    UnitTestUtils.mockJobConsoleLogger();
    PowerMockito.mockStatic(DockerUtils.class);
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.pullImage(anyString());/* w  w  w .j  a v  a 2s.  c  o  m*/
    when(DockerUtils.createContainer(anyString(), anyString(), anyMap())).thenReturn("123");
    when(DockerUtils.getContainerUid(anyString())).thenReturn("4:5");
    when(DockerUtils.execCommand(anyString(), any(), any())).thenReturn(0);
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.removeContainer(anyString());
    when(DockerUtils.getCommandString(anyString(), any())).thenCallRealMethod();
    PowerMockito.mockStatic(SystemHelper.class);
    when(SystemHelper.getSystemUid()).thenReturn("7:8");

    DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, "execute");
    JsonObject requestBody = Json.createObjectBuilder()
            .add("config", Json.createObjectBuilder()
                    .add("IMAGE", Json.createObjectBuilder().add("value", "ubuntu:latest").build())
                    .add("COMMAND", Json.createObjectBuilder().add("value", "echo").build())
                    .add("ARGUMENTS", Json.createObjectBuilder().add("value", "Hello\nWorld").build()).build())
            .add("context", Json.createObjectBuilder().add("workingDirectory", "pipelines/test")
                    .add("environmentVariables",
                            Json.createObjectBuilder().add("TEST1", "value1").add("TEST2", "value2").build())
                    .build())
            .build();
    request.setRequestBody(requestBody.toString());
    final GoPluginApiResponse response = new DockerExecPlugin().handle(request);

    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.pullImage("ubuntu:latest");
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.createContainer("ubuntu:latest",
            Paths.get(System.getProperty("user.dir"), "pipelines/test").toAbsolutePath().toString(),
            Stream.<Map.Entry<String, String>>builder().add(new SimpleEntry<>("TEST1", "value1"))
                    .add(new SimpleEntry<>("TEST2", "value2")).build()
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.getContainerUid("123");
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.execCommand("123", "root", "chown", "-R", "4:5", ".");
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.execCommand("123", null, "echo", "Hello", "World");
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.execCommand("123", "root", "chown", "-R", "7:8", ".");
    PowerMockito.verifyStatic(DockerUtils.class);
    DockerUtils.removeContainer("123");
    assertEquals("Expected 2xx response", DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE,
            response.responseCode());
    final JsonObject responseBody = Json.createReader(new StringReader(response.responseBody())).readObject();
    assertEquals("Expected success", Boolean.TRUE, responseBody.getBoolean("success"));
    assertEquals("Wrong message", "Command 'echo 'Hello' 'World'' completed with status 0",
            Json.createReader(new StringReader(response.responseBody())).readObject().getString("message"));
}

From source file:csg.files.CSGFiles.java

@Override
public void loadData(AppDataComponent data, AppDataComponent recData, AppDataComponent schData,
        AppDataComponent projectData, AppDataComponent courseData, String filePath) throws IOException {
    // CLEAR THE OLD DATA OUT
    TAData dataManager = (TAData) data;/* w w w.ja v  a  2 s .c o  m*/
    ScheduleData schDataManager = (ScheduleData) schData;
    RecitationData recDataManager = (RecitationData) recData;
    ProjectData projectDataManager = (ProjectData) projectData;
    CourseData courseDataManager = (CourseData) courseData;
    workspace = (CSGWorkspace) app.getWorkspaceComponent();

    // LOAD THE JSON FILE WITH ALL THE DATA
    JsonObject json = loadJSONFile(filePath);

    // LOAD THE START AND END HOURS
    String startHour = json.getString(JSON_START_HOUR);
    String endHour = json.getString(JSON_END_HOUR);
    dataManager.initHours(startHour, endHour);

    // NOW RELOAD THE WORKSPACE WITH THE LOADED DATA
    app.getWorkspaceComponent().reloadWorkspace(app.getTADataComponent());

    int startDay = json.getInt(JSON_STARTDAY);
    int startMonth = json.getInt(JSON_STARTMONTH);
    int startYear = json.getInt(JSON_STARTYEAR);

    courseDataManager.setStartDay(startDay);
    courseDataManager.setStartMonth(startMonth);
    courseDataManager.setStartYear(startYear);

    if (startDay != 0 && startMonth != 0 && startYear != 0) {
        LocalDate startDate = LocalDate.of(startYear, startMonth, startDay);
        workspace.getMonStartDatePicker().setValue(startDate);
    } else {
        workspace.getMonStartDatePicker().setValue(null);
    }

    int endDay = json.getInt(JSON_ENDDAY);
    int endMonth = json.getInt(JSON_ENDMONTH);
    int endYear = json.getInt(JSON_ENDYEAR);

    courseDataManager.setEndDay(endDay);
    courseDataManager.setEndMonth(endMonth);
    courseDataManager.setEndYear(endYear);

    if (endDay != 0 && endMonth != 0 && endYear != 0) {
        LocalDate endDate = LocalDate.of(endYear, endMonth, endDay);
        workspace.getFriEndDatePicker().setValue(endDate);
    } else {
        workspace.getFriEndDatePicker().setValue(null);
    }

    // NOW LOAD ALL THE UNDERGRAD TAs
    JsonArray jsonTAArray = json.getJsonArray(JSON_UNDERGRAD_TAS);
    for (int i = 0; i < jsonTAArray.size(); i++) {
        JsonObject jsonTA = jsonTAArray.getJsonObject(i);
        String name = jsonTA.getString(JSON_NAME);
        String email = jsonTA.getString(JSON_EMAIL);
        boolean ug = jsonTA.getBoolean(JSON_UG);
        BooleanProperty isUndergrad = new SimpleBooleanProperty();
        isUndergrad.setValue(ug);
        dataManager.addTA(name, email, isUndergrad);
    }

    // AND THEN ALL THE OFFICE HOURS
    JsonArray jsonOfficeHoursArray = json.getJsonArray(JSON_OFFICE_HOURS);
    for (int i = 0; i < jsonOfficeHoursArray.size(); i++) {
        JsonObject jsonOfficeHours = jsonOfficeHoursArray.getJsonObject(i);
        String day = jsonOfficeHours.getString(JSON_DAY);
        String time = jsonOfficeHours.getString(JSON_TIME);
        String name = jsonOfficeHours.getString(JSON_NAME);
        dataManager.addOfficeHoursReservation(day, time, name);
    }

    JsonArray jsonRecitationArray = json.getJsonArray(JSON_RECITATION);
    for (int i = 0; i < jsonRecitationArray.size(); i++) {
        JsonObject jsonRec = jsonRecitationArray.getJsonObject(i);
        String section = jsonRec.getString(JSON_SECTION);
        String instructor = jsonRec.getString(JSON_INSTRUCTOR);
        String dayTime = jsonRec.getString(JSON_DAYTIME);
        String location = jsonRec.getString(JSON_LOCATION);
        String firstTA = jsonRec.getString(JSON_FIRSTTA);
        String secondTA = jsonRec.getString(JSON_SECONDTA);
        recDataManager.addRecitation(section, instructor, dayTime, location, firstTA, secondTA);
    }

    JsonArray jsonScheduleArray = json.getJsonArray(JSON_SCHEDULEITEM);
    for (int i = 0; i < jsonScheduleArray.size(); i++) {
        JsonObject jsonSch = jsonScheduleArray.getJsonObject(i);
        String type = jsonSch.getString(JSON_TYPE);
        int month = jsonSch.getInt(JSON_MONTH);
        int day = jsonSch.getInt(JSON_DAY);
        int year = jsonSch.getInt(JSON_YEAR);
        String time = jsonSch.getString(JSON_TIME);
        String title = jsonSch.getString(JSON_TITLE);
        String topic = jsonSch.getString(JSON_TOPIC);
        String link = jsonSch.getString(JSON_LINK);
        String criteria = jsonSch.getString(JSON_CRITERIA);
        schDataManager.addScheduleItem(type, LocalDate.of(year, month, day), time, title, topic, link,
                criteria);
    }

    JsonArray jsonTeamArray = json.getJsonArray(JSON_TEAMS);
    for (int i = 0; i < jsonTeamArray.size(); i++) {
        JsonObject jsonTeam = jsonTeamArray.getJsonObject(i);
        String name = jsonTeam.getString(JSON_NAME);
        String color = jsonTeam.getString(JSON_COLOR);
        String textColor = jsonTeam.getString(JSON_TEXTCOLOR);
        String link = jsonTeam.getString(JSON_LINK);
        projectDataManager.addTeam(name, color, textColor, link);
    }

    JsonArray jsonStudentArray = json.getJsonArray(JSON_STUDENTS);
    for (int i = 0; i < jsonStudentArray.size(); i++) {
        JsonObject jsonStudent = jsonStudentArray.getJsonObject(i);
        String firstName = jsonStudent.getString(JSON_FIRSTNAME);
        String lastName = jsonStudent.getString(JSON_LASTNAME);
        String team = jsonStudent.getString(JSON_TEAM);
        String role = jsonStudent.getString(JSON_ROLE);
        projectDataManager.addStudent(firstName, lastName, team, role);
    }

    JsonArray jsonTemplateArray = json.getJsonArray(JSON_COURSETEMPLATE);
    courseDataManager.getTemplates().clear();
    for (int i = 0; i < jsonTemplateArray.size(); i++) {
        JsonObject jsonTemplate = jsonTemplateArray.getJsonObject(i);
        boolean use = jsonTemplate.getBoolean(JSON_USE);
        String navbar = jsonTemplate.getString(JSON_NAVBAR);
        String fileName = jsonTemplate.getString(JSON_FILENAME);
        String script = jsonTemplate.getString(JSON_SCRIPT);
        courseDataManager.addTemplate(use, navbar, fileName, script);
    }

    JsonObject courseJson = json.getJsonObject(JSON_COURSE);
    courseDataManager.setNumber(courseJson.getString(JSON_NUMBER));
    courseDataManager.setSemester(courseJson.getString(JSON_SEMESTER));
    courseDataManager.setSubject(courseJson.getString(JSON_SUBJECT));
    courseDataManager.setYear(courseJson.getString(JSON_YEAR));
    courseDataManager.setTitle(courseJson.getString(JSON_TITLE));
    courseDataManager.setInsName(courseJson.getString(JSON_INSTRUCTORNAME));
    courseDataManager.setInsHome(courseJson.getString(JSON_INSTRUCTORHOME));
    courseDataManager.setBannerLink(courseJson.getString(JSON_BANNER));
    courseDataManager.setLeftFooterLink(courseJson.getString(JSON_LEFTFOOTER));
    courseDataManager.setRightFooterLink(courseJson.getString(JSON_RIGHTFOOTER));
    courseDataManager.setTemplateDir(courseJson.getString(JSON_TEMPLATEDIR));
    courseDataManager.setExportDir(courseJson.getString(JSON_EXPORTDIR));
    courseDataManager.setStyleSheet(courseJson.getString(JSON_STYLESHEET));

    workspace.getSubjectCombo().setValue(courseDataManager.getSubject());
    workspace.getNumCombo().setValue(courseDataManager.getNumber());
    workspace.getSemCombo().setValue(courseDataManager.getSemester());
    workspace.getYearCombo().setValue(courseDataManager.getYear());
    workspace.getTitleTextField().setText(courseDataManager.getTitle());
    workspace.getInsNameTextField().setText(courseDataManager.getInsName());
    workspace.getInsHomeTextField().setText(courseDataManager.getInsHome());
    workspace.getStyleSheetCombo().setValue(courseDataManager.getStyleSheet());

    if (!courseDataManager.getBannerLink().isEmpty()) {
        FileInputStream bannerLocation = new FileInputStream(courseJson.getString(JSON_BANNER));
        Image newImg = new Image(bannerLocation);
        workspace.getBannerImage().setImage(newImg);
    } else {
        workspace.getBannerImage().setImage(null);
    }

    if (!courseDataManager.getLeftFooterLink().isEmpty()) {
        FileInputStream leftFooterLocation = new FileInputStream(courseJson.getString(JSON_LEFTFOOTER));
        Image newImg2 = new Image(leftFooterLocation);
        workspace.getLeftFooterImage().setImage(newImg2);
    } else {
        workspace.getLeftFooterImage().setImage(null);
    }

    if (!courseDataManager.getRightFooterLink().isEmpty()) {
        FileInputStream rightFooterLocation = new FileInputStream(courseJson.getString(JSON_RIGHTFOOTER));
        Image newImg3 = new Image(rightFooterLocation);
        workspace.getRightFooterImage().setImage(newImg3);
    } else {
        workspace.getRightFooterImage().setImage(null);
    }
    workspace.getCourseTemplateLocLabel().setText(courseJson.getString(JSON_TEMPLATEDIR));
    workspace.getExportLabel().setText(courseJson.getString(JSON_EXPORTDIR));

}

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}/*from   w  w  w.  jav a 2s  .  c om*/
 * @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

/**
 * Enroll the user with member service/*from  w w w.ja  va 2 s  . c  o m*/
 *
 * @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.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);/* w  w  w  . j  a v a 2  s. co m*/
        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;
}