Example usage for com.google.gson JsonArray JsonArray

List of usage examples for com.google.gson JsonArray JsonArray

Introduction

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

Prototype

public JsonArray() 

Source Link

Document

Creates an empty JsonArray.

Usage

From source file:com.buddycloud.channeldirectory.crawler.node.ActivityHelper.java

License:Apache License

/**
 * @param postData/*  w  ww.  j a v a  2 s  .  co m*/
 * @param dataSource
 * @param configuration 
 * @throws ParseException 
 */
public static void updateActivity(PostData postData, ChannelDirectoryDataSource dataSource,
        Properties properties) {

    String channelJid = postData.getParentSimpleId();

    try {
        if (!isChannelRegistered(channelJid, properties)) {
            return;
        }
    } catch (Exception e1) {
        LOGGER.error("Could not retrieve channel info.", e1);
        return;
    }

    Long published = postData.getPublished().getTime();
    long thisPostPublishedInHours = published / ONE_HOUR;

    ChannelActivity oldChannelActivity = null;
    try {
        oldChannelActivity = retrieveActivityFromDB(channelJid, dataSource);
    } catch (SQLException e) {
        return;
    }

    JsonArray newChannelHistory = new JsonArray();

    long summarizedActivity = 0;

    boolean newActivity = true;

    if (oldChannelActivity != null) {
        newActivity = false;
        JsonArray oldChannelHistory = oldChannelActivity.activity;
        JsonObject firstActivityInWindow = oldChannelHistory.get(0).getAsJsonObject();

        long firstActivityPublishedInHours = firstActivityInWindow.get(PUBLISHED_LABEL).getAsLong();
        int hoursToAppend = (int) (firstActivityPublishedInHours - thisPostPublishedInHours);

        // Too old
        if (hoursToAppend + oldChannelHistory.size() >= DAY_IN_HOURS) {
            return;
        }

        // Crawled already
        if (postData.getPublished().compareTo(oldChannelActivity.earliest) >= 0
                && postData.getPublished().compareTo(oldChannelActivity.updated) <= 0) {
            return;
        }

        for (int i = 0; i < hoursToAppend; i++) {
            JsonObject activityobject = new JsonObject();
            activityobject.addProperty(PUBLISHED_LABEL, thisPostPublishedInHours + i);
            activityobject.addProperty(ACTIVITY_LABEL, 0);
            newChannelHistory.add(activityobject);
        }

        for (int i = 0; i < oldChannelHistory.size(); i++) {
            JsonObject activityObject = oldChannelHistory.get(i).getAsJsonObject();
            summarizedActivity += activityObject.get(ACTIVITY_LABEL).getAsLong();
            newChannelHistory.add(activityObject);
        }

    } else {
        JsonObject activityobject = new JsonObject();
        activityobject.addProperty(PUBLISHED_LABEL, thisPostPublishedInHours);
        activityobject.addProperty(ACTIVITY_LABEL, 0);
        newChannelHistory.add(activityobject);
    }

    // Update first activity
    JsonObject firstActivity = newChannelHistory.get(0).getAsJsonObject();
    firstActivity.addProperty(ACTIVITY_LABEL, firstActivity.get(ACTIVITY_LABEL).getAsLong() + 1);
    summarizedActivity += 1;

    if (newActivity) {
        insertActivityInDB(channelJid, newChannelHistory, summarizedActivity, postData.getPublished(),
                dataSource);
    } else {
        updateActivityInDB(channelJid, newChannelHistory, summarizedActivity, postData.getPublished(),
                dataSource);
    }
}

From source file:com.canoo.dolphin.impl.codec.CreatePresentationModelEncoder.java

License:Apache License

@Override
public JsonObject encode(CreatePresentationModelCommand command) {
    Assert.requireNonNull(command, "command");

    final JsonObject jsonCommand = new JsonObject();
    jsonCommand.addProperty(PM_ID, command.getPmId());
    jsonCommand.addProperty(PM_TYPE, command.getPmType());

    final JsonArray jsonArray = new JsonArray();
    for (final Map<String, Object> attribute : command.getAttributes()) {
        final JsonObject jsonAttribute = new JsonObject();
        jsonAttribute.addProperty(ATTRIBUTE_NAME, String.valueOf(attribute.get("propertyName")));
        jsonAttribute.addProperty(ATTRIBUTE_ID, String.valueOf(attribute.get("id")));
        final Object value = attribute.get("value");
        if (value != null) {
            jsonAttribute.add(ATTRIBUTE_VALUE, encodeValue(attribute.get("value")));
        }/*from w w w.ja  v  a 2s.  c om*/
        jsonArray.add(jsonAttribute);
    }
    jsonCommand.add(PM_ATTRIBUTES, jsonArray);
    jsonCommand.addProperty(ID, "CreatePresentationModel");

    return jsonCommand;
}

