Example usage for com.google.gson JsonObject toString

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:com.confighub.core.store.diff.TokenDiffTracker.java

License:Open Source License

@PreUpdate
public void preUpdate(APersisted obj) {
    OriginalToken o = (OriginalToken) getIfRecorded(obj);
    if (null == o || !(obj instanceof Token))
        return;//from  w  ww. j a va2s  . co m

    Token token = (Token) obj;
    JsonObject json = new JsonObject();

    if (!Utils.equal(token.getName(), o.name))
        json.addProperty("name", o.name);

    if (token.isActive() != o.active)
        json.addProperty("active", o.active);

    if (!Utils.equal(token.getExpires(), o.expires))
        json.addProperty("expires", null == o.expires ? "" : o.expires.toString());

    if (token.isForceKeyPushEnabled() != o.forceKeyPushEnabled)
        json.addProperty("forceKeyPushEnabled", o.forceKeyPushEnabled);

    boolean hadSps = null != o.securityProfiles && o.securityProfiles.size() > 0;
    boolean hasSps = null != token.getSecurityProfiles() && token.getSecurityProfiles().size() > 0;

    if (!hadSps && !hasSps)
        ;
    else if (hadSps && !hasSps) {
        JsonArray sps = new JsonArray();
        o.securityProfiles.forEach(sp -> sps.add(sp));
        json.add("sps", sps);
    } else if (!hadSps && hasSps) {
        json.add("sps", new JsonArray());
    } else {
        Set<String> current = new HashSet<>();
        token.getSecurityProfiles().forEach(sp -> current.add(sp.getName()));
        current.removeAll(o.securityProfiles);

        if (current.size() > 0) {
            JsonArray sps = new JsonArray();
            o.securityProfiles.forEach(sp -> sps.add(sp));
            json.add("sps", sps);
        } else {
            Set<String> clone = new HashSet<>();
            o.securityProfiles.forEach(sp -> clone.add(new String(sp)));

            current.clear();
            token.getSecurityProfiles().forEach(sp -> clone.add(sp.getName()));

            clone.removeAll(current);
            if (clone.size() > 0) {
                JsonArray sps = new JsonArray();
                o.securityProfiles.forEach(sp -> sps.add(sp));
                json.add("sps", sps);
            }
        }
    }

    if (!Utils.equal(token.getTeamRules(), o.teamRules))
        json.addProperty("rulesTeam", null == o.teamRules ? "" : o.teamRules.getName());

    if (!Utils.equal(token.getManagingTeam(), o.managingTeam))
        json.addProperty("managingTeam", null == o.managingTeam ? "" : o.managingTeam.getName());

    if (!Utils.equal(token.getUser(), o.user))
        json.addProperty("user", null == o.user ? "" : o.user.getUsername());

    if (!Utils.equal(token.getManagedBy(), o.managedBy))
        json.addProperty("managedBy", o.managedBy.name());

    markForNotification();
    token.diffJson = json.toString();
}

From source file:com.confighub.core.store.RevisionEntry.java

License:Open Source License

public void set(RevisionEntityContext rec) {
    this.userId = rec.getUserId();
    this.appId = rec.getAppId();
    this.repositoryId = rec.getRepositoryId();
    this.changeComment = rec.getChangeComment();
    this.notify = rec.isNotify();

    Set<APersisted.ClassName> recType = rec.getType();
    JsonObject json = new JsonObject();

    if (rec.isContextResize()) {
        rec.getRevTypes().forEach((id, revType) -> {
            if (this.repositoryId.equals(id)) {
                json.addProperty(id.toString(), revType.name());
            }/*from w w  w  .j a v  a 2s . c o m*/
        });
        this.commitGroup = CommitGroup.RepoSettings;
    } else {
        Set<String> searchKeys = rec.getSearchKey();
        if (null != searchKeys && searchKeys.size() > 0) {
            this.searchKey = "|" + Utils.join(searchKeys, "|") + "|";
        }

        rec.getRevTypes().forEach((id, revType) -> json.addProperty(id.toString(), revType.name()));

        if (null != recType) {
            switch (recType.iterator().next()) {
            case Repository:
                this.commitGroup = CommitGroup.RepoSettings;
                break;

            case ContextItem:
            case Property:
            case PropertyKey:
                // if its already a file change - leave it at that.
                if (CommitGroup.Files.equals(this.commitGroup)) {
                    break;
                }

                this.commitGroup = CommitGroup.Config;
                break;

            case RepoFile:
            case AbsoluteFilePath:
                this.commitGroup = CommitGroup.Files;
                break;

            case SecurityProfile:
                this.commitGroup = CommitGroup.Security;
                break;

            case Token:
                this.commitGroup = CommitGroup.Tokens;
                break;

            case Tag:
                this.commitGroup = CommitGroup.Tags;
                break;

            case Team:
            case AccessRule:
                this.commitGroup = CommitGroup.Teams;
                break;
            }
        }
    }

    this.type = Utils.join(recType, ",");
    this.revType = json.toString();
}

