Example usage for com.google.gson JsonArray add

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

Introduction

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

Prototype

public void add(JsonElement element) 

Source Link

Document

Adds the specified element to self.

Usage

From source file:com.blackducksoftware.integration.hub.HubIntRestService.java

License:Apache License

/**
 * Generates a new Hub report for the specified version.
 *
 * @return the Report URL//from  w  ww.j a  v a 2s . c om
 *
 */
public String generateHubReport(final ProjectVersionItem version, final ReportFormatEnum reportFormat,
        final ReportCategoriesEnum[] categories)
        throws IOException, BDRestException, URISyntaxException, UnexpectedHubResponseException {
    if (ReportFormatEnum.UNKNOWN == reportFormat) {
        throw new IllegalArgumentException("Can not generate a report of format : " + reportFormat);
    }

    final JsonObject json = new JsonObject();
    json.addProperty("reportFormat", reportFormat.name());

    if (categories != null) {
        final JsonArray categoriesJson = new JsonArray();
        for (final ReportCategoriesEnum category : categories) {
            categoriesJson.add(category.name());
        }
        json.add("categories", categoriesJson);
    }

    final StringRepresentation stringRep = new StringRepresentation(
            hubServicesFactory.getRestConnection().getGson().toJson(json));
    stringRep.setMediaType(MediaType.APPLICATION_JSON);
    stringRep.setCharacterSet(CharacterSet.UTF_8);
    String location = null;
    try {
        location = hubServicesFactory.getRestConnection().httpPostFromAbsoluteUrl(getVersionReportLink(version),
                stringRep);
    } catch (final ResourceDoesNotExistException ex) {
        throw new BDRestException("There was a problem generating a report for this Version.", ex,
                ex.getResource());
    }

    return location;
}

From source file:com.bosch.osmi.bdp.access.mock.generator.MockDataGenerator.java

License:Open Source License

private void evaluateElements(Collection<?> collection, JsonArray parent)
        throws InvocationTargetException, IllegalAccessException {
    for (Object object : collection) {
        JsonObject jsonObject = new JsonObject();
        parent.add(jsonObject);
        evaluate(object, jsonObject);//from   w w w . j  ava 2s  . c  o m
    }
}

From source file:com.btbb.figadmin.VanillaBans.java

License:Open Source License

public static void exportBans(List<EditBan> bans) throws IOException {
    JsonArray mcbans = new JsonArray();
    JsonArray ipbans = new JsonArray();
    for (EditBan b : bans) {
        String created = "", expires = "";
        if (b.time > 0)
            created = mcDateFormat.format(new Date(b.time));
        if (b.endTime > 0)
            expires = mcDateFormat.format(new Date(b.endTime));
        if (b.type == EditBan.BanType.IPBAN && b.ipAddress != null)
            ipbans.add(new IPBan(b.ipAddress, created, b.admin, expires, b.reason).toJson());
        if (b.type == EditBan.BanType.BAN || (b.type == EditBan.BanType.IPBAN && b.ipAddress == null))
            mcbans.add(new MCBan(b.uuid.toString(), b.name, created, b.admin, expires, b.reason).toJson());
    }// w  ww.j a v  a  2 s  .c  om

    GsonBuilder gsonbuilder = (new GsonBuilder()).setPrettyPrinting();
    Gson b = gsonbuilder.create();
    String s = b.toJson(mcbans);
    BufferedWriter bufferedwriter = null;

    try {
        bufferedwriter = Files.newWriter(new File("banned-players.json"), Charsets.UTF_8);
        bufferedwriter.write(s);
    } finally {
        IOUtils.closeQuietly(bufferedwriter);

        s = b.toJson(ipbans);
    }
    try {
        bufferedwriter = Files.newWriter(new File("banned-ips.json"), Charsets.UTF_8);
        bufferedwriter.write(s);
    } finally {
        IOUtils.closeQuietly(bufferedwriter);
    }
}

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

License:Apache License

/**
 * @param postData/*w  w w  . jav a2s.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")));
        }// w w w .j av a  2 s .c o  m
        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;
    }// ww w.  j  a v  a2 s. c om

    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();//from   w  w w.  ja  va2 s.c  o 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   w ww .j av a  2  s .c  om
        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 {// w ww.j  a  va2  s. com
        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 {// w ww . j  a v a  2 s .  c o m
        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);
}