From source file:com.canoo.dolphin.server.mbean.beans.ModelJsonSerializer.java

License:Apache License

public static JsonObject toJson(Object dolphinModel) {
    if (dolphinModel == null) {
        return null;
    }/*  www  .  java 2  s  .  c  o m*/

    JsonObject jsonObject = new JsonObject();

    for (Field field : ReflectionHelper.getInheritedDeclaredFields(dolphinModel.getClass())) {
        if (ReflectionHelper.isProperty(field.getType())) {
            Property property = (Property) ReflectionHelper.getPrivileged(field, dolphinModel);
            Object value = property.get();
            if (value == null) {
                jsonObject.add(field.getName(), null);
            } else if (Number.class.isAssignableFrom(value.getClass())
                    || Double.TYPE.isAssignableFrom(value.getClass())
                    || Float.TYPE.isAssignableFrom(value.getClass())
                    || Long.TYPE.isAssignableFrom(value.getClass())
                    || Integer.TYPE.isAssignableFrom(value.getClass())) {
                jsonObject.add(field.getName(), new JsonPrimitive((Number) value));
            } else if (String.class.isAssignableFrom(value.getClass())) {
                jsonObject.add(field.getName(), new JsonPrimitive((String) value));
            } else if (Boolean.class.isAssignableFrom(value.getClass())
                    || Boolean.TYPE.isAssignableFrom(value.getClass())) {
                jsonObject.add(field.getName(), new JsonPrimitive((Boolean) value));
            } else {
                jsonObject.add(field.getName(), toJson(value));
            }
        } else if (ReflectionHelper.isObservableList(field.getType())) {
            ObservableList list = (ObservableList) ReflectionHelper.getPrivileged(field, dolphinModel);
            JsonArray jsonArray = new JsonArray();
            for (Object value : list) {
                if (value == null) {
                    //TODO
                    //jsonArray.add(null);
                } else if (Number.class.isAssignableFrom(value.getClass())
                        || Double.TYPE.isAssignableFrom(value.getClass())
                        || Float.TYPE.isAssignableFrom(value.getClass())
                        || Long.TYPE.isAssignableFrom(value.getClass())
                        || Integer.TYPE.isAssignableFrom(value.getClass())) {
                    jsonArray.add(new JsonPrimitive((Number) value));
                } else if (String.class.isAssignableFrom(value.getClass())) {
                    jsonArray.add(new JsonPrimitive((String) value));
                } else if (Boolean.class.isAssignableFrom(value.getClass())
                        || Boolean.TYPE.isAssignableFrom(value.getClass())) {
                    jsonArray.add(new JsonPrimitive((Boolean) value));
                } else {
                    jsonArray.add(toJson(value));
                }
            }
            jsonObject.add(field.getName(), jsonArray);
        }

    }
    return jsonObject;
}

From source file:com.certus.mobile.actions.getAllProductsAction.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Session s = com.certus.connection.HibernateUtil.getSessionFactory().openSession();
    if (request.getParameter("cartList") != null) {
        String jsonList = request.getParameter("cartList");
        Type type = new TypeToken<List<CartItem>>() {
        }.getType();//w w w  .  j a  v a  2 s . co  m
        List<CartItem> conList = new Gson().fromJson(jsonList, type);
        List<ProductHasSize> myList = getCompleteProductCart(conList, s);

        String element = new Gson().toJson(myList, new TypeToken<List<ProductHasSize>>() {
        }.getType());
        response.getWriter().write(element);

    } else {
        JsonArray array = new JsonArray();
        JsonObject jo = new JsonObject();
        jo.add("error", new JsonPrimitive("Error response"));
        array.add(jo);
        String element = new Gson().toJson(array);
        response.getWriter().write(element);
    }

}

