Example usage for javax.json JsonObject getJsonObject

List of usage examples for javax.json JsonObject getJsonObject

Introduction

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

Prototype

JsonObject getJsonObject(String name);

Source Link

Document

Returns the object value to which the specified name is mapped.

Usage

From source file:org.codice.plugin.version.MavenVersionValidationPlugin.java

public void execute() throws MojoExecutionException, MojoFailureException {
    String jsonContents;/*from  ww  w  .  j av  a 2s .  com*/
    File jsonFile;
    boolean hasRangeChars = false;

    JsonObject jsonObject;

    String baseDir = null;
    try {
        baseDir = project.getBasedir().getCanonicalPath();
    } catch (IOException e) {
        getLog().error("Could not find base directory", e);
    }

    if (baseDir != null) {
        String[] fileList = getListOfPackageJsonFiles(baseDir, FILE_NAME);

        for (String filepath : fileList) {
            jsonFile = Paths.get(baseDir, File.separator, filepath).toFile();

            try {
                jsonContents = FileUtils.readFileToString(jsonFile, (Charset) null);
                JsonReader jsonReader = Json.createReader(new StringReader(jsonContents));
                jsonObject = jsonReader.readObject();

                hasRangeChars |= hasRangeChars(jsonObject.getJsonObject("devDependencies"),
                        jsonFile.toString());
                hasRangeChars |= hasRangeChars(jsonObject.getJsonObject("dependencies"), jsonFile.toString());
            } catch (IOException e) {
                getLog().error("Could not find file", e);
            }
        }
        if (hasRangeChars) {
            throw new MojoFailureException(MOJO_EXCEPTION_MESSAGE);
        }
    }
}

From source file:de.tu_dortmund.ub.hb_ng.SolRDF.java

@Override
public String getAccessRights(String graph, String uri) throws LinkedDataStorageException {

    this.logger.info("getAccessRights: graph=" + graph);
    this.logger.info("getAccessRights: uri=" + uri);

    String accessRights = "";

    if (uri.endsWith("/about")) {

        accessRights = "public";
    } else {//from ww w.j a  v  a 2 s. co m

        // TODO config.properties
        String sparql = "SELECT ?o WHERE { GRAPH <http://data.ub.tu-dortmund.de/graph/"
                + this.config.getProperty("storage.graph.main") + "-public> { <" + uri
                + "/about> <http://purl.org/dc/terms#accessRights> ?o } }";

        try {

            JsonReader jsonReader = Json.createReader(
                    IOUtils.toInputStream(this.sparqlQuery(graph, URLEncoder.encode(sparql, "UTF-8"),
                            "application/sparql-results+json;charset=UTF-8"), "UTF-8"));

            JsonObject jsonObject = jsonReader.readObject();

            JsonArray bindings = jsonObject.getJsonObject("results").getJsonArray("bindings");

            if (bindings.size() == 0) {

                accessRights = "internal";
            } else {

                for (JsonObject binding : bindings.getValuesAs(JsonObject.class)) {

                    accessRights = binding.getJsonObject("o").getJsonString("value").getString();
                }
            }

            this.logger.info("accessRights: " + accessRights);
        } catch (IOException e) {

            this.logger.error("something went wrong", e);
            throw new LinkedDataStorageException(e.getMessage(), e.getCause());
        }
    }

    return accessRights;
}

From source file:de.pangaea.fixo3.CreateFixO3.java

