Example usage for com.google.gson JsonObject addProperty

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

Introduction

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

Prototype

public void addProperty(String property, Character value) 

Source Link

Document

Convenience method to add a char member.

Usage

From source file:com.arcbees.vcs.util.PolymorphicTypeAdapter.java

License:Apache License

@Override
public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject retValue = new JsonObject();

    String className = src.getClass().getCanonicalName();
    retValue.addProperty(CLASSNAME, className);

    JsonElement jsonElement = context.serialize(src);
    retValue.add(VALUE, jsonElement);/*  ww w . j a  va2 s .co  m*/

    return retValue;
}

From source file:com.arvato.thoroughly.util.RestTemplateUtil.java

License:Open Source License

/**
 * @param url/*w w w.j  a  v a  2 s .com*/
 * @param content
 *           It must be json format data
 * @return Results <br>
 *         code : http status <br>
 *         responseBody : http response body
 */
public JsonObject post(String url, String content) throws TmallAppException {
    LOGGER.trace("Post url:" + url);
    HttpEntity<String> request = new HttpEntity<String>(content, createHeaders());
    ResponseEntity<String> entity = null;
    try {
        entity = restTemplate.postForEntity(url, request, String.class);
    } catch (RestClientException e) {
        LOGGER.error(e.getMessage(), e);
        throw new TmallAppException(ResponseCode.CONNECTION_REFUSED.getCode(),
                "Connection refused:unknown URL content:" + url);
    }

    LOGGER.trace("Post data :" + content);
    LOGGER.trace("Response status:" + entity.getStatusCode().value());
    LOGGER.trace("Response body:" + entity.getBody());

    JsonObject responseObject = new JsonObject();
    if (entity.getStatusCode().value() == 200) {
        String responseBody = entity.getBody();
        JsonParser parser = new JsonParser();
        responseObject = parser.parse(responseBody).getAsJsonObject();
    } else {
        responseObject.addProperty("code", entity.getStatusCode().toString());
        responseObject.addProperty("msg", entity.getBody());
    }
    return responseObject;
}

From source file:com.asakusafw.yaess.tools.Explain.java

License:Apache License

private static JsonObject analyzeBatch(BatchScript script) {
    assert script != null;
    JsonArray jobflows = new JsonArray();
    for (FlowScript flowScript : script.getAllFlows()) {
        JsonObject jobflow = analyzeJobflow(flowScript);
        jobflows.add(jobflow);//from   ww w  .j  a  v a 2s  .  c o  m
    }
    JsonObject batch = new JsonObject();
    batch.addProperty("id", script.getId());
    batch.add("jobflows", jobflows);
    return batch;
}

From source file:com.asakusafw.yaess.tools.Explain.java

License:Apache License

private static JsonObject analyzeJobflow(FlowScript flowScript) {
    assert flowScript != null;
    JsonArray phases = new JsonArray();
    for (Map.Entry<ExecutionPhase, Set<ExecutionScript>> entry : flowScript.getScripts().entrySet()) {
        ExecutionPhase phase = entry.getKey();
        if (entry.getValue().isEmpty() == false || phase == ExecutionPhase.SETUP
                || phase == ExecutionPhase.CLEANUP) {
            phases.add(new JsonPrimitive(phase.getSymbol()));
        }/*from   w  w  w. j av a2  s .  co  m*/
    }
    JsonObject jobflow = new JsonObject();
    jobflow.addProperty("id", flowScript.getId());
    jobflow.add("blockers", toJsonArray(flowScript.getBlockerIds()));
    jobflow.add("phases", phases);
    return jobflow;
}

From source file:com.att.pirates.controller.ProjectController.java

@RequestMapping(value = "/projects/{prismId}/applicationlist", method = RequestMethod.GET)
public @ResponseBody String getApplicationListForPrismId(@PathVariable("prismId") String prismId) {
    List<ProjectApplications> apps = DataService.getProjectApplications(prismId);
    JsonObject jsonResponse = new JsonObject();

    for (ProjectApplications ap : apps) {
        jsonResponse.addProperty(ap.getApplicationName(), ap.getApplicationName());
    }/*  w  w w .  j  av a  2s . c  om*/

    logger.error(msgHeader + jsonResponse.toString());
    return jsonResponse.toString();
}

From source file:com.att.pirates.controller.ProjectController.java

