Example usage for javax.json JsonArray isEmpty

List of usage examples for javax.json JsonArray isEmpty

Introduction

In this page you can find the example usage for javax.json JsonArray isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:fr.ortolang.diffusion.client.cmd.ReindexAllRootCollectionCommand.java

@Override
public void execute(String[] args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;//  w ww  .ja va 2  s.  c  om
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help();
        }

        String[] credentials = getCredentials(cmd);
        String username = credentials[0];
        String password = credentials[1];

        boolean fakeMode = cmd.hasOption("F");

        OrtolangClient client = OrtolangClient.getInstance();
        if (username.length() > 0) {
            client.getAccountManager().setCredentials(username, password);
            client.login(username);
        }
        System.out.println("Connected as user: " + client.connectedProfile());
        System.out.println("Looking for root collection ...");

        // Looking for root collection
        List<String> rootCollectionKeys = new ArrayList<>();

        int offset = 0;
        int limit = 100;
        JsonObject listOfObjects = client.listObjects("core", "collection", "PUBLISHED", offset, limit);
        JsonArray keys = listOfObjects.getJsonArray("entries");

        while (!keys.isEmpty()) {
            for (JsonString objectKey : keys.getValuesAs(JsonString.class)) {
                JsonObject objectRepresentation = client.getObject(objectKey.getString());
                JsonObject objectProperty = objectRepresentation.getJsonObject("object");
                boolean isRoot = objectProperty.getBoolean("root");
                if (isRoot) {
                    rootCollectionKeys.add(objectKey.getString());
                }
            }
            offset += limit;
            listOfObjects = client.listObjects("core", "collection", "PUBLISHED", offset, limit);
            keys = listOfObjects.getJsonArray("entries");
        }

        System.out.println("Reindex keys : " + rootCollectionKeys);
        if (!fakeMode) {
            for (String key : rootCollectionKeys) {
                client.reindex(key);
            }
        }

        client.logout();
        client.close();

    } catch (ParseException e) {
        System.out.println("Failed to parse command line properties " + e.getMessage());
        help();
    } catch (OrtolangClientException | OrtolangClientAccountException e) {
        System.out.println("Unexpected error !!");
        e.printStackTrace();
    }
}

From source file:fr.ortolang.diffusion.client.cmd.ReindexCommand.java

@Override
public void execute(String[] args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;/*from  ww w  . j  av  a2 s .  co m*/
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help();
        }

        String[] credentials = getCredentials(cmd);
        String username = credentials[0];
        String password = credentials[1];

        String type = cmd.getOptionValue("t");
        String service = cmd.getOptionValue("s");
        String status = cmd.getOptionValue("a", "PUBLISHED");
        boolean fakeMode = cmd.hasOption("F");

        if (service != null) {

            OrtolangClient client = OrtolangClient.getInstance();
            if (username.length() > 0) {
                client.getAccountManager().setCredentials(username, password);
                client.login(username);
            }
            System.out.println("Connected as user: " + client.connectedProfile());
            System.out.println("Retrieving for published objects from service " + service + ", with type "
                    + type + " and with status " + status + " ...");

            List<String> objectKeys = new ArrayList<>();

            int offset = 0;
            int limit = 100;
            JsonObject listOfObjects = client.listObjects(service, type, status, offset, limit);
            JsonArray keys = listOfObjects.getJsonArray("entries");

            while (!keys.isEmpty()) {
                objectKeys.addAll(keys.getValuesAs(JsonString.class).stream().map(JsonString::getString)
                        .collect(Collectors.toList()));
                offset += limit;
                listOfObjects = client.listObjects(service, type, status, offset, limit);
                keys = listOfObjects.getJsonArray("entries");
            }
            System.out.println("Reindex keys (" + objectKeys.size() + ") : " + objectKeys);
            if (!fakeMode) {
                for (String key : objectKeys) {
                    client.reindex(key);
                }
                System.out.println("All keys reindexed.");
            }
            client.logout();
            client.close();
        } else {
            help();
        }
    } catch (ParseException e) {
        System.out.println("Failed to parse command line properties " + e.getMessage());
        help();
    } catch (OrtolangClientException | OrtolangClientAccountException e) {
        System.out.println("Unexpected error !!");
        e.printStackTrace();
    }
}

From source file:co.runrightfast.core.application.event.AppEvent.java

private void addTags(final JsonObjectBuilder json) {
    final JsonArray jsonArray = JsonUtils.toJsonArray(tags);
    if (!jsonArray.isEmpty()) {
        json.add("tags", jsonArray);
    }/*  w  w w.j  a  v a 2 s . c  om*/
}

From source file:io.bibleget.HTTPCaller.java

public int isValidBook(String book) {
    try {//ww w.  j av  a  2s. c  om
        JsonArrayBuilder biblebooksBldr = Json.createArrayBuilder();
        BibleGetDB bibleGetDB;
        bibleGetDB = BibleGetDB.getInstance();
        for (int i = 0; i < 73; i++) {
            String usrprop = bibleGetDB.getMetaData("BIBLEBOOKS" + Integer.toString(i));
            //System.out.println("value of BIBLEBOOKS"+Integer.toString(i)+": "+usrprop);                
            JsonReader jsonReader = Json.createReader(new StringReader(usrprop));
            JsonArray jsbooks = jsonReader.readArray();
            biblebooksBldr.add(jsbooks);
        }
        JsonArray biblebooks = biblebooksBldr.build();
        if (!biblebooks.isEmpty()) {
            return idxOf(book, biblebooks);
        }
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(HTTPCaller.class.getName()).log(Level.SEVERE, null, ex);
    }
    return -1;
}

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.//from   w  w w  . ja  va  2 s .  com
 *
 * @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