private void addFixedOceanObservatory(JsonObject jo) {
    String label;/*from w  w  w  . j  a va 2s.  c  om*/

    if (jo.containsKey("label"))
        label = jo.getString("label");
    else
        throw new RuntimeException("Label is expected [jo = " + jo + "]");

    IRI observatory = IRI.create(FIXO3.ns.toString() + md5Hex(label));

    m.addIndividual(observatory);
    m.addType(observatory, FixedPointOceanObservatory);
    m.addLabel(observatory, label);

    if (jo.containsKey("title")) {
        m.addTitle(observatory, jo.getString("title"));
    }
    if (jo.containsKey("comment")) {
        m.addComment(observatory, jo.getString("comment"));
    }
    if (jo.containsKey("source")) {
        m.addSource(observatory, IRI.create(jo.getString("source")));
    }
    if (jo.containsKey("location")) {
        JsonObject j = jo.getJsonObject("location");

        String place, coordinates;

        if (j.containsKey("place"))
            place = j.getString("place");
        else
            throw new RuntimeException("Place is expected [j = " + j + "]");

        if (j.containsKey("coordinates"))
            coordinates = j.getString("coordinates");
        else
            throw new RuntimeException("Coordinates are expected [j = " + j + "]");

        String fl = place + " @ " + coordinates;
        String gl = coordinates;

        IRI feature = IRI.create(FIXO3.ns.toString() + md5Hex(fl));
        IRI geometry = IRI.create(FIXO3.ns.toString() + md5Hex(gl));

        m.addIndividual(feature);
        m.addType(feature, Feature);
        m.addLabel(feature, fl);
        m.addObjectAssertion(observatory, location, feature);

        if (coordinates.startsWith("POINT"))
            m.addType(geometry, Point);
        else
            throw new RuntimeException("Coordinates not recognized, expected POINT [j = " + j + "]");

        m.addIndividual(geometry);
        m.addLabel(geometry, gl);
        m.addObjectAssertion(feature, hasGeometry, geometry);
        m.addDataAssertion(geometry, asWKT, coordinates, wktLiteral);
    }

    if (!jo.containsKey("attachedSystems"))
        return;

    JsonArray attachedSystems = jo.getJsonArray("attachedSystems");

    for (JsonObject j : attachedSystems.getValuesAs(JsonObject.class)) {
        String l, t;

        if (j.containsKey("label"))
            l = j.getString("label");
        else
            throw new RuntimeException("Label expected [j = " + j + "]");

        if (j.containsKey("type"))
            t = j.getString("type");
        else
            throw new RuntimeException("Type excepted [j = " + j + "]");

        IRI system = IRI.create(FIXO3.ns.toString() + md5Hex(l));

        m.addIndividual(system);
        m.addType(system, IRI.create(t));
        m.addLabel(system, l);
        m.addObjectAssertion(observatory, attachedSystem, system);
    }
}