@RequestMapping(value = "/pid/{prismId}/getProjectNotesJson", method = RequestMethod.GET)
public @ResponseBody String getCompanies(@PathVariable("prismId") String prismId, HttpServletRequest request) {
    // logger.error(msgHeader + " getCompanies prismId: " + prismId);
    JQueryDataTableParamModel param = DataTablesParamUtility.getParam(request);

    String sEcho = param.sEcho;//  ww w. ja  va  2s  .  c o m
    int iTotalRecords; // total number of records (unfiltered)
    int iTotalDisplayRecords; //value will be set when code filters companies by keyword
    List<Company> allNotes = GlobalDataController.GetCompanies(prismId);

    iTotalRecords = allNotes.size();
    List<Company> companies = new LinkedList<Company>();
    for (Company c : allNotes) {
        if (c.getName().toLowerCase().contains(param.sSearch.toLowerCase())
                || c.getAddress().toLowerCase().contains(param.sSearch.toLowerCase())
                || c.getTown().toLowerCase().contains(param.sSearch.toLowerCase())
                || c.getDateCreated().toLowerCase().contains(param.sSearch.toLowerCase())) {
            companies.add(c); // add company that matches given search criterion
        }
    }
    iTotalDisplayRecords = companies.size();// number of companies that match search criterion should be returned

    final int sortColumnIndex = param.iSortColumnIndex;
    final int sortDirection = param.sSortDirection.equals("asc") ? -1 : 1;

    Collections.sort(companies, new Comparator<Company>() {
        @Override
        public int compare(Company c1, Company c2) {
            switch (sortColumnIndex) {
            case 0:
                return 0; // sort by id is not allowed
            case 1:
                return c1.getName().compareTo(c2.getName()) * sortDirection;
            case 2:
                return c1.getAddress().compareTo(c2.getAddress()) * sortDirection;
            case 3:
                return c1.getTown().compareTo(c2.getTown()) * sortDirection;
            case 4:
                SimpleDateFormat yFormat = new SimpleDateFormat("MM/dd/yyyy");
                try {
                    Date c1d = yFormat.parse(c1.getDateCreated());
                    Date c2d = yFormat.parse(c2.getDateCreated());

                    return c1d.compareTo(c2d) * sortDirection;
                } catch (ParseException ex) {
                    logger.error(ex.getMessage());
                }
            }
            return 0;
        }
    });

    if (companies.size() < param.iDisplayStart + param.iDisplayLength) {
        companies = companies.subList(param.iDisplayStart, companies.size());
    } else {
        companies = companies.subList(param.iDisplayStart, param.iDisplayStart + param.iDisplayLength);
    }

    try {
        JsonObject jsonResponse = new JsonObject();
        jsonResponse.addProperty("sEcho", sEcho);
        jsonResponse.addProperty("iTotalRecords", iTotalRecords);
        jsonResponse.addProperty("iTotalDisplayRecords", iTotalDisplayRecords);
        Gson gson = new Gson();
        jsonResponse.add("aaData", gson.toJsonTree(companies));

        String tmp = jsonResponse.toString();
        // logger.error(msgHeader + ".. json string: " + tmp);
        return jsonResponse.toString();
    } catch (JsonIOException e) {
        logger.error(msgHeader + e.getMessage());
    }
    return null;
}

From source file:com.avishkar.NewGetFollowersIDs.java

License:Apache License

