Example usage for com.google.gson JsonElement getAsJsonArray

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

Introduction

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

Prototype

public JsonArray getAsJsonArray() 

Source Link

Document

convenience method to get this element as a JsonArray .

Usage

From source file:com.contentful.java.cda.ResourceTypeAdapter.java

License:Apache License

/**
 * Sets the base fields for a resource./*from  w w w  .  j  a  v  a  2  s.c  o  m*/
 * This will set the list fields based on the target's type, depending on whether
 * it is an instance of the {@code ResourceWithMap} class or the {@code ResourceWithList},
 * different results will be provided.
 *
 * This method will also set the map of system attributes for the resource.
 *
 * @param target Target {@link CDAResource} object to set fields for.
 * @param sys JsonObject representing the system attributes of the resource in JSON form.
 * @param jsonElement JsonElement representing the resource in JSON form.
 * @param context De-serialization context.
 * @throws JsonParseException on failure.
 */
@SuppressWarnings("unchecked")
private void setBaseFields(CDAResource target, JsonObject sys, JsonElement jsonElement,
        JsonDeserializationContext context) {
    CDASpace space = spaceWrapper.get();

    // System attributes
    Map<String, Object> sysMap = context.deserialize(sys, Map.class);
    if (sysMap.containsKey("space")) {
        sysMap.put("space", space);
    }
    target.setSys(sysMap);

    // Fields
    JsonElement fields = jsonElement.getAsJsonObject().get("fields");
    if (target instanceof ResourceWithMap) {
        ResourceWithMap res = (ResourceWithMap) target;
        target.setLocale(space.getDefaultLocale());
        res.setRawFields(context.<Map<String, Object>>deserialize(fields.getAsJsonObject(), Map.class));
        res.getLocalizedFieldsMap().put(space.getDefaultLocale(), res.getRawFields());
    } else if (target instanceof ResourceWithList) {
        ResourceWithList<Object> res = (ResourceWithList<Object>) target;
        res.setFields(context.<List<Object>>deserialize(fields.getAsJsonArray(), List.class));
    }
}

From source file:com.continusec.client.ObjectHash.java

License:Apache License

/**
 * Calculate the objecthash for a Gson JsonElement object, with a custom redaction prefix string.
 * @param o the Gson JsonElement to calculated the objecthash for.
 * @param r the string to use as a prefix to indicate that a string should be treated as a redacted subobject.
 * @return the objecthash for this object
 * @throws ContinusecException upon error
 *///from   ww w . jav a2 s  .  co m
public static final byte[] objectHashWithRedaction(JsonElement o, String r) throws ContinusecException {
    if (o == null || o.isJsonNull()) {
        return hashNull();
    } else if (o.isJsonArray()) {
        return hashArray(o.getAsJsonArray(), r);
    } else if (o.isJsonObject()) {
        return hashObject(o.getAsJsonObject(), r);
    } else if (o.isJsonPrimitive()) {
        JsonPrimitive p = o.getAsJsonPrimitive();
        if (p.isBoolean()) {
            return hashBoolean(p.getAsBoolean());
        } else if (p.isNumber()) {
            return hashDouble(p.getAsDouble());
        } else if (p.isString()) {
            return hashString(p.getAsString(), r);
        } else {
            throw new InvalidObjectException();
        }
    } else {
        throw new InvalidObjectException();
    }
}

From source file:com.continusec.client.ObjectHash.java

License:Apache License

private static final JsonElement shedObject(JsonObject o, String r) throws ContinusecException {
    JsonObject rv = new JsonObject();
    for (Map.Entry<String, JsonElement> e : o.entrySet()) {
        JsonElement v = e.getValue();
        if (v.isJsonArray()) {
            JsonArray a = v.getAsJsonArray();
            if (a.size() == 2) {
                rv.add(e.getKey(), shedRedactable(a.get(1), r));
            } else {
                throw new InvalidObjectException();
            }//  w w w . j  ava 2 s . c  om
        } else if (v.isJsonPrimitive()) {
            JsonPrimitive p = v.getAsJsonPrimitive();
            if (p.isString()) {
                if (p.getAsString().startsWith(r)) {
                    // all good, but we shed it.
                } else {
                    throw new InvalidObjectException();
                }
            } else {
                throw new InvalidObjectException();
            }
        } else {
            throw new InvalidObjectException();
        }
    }
    return rv;
}

From source file:com.continusec.client.ObjectHash.java

License:Apache License

