Example usage for javax.json JsonObject getInt

List of usage examples for javax.json JsonObject getInt

Introduction

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

Prototype

int getInt(String name);

Source Link

Document

A convenience method for getJsonNumber(name).intValue()

Usage

From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Gets the information for the given ElectionID from the bulletin board and returns it as a election object
 * @param electionId//from  w w w.j  a  v  a  2  s  . c o  m
 * the identifier (id) for the desired election
 * @return returns tje election object for a given id
 */
public Election getElectionById(int electionId) {
    Election election = null;
    try {

        URL url = new URL(bulletinBoardUrl + "/elections/" + electionId);

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonObject obj = jsonReader.readObject();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Parameters parameters = this.getParameters();

        //gets the json string and transforms it into a election object

        //translates the header information of the election
        String title = obj.getString("electionTitle");
        LocalDateTime beginDate = LocalDateTime.parse(obj.getString("beginDate"), format);
        LocalDateTime endDate = LocalDateTime.parse(obj.getString("endDate"), format);
        String appVersion = obj.getString("appVersion");
        String coefficientsString = obj.getString("coefficients");
        String h_HatString = obj.getString("electionGenerator");
        List<Voter> voterlist = new ArrayList<Voter>();

        //get th list of voters
        for (JsonObject result : obj.getJsonArray("voters").getValuesAs(JsonObject.class)) {

            String voterEmail = result.getString("email");
            String voterPublicCredential = result.getString("publicCredential");
            String voterAppVersion = result.getString("appVersion");

            Voter voter = new Voter(voterEmail, voterPublicCredential, voterAppVersion);
            voterlist.add(voter);
        }
        //get the votingTopic
        JsonObject electionTopicObj = obj.getJsonObject("votingTopic");

        String topic = electionTopicObj.getString("topic");
        int pick = electionTopicObj.getInt("pick");

        ElectionTopic electionTopic = new ElectionTopic(topic, pick);
        JsonArray optionsArray = electionTopicObj.getJsonArray("options");
        for (int i = 0; i < optionsArray.size(); i++) {
            electionTopic.addOption(optionsArray.getString(i));
        }

        election = new Election(electionId, title, voterlist, parameters, beginDate, endDate, electionTopic,
                appVersion, h_HatString, coefficientsString);

    } catch (IOException x) {
        System.err.println(x);
    }
    return election;
}

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  www.  j a v a  2 s.  c  om*/
 */
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:eu.forgetit.middleware.component.Extractor.java

public void executeImageAnalysis(Exchange exchange) {

    taskStep = "EXTRACTOR_IMAGE_ANALYSIS";

    logger.debug("New message retrieved for " + taskStep);

    JsonObjectBuilder job = Json.createObjectBuilder();

    JsonObject headers = MessageTools.getHeaders(exchange);

    long taskId = Long.parseLong(headers.getString("taskId"));
    scheduler.updateTask(taskId, TaskStatus.RUNNING, taskStep, null);

    JsonObject jsonBody = MessageTools.getBody(exchange);

    if (jsonBody != null) {

        String cmisServerId = jsonBody.getString("cmisServerId");
        JsonArray jsonEntities = jsonBody.getJsonArray("entities");

        job.add("cmisServerId", cmisServerId);
        job.add("entities", jsonEntities);

        for (JsonValue jsonValue : jsonEntities) {

            JsonObject jsonObject = (JsonObject) jsonValue;

            String type = jsonObject.getString("type");

            if (type.equals(Collection.class.getName()))
                continue;

            long pofId = jsonObject.getInt("pofId");

            try {

                String collectorStorageFolder = ConfigurationManager.getConfiguration()
                        .getString("collector.storage.folder");

                Path sipPath = Paths.get(collectorStorageFolder + File.separator + pofId);

                Path metadataPath = Paths.get(sipPath.toString(), "metadata");

                Path contentPath = Paths.get(sipPath.toString(), "content");

                Path imageAnalysisPath = Paths.get(metadataPath.toString(), "imageAnalysis.xml");

                String imagePaths = getImagePaths(contentPath, pofId);

                if (imagePaths != null && !imagePaths.isEmpty()) {

                    String response = service.img_request(imagePaths, "all", null);

                    FileUtils.writeStringToFile(imageAnalysisPath.toFile(), response);

                    logger.debug("Image Analysis completed for " + imagePaths);
                }//from   www . ja  v a  2  s  .c  om

            } catch (IOException e) {

                e.printStackTrace();
            }

        }

        exchange.getOut().setBody(job.build().toString());
        exchange.getOut().setHeaders(exchange.getIn().getHeaders());

    } else {

        scheduler.updateTask(taskId, TaskStatus.FAILED, taskStep, null);

        job.add("Message", "Task " + taskId + " failed");

        scheduler.sendMessage("activemq:queue:ERROR.QUEUE", exchange.getIn().getHeaders(), job.build());
    }

}

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

/**
 * Creates an order, containing the ordered products and related services.
 *
 * @param orderjson The order, represented as a JSON string
 * @throws DataAccessException//from ww w  .j  a v a 2 s  .  com
 */
@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:org.apache.tamaya.etcd.EtcdAccessor.java

/**
 * Ask etcd for a single key, value pair. Hereby the response returned from
 * etcd://from   ww w  .  j av  a 2  s. co  m
 * 
 * <pre>
 * {
 * "action": "get",
 * "node": {
 * "createdIndex": 2,
 * "key": "/message",
 * "modifiedIndex": 2,
 * "value": "Hello world"
 * }
 * }
 * </pre>
 * 
 * is mapped to:
 * 
 * <pre>
 *     key=value
 *     _key.source=[etcd]http://127.0.0.1:4001
 *     _key.createdIndex=12
 *     _key.modifiedIndex=34
 *     _key.ttl=300
 *     _key.expiration=...
 * </pre>
 *
 * @param key the requested key
 * @return the mapped result, including meta-entries.
 */