From source file:com.continuuity.loom.common.queue.Element.java

License:Apache License

@Override
public String toString() {
    JsonObject object = new JsonObject();
    object.addProperty("id", id);
    object.addProperty("value", value);
    return object.toString();
}

From source file:com.continuuity.loom.provisioner.mock.MockProvisionerService.java

License:Apache License

private void heartbeat() throws Exception {
    JsonObject heartbeat = new JsonObject();
    heartbeat.add("usage", GSON.toJsonTree(provisionerTenantStore.getUsage()));
    heartbeatRequest.setEntity(new StringEntity(GSON.toJson(heartbeat)));
    try {//w w  w.j  a  va2 s .c  om
        LOG.debug("sending heartbeat {}...", heartbeat.toString());
        CloseableHttpResponse response = httpClient.execute(heartbeatRequest);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode / 100 == 2) {
                LOG.debug("heartbeat successfull.");
            } else if (response.getStatusLine().getStatusCode() == 404) {
                // if we try and heartbeat and get back a 404, register again.
                LOG.debug("heartbeat returned a 404, will try to register.");
                register();
            } else {
                LOG.info("heartbeat for provisioner {} failed. Got a {} status with message:\n {}.", id,
                        getResponseString(response), statusCode);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        LOG.error("Exception while sending heartbeat.", e);
    } finally {
        heartbeatRequest.reset();
    }
}

From source file:com.continuuity.loom.provisioner.mock.MockWorker.java

License:Apache License

private JsonObject takeTask() {
    try {/*from w w  w  .  j  a v a 2s.c  om*/
        JsonObject body = new JsonObject();
        body.addProperty("provisionerId", provisionerId);
        body.addProperty("workerId", provisionerId + "." + workerId);
        body.addProperty("tenantId", tenantId);
        takeRequest.setEntity(new StringEntity(body.toString()));

        Reader reader = null;
        CloseableHttpResponse response = httpClient.execute(takeRequest, httpContext);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode / 100 != 2) {
                LOG.error("Error taking task. Got status code {} with message:\n{}", statusCode,
                        getResponseString(response));
                return null;
            } else if (statusCode != 200) {
                return null;
            }
            reader = new InputStreamReader(response.getEntity().getContent(), Charsets.UTF_8);
            JsonObject task = GSON.fromJson(reader, JsonObject.class);
            LOG.debug("task details: {}", task.toString());
            return task;
        } finally {
            if (reader != null) {
                reader.close();
            }
            response.close();
        }
    } catch (Exception e) {
        LOG.error("Exception making take request.", e);
        return null;
    } finally {
        takeRequest.reset();
    }
}

From source file:com.controller.dialog.ShowNewAnnDetail.java

/**
 * /*from  www  .j a  v  a2 s . co m*/
 *
 * @return
 * @throws Exception
 */