/**
 * Strip away object values that are marked as redacted, and switch nonce-tuples back to normal values.
 * This is useful when an object has been stored with Redactable nonces added, but now it has been retrieved
 * and normal processing needs to be performed on it.
 * @param o the Gson JsonElement that contains the redacted elements and nonce-tuples.
 * @param r the redaction prefix that indicates if a string represents a redacted sub-object.
 * @return a new cleaned up JsonElement//from   w ww  .ja va 2 s. c  o m
 * @throws ContinusecException upon error
 */
public static final JsonElement shedRedactable(JsonElement o, String r) throws ContinusecException {
    if (o == null) {
        return null;
    } else if (o.isJsonArray()) {
        return shedArray(o.getAsJsonArray(), r);
    } else if (o.isJsonObject()) {
        return shedObject(o.getAsJsonObject(), r);
    } else {
        return o;
    }
}

From source file:com.continuuity.loom.macro.Expander.java

License:Apache License

/**
 * Given a JSON tree, find the element specified by the path (or the root if path is null). In that subtree,
 * recursively traverse all elements, and expand all String typed right hand side values.  If a macro cannot be
 * expanded due to the cluster object missing certain data, that macro will be left unexpanded.
 *
 * @param json A JSON tree/*from   www  .  j a  v a  2s .c o  m*/
 * @param path the path to expand under
 * @param cluster the cluster to use for expanding macros.
 * @param nodes the cluster nodes to use for expanding macros.
 * @param node the cluster node to use for expanding macros.
 * @return a new JSON tree if any expansion took place, and the original JSON tree otherwise.
 * @throws SyntaxException if a macro expression is ill-formed.
 * @throws IncompleteClusterException if the cluster does not have the meta data to expand all macros.
 */
public static JsonElement expand(JsonElement json, @Nullable java.util.List<String> path, Cluster cluster,
        Set<Node> nodes, Node node) throws SyntaxException, IncompleteClusterException {

    // if path is given,
    if (path != null && !path.isEmpty()) {
        String first = path.get(0);
        if (json.isJsonObject()) {
            JsonObject object = json.getAsJsonObject();
            JsonElement json1 = object.get(first);
            if (json1 != null) {
                JsonElement expanded = expand(json1, path.subList(1, path.size()), cluster, nodes, node);
                if (expanded != json1) {
                    // only construct new json object if actual expansion happened
                    JsonObject object1 = new JsonObject();
                    for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
                        object1.add(entry.getKey(), entry.getKey().equals(first) ? expanded : entry.getValue());
                    }
                    return object1;
                }
            }
        }
        // path was given, but either no corresponding subtree was found or no expansion happened...
        return json;
    }

    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            String value = primitive.getAsString();
            String expanded = expand(value, cluster, nodes, node);
            if (!expanded.equals(value)) {
                // only return a new json element if actual expansion happened
                return new JsonPrimitive(expanded);
            }
        }
    }

    if (json.isJsonArray()) {
        JsonArray array = json.getAsJsonArray();
        JsonArray array1 = new JsonArray();
        boolean expansionHappened = false;
        for (JsonElement element : array) {
            JsonElement expanded = expand(element, path, cluster, nodes, node);
            if (expanded != element) {
                expansionHappened = true;
            }
            array1.add(expanded);
        }
        // only return a new json array if actual expansion happened
        if (expansionHappened) {
            return array1;
        }
    }

    if (json.isJsonObject()) {
        JsonObject object = json.getAsJsonObject();
        JsonObject object1 = new JsonObject();
        boolean expansionHappened = false;
        for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
            JsonElement expanded = expand(entry.getValue(), path, cluster, nodes, node);
            if (expanded != entry.getValue()) {
                expansionHappened = true;
            }
            object1.add(entry.getKey(), expand(entry.getValue(), path, cluster, nodes, node));
        }
        if (expansionHappened) {
            return object1;
        }
    }

    return json;
}

