List of usage examples for javax.json JsonArray getJsonObject
JsonObject getJsonObject(int index);
From source file:com.rhcloud.javaee.movieinfo.business.actor.boundry.ActorResourceIT.java
@Test public void get_all_actors() { Response getResponse = null;/*from w ww .j ava 2s .c om*/ try { getResponse = provider.target().path("/" + ACTORS_PATH).request(APPLICATION_JSON).get(); } finally { System.out.println("Server responded ? " + (getResponse != null)); assumeThat(getResponse, is(notNullValue())); } assertThat(getResponse, is(successful())); assertThat(getResponse.hasEntity(), is(true)); JsonArray payload = getResponse.readEntity(JsonArray.class); assertThat(payload, is(notNullValue())); final int size = payload.size(); assertThat(size, is(not(0))); JsonObject value = payload.getJsonObject(size - 1); assertThat(value, is(notNullValue())); assertThat(value.getInt("id") >= size, is(true)); }
From source file:com.buffalokiwi.aerodrome.jet.orders.OrderRec.java
/** * Turn Jet Json into an OrderRec//from w w w.ja v a2 s . c o m * @param json Jet json * @return object */ public static OrderRec fromJson(final JsonObject json) { Utils.checkNull(json, "json"); final Builder b = new Builder().setMerchantOrderId(json.getString("merchant_order_id", "")) .setReferenceOrderId(json.getString("reference_order_id", "")) .setCustomerReferenceOrderId(json.getString("customer_reference_order_id", "")) .setFulfillmentNode(json.getString("fulfillment_node", "")) .setAltOrderId(json.getString("alt_order_id", "")).setHashEmail(json.getString("hash_email", "")) .setStatus(OrderStatus.fromText(json.getString("status", ""))) .setExceptionState(OrderExceptionState.fromText(json.getString("exception_state", ""))) .setOrderPlacedDate(JetDate.fromJetValueOrNull(json.getString("order_placed_date", ""))) .setOrderTransmissionDate(JetDate.fromJetValueOrNull(json.getString("order_transmission_date", ""))) .setJetRequestDirectedCancel(json.getBoolean("jet_requested_directed_cancel", false)) .setOrderReadyDate(JetDate.fromJetValueOrNull(json.getString("order_ready_date", ""))) .setHasShipments(json.getBoolean("has_shipments", false)) .setOrderAckDate(JetDate.fromJetValueOrNull(json.getString("order_acknowledge_date", ""))) .setAckStatus(AckStatus.fromText(json.getString("acknowledgement_status", ""))); buildOrderDetail(b, json.getJsonObject("order_detail")); buildBuyer(b, json.getJsonObject("buyer")); buildShipTo(b, json.getJsonObject("shipping_to")); buildOrderTotals(b, json.getJsonObject("order_totals")); try { buildOrderItems(b, json.getJsonArray("order_items")); } catch (JetException e) { APILog.error(LOG, e, "Failed to generate order items"); } //..Build the shipments final JsonArray shipments = json.getJsonArray("shipments"); if (shipments != null) { for (int i = 0; i < shipments.size(); i++) { final JsonObject shipment = shipments.getJsonObject(i); if (shipment == null) continue; b.getShipments().add(ShipmentRec.fromJson(shipment)); } } return new OrderRec(b); }
From source file:com.buffalokiwi.aerodrome.jet.orders.OrderRec.java
private static void buildOrderItems(final Builder b, final JsonArray json) throws JetException { if (json == null) return;/*w w w. j a v a 2s. c o m*/ final List<OrderItemRec> l = new ArrayList<>(); for (int i = 0; i < json.size(); i++) { l.add(OrderItemRec.fromJson(json.getJsonObject(i))); } b.setOrderItems(l); }
From source file:org.apache.tamaya.etcd.EtcdAccessor.java
/** * Recursively read out all key/values from this etcd JSON array. * * @param result map with key, values and metadata. * @param node the node to parse./*from w w w .j av a2 s .co m*/ */ private void addNodes(Map<String, String> result, JsonObject node) { if (!node.containsKey("dir") || "false".equals(node.get("dir").toString())) { final String key = node.getString("key").substring(1); result.put(key, node.getString("value")); if (node.containsKey("createdIndex")) { result.put("_" + key + ".createdIndex", String.valueOf(node.getInt("createdIndex"))); } if (node.containsKey("modifiedIndex")) { result.put("_" + key + ".modifiedIndex", String.valueOf(node.getInt("modifiedIndex"))); } if (node.containsKey("expiration")) { result.put("_" + key + ".expiration", String.valueOf(node.getString("expiration"))); } if (node.containsKey("ttl")) { result.put("_" + key + ".ttl", String.valueOf(node.getInt("ttl"))); } result.put("_" + key + ".source", "[etcd]" + serverURL); } else { final JsonArray nodes = node.getJsonArray("nodes"); if (nodes != null) { for (int i = 0; i < nodes.size(); i++) { addNodes(result, nodes.getJsonObject(i)); } } } }
From source file:de.tu_dortmund.ub.data.dswarm.Task.java
/** * get the resource id of the resource for the data model for the the prototype project * * @param dataModelID//ww w.j av a 2 s . co m * @return * @throws Exception */ private String getProjectResourceID(String dataModelID) throws Exception { String resourceID = null; CloseableHttpClient httpclient = HttpClients.createDefault(); try { // Hole Mappings aus dem Projekt mit 'projectID' HttpGet httpGet = new HttpGet(config.getProperty("engine.dswarm.api") + "datamodels/" + dataModelID); CloseableHttpResponse httpResponse = httpclient.execute(httpGet); logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpGet.getRequestLine()); try { int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); switch (statusCode) { case 200: { StringWriter writer = new StringWriter(); IOUtils.copy(httpEntity.getContent(), writer, "UTF-8"); String responseJson = writer.toString(); logger.info("[" + config.getProperty("service.name") + "] responseJson : " + responseJson); JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(responseJson, "UTF-8")); JsonObject jsonObject = jsonReader.readObject(); JsonArray resources = jsonObject.getJsonObject("configuration").getJsonArray("resources"); resourceID = resources.getJsonObject(0).getJsonString("uuid").getString(); logger.info("[" + config.getProperty("service.name") + "] resourceID : " + resourceID); break; } default: { logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : " + httpResponse.getStatusLine().getReasonPhrase()); } } EntityUtils.consume(httpEntity); } finally { httpResponse.close(); } } finally { httpclient.close(); } return resourceID; }
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//w w w .ja v a2s . co 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:httputils.RavelloHttpClient.java
public JsonObject publishBlueprint(String applicationName, int blueprintId, int stopTime, int startupDelay, String preferredCloud, String preferredRegion, boolean startAllVms, boolean costOptimized) throws RavelloException, InterruptedException { JsonObject value = null;//from ww w . ja v a2 s .c o m HttpResponse response = null; try { response = this.getBlueprint(blueprintId); if (!HttpUtil.verifyResponseWithoutConsuming(response)) { EntityUtils.consumeQuietly(response.getEntity()); throw new RavelloException("Failed to get blueprint number " + blueprintId + " error: " + response.getStatusLine().toString()); } JsonObject vmTemp = HttpUtil.convertResponseToJson(response); EntityUtils.consume(response.getEntity()); JsonBuilderFactory factory = Json.createBuilderFactory(null); Iterator<Map.Entry<String, JsonValue>> it = vmTemp.entrySet().iterator(); JsonObjectBuilder builder = factory.createObjectBuilder(); Map.Entry<String, JsonValue> ent; while (it.hasNext()) { ent = it.next(); if (!ent.getKey().equals("id") && !ent.getKey().equals("owner")) { builder.add(ent.getKey(), ent.getValue()); } } builder.add("name", applicationName); value = builder.build(); vmTemp = null; response = this.createApplication(value); this.verifyResponseAndConsume(response, "Failed to create application - error: "); value = HttpUtil.convertResponseToJson(response); EntityUtils.consumeQuietly(response.getEntity()); int appId = value.getInt("id"); if (costOptimized) { value = factory.createObjectBuilder().add("startAllVms", startAllVms).build(); } else { value = factory.createObjectBuilder().add("startAllVms", startAllVms) .add("preferredCloud", preferredCloud).add("preferredRegion", preferredRegion) .add("optimizationLevel", "PERFORMANCE_OPTIMIZED").build(); } response = this.post("/applications/" + appId + "/publish", value); this.verifyResponseAndConsume(response, "Failed to publish application - error: "); value = factory.createObjectBuilder().add("expirationFromNowSeconds", stopTime).build(); response = this.post("/applications/" + appId + "/setExpiration", value); if (!HttpUtil.verifyResponseAndConsume(response)) { throw new RavelloException("Failed to set expiration time for application - error: " + response.getStatusLine().toString() + "\n" + "THIS ERROR MAY CAUSE APPLICATION TO RUN INDEFINITELY - MAKE SURE TO CHECK IT STOPPED"); } if (!startAllVms) { response = this.getApplication(appId); if (!HttpUtil.verifyResponseWithoutConsuming(response)) { EntityUtils.consumeQuietly(response.getEntity()); throw new RavelloException( "Failed to get application status - error: " + response.getStatusLine().toString()); } value = HttpUtil.convertResponseToJson(response); return value; } String state; JsonArray jArr; boolean allStarted; while (true) { allStarted = true; response = this.getApplication(appId); if (!HttpUtil.verifyResponseWithoutConsuming(response)) { EntityUtils.consumeQuietly(response.getEntity()); throw new RavelloException( "Failed to get application status - error: " + response.getStatusLine().toString()); } value = HttpUtil.convertResponseToJson(response); jArr = value.getJsonObject("deployment").getJsonArray("vms"); for (int jt = 0; jt < jArr.size(); jt++) { state = jArr.getJsonObject(jt).getString("state"); allStarted = state.equals("STARTED"); if (state.equals("ERROR")) { throw new RavelloException( "vm" + jArr.getJsonObject(jt).getString("name") + " failed to start"); } if (!allStarted) { break; } } if (allStarted) { break; } else { EntityUtils.consumeQuietly(response.getEntity()); Thread.sleep(20000); } } } catch (ClientProtocolException e) { throw new RavelloException("ClientProtocolException - " + e.getMessage()); } catch (IOException e) { throw new RavelloException("IOException - " + e.getMessage()); } catch (NullPointerException e) { throw new RavelloException("NullPointerException - " + e.getMessage()); } Thread.sleep(startupDelay * 1000); return value; }
From source file:com.buffalokiwi.aerodrome.jet.products.JetAPIProduct.java
/** * Retrieve a set of product shipping exceptions. * @param sku Sku/*from w w w . j ava 2s .c om*/ * @return exceptions * @throws APIException * @throws JetException */ @Override public List<FNodeShippingRec> getShippingExceptions(final String sku) throws APIException, JetException { checkSku(sku); final JsonArray nodes = sendGetProductShippingExceptions(sku).getJsonObject() .getJsonArray("fulfillment_nodes"); final List<FNodeShippingRec> out = new ArrayList<>(); if (nodes == null) return out; for (int i = 0; i < nodes.size(); i++) { out.add(FNodeShippingRec.fromJSON(nodes.getJsonObject(i))); } return out; }
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 . j a v a 2s .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
/** * Enroll the user with member service// w w w .j av a 2 s .co 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; } }