/**
 * gets all identities that the registrar is allowed to see
 *
 * @param registrar The identity of the registrar (i.e. who is performing the registration).
 * @return the identity that was requested
 * @throws IdentityException        if adding an identity fails.
 * @throws InvalidArgumentException Invalid (null) argument specified
 *///from   w w  w  .j  av  a 2s  .  c o  m

public Collection<HFCAIdentity> getHFCAIdentities(User registrar)
        throws IdentityException, InvalidArgumentException {
    if (registrar == null) {
        throw new InvalidArgumentException("Registrar should be a valid member");
    }

    logger.debug(format("identity  url: %s, registrar: %s", url, registrar.getName()));

    try {
        JsonObject result = httpGet(HFCAIdentity.HFCA_IDENTITY, registrar);

        Collection<HFCAIdentity> allIdentities = new ArrayList<>();

        JsonArray identities = result.getJsonArray("identities");
        if (identities != null && !identities.isEmpty()) {
            for (int i = 0; i < identities.size(); i++) {
                JsonObject identity = identities.getJsonObject(i);
                HFCAIdentity idObj = new HFCAIdentity(identity);
                allIdentities.add(idObj);
            }
        }

        logger.debug(format("identity  url: %s, registrar: %s done.", url, registrar));
        return allIdentities;
    } catch (HTTPException e) {
        String msg = format("[HTTP Status Code: %d] - Error while getting all users from url '%s': %s",
                e.getStatusCode(), url, e.getMessage());
        IdentityException identityException = new IdentityException(msg, e);
        logger.error(msg);
        throw identityException;
    } catch (Exception e) {
        String msg = format("Error while getting all users from url '%s': %s", url, e.getMessage());
        IdentityException identityException = new IdentityException(msg, e);
        logger.error(msg);
        throw identityException;
    }

}

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

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

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

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

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

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

    setUpSSL();

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

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

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

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

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

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

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

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

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

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

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

        Base64.Decoder b64dec = Base64.getDecoder();

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

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

        return new X509Enrollment(keypair, signedPem);

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

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

}

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

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

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

    // If the status code in the response is greater or equal to the status code set in the client object then an exception will
    // be thrown, otherwise, we continue to read the response and return any error code that is less than 'statusCode'
    if (respStatusCode >= statusCode) {
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s. Response: %s", type, url, body, responseBody),
                respStatusCode);//from   w w w .j  a  va2s . c o 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;
}

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

private void generateResponse(JsonObject result) {
    if (result.containsKey("name")) {
        this.name = result.getString("name");
    }//w  w  w.j a va2 s  .  c  o m
    if (result.containsKey("affiliations")) {
        JsonArray affiliations = result.getJsonArray("affiliations");
        if (affiliations != null && !affiliations.isEmpty()) {
            for (int i = 0; i < affiliations.size(); i++) {
                JsonObject aff = affiliations.getJsonObject(i);
                this.childHFCAAffiliations.add(new HFCAAffiliation(aff));
            }
        }
    }
    if (result.containsKey("identities")) {
        JsonArray ids = result.getJsonArray("identities");
        if (ids != null && !ids.isEmpty()) {
            for (int i = 0; i < ids.size(); i++) {
                JsonObject id = ids.getJsonObject(i);
                HFCAIdentity hfcaID = new HFCAIdentity(id);
                this.identities.add(hfcaID);
            }
        }
    }
}

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

/**
 * read retrieves a specific identity/*from w  w  w  . java 2 s  .  com*/
 *
 * @param registrar The identity of the registrar (i.e. who is performing the registration).
 * @return statusCode The HTTP status code in the response
 * @throws IdentityException    if retrieving an identity fails.
 * @throws InvalidArgumentException Invalid (null) argument specified
 */

public int read(User registrar) throws IdentityException, InvalidArgumentException {
    if (registrar == null) {
        throw new InvalidArgumentException("Registrar should be a valid member");
    }

    String readIdURL = "";
    try {
        readIdURL = HFCA_IDENTITY + "/" + enrollmentID;
        logger.debug(format("identity  url: %s, registrar: %s", readIdURL, registrar.getName()));

        JsonObject result = client.httpGet(readIdURL, registrar);

        statusCode = result.getInt("statusCode");
        if (statusCode < 400) {
            type = result.getString("type");
            maxEnrollments = result.getInt("max_enrollments");
            affiliation = result.getString("affiliation");

            JsonArray attributes = result.getJsonArray("attrs");
            Collection<Attribute> attrs = new ArrayList<Attribute>();
            if (attributes != null && !attributes.isEmpty()) {
                for (int i = 0; i < attributes.size(); i++) {
                    JsonObject attribute = attributes.getJsonObject(i);
                    Attribute attr = new Attribute(attribute.getString("name"), attribute.getString("value"),
                            attribute.getBoolean("ecert", false));
                    attrs.add(attr);
                }
            }
            this.attrs = attrs;

            logger.debug(format("identity  url: %s, registrar: %s done.", readIdURL, registrar));
        }
        this.deleted = false;
        return statusCode;
    } catch (HTTPException e) {
        String msg = format("[Code: %d] - Error while getting user '%s' from url '%s': %s", e.getStatusCode(),
                getEnrollmentId(), readIdURL, e.getMessage());
        IdentityException identityException = new IdentityException(msg, e);
        logger.error(msg);
        throw identityException;
    } catch (Exception e) {
        String msg = format("Error while getting user '%s' from url '%s': %s", enrollmentID, readIdURL,
                e.getMessage());
        IdentityException identityException = new IdentityException(msg, e);
        logger.error(msg);
        throw identityException;
    }

}