From source file:ufrj.pedroeusebio.biblioteca_pdf.Controller.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
    String json = "";
    if (br != null) {
        json = br.readLine();/*from ww w.ja  v  a 2  s  .  c  o m*/
    }
    JsonReader reader = Json.createReader(new StringReader(json));
    JsonObject JSONObject = reader.readObject();
    reader.close();

    JsonObject innerObj;
    RespostaDTO dto = new RespostaDTO();
    BibliotecaDAO Biblioteca = new BibliotecaDAO();
    ArrayList<JSONArray> answer = new ArrayList<>();
    Biblioteca.setStrQuery("");
    String Query = "";
    try {
        if (!JSONObject.getString("patrimonio").isEmpty()) {
            System.out.println("entrei !!");
            dto.setPatrimonio(JSONObject.getString("patrimonio"));
            if (Biblioteca.getStrQuery().isEmpty()) {
                Query += "SELECT patrimonio FROM public.dadoscatalogo WHERE patrimonio='" + dto.getPatrimonio()
                        + "' ";
                Biblioteca.setStrQuery(Query);
            } else {
                Query += Biblioteca.QueryGenatator("patrimonio", dto.getPatrimonio(), null, "dadoscatalogo");
            }
        }
    } catch (Exception e) {
    }
    try {
        if (!JSONObject.getJsonObject("titulo").isEmpty()) {
            innerObj = JSONObject.getJsonObject("titulo");
            dto.setTitulo(innerObj.getString("texto"));
            if (Biblioteca.getStrQuery().isEmpty()) {
                Query += "SELECT patrimonio FROM public.dadoscatalogo WHERE titulo='" + dto.getTitulo() + "' ";
                Biblioteca.setStrQuery(Query);
            } else {
                Query += Biblioteca.QueryGenatator("titulo", dto.getTitulo(), innerObj.getString("mode"),
                        "dadoscatalogo");
            }
            ;
        }
    } catch (Exception e) {
    }
    try {
        if (!JSONObject.getJsonObject("autoria").isEmpty()) {
            innerObj = JSONObject.getJsonObject("autoria");
            dto.setAutoria(innerObj.getString("texto"));
            if (Biblioteca.getStrQuery().isEmpty()) {
                Query += "SELECT patrimonio FROM public.dadoscatalogo WHERE autoria='" + dto.getAutoria()
                        + "' ";
                Biblioteca.setStrQuery(Query);
            } else {
                Query += Biblioteca.QueryGenatator("autoria", dto.getAutoria(), innerObj.getString("mode"),
                        "dadoscatalogo");
            }
        }
    } catch (Exception e) {
    }
    try {
        if (!JSONObject.getJsonObject("veiculo").isEmpty()) {
            innerObj = JSONObject.getJsonObject("veiculo");
            dto.setVeiculo(innerObj.getString("texto"));
            if (Biblioteca.getStrQuery().isEmpty()) {
                Query += "SELECT patrimonio FROM public.dadoscatalogo WHERE veiculo='" + dto.getVeiculo()
                        + "' ";
                Biblioteca.setStrQuery(Query);
            } else {
                Query += Biblioteca.QueryGenatator("veiculo", dto.getAutoria(), innerObj.getString("mode"),
                        "dadoscatalogo");
            }
        }
    } catch (Exception e) {
    }
    try {
        if (!JSONObject.getJsonObject("datapublicacao").isEmpty()) {
            innerObj = JSONObject.getJsonObject("datapublicacao");
            dto.setData(innerObj.getString("texto"));
            if (Biblioteca.getStrQuery().isEmpty()) {
                Query += "SELECT patrimonio FROM public.dadoscatalogo WHERE data_publicacao='" + dto.getData()
                        + "' ";
                Biblioteca.setStrQuery(Query);
            } else {
                Query += Biblioteca.QueryGenatator("datapublicacao", dto.getData(), innerObj.getString("mode"),
                        "dadoscatalogo");
            }
        }
    } catch (Exception e) {
    }
    try {
        if (!JSONObject.getJsonObject("palchave").isEmpty()) {
            innerObj = JSONObject.getJsonObject("palchave");
            String[] parts = innerObj.getString("texto").replaceAll("\\s", "").split(";");
            for (int i = 0; i < parts.length; i++) {
                if (Biblioteca.getStrQuery().isEmpty()) {
                    Query += "SELECT patrimonio FROM public.palavras_chave WHERE palchave='" + parts[i] + "' ";
                    Biblioteca.setStrQuery(Query);
                } else if (!Biblioteca.getStrQuery().isEmpty()) {
                    Query += Biblioteca.QueryGenatator("palchave", parts[i], innerObj.getString("mode"),
                            "palavras_chave");
                }
            }
        }
    } catch (Exception e) {
    }
    try {
        if (JSONObject.getJsonObject("palchave").isEmpty()
                && JSONObject.getJsonObject("datapublicacao").isEmpty()
                && JSONObject.getJsonObject("veiculo").isEmpty()
                && JSONObject.getJsonObject("autoria").isEmpty() && JSONObject.getJsonObject("titulo").isEmpty()
                && JSONObject.getJsonObject("patrimonio").isEmpty()) {
            Query = "SELECT patrimonio FROM public.dadoscatalogo;";

        }
    } catch (Exception e) {

    }

    answer.addAll(Biblioteca.ExecuteQuery(Query));

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.print(answer);
    out.flush();

}

From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.exac.EXACResourceImplementation.java