From source file:com.controller.partner.PartnerManagePromotion.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    session = request.getSession(false);// don't create if it doesn't exist
    if (session != null && !session.isNew()) {
        try {//from   w w w . j a  va 2s. com
            if (conn == null || conn.isClosed()) {
                conn = (Connection) DBUtil.getConnection();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        type = request.getParameter("type");
        branch_id = request.getParameter("branch_id");
        applicableToAll = request.getParameter("applicable_to");
        promo_code = request.getParameter("promo_code");
        appToStatus = request.getParameterValues("appToHidden");
        partner_id = request.getParameter("branch_owner");
        site_id = (String) session.getAttribute("siteId");
        String[] include1 = request.getParameterValues("includeSelect1");
        String[] include2 = request.getParameterValues("includeSelect2");
        String[] exclude1 = request.getParameterValues("excludeSelect1");
        String[] exclude2 = request.getParameterValues("excludeSelect2");
        if ("facility_types_include".equals(type)) {
            promotionData = partnerManagePromotionDAO.getFacilitiesInclude(branch_id, conn);
            Gson gson = new Gson();
            JsonElement element = gson.toJsonTree(promotionData, new TypeToken<List<FacilityMaster>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if ("facility_types_exclude".equals(type)) {
            promotionData = partnerManagePromotionDAO.getFacilitiesExclude(branch_id, conn);
            Gson gson = new Gson();
            JsonElement element = gson.toJsonTree(promotionData, new TypeToken<List<FacilityMaster>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if ("profile_category_include".equals(type)) {
            profileCategory = partnerManagePromotionDAO.getProfileCategoryFacilitiesInclude(conn);
            Gson gson = new Gson();
            JsonElement element = gson.toJsonTree(profileCategory, new TypeToken<List<LookupMaster>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if ("profile_category_exclude".equals(type)) {
            profileCategory = partnerManagePromotionDAO.getProfileCategoryFacilitiesExclude(conn);
            Gson gson = new Gson();
            JsonElement element = gson.toJsonTree(profileCategory, new TypeToken<List<LookupMaster>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if ("gender_include".equals(type)) {
            genderData = partnerManagePromotionDAO.getGenderFacilitiesInclude(conn);
            Gson gson = new Gson();
            JsonElement element = gson.toJsonTree(genderData, new TypeToken<List<LookupMaster>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if ("gender_exclude".equals(type)) {
            genderData = partnerManagePromotionDAO.getGenderFacilitiesExclude(conn);
            Gson gson = new Gson();
            JsonElement element = gson.toJsonTree(genderData, new TypeToken<List<LookupMaster>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if ("check_promo_code_available".equals(type)) {
            promotion = partnerManagePromotionDAO.getPromoCodeDetails(promo_code, branch_id, conn);
            Gson gson = new Gson();
            JsonElement element = gson.toJsonTree(promotion, new TypeToken<List<PromotionMaster>>() {
            }.getType());
            JsonArray jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
        } else if ("submit_promotion".equals(type)) {
            System.out.println("Submit promotion");
            PromotionMaster pm = new PromotionMaster();
            pm.setPromo_code(request.getParameter("promo_code"));
            pm.setPromo_name(request.getParameter("promo_name"));
            pm.setBranch_id(branch_id);
            pm.setPromo_type(request.getParameter("promo_type"));
            pm.setCreated_date(request.getParameter("fdate"));
            pm.setTransaction_limit_type(request.getParameter("transaction_limit_type"));
            pm.setStatus(request.getParameter("status"));
            pm.setLimit_value(Integer.parseInt(request.getParameter("limit_value")));
            pm.setApproval_status(request.getParameter("approval_status"));
            pm.setEffective_start_date(request.getParameter("effective_from"));
            pm.setEffective_end_date(request.getParameter("effective_to"));
            pm.setApplicable_to_all(request.getParameter("applicable_to"));
            pm.setUsed_value(request.getParameter("accrued_value"));
            pm.setDiscount_type(request.getParameter("discount_type"));
            pm.setDiscount_value(Integer.parseInt(request.getParameter("discount_value")));
            pm.setConditions(request.getParameter("condition"));
            pm.setPartner_id(partner_id);
            pm.setSite_id(site_id);
            promo_id = promoDao.addPromotionData(pm, conn);
            if ("No".equals(applicableToAll)) {
                for (int i = 0; i <= 1; i++) {
                    enableRule = request.getParameter("enableRule" + i);
                    if (enableRule == null) {
                        enableRuleArr[i] = "Off";
                    } else {
                        enableRuleArr[i] = "On";
                    }
                    applicableType[i] = request.getParameter("applicable_type" + i);
                    applicableTo[i] = request.getParameter("applicable_to" + i);
                }
                count = promoDao.addPromoDetailsRulesData(promo_id, branch_id, enableRuleArr, applicableType,
                        applicableTo, appToStatus, include1, include2, exclude1, exclude2, reference_id,
                        reference_name, conn);
                if (count > 0) {
                    request.setAttribute("displayVal", "Promotion Registered !!");
                    request.setAttribute("condition", "Success");
                    request.getRequestDispatcher("/WEB-INF/common-jsp/successErrorLanding.jsp").forward(request,
                            response);
                } else {
                    request.setAttribute("displayVal", "Something wrong.Please try again !!");
                    request.setAttribute("condition", "Failure");
                    request.getRequestDispatcher("/WEB-INF/common-jsp/successErrorLanding.jsp").forward(request,
                            response);
                }
            } else {
                if (count > 0) {
                    request.setAttribute("displayVal", "Promotion Registered !!");
                    request.setAttribute("condition", "Success");
                    request.getRequestDispatcher("/WEB-INF/common-jsp/successErrorLanding.jsp").forward(request,
                            response);
                } else {
                    request.setAttribute("displayVal", "Something wrong.Please try again !!");
                    request.setAttribute("condition", "Failure");
                    request.getRequestDispatcher("/WEB-INF/common-jsp/successErrorLanding.jsp").forward(request,
                            response);
                }
            }
        }
        // Close connection
        try {
            if (conn != null || !conn.isClosed()) {
                DBUtil.closeConnection(conn);
                System.out.println(conn + " Connection closed");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        request.setAttribute("errorDisplay", "");
        request.setAttribute("error", "Session timed out,Please login again !!");
        request.getRequestDispatcher("/login.jsp").include(request, response);
    }
}

From source file:com.controller.Recipe.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w w  w . j av a2 s . c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        HttpSession session = request.getSession();

        RecipeBean recipeBean = new RecipeBean();
        RecipeDAO recipeDAO = new RecipeDAO();

        ArrayList recipeDetails = new ArrayList();
        Gson gson = new Gson();
        JsonElement element;
        JsonArray jsonArray;

        String name = request.getParameter("name");
        String meal[] = request.getParameterValues("meal");
        String diet = request.getParameter("diet");
        String cusine = request.getParameter("cusine");
        String people = request.getParameter("people");
        String calories = request.getParameter("calories");
        String time = request.getParameter("time");
        String steps = request.getParameter("steps");
        String ingList = request.getParameter("ingredients");
        UserDetailsBean userDetailsBean = (UserDetailsBean) session.getAttribute("userDetails");
        String userId = userDetailsBean.getUserId();

        String task = request.getParameter("task");
        System.out.println(calories);
        System.out.println(name);
        System.out.println(cusine);
        System.out.println(diet);
        System.out.println(time);
        switch (task) {

        case "add":
            String ingredients[] = request.getParameter("ingredients").split(",");
            recipeBean.setCalories(calories);
            recipeBean.setCusine(cusine);
            recipeBean.setDiet(diet);
            recipeBean.setIngredients(ingredients);
            recipeBean.setMeal(meal);
            recipeBean.setName(name);
            recipeBean.setPeople(people);
            recipeBean.setSteps(steps);
            recipeBean.setTime(time);
            recipeBean.setUserId(userId);

            String recipeId = recipeDAO.addRecipeDetails(recipeBean);
            session.setAttribute("recipeId", recipeId);

            //add type of meal information
            recipeDAO.addMealInfo(meal, recipeId);

            //add ingredients
            recipeDAO.addIngredients(ingredients, recipeId);
            break;

        case "single":

            recipeId = request.getParameter("recipeId");
            recipeDetails = recipeDAO.getSingleRecipe(recipeId);
            request.setAttribute("recipeDetails", recipeDetails);
            request.getRequestDispatcher("singleRecipe.jsp").forward(request, response);

            break;

        case "allRecipes":
            recipeDetails = recipeDAO.getAllRecipes();

            element = gson.toJsonTree(recipeDetails, new TypeToken<List<RecipeBean>>() {
            }.getType());
            jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
            break;

        case "byName":
            name = request.getParameter("recipeName");
            recipeDetails = recipeDAO.getRecipeByName(name);

            element = gson.toJsonTree(recipeDetails, new TypeToken<List<RecipeBean>>() {
            }.getType());

            jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
            break;

        case "advanceSearch":
            recipeBean.setCalories(calories);
            recipeBean.setCusine(cusine);
            recipeBean.setDiet(diet);
            recipeBean.setName(name);
            recipeBean.setTime(time);

            if (!"".equals(cusine)) {
                System.out.println("changes1");
                recipeDetails = recipeDAO.getRecipeByCusine(recipeBean, recipeDetails);
            }
            if (!"".equals(diet)) {
                System.out.println("changes2");
                recipeDetails = recipeDAO.getRecipeByDiet(recipeBean, recipeDetails);
            }
            if (!"".equals(name)) {
                System.out.println("changes3");
                recipeDetails = recipeDAO.getRecipeByName(name, recipeDetails);
            }
            if (!"".equals(calories)) {
                System.out.println("changes4");
                recipeDetails = recipeDAO.getRecipeByCalories(recipeBean, recipeDetails);
            }
            if (!"".equals(time)) {
                System.out.println("changes5");
                recipeDetails = recipeDAO.getRecipeByTime(recipeBean, recipeDetails);
            }

            System.out.println("ingprev " + ingList);
            if (ingList != null) {
                System.out.println("ing");
                String ingredientsList[] = ingList.split(",");
                recipeDetails = recipeDAO.getRecipeByIngredients(ingredientsList, recipeDetails);
            }

            element = gson.toJsonTree(recipeDetails, new TypeToken<List<RecipeBean>>() {
            }.getType());
            jsonArray = element.getAsJsonArray();
            response.setContentType("application/json");
            response.getWriter().print(jsonArray);
            break;
        }

    }
}

From source file:com.couchbase.cbadmin.assets.NodeGroupList.java

License:Open Source License

public NodeGroupList(JsonObject json) throws RestApiException {
    JsonElement e = json.get("uri");
    if (e == null || e.isJsonPrimitive() == false) {
        throw new RestApiException("Expected modification URI", json);
    }//from w  ww .  j a va2s.  c  om
    assignmentUri = URI.create(e.getAsString());

    e = json.get("groups");
    if (e == null || e.isJsonArray() == false) {
        throw new RestApiException("Expected 'groups'", e);
    }

    groups = new ArrayList<NodeGroup>();
    for (JsonElement groupElem : e.getAsJsonArray()) {
        if (groupElem.isJsonObject() == false) {
            throw new RestApiException("Expected object for group", groupElem);
        }
        groups.add(new NodeGroup(groupElem.getAsJsonObject()));
    }
}

From source file:com.couchbase.cbadmin.client.ConnectionInfo.java

License:Open Source License

public ConnectionInfo(JsonObject poolsJson) throws RestApiException {
    JsonElement eTmp;
    eTmp = poolsJson.get("implementationVersion");
    if (eTmp == null) {
        throw new RestApiException("implementationVersion missing", poolsJson);
    }//from  ww  w.  ja va 2s . co  m
    clusterVersion = eTmp.getAsString();

    eTmp = poolsJson.get("pools");
    if (eTmp == null || eTmp.isJsonArray() == false) {
        throw new RestApiException("pools missing", poolsJson);
    }

    if (eTmp.getAsJsonArray().size() > 0) {
        clusterActive = true;
        eTmp = eTmp.getAsJsonArray().get(0);

        if (eTmp.isJsonObject() == false) {
            throw new RestApiException("Expected object in pools entry", eTmp);
        }

        eTmp = eTmp.getAsJsonObject().get("uri");
        if (eTmp == null || eTmp.isJsonPrimitive() == false) {
            throw new RestApiException("uri missing or malformed", eTmp);
        }

        clusterId = eTmp.getAsString();

    } else {
        clusterActive = false;
        clusterId = null;
    }

    eTmp = poolsJson.get("isAdminCreds");
    adminCreds = eTmp != null && eTmp.getAsBoolean();
}

From source file:com.couchbase.cbadmin.client.CouchbaseAdmin.java

License:Open Source License

@Override
public Map<String, Bucket> getBuckets() throws RestApiException {
    JsonElement e;
    Map<String, Bucket> ret = new HashMap<String, Bucket>();

    try {//from  w ww . ja v a 2  s.  c om
        e = getJson(P_BUCKETS);
    } catch (IOException ex) {
        throw new RestApiException(ex);
    }

    JsonArray arr;
    if (!e.isJsonArray()) {
        throw new RestApiException("Expected JsonObject", e);
    }

    arr = e.getAsJsonArray();
    for (int i = 0; i < arr.size(); i++) {
        JsonElement tmpElem = arr.get(i);
        if (!tmpElem.isJsonObject()) {
            throw new RestApiException("Expected JsonObject", tmpElem);
        }

        Bucket bucket = new Bucket(tmpElem.getAsJsonObject());
        ret.put(bucket.getName(), bucket);
    }
    return ret;
}