Example usage for com.google.gson JsonObject getAsJsonArray

List of usage examples for com.google.gson JsonObject getAsJsonArray

Introduction

In this page you can find the example usage for com.google.gson JsonObject getAsJsonArray.

Prototype

public JsonArray getAsJsonArray(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonArray.

Usage

From source file:com.citrus.sdk.payment.MerchantPaymentOption.java

License:Apache License

public static MerchantPaymentOption getMerchantPaymentOptions(JsonObject merchantPaymentOptionsObj,
        Map<String, PGHealth> pgHealthMap) {
    MerchantPaymentOption merchantPaymentOption;
    Set<CardScheme> debitCardSchemeSet = null;
    Set<CardScheme> creditCardSchemeSet = null;
    ArrayList<NetbankingOption> netbankingOptionList = null;

    JsonArray bankArray = merchantPaymentOptionsObj.getAsJsonArray("netBanking");
    JsonArray creditCardArray = merchantPaymentOptionsObj.getAsJsonArray("creditCard");
    JsonArray debitCardArray = merchantPaymentOptionsObj.getAsJsonArray("debitCard");

    int size = -1;
    // Parse credit card scheme
    size = creditCardArray.size();//ww  w  .  j a  v a 2s  .c om
    for (int i = 0; i < size; i++) {
        JsonElement element = creditCardArray.get(i);
        String cardScheme = element.getAsString();

        if (creditCardSchemeSet == null) {
            creditCardSchemeSet = new HashSet<>();
        }

        creditCardSchemeSet.add(getCardScheme(cardScheme));
    }

    // Parse debit card scheme
    size = debitCardArray.size();
    for (int i = 0; i < size; i++) {
        JsonElement element = debitCardArray.get(i);
        String cardScheme = element.getAsString();

        if (debitCardSchemeSet == null) {
            debitCardSchemeSet = new HashSet<>();
        }

        debitCardSchemeSet.add(getCardScheme(cardScheme));
    }

    // Parse netbanking options
    size = bankArray.size();
    for (int i = 0; i < size; i++) {
        JsonElement element = bankArray.get(i);
        if (element.isJsonObject()) {
            JsonObject bankOption = element.getAsJsonObject();

            element = bankOption.get("bankName");
            String bankName = element.getAsString();

            element = bankOption.get("issuerCode");
            String issuerCode = element.getAsString();

            if (!TextUtils.isEmpty(bankName) && !TextUtils.isEmpty(issuerCode)) {
                NetbankingOption netbankingOption = new NetbankingOption(bankName, issuerCode);

                if (pgHealthMap != null) {
                    netbankingOption.setPgHealth(pgHealthMap.get(issuerCode));
                }

                if (netbankingOptionList == null) {
                    netbankingOptionList = new ArrayList<>();
                }

                netbankingOptionList.add(netbankingOption);
            }
        }
    }

    merchantPaymentOption = new MerchantPaymentOption(creditCardSchemeSet, debitCardSchemeSet,
            netbankingOptionList);

    return merchantPaymentOption;
}

From source file:com.claresco.tinman.json.XapiCredentialsJson.java

License:Open Source License

@Override
public XapiCredentials deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
        throws JsonParseException {
    JsonObject theJsonCredentials = JsonUtility.convertJsonElementToJsonObject(arg0);

    // Default values
    XapiPerson thePerson = null;//from   w  ww.j ava 2s  .  c o  m
    boolean theHistorical = false;
    ArrayList<String> theScope = new ArrayList<String>();
    String theExpiry = null;
    ArrayList<String> theActivityIDs = new ArrayList<String>();
    String theRegistration = null;

    // Retrieve actor
    if (JsonUtility.hasElement(theJsonCredentials, ACTORS)) {
        thePerson = JsonUtility.delegateDeserialization(arg2, JsonUtility.get(theJsonCredentials, ACTORS),
                XapiPerson.class);
    }
    // Retrieve historical
    if (JsonUtility.hasElement(theJsonCredentials, HISTORICAL)) {
        theHistorical = JsonUtility.getElementAsBool(theJsonCredentials, HISTORICAL);
    }
    // Retrieve expiry
    if (JsonUtility.hasElement(theJsonCredentials, EXPIRY)) {
        theExpiry = JsonUtility.getElementAsString(theJsonCredentials, EXPIRY);
    }
    //Retrieve registration
    if (JsonUtility.hasElement(theJsonCredentials, REGISTRATION)) {
        theRegistration = JsonUtility.getElementAsString(theJsonCredentials, REGISTRATION);
    }
    //Retrieve scope
    if (JsonUtility.hasElement(theJsonCredentials, SCOPE)) {
        JsonArray theArray = theJsonCredentials.getAsJsonArray(SCOPE);
        for (JsonElement e : theArray) {
            theScope.add(e.getAsString());
        }
    }
    //Retrieve activities
    if (JsonUtility.hasElement(theJsonCredentials, ACTIVITY)) {
        JsonArray theArray = theJsonCredentials.getAsJsonArray(ACTIVITY);
        for (JsonElement e : theArray) {
            theActivityIDs.add(e.getAsString());
        }
    }

    DateTime theReceivedTimestamp = DateTime.now();

    try {
        return new XapiCredentials(theScope, theExpiry, theHistorical, thePerson, theActivityIDs,
                theRegistration, theReceivedTimestamp);
    } catch (XapiBadParamException e) {
        throw new XapiBadRequestException(e.getMessage());
    }

}

From source file:com.cloudant.client.api.Search.java

License:Open Source License

/**
 * Queries a Search Index and returns ungrouped results. In case the query
 * used grouping, an empty list is returned
 *
 * @param <T>      Object type T//from w  ww  .  j a  va2  s  . c  o  m
 * @param query    the Lucene query to be passed to the Search index
 * @param classOfT The class of type T
 * @return The result of the search query as a {@code List<T> }
 */
public <T> List<T> query(String query, Class<T> classOfT) {
    InputStream instream = null;
    List<T> result = new ArrayList<T>();
    try {
        Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8");
        JsonObject json = new JsonParser().parse(reader).getAsJsonObject();
        if (json.has("rows")) {
            if (!includeDocs) {
                log.warn("includeDocs set to false and attempting to retrieve doc. "
                        + "null object will be returned");
            }
            for (JsonElement e : json.getAsJsonArray("rows")) {
                result.add(JsonToObject(db.getGson(), e, "doc", classOfT));
            }
        } else {
            log.warn("No ungrouped result available. Use queryGroups() if grouping set");
        }
        return result;
    } catch (UnsupportedEncodingException e1) {
        // This should never happen as every implementation of the java platform is required
        // to support UTF-8.
        throw new RuntimeException(e1);
    } finally {
        close(instream);
    }
}

From source file:com.cloudant.client.api.Search.java

License:Open Source License

/**
 * Queries a Search Index and returns grouped results in a map where key
 * of the map is the groupName. In case the query didnt use grouping,
 * an empty map is returned//ww w  .j a v a2 s. c  o m
 *
 * @param <T>      Object type T
 * @param query    the Lucene query to be passed to the Search index
 * @param classOfT The class of type T
 * @return The result of the grouped search query as a ordered {@code Map<String,T> }
 */
public <T> Map<String, List<T>> queryGroups(String query, Class<T> classOfT) {
    InputStream instream = null;
    try {
        Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8");
        JsonObject json = new JsonParser().parse(reader).getAsJsonObject();
        Map<String, List<T>> result = new LinkedHashMap<String, List<T>>();
        if (json.has("groups")) {
            for (JsonElement e : json.getAsJsonArray("groups")) {
                String groupName = e.getAsJsonObject().get("by").getAsString();
                List<T> orows = new ArrayList<T>();
                if (!includeDocs) {
                    log.warn("includeDocs set to false and attempting to retrieve doc. "
                            + "null object will be returned");
                }
                for (JsonElement rows : e.getAsJsonObject().getAsJsonArray("rows")) {
                    orows.add(JsonToObject(db.getGson(), rows, "doc", classOfT));
                }
                result.put(groupName, orows);
            } // end for(groups)
        } // end hasgroups
        else {
            log.warn("No grouped results available. Use query() if non grouped query");
        }
        return result;
    } catch (UnsupportedEncodingException e1) {
        // This should never happen as every implementation of the java platform is required
        // to support UTF-8.
        throw new RuntimeException(e1);
    } finally {
        close(instream);
    }
}

From source file:com.cloudant.client.api.Search.java

License:Open Source License

/**
 * Performs a Cloudant Search and returns the result as an {@link SearchResult}
 *
 * @param <T>      Object type T, an instance into which the rows[].doc/group[].rows[].doc
 *                 attribute of the Search result response should be deserialized into. Same
 *                 goes for the rows[].fields/group[].rows[].fields attribute
 * @param query    the Lucene query to be passed to the Search index
 * @param classOfT The class of type T.//from  w  ww  .  j a  v  a  2 s  . com
 * @return The Search result entries
 */
public <T> SearchResult<T> querySearchResult(String query, Class<T> classOfT) {
    InputStream instream = null;
    try {
        Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8");
        JsonObject json = new JsonParser().parse(reader).getAsJsonObject();
        SearchResult<T> sr = new SearchResult<T>();
        sr.setTotalRows(getAsLong(json, "total_rows"));
        sr.setBookmark(getAsString(json, "bookmark"));
        if (json.has("rows")) {
            sr.setRows(getRows(json.getAsJsonArray("rows"), sr, classOfT));
        } else if (json.has("groups")) {
            setGroups(json.getAsJsonArray("groups"), sr, classOfT);
        }

        if (json.has("counts")) {
            sr.setCounts(getFieldsCounts(json.getAsJsonObject("counts").entrySet()));
        }

        if (json.has("ranges")) {
            sr.setRanges(getFieldsCounts(json.getAsJsonObject("ranges").entrySet()));
        }
        return sr;
    } catch (UnsupportedEncodingException e) {
        // This should never happen as every implementation of the java platform is required
        // to support UTF-8.
        throw new RuntimeException(e);
    } finally {
        close(instream);
    }
}

From source file:com.cloudant.client.api.Search.java

License:Open Source License

private <T> void setGroups(JsonArray jsongroups, SearchResult<T> sr, Class<T> classOfT) {
    for (JsonElement e : jsongroups) {
        SearchResult<T>.SearchResultGroups group = sr.new SearchResultGroups();
        JsonObject oe = e.getAsJsonObject();
        group.setBy(oe.get("by").getAsString());
        group.setTotalRows(oe.get("total_rows").getAsLong());
        group.setRows(getRows(oe.getAsJsonArray("rows"), sr, classOfT));
        sr.getGroups().add(group);/* w w  w  .ja v a  2 s .  co  m*/
    }
}

From source file:com.cloudant.client.internal.views.ViewMultipleRequester.java

License:Open Source License

public List<ViewResponse<K, V>> getViewResponses() throws IOException {
    //build the queries array of data to POST
    JsonArray queries = new JsonArray();
    ViewQueryParameters<K, V> viewQueryParameters = null;
    for (ViewQueryParameters<K, V> params : requestParameters) {
        if (viewQueryParameters == null) {
            viewQueryParameters = params;
        }/* w  ww.j  a  v a2  s .c  o  m*/
        queries.add(params.asJson());
    }
    JsonObject queryJson = new JsonObject();
    queryJson.add("queries", queries);
    //construct and execute the POST request
    HttpPost post = new HttpPost(viewQueryParameters.getViewURIBuilder().buildEncoded());
    StringEntity entity = new StringEntity(queryJson.toString(), "UTF-8");
    entity.setContentType("application/json");
    post.setEntity(entity);
    JsonObject jsonResponse = ViewRequester.executeRequestWithResponseAsJson(viewQueryParameters, post);
    //loop the returned array creating the ViewResponse objects
    List<ViewResponse<K, V>> responses = new ArrayList<ViewResponse<K, V>>();
    JsonArray jsonResponses = jsonResponse.getAsJsonArray("results");
    if (jsonResponses != null) {
        int index = 0;
        for (ViewQueryParameters<K, V> params : requestParameters) {
            JsonObject response = jsonResponses.get(index).getAsJsonObject();
            responses.add(new ViewResponseImpl<K, V>(params, response));
            index++;
        }
        return responses;
    } else {
        return Collections.emptyList();
    }
}

From source file:com.cloudant.client.internal.views.ViewResponseImpl.java

License:Open Source License

public ViewResponseImpl(ViewQueryParameters<K, V> initialQueryParameters, JsonObject response,
        PageMetadata<K, V> pageMetadata) {
    this.initialQueryParameters = initialQueryParameters;

    if (pageMetadata == null) {
        previousPageMetadata = null;//from w  w  w  . j  a  v a2  s.c  om
        pageNumber = 1l;
        //from a first page we can only page FORWARD
        pageMetadata = new PageMetadata<K, V>(PageMetadata.PagingDirection.FORWARD);
    } else {
        this.pageNumber = pageMetadata.pageNumber;
    }

    //build the rows from the response
    JsonArray rowsArray = response.getAsJsonArray("rows");
    if (rowsArray != null) {
        for (JsonElement row : rowsArray) {
            rows.add(new RowImpl<K, V>(initialQueryParameters, row));
        }
    }
    int resultRows = rows.size();

    JsonElement totalRowsElement = response.get("total_rows");
    if (totalRowsElement != null) {
        totalRows = totalRowsElement.getAsLong();
    } else {
        //if there is no total rows element, use the rows size
        totalRows = rows.size();
    }

    long rowsPerPage = (initialQueryParameters.getRowsPerPage() != null)
            ? initialQueryParameters.getRowsPerPage().longValue()
            : totalRows;

    //we expect limit = rowsPerPage + 1 results, if we have rowsPerPage or less we are on the
    // last page
    hasNext = resultRows > rowsPerPage;

    if (PageMetadata.PagingDirection.BACKWARD == pageMetadata.direction) {
        //Result needs reversing because to implement backward paging the view reading
        // order is reversed
        Collections.reverse(rows);
    }

    //set previous page links if not the first page
    if (this.pageNumber > 1) {
        hasPrevious = true;
        //set up previous page data, i.e. paging backward
        previousPageMetadata = new PageMetadata<K, V>(PageMetadata.PagingDirection.BACKWARD);
        //decrement the page number for the previous page
        previousPageMetadata.pageNumber = this.pageNumber - 1l;
        //this page's startKey will also be the startKey for the previous page, but with a
        // descending lookup indicated by the paging direction
        previousPageMetadata.pageRequestParameters = initialQueryParameters
                .reversePaginationQueryParameters(rows.get(0).getKey(), rows.get(0).getId());
    } else {
        hasPrevious = false;
    }

    // If we are not on the last page, we need to use the last
    // result as the start key for the next page and therefore
    // we don't return it to the user.
    // If we are on the last page, the final row should be returned
    // to the user.
    int lastIndex = resultRows - 1;
    if (hasNext) {
        //Construct the next page metadata (i.e. paging forward)
        nextPageMetadata = new PageMetadata<K, V>(PageMetadata.PagingDirection.FORWARD);
        //the last element is the start of the next page
        nextPageMetadata.pageRequestParameters = initialQueryParameters
                .forwardPaginationQueryParameters(rows.get(lastIndex).getKey(), rows.get(lastIndex).getId());
        //increment the page number for the next page
        nextPageMetadata.pageNumber = this.pageNumber + 1l;
        //the final element is the first element of the next page, so remove from the list
        rows.remove(lastIndex);
    } else {
        nextPageMetadata = null;
    }

    // calculate paging display info
    long offset = (this.pageNumber - 1) * rowsPerPage;
    resultFrom = offset + 1;
    resultTo = offset + (hasNext ? rowsPerPage : resultRows);
}

From source file:com.comcast.magicwand.spells.appium.dawg.utils.AppiumServerController.java

License:Apache License

/**
 * Checks whether appium server has any running sessions
 * @param url URL of a the server/* ww  w  . ja v a  2 s  .  c o  m*/
 * @return True if there are active sessions; False otherwise
 */
@SuppressWarnings("squid:S1155") // ignore 'Use isEmpty() to check whether the collection is empty or not.' error
public boolean hasRunningSessions(URL url) {
    URL appiumStatusUrl = null;
    try {
        appiumStatusUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), APPIUM_SESSIONS_ENDPOINT);
        JsonObject response = callAppiumEndpoint(appiumStatusUrl);
        JsonArray sessions = response.getAsJsonArray("value");

        return sessions.size() > 0;
    } catch (MalformedURLException e) {
        LOGGER.error(MALFORMED_URL_MSG + appiumStatusUrl, e);
        return false;
    }
}

From source file:com.commonsware.android.ion.QuestionsFragment.java

License:Apache License

@Override
public void onCompleted(Exception e, JsonObject json) {
    if (e != null) {
        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
        Log.e(getClass().getSimpleName(), "Exception from Retrofit request to StackOverflow", e);
    }/*from ww w.  ja v  a2 s  .  c om*/

    if (json != null) {
        JsonArray items = json.getAsJsonArray("items");
        ArrayList<JsonObject> normalized = new ArrayList<JsonObject>();

        for (int i = 0; i < items.size(); i++) {
            normalized.add(items.get(i).getAsJsonObject());
        }

        setListAdapter(new ItemsAdapter(normalized));
    }
}