@Override
public Result runProcess(SecureSession session, IRCTProcess process, Result result)
        throws ResourceInterfaceException {
    HttpClient client = createClient(session);
    try {//  w  w  w .  ja va 2 s .  c o  m
        ResultSet resultSetField = (ResultSet) process.getObjectValues().get("RESULTSET");
        String chromosomeColumn = process.getStringValues().get("CHROMOSOME");
        String positionColumn = process.getStringValues().get("POSITION");
        String referenceColumn = process.getStringValues().get("REFERENCE");
        String variantColumn = process.getStringValues().get("VARIANT");

        ResultSet rs = createResultSet(result, resultSetField);

        // Move to First
        resultSetField.first();
        // Loop through all rows and get the data needed for the bulk
        // request
        resultSetField.beforeFirst();
        JsonArrayBuilder jsonArray = Json.createArrayBuilder();
        while (resultSetField.next()) {

            String queryString = resultSetField.getString(chromosomeColumn);
            queryString += "-" + resultSetField.getString(positionColumn);
            queryString += "-" + resultSetField.getString(referenceColumn);
            queryString += "-" + resultSetField.getString(variantColumn);

            // Run the Bulk request(s)
            jsonArray.add(queryString);

        }

        HttpPost post = new HttpPost(this.resourceURL + "/rest/bulk/variant");

        // Set Header
        try {
            post.setEntity(new StringEntity(jsonArray.build().toString()));
            HttpResponse response = client.execute(post);
            JsonReader reader = Json.createReader(response.getEntity().getContent());
            JsonObject responseObject = reader.readObject();

            //Merge the results back into the result set
            resultSetField.beforeFirst();
            rs.first();
            while (resultSetField.next()) {
                rs.appendRow();
                //Copy the original data over
                for (Column column : resultSetField.getColumns()) {
                    rs.updateString(column.getName(), resultSetField.getString(column.getName()));
                }
                //Add the new data if it exists
                String queryString = resultSetField.getString(chromosomeColumn);
                queryString += "-" + resultSetField.getString(positionColumn);
                queryString += "-" + resultSetField.getString(referenceColumn);
                queryString += "-" + resultSetField.getString(variantColumn);

                if (responseObject.containsKey(queryString)) {
                    JsonObject varObject = responseObject.getJsonObject(queryString).getJsonObject("variant");
                    for (String newColumnString : this.exacColumns) {
                        String value = getValue(varObject, newColumnString);
                        if (value != null) {
                            rs.updateString(newColumnString, value.toString());
                        }
                    }
                }
            }

            result.setData(rs);
            result.setResultStatus(ResultStatus.COMPLETE);
        } catch (IOException | PersistableException e) {
            e.printStackTrace();
            result.setResultStatus(ResultStatus.ERROR);
            result.setMessage(e.getMessage());
        }

    } catch (ResultSetException e) {
        e.printStackTrace();
        result.setResultStatus(ResultStatus.ERROR);
        result.setMessage(e.getMessage());
    }

    return result;
}

From source file:com.buffalokiwi.aerodrome.jet.orders.OrderRec.java

/**
 * Turn Jet Json into an OrderRec//w w w  .  jav a  2  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: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.  co  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.hyperledger.fabric_ca.sdk.HFCAClient.java

/**
 * Return information on the Fabric Certificate Authority.
 * No credentials are needed for this API.
 *
 * @return {@link HFCAInfo}//from   ww w .  jav a 2s.co 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

/**
 * Enroll the user with member service/*  ww w .  j av a 2s  .  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

/** idemixEnroll returns an Identity Mixer Enrollment, which supports anonymity and unlinkability
 *
 * @param enrollment a x509 enrollment credential
 * @return IdemixEnrollment/*from ww w . jav  a 2s. c  om*/
 * @throws EnrollmentException
 * @throws InvalidArgumentException
 */