@RequestMapping(params = "query", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public String doQuery(HttpServletRequest req) throws Exception {
    JsonArray jsonArray = new JsonArray();
    String queryStr = req.getParameter("queryStr").trim();
    JsonObject rtnJson = new JsonObject();
    try {
        //?Service
        AnnouncementHeaderService announcementHeaderService = (AnnouncementHeaderService) ServiceFactory
                .getService("announcementHeaderService");
        List<AnnouncementHeader> list;
        if (queryStr.isEmpty()) {
            list = announcementHeaderService.findAll();
        } else {
            AnnouncementHeader annHeader = new AnnouncementHeader();
            annHeader.setAnnouncementDesc(queryStr);
            list = announcementHeaderService.query(annHeader);
        }
        if (list != null && !list.isEmpty()) {
            list.stream().map((AnnouncementHeader annObj) -> {
                JsonObject jsonObj = new JsonObject();
                jsonObj.addProperty("AnnouncementDesc", annObj.getAnnouncementDesc()
                        + "<input type='hidden' id='hidAnnID' value='" + annObj.getAnnID() + "' />");
                jsonObj.addProperty("BegTime", String.valueOf(annObj.getBegTime()));
                return jsonObj;
            }).forEach(jsonArray::add);
        }
        if (jsonArray.size() == 0) {
            rtnJson.addProperty("fail", "??");
        } else {
            rtnJson.addProperty("success", jsonArray.toString());
        }
    } catch (Exception e) {
        throw e;
    }
    return rtnJson.toString();
}

From source file:com.controller.rest.FileREST.java

/**
 * AP?//w w  w.j a va2 s  .c  o m
 *
 * @param session
 * @param req
 * @param ataType
 * @return
 * @throws java.lang.Exception
 */
@RequestMapping(value = "/file/isAPTempFileExists", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public String isAPTempFileExists(HttpSession session, HttpServletRequest req,
        @RequestParam("ataType") String ataType) throws Exception {
    JsonObject jsonObj = new JsonObject();
    //?
    UserHeader LOGININFO = ((UserHeader) session.getAttribute("LoginInfo"));
    AtaType AtaTypeEnum;
    //?AtaType euum
    try {
        AtaTypeEnum = AtaType.valueOf(ataType);
    } catch (Exception e) {
        throw new MyException("");
    }
    try {
        //AP
        Path tempPath = new CreateFilePath().GetAPTempPath(
                req.getSession().getServletContext().getRealPath("/resources/temp"), LOGININFO, AtaTypeEnum, "",
                "");
        //?
        File books = new File(tempPath.toString());
        if (books.listFiles().length == 0) {
            throw new MyException("?");
        }
        jsonObj.addProperty("success", "OK");
    } catch (Exception e) {
        throw e;
    }
    return jsonObj.toString();
}

From source file:com.controller.system.DepManager.java

/**
 * /*w w w  .ja va  2s . c  o m*/
 *
 * @param session
 * @param req
 * @param rps
 * @param depHeader
 * @return
 * @throws Exception
 */
@RequestMapping(params = "save", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public String doSave(HttpSession session, HttpServletRequest req, HttpServletResponse rps,
        @ModelAttribute DepHeader depHeader) throws Exception {
    int userID = ((UserHeader) session.getAttribute("LoginInfo")).getUserID();
    //?
    Timestamp sysTime = new Timestamp(System.currentTimeMillis());

    JsonObject jsonObj = new JsonObject();
    try {
        //?Service
        DepHeaderService depHeaderService = (DepHeaderService) ServiceFactory.getService("depHeaderService");
        depHeader.setModTime(sysTime);
        depHeader.setModUserID(userID);
        depHeader.setCreTime(sysTime);
        if (depHeaderService.addDepHeader(depHeader)) {
            jsonObj.addProperty("success", "?");
        } else {
            jsonObj.addProperty("fail", "");
        }
    } catch (Exception e) {
        throw e;
    }
    return jsonObj.toString();
}

From source file:com.controller.system.DepManager.java

/**
 * /*from  w  w w  .  ja  va 2  s  .com*/
 *
 * @param session
 * @param req
 * @param rps
 * @param depHeader
 * @return
 * @throws Exception
 */
@RequestMapping(params = "update", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public String doUpdate(HttpSession session, HttpServletRequest req, HttpServletResponse rps,
        @ModelAttribute DepHeader depHeader) throws Exception {
    int userID = ((UserHeader) session.getAttribute("LoginInfo")).getUserID();
    //?
    Timestamp sysTime = new Timestamp(System.currentTimeMillis());
    JsonObject jsonObj = new JsonObject();
    try {
        //?Service
        DepHeaderService depHeaderService = (DepHeaderService) ServiceFactory.getService("depHeaderService");
        DepHeader depObj = new DepHeader();
        depObj.setDepID(depHeader.getDepID());
        depObj = depHeaderService.findByOne(depObj);
        depObj.setDepName(depHeader.getDepName());
        depObj.setUnitLevel(depHeader.getUnitLevel());
        depObj.setModUserID(userID);
        depObj.setModTime(sysTime);
        if (depHeaderService.updateDepHeader(depObj)) {
            jsonObj.addProperty("success", "?");
        } else {
            jsonObj.addProperty("fail", "");
        }
    } catch (Exception e) {
        throw e;
    }
    return jsonObj.toString();
}

From source file:com.controller.system.DepManager.java

/**
 * //  www .ja v  a 2 s. co  m
 *
 * @param req
 * @param rps
 * @param depID
 * @return
 * @throws Exception
 */
@RequestMapping(params = { "del" }, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public String doDel(HttpServletRequest req, HttpServletResponse rps, @RequestParam("depid") String depID)
        throws Exception {
    JsonObject jsonObj = new JsonObject();
    try {
        //?Service
        DepHeaderService depHeaderService = (DepHeaderService) ServiceFactory.getService("depHeaderService");
        DepHeader depHeader = new DepHeader();
        depHeader.setDepID(depID);
        depHeader = depHeaderService.findByOne(depHeader);
        if (depHeaderService.deleteDepHeader(depHeader)) {
            jsonObj.addProperty("success", "?");
        } else {
            jsonObj.addProperty("fail", "");
        }
    } catch (Exception e) {
        throw e;
    }
    return jsonObj.toString();
}