private static List<Long> getUserFollwers(long twitterUserId)
        throws UnknownHostException, TwitterException, InterruptedException {
    Twitter twitter = new TwitterFactory(AccessTokenUtil.getConfig()).getInstance();
    List<Long> filteredUserListOnFollowerCount = new ArrayList<Long>();
    final Gson gson = new Gson();
    try {//from   w ww .j  a v  a 2s . c o  m

        checkRateLimit("/followers/ids", twitter);
        System.out.println("Listing followers's Follower for ID:" + twitterUserId + System.lineSeparator());
        IDs followerIDs = twitter.getFollowersIDs(twitterUserId, -1);
        JsonObject followerJSON = new JsonObject();

        followerJSON.addProperty("id", twitterUserId);
        followerJSON.addProperty("followers", gson.toJson(followerIDs.getIDs()));
        DBAccess.insert(gson.toJson(followerJSON));

        System.out.println("Current Followers Fetched Size:" + followerIDs.getIDs().length);
        // Filtering for influential user
        if (followerIDs.getIDs().length > 1000) {
            System.out.println("User assumed as Influential");
            return null;
        }
        int from = 0;
        int to = 99;
        int limit = checkRateLimit("/users/lookup", twitter);
        while (from < followerIDs.getIDs().length) {
            if (to > followerIDs.getIDs().length)
                to = followerIDs.getIDs().length - 1;
            if (limit == 0)
                checkRateLimit("/users/lookup", twitter);
            ResponseList<User> followers = twitter
                    .lookupUsers(Arrays.copyOfRange(followerIDs.getIDs(), from, to));
            System.out.println("Recieved User count:" + followers.size());
            for (User user : followers) {
                DBAccess.insertUser(gson.toJson(user));
                if (user.getFollowersCount() < 1000) {
                    // if(user.getStatusesCount()>0 &&
                    // user.getStatus()!=null &&
                    // sevenDaysAgo.after(user.getStatus().getCreatedAt()))
                    filteredUserListOnFollowerCount.add(user.getId());
                    getStatuses(user.getScreenName(), twitter);
                } else
                    System.out.println("User " + user.getScreenName()
                            + " is pruned for Influential or over subscription." + " Follower count:"
                            + user.getFollowersCount() + " Friends Count:" + user.getFriendsCount());
            }

            from += 100;
            to += 100;
            limit--;
        }
    } catch (TwitterException te) {
        if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED
                || te.getStatusCode() == HttpResponseCode.NOT_FOUND) {
            System.out.println("Encountered locked profile. Skipping " + twitterUserId);
            return null;

            // log something here
        }
        te.printStackTrace();
        System.out.println("Failed to get followers' Follower: " + te.getMessage());
        // System.exit(-1);
    }

    return filteredUserListOnFollowerCount;
}

From source file:com.azure.webapi.JsonEntityParser.java

License:Open Source License

/**
 * Changes returned JSon object's id property name to match with type's id property name.
 * @param element/*from  w w w.j  a v  a2s  .c om*/
 * @param propertyName
 */
private static void changeIdPropertyName(JsonObject element, String propertyName) {
    // If the property name is id or if there's no id defined, then return without performing changes
    if (propertyName.equals("id") || propertyName.length() == 0)
        return;

    // Get the current id value and remove the JSon property
    JsonElement idElement = element.get("id");
    if (idElement != null) {
        String value = idElement.getAsString();
        element.remove("id");
        // Create a new id property using the given property name
        element.addProperty(propertyName, value);
    }
}

From source file:com.azure.webapi.MobileServiceTableBase.java

License:Open Source License

/**
 * Updates the JsonObject to have an id property
 * @param json//from w ww.ja va  2s . c o m
 *            the element to evaluate
 */
protected void updateIdProperty(final JsonObject json) throws IllegalArgumentException {
    for (Map.Entry<String, JsonElement> entry : json.entrySet()) {
        String key = entry.getKey();
        if (key.equalsIgnoreCase("id")) {
            JsonElement element = entry.getValue();
            if (isValidTypeId(element)) {
                if (!key.equals("id")) {
                    //force the id name to 'id', no matter the casing 
                    json.remove(key);
                    // Create a new id property using the given property name
                    json.addProperty("id", entry.getValue().getAsNumber());
                }
                return;
            } else {
                throw new IllegalArgumentException("The id must be numeric");
            }
        }
    }
}

From source file:com.babyspace.mamshare.app.activity.ParallaxToolbarListViewActivity.java

License:Apache License

private void queryData() {
    //mSwipeLayout.setRefreshing(true);

    ++queryCount;/*w  w  w . ja  va  2 s  . c o m*/
    /*        footerProgressBar.setVisibility(View.VISIBLE);
            footerText.setText("...");*/

    //   Start0
    if (!isRefreshAdd)
        queryStart = 0;

    JsonObject jsonParameter = new JsonObject();

    jsonParameter.addProperty("num", queryNum);
    jsonParameter.addProperty("start", queryStart);

    //showLoadingProgress();
    if (queryCall != null)
        queryCall.cancel();
    queryCall = OkHttpExecutor.query(UrlConstants.HomeGuidanceList, jsonParameter, HomeGuidanceEvent.class,
            false, this);

}