public Map<String, String> get(String key) {
    final Map<String, String> result = new HashMap<>();
    try {
        final HttpGet httpGet = new HttpGet(serverURL + "/v2/keys/" + key);
        httpGet.setConfig(RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(socketTimeout)
                .setConnectionRequestTimeout(timeout).setConnectTimeout(connectTimeout).build());
        try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                final HttpEntity entity = response.getEntity();
                final JsonReader reader = readerFactory
                        .createReader(new StringReader(EntityUtils.toString(entity)));
                final JsonObject o = reader.readObject();
                final JsonObject node = o.getJsonObject("node");
                if (node.containsKey("value")) {
                    result.put(key, node.getString("value"));
                    result.put("_" + key + ".source", "[etcd]" + serverURL);
                }
                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")));
                }
                EntityUtils.consume(entity);
            } else {
                result.put("_" + key + ".NOT_FOUND.target", "[etcd]" + serverURL);
            }
        }
    } catch (final Exception e) {
        LOG.log(Level.INFO, "Error reading key '" + key + "' from etcd: " + serverURL, e);
        result.put("_ERROR", "Error reading key '" + key + "' from etcd: " + serverURL + ": " + e.toString());
    }
    return result;
}

From source file:org.btc4j.daemon.BtcJsonRpcHttpClient.java

public JsonValue invoke(String method, JsonArray parameters) throws BtcException {
    JsonObjectBuilder builder = Json.createObjectBuilder();
    builder.add(JSONRPC_REALM, JSONRPC_VERSION).add(JSONRPC_METHOD, method);
    if (parameters != null) {
        builder.add(JSONRPC_PARAMS, parameters);
    } else {//from ww w  .  j av  a 2 s  . c o  m
        builder.addNull(JSONRPC_PARAMS);
    }
    String guid = UUID.randomUUID().toString();
    builder.add(JSONRPC_ID, guid);
    JsonObject request = builder.build();
    JsonObject response = jsonObject(jsonValue(jsonInvoke(String.valueOf(request))));
    if (response == null) {
        LOG.severe(BTC4J_DAEMON_DATA_NULL_JSON);
        throw new BtcException(BtcException.BTC4J_ERROR_CODE,
                BtcException.BTC4J_ERROR_MESSAGE + ": " + BTC4J_DAEMON_DATA_NULL_JSON);
    }
    if (!(guid.equals(jsonId(response)))) {
        LOG.severe(BTC4J_DAEMON_DATA_INVALID_ID);
        throw new BtcException(BtcException.BTC4J_ERROR_CODE,
                BtcException.BTC4J_ERROR_MESSAGE + ": " + BTC4J_DAEMON_DATA_INVALID_ID);
    }
    JsonValue error = response.get(JSONRPC_ERROR);
    if ((error != null) && (error.getValueType().equals(ValueType.OBJECT))) {
        JsonObject errorObj = (JsonObject) error;
        int code = errorObj.getInt(JSONRPC_CODE);
        String message = errorObj.getString(JSONRPC_MESSAGE);
        JsonObject data = (JsonObject) errorObj.get(JSONRPC_DATA);
        String dataStr = (data == null) ? "" : (" " + String.valueOf(data));
        LOG.severe("error: " + code + " " + message + dataStr);
        throw new BtcException(code, message + dataStr);
    }
    return response.get(JSONRPC_RESULT);

}

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;/*from   w  ww.  j ava  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: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;
    HttpResponse response = null;/* www .j ava2  s  .c o  m*/

    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:org.hyperledger.fabric_ca.sdk.HFCAClient.java

/**
 * Gets all certificates that the registrar is allowed to see and based on filter parameters that
 * are part of the certificate request.//  w w w. j  a v a2s .c  o  m
 *
 * @param registrar The identity of the registrar (i.e. who is performing the registration).
 * @param req The certificate request that contains filter parameters
 * @return HFCACertificateResponse object
 * @throws HFCACertificateException Failed to process get certificate request
 */
public HFCACertificateResponse getHFCACertificates(User registrar, HFCACertificateRequest req)
        throws HFCACertificateException {
    try {
        logger.debug(format("certificate url: %s, registrar: %s", HFCA_CERTIFICATE, registrar.getName()));

        JsonObject result = httpGet(HFCA_CERTIFICATE, registrar, req.getQueryParameters());

        int statusCode = result.getInt("statusCode");
        Collection<HFCACredential> certs = new ArrayList<>();
        if (statusCode < 400) {
            JsonArray certificates = result.getJsonArray("certs");
            if (certificates != null && !certificates.isEmpty()) {
                for (int i = 0; i < certificates.size(); i++) {
                    String certPEM = certificates.getJsonObject(i).getString("PEM");
                    certs.add(new HFCAX509Certificate(certPEM));
                }
            }
            logger.debug(format("certificate url: %s, registrar: %s done.", HFCA_CERTIFICATE, registrar));
        }
        return new HFCACertificateResponse(statusCode, certs);
    } catch (HTTPException e) {
        String msg = format("[Code: %d] - Error while getting certificates from url '%s': %s",
                e.getStatusCode(), HFCA_CERTIFICATE, e.getMessage());
        HFCACertificateException certificateException = new HFCACertificateException(msg, e);
        logger.error(msg);
        throw certificateException;
    } catch (Exception e) {
        String msg = format("Error while getting certificates from url '%s': %s", HFCA_CERTIFICATE,
                e.getMessage());
        HFCACertificateException certificateException = new HFCACertificateException(msg, e);
        logger.error(msg);
        throw certificateException;
    }
}

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.  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;
    }

}