public Enrollment idemixEnroll(Enrollment enrollment, String mspID)
        throws EnrollmentException, InvalidArgumentException {
    if (cryptoSuite == null) {
        throw new InvalidArgumentException("Crypto primitives not set");
    }

    if (enrollment == null) {
        throw new InvalidArgumentException("enrollment is missing");
    }

    if (Utils.isNullOrEmpty(mspID)) {
        throw new InvalidArgumentException("mspID cannot be null or empty");
    }

    if (enrollment instanceof IdemixEnrollment) {
        throw new InvalidArgumentException("enrollment type must be x509");
    }
    final RAND rng = IdemixUtils.getRand();
    try {
        setUpSSL();

        // Get nonce
        IdemixEnrollmentRequest idemixEnrollReq = new IdemixEnrollmentRequest();
        String body = idemixEnrollReq.toJson();
        JsonObject result = httpPost(url + HFCA_IDEMIXCRED, body, enrollment);
        if (result == null) {
            throw new EnrollmentException("No response received for idemix enrollment request");
        }
        String nonceString = result.getString("Nonce");
        if (Utils.isNullOrEmpty(nonceString)) {
            throw new InvalidArgumentException(
                    "fabric-ca-server did not return a nonce in the response from " + HFCA_IDEMIXCRED);
        }
        byte[] nonceBytes = Base64.getDecoder().decode(nonceString.getBytes());
        BIG nonce = BIG.fromBytes(nonceBytes);

        // Get issuer public key and revocation key from the cainfo section of response
        JsonObject info = result.getJsonObject("CAInfo");
        if (info == null) {
            throw new Exception(
                    "fabric-ca-server did not return 'cainfo' in the response from " + HFCA_IDEMIXCRED);
        }
        IdemixIssuerPublicKey ipk = getIssuerPublicKey(info.getString("IssuerPublicKey"));
        PublicKey rpk = getRevocationPublicKey(info.getString("IssuerRevocationPublicKey"));

        // Create and send idemix credential request
        BIG sk = new BIG(IdemixUtils.randModOrder(rng));
        IdemixCredRequest idemixCredRequest = new IdemixCredRequest(sk, nonce, ipk);
        idemixEnrollReq.setIdemixCredReq(idemixCredRequest);
        body = idemixEnrollReq.toJson();
        result = httpPost(url + HFCA_IDEMIXCRED, body, enrollment);
        if (result == null) {
            throw new EnrollmentException("No response received for idemix enrollment request");
        }

        // Deserialize idemix credential
        String credential = result.getString("Credential");
        if (Utils.isNullOrEmpty(credential)) {
            throw new InvalidArgumentException(
                    "fabric-ca-server did not return a 'credential' in the response from " + HFCA_IDEMIXCRED);
        }
        byte[] credBytes = Base64.getDecoder().decode(credential.getBytes(UTF_8));
        Idemix.Credential credProto = Idemix.Credential.parseFrom(credBytes);
        IdemixCredential cred = new IdemixCredential(credProto);

        // Deserialize idemix cri (Credential Revocation Information)
        String criStr = result.getString("CRI");
        if (Utils.isNullOrEmpty(criStr)) {
            throw new InvalidArgumentException(
                    "fabric-ca-server did not return a 'CRI' in the response from " + HFCA_IDEMIXCRED);
        }
        byte[] criBytes = Base64.getDecoder().decode(criStr.getBytes(UTF_8));
        Idemix.CredentialRevocationInformation cri = Idemix.CredentialRevocationInformation.parseFrom(criBytes);

        JsonObject attrs = result.getJsonObject("Attrs");
        if (attrs == null) {
            throw new EnrollmentException(
                    "fabric-ca-server did not return 'attrs' in the response from " + HFCA_IDEMIXCRED);
        }
        String ou = attrs.getString("OU");
        if (Utils.isNullOrEmpty(ou)) {
            throw new InvalidArgumentException(
                    "fabric-ca-server did not return a 'ou' attribute in the response from " + HFCA_IDEMIXCRED);
        }
        int role = attrs.getInt("Role"); // Encoded IdemixRole from Fabric-Ca

        // Return the idemix enrollment
        return new IdemixEnrollment(ipk, rpk, mspID, sk, cred, cri, ou, role);

    } catch (EnrollmentException ee) {
        logger.error(ee.getMessage(), ee);
        throw ee;
    } catch (Exception e) {
        EnrollmentException ee = new EnrollmentException("Failed to get Idemix credential", e);
        logger.error(e.getMessage(), e);
        throw ee;
    }
}