From source file:com.certus.mobile.actions.mobileFindSubCategoriesAction.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Session s = com.certus.connection.HibernateUtil.getSessionFactory().openSession();
    String catName = request.getParameter("catName");
    if (catName != null) {
        Category category = (Category) s.createCriteria(Category.class, "cat")
                .add(Restrictions.eq("cat.catName", catName)).uniqueResult();

        JsonObject jo = new JsonObject();
        JsonArray subCatAry = new JsonArray();
        for (SubCategory sub : category.getSubCategories()) {
            JsonObject subJo = new JsonObject();
            subJo.add("sub_id", new JsonPrimitive(sub.getId()));
            subJo.add("sub_name", new JsonPrimitive(sub.getSubCategoryName()));
            subCatAry.add(subJo);/*from ww w  . java2s  . co  m*/
        }
        jo.add("cat_id", new JsonPrimitive(category.getId()));
        jo.add("cat_name", new JsonPrimitive(category.getCatName()));
        jo.add("sub_categories", subCatAry);
        String element = new Gson().toJson(jo);
        response.getWriter().write(element);
    }
}

From source file:com.certus.mobile.actions.mobileRecentItemsAction.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Session sess = com.certus.connection.HibernateUtil.getSessionFactory().openSession();
    FilterRecentItems im = new FilterRecentItems();
    String path = "";
    try {/*www  . j  a  v a 2  s .  c  om*/
        Context env1 = (Context) new InitialContext().lookup("java:comp/env");
        path += (String) env1.lookup("uploadpathproducts");
    } catch (Exception e) {
        e.printStackTrace();
    }
    JsonArray ary = new JsonArray();
    for (Integer i : im.getRecentItems()) {
        Product pr = (Product) sess.load(Product.class, i);
        if (pr.isAvailability()) {
            JsonObject jo = new JsonObject();
            jo.add("pid", new JsonPrimitive(pr.getId()));
            jo.add("p_name", new JsonPrimitive(pr.getName()));
            jo.add("cat_id", new JsonPrimitive(pr.getSubCategory().getCategory().getId()));
            jo.add("subcat_id", new JsonPrimitive(pr.getSubCategory().getId()));
            jo.add("disc_Per", new JsonPrimitive(pr.getDiscountPrice()));
            jo.add("brand", new JsonPrimitive(pr.getBrand().getBrandName()));
            jo.add("image", new JsonPrimitive(path + pr.getImageMain()));
            ary.add(jo);
            //  Product pl = new Gson().fromJson(jo, Product.class);
        }
    }
    String element = new Gson().toJson(ary);
    sess.close();
    response.getWriter().write(element);

}

From source file:com.certus.mobile.actions.mobileSliderImagesAction.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String sliderImgPath = "";
    try {/*from w  w w  .  j a  v  a 2 s .c om*/
        Context envSlide = (Context) new InitialContext().lookup("java:comp/env");
        sliderImgPath = (String) envSlide.lookup("sliderImgs");
    } catch (NamingException ex) {
        Logger.getLogger(mobileSliderImagesAction.class.getName()).log(Level.SEVERE, null, ex);
    }

    Session sez = com.certus.connection.HibernateUtil.getSessionFactory().openSession();
    List<SliderFacts> sf = sez.createCriteria(SliderFacts.class).list();
    JsonArray array = new JsonArray();
    for (SliderFacts s : sf) {
        JsonObject jo = new JsonObject();
        jo.add("img", new JsonPrimitive(sliderImgPath + s.getImage()));
        array.add(jo);
    }
    String element = new Gson().toJson(array);
    response.getWriter().write(element);
}

From source file:com.certus.mobile.controllers.SingleItemTypeAdapter.java

@Override
public JsonElement serialize(ProductHasSize phs, Type type, JsonSerializationContext jsc) {
    String path = "";
    try {//from   w w  w.  j  av a 2 s .  c  o  m
        Context env1 = (Context) new InitialContext().lookup("java:comp/env");
        path += (String) env1.lookup("uploadpathproducts");
    } catch (Exception e) {
        e.printStackTrace();
    }

    JsonObject jo = new JsonObject();
    jo.add("pid", new JsonPrimitive(phs.getProduct().getId()));
    jo.add("name", new JsonPrimitive(phs.getProduct().getName()));
    jo.add("price", new JsonPrimitive(phs.getPrice()));
    jo.add("disc_per", new JsonPrimitive(phs.getProduct().getDiscountPrice()));
    jo.add("brand", new JsonPrimitive(phs.getProduct().getBrand().getBrandName()));
    jo.add("desc", new JsonPrimitive(phs.getProduct().getDescription()));
    jo.add("img", new JsonPrimitive(path + phs.getProduct().getImageMain()));
    JsonArray sizesAry = new JsonArray();
    JsonArray pricesAry = new JsonArray();
    JsonArray qntyAry = new JsonArray();
    for (ProductHasSize pp : phs.getProduct().getProductHasSizes()) {
        sizesAry.add(new JsonPrimitive(pp.getSize().getSizeName()));
        pricesAry.add(new JsonPrimitive(pp.getPrice()));
        qntyAry.add(new JsonPrimitive(pp.getQnty()));
    }
    jo.add("sizes", sizesAry);
    jo.add("prices", pricesAry);
    jo.add("avl_qnty", qntyAry);
    JsonArray reviewsAry = new JsonArray();
    for (Review r : phs.getProduct().getReviews()) {
        JsonObject reviews = new JsonObject();
        reviews.add("comment", new JsonPrimitive(r.getComment()));
        reviews.add("date", new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd").format(r.getDateComnt())));
        reviews.add("user", new JsonPrimitive(r.getUser().getFName() + " " + r.getUser().getLName()));
        reviewsAry.add(reviews);
    }
    jo.add("reviews", reviewsAry);
    return jo;
}

From source file:com.cinchapi.concourse.importer.LineBasedImporter.java

License:Apache License

/**
 * Import the data contained in {@code file} into {@link Concourse}.
 * <p>// w w  w.  j a  va 2 s .  c  om
 * <strong>Note</strong> that if {@code resolveKey} is specified, an attempt
 * will be made to add the data in from each group into the existing records
 * that are found using {@code resolveKey} and its corresponding value in
 * the group.
 * </p>
 * 
 * @param file
 * @param resolveKey
 * @return a collection of {@link ImportResult} objects that describes the
 *         records created/affected from the import and whether any errors
 *         occurred.
 */
public final Set<Long> importFile(String file, @Nullable String resolveKey) {
    // TODO add option to specify batchSize, which is how many objects to
    // send over the wire in one atomic batch
    List<String> lines = FileOps.readLines(file);
    String[] keys = header();
    JsonArray array = new JsonArray();
    boolean checkedFileFormat = false;
    for (String line : lines) {
        if (!checkedFileFormat) {
            validateFileFormat(line);
            checkedFileFormat = true;
        }
        if (keys == null) {
            keys = parseKeys(line);
            log.info("Parsed keys from header: " + line);
        } else {
            JsonObject object = parseLine(line, keys);
            if (resolveKey != null && object.has(resolveKey)) {
                JsonElement resolveValue = object.get(resolveKey);
                if (!resolveValue.isJsonArray()) {
                    JsonArray temp = new JsonArray();
                    temp.add(resolveValue);
                    resolveValue = temp;
                }
                for (int i = 0; i < resolveValue.getAsJsonArray().size(); ++i) {
                    String value = resolveValue.getAsJsonArray().get(i).toString();
                    Object stored = Convert.stringToJava(value);
                    Set<Long> resolved = concourse.find(resolveKey, Operator.EQUALS, stored);
                    for (long record : resolved) {
                        object = parseLine(line, keys); // this is
                                                        // inefficient, but
                                                        // there is no good
                                                        // way to clone the
                                                        // original object
                        object.addProperty(Constants.JSON_RESERVED_IDENTIFIER_NAME, record);
                        array.add(object);
                    }
                }
            } else {
                array.add(object);
            }
            log.info("Importing {}", line);
        }

    }
    Set<Long> records = importString(array.toString());
    return records;
}

From source file:com.cinchapi.concourse.server.ConcourseServer.java

License:Apache License

/**
 * Do the work to jsonify (dump to json string) each of the {@code records},
 * possibly at {@code timestamp} (if it is greater than 0) using the
 * {@code store}.//w w w  . j  a  v  a2  s  .c  om
 * 
 * @param records
 * @param timestamp
 * @param identifier - will include the primary key for each record in the
 *            dump, if set to {@code true}
 * @param store
 * @return the json string dump
 */
private static String jsonify0(List<Long> records, long timestamp, boolean identifier, Store store) {
    JsonArray array = new JsonArray();
    for (long record : records) {
        Map<String, Set<TObject>> data = timestamp == 0 ? store.select(record)
                : store.select(record, timestamp);
        JsonElement object = DataServices.gson().toJsonTree(data);
        if (identifier) {
            object.getAsJsonObject().addProperty(GlobalState.JSON_RESERVED_IDENTIFIER_NAME, record);
        }
        array.add(object);
    }
    return array.size() == 1 ? array.get(0).toString() : array.toString();
}