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.goodow.realtime.server.rpc.SnapshotHandler.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String id = requireParameter(req, Constants.Params.ID);
    String sid = requireParameter(req, Constants.Params.SESSION_ID);
    String revisionString = optionalParameter(req, Constants.Params.REVISION, null);
    @Nullable/* w  w  w  . j a va2  s. c o m*/
    Long revision = revisionString == null ? null : Long.parseLong(revisionString);

    JsonObject obj;
    try {
        if (revision == null) {
            Pair<ConnectResult, String> pair = loader.load(id,
                    new Session(context.get().getAccountInfo().getUserId(), sid), true);
            obj = new JsonObject();
            // obj.addProperty(Params.SESSION_ID, sid);
            serialize(pair, obj);
        } else {
            String snapshot = loader.loadStaticAtVersion(new ObjectId(id), revision);
            obj = new JsonObject();
            obj.add(Constants.Params.SNAPSHOT, new JsonParser().parse(snapshot));
        }
    } catch (AccessDeniedException e) {
        log.log(Level.SEVERE, "Object not found or access denied", e);
        return;
    } catch (SlobNotFoundException e) {
        log.log(Level.SEVERE, "Object not found or access denied", e);
        return;
    } catch (IOException e) {
        log.log(Level.SEVERE, "Server error loading object", e);
        return;
    }
    RpcUtil.writeJsonResult(req, resp, obj.toString());
}

From source file:com.goodow.realtime.server.servlet.InitHandler.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    JsonObject obj = initVars();
    resp.setContentType("application/json");
    resp.getWriter().print(obj.toString());
}

From source file:com.goodow.wind.server.rpc.DeltaHandler.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String keyString = requireParameter(req, Params.ID);
    JsonObject toRtn;
    try {/*from   w  ww.  j a  v  a  2s.co m*/
        if (!keyString.startsWith("[")) {
            Long version = Long.parseLong(requireParameter(req, Params.VERSION));
            String endVersionString = optionalParameter(req, Params.END_VERSION, null);
            Long endVersion = endVersionString == null ? null : Long.parseLong(endVersionString);
            toRtn = fetchHistory(new ObjectId(keyString), version, endVersion);
        } else {
            JsonElement keys = new JsonParser().parse(keyString);
            assert keys.isJsonArray();
            String sid = requireParameter(req, Params.SESSION_ID);
            toRtn = fetchHistories(new SessionId(sid), keys.getAsJsonArray());
        }
    } catch (SlobNotFoundException e) {
        throw new BadRequestException("Object not found or access denied", e);
    } catch (AccessDeniedException e) {
        throw new BadRequestException("Object not found or access denied", e);
    } catch (NumberFormatException nfe) {
        throw new BadRequestException("Parse error", nfe);
    }

    resp.setContentType("application/json");
    Util.writeJsonResult(resp.getWriter(), toRtn.toString());
}

From source file:com.goodow.wind.server.rpc.SnapshotHandler.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String key = requireParameter(req, Constants.Params.ID);
    String versionString = optionalParameter(req, Constants.Params.VERSION, null);
    @Nullable/*  w w w. j  av  a2  s  .c om*/
    Long version = versionString == null ? null : Long.parseLong(versionString);

    JsonObject obj;
    try {
        if (version == null) {
            String sid = requireParameter(req, Constants.Params.SESSION_ID);
            String jsonType = optionalParameter(req, Constants.Params.KIND, null);
            Pair<ConnectResult, String> pair = loader.loadOrCreate(key, new SessionId(sid),
                    jsonType == null ? null : JsonType.valueOf(jsonType));
            obj = serialize(pair);
        } else {
            String snapshot = loader.loadStaticAtVersion(new ObjectId(key), version);
            obj = new JsonObject();
            obj.add(Constants.Params.SNAPSHOT, new JsonParser().parse(snapshot));
        }
    } catch (AccessDeniedException e) {
        log.log(Level.SEVERE, "Object not found or access denied", e);
        return;
    } catch (SlobNotFoundException e) {
        log.log(Level.SEVERE, "Object not found or access denied", e);
        return;
    } catch (IOException e) {
        log.log(Level.SEVERE, "Server error loading object", e);
        return;
    }

    resp.setContentType("application/json");
    Util.writeJsonResult(resp.getWriter(), obj.toString());
}

From source file:com.goodow.wind.server.rpc.SubmitDeltaHandler.java

License:Apache License

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String sid = requireParameter(req, Constants.Params.SESSION_ID);
    String key = requireParameter(req, Constants.Params.ID);
    String versionString = requireParameter(req, Constants.Params.VERSION);
    long version;
    try {//from   w  ww  .j  a  v a  2s.c  om
        version = Long.parseLong(versionString);
    } catch (NumberFormatException e) {
        throw new RuntimeException(e);
    }
    String deltas = requireParameter(req, Constants.Params.DELTAS);

    ServerMutateRequest mutateRequest = new ServerMutateRequest();
    mutateRequest.setSession(new ObjectSession(new ObjectId(key), new SessionId(sid)));
    mutateRequest.setVersion(version);
    mutateRequest.setDeltas(deltas);

    MutateResult res;
    try {
        res = slobFacilities.getSlobStore().mutateObject(mutateRequest);
    } catch (SlobNotFoundException e) {
        throw new BadRequestException("Object not found or access denied", e);
    } catch (AccessDeniedException e) {
        throw new BadRequestException("Object not found or access denied", e);
    }

    JsonObject json = new JsonObject();
    json.addProperty(Constants.Params.VERSION, res.getResultingVersion());
    resp.setContentType("application/json");
    Util.writeJsonResult(resp.getWriter(), json.toString());
}

From source file:com.goodow.wind.server.rpc.VersionHandler.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String sid = requireParameter(req, Constants.Params.SESSION_ID);
    String key = requireParameter(req, Constants.Params.ID);
    ObjectSession session = new ObjectSession(new ObjectId(key), new SessionId(sid));
    log.info("connect " + session);

    ConnectResult result;//from   w  ww .j av  a2 s.  c  o  m
    try {
        result = slobFacilities.getSlobStore().reconnect(session.getObjectId(), session.getSessionId());
    } catch (SlobNotFoundException e) {
        throw new BadRequestException("Object not found or access denied", e);
    } catch (AccessDeniedException e) {
        throw new BadRequestException("Object not found or access denied", e);
    }
    log.info("connect " + session + ": " + result);

    JsonObject obj = new JsonObject();
    obj.addProperty(Constants.Params.VERSION, result.getVersion());

    resp.setContentType("application/json");
    Util.writeJsonResult(resp.getWriter(), obj.toString());
}

From source file:com.google.appinventor.components.runtime.ProbeBase.java

License:Open Source License

protected void saveToDB(IJsonObject completeProbeUri, IJsonObject data) {

    Log.i(TAG, "Writing data: " + completeProbeUri + ": " + data.toString());
    final JsonObject dataObject = data.getAsJsonObject();
    dataObject.add("probe", completeProbeUri.get(RuntimeTypeAdapterFactory.TYPE));
    dataObject.add("timezoneOffset", new JsonPrimitive(localOffsetSeconds)); // nice
    // move//w  w w .ja v a 2  s  . c  o m
    final long timestamp = data.get(BaseProbeKeys.TIMESTAMP).getAsLong();
    final String probeName = completeProbeUri.get("@type").getAsString();

    Bundle b = new Bundle();
    b.putString(NameValueDatabaseService.DATABASE_NAME_KEY, PROBE_BASE_NAME);
    b.putLong(NameValueDatabaseService.TIMESTAMP_KEY, timestamp);
    b.putString(NameValueDatabaseService.NAME_KEY, probeName);
    b.putString(NameValueDatabaseService.VALUE_KEY, dataObject.toString());
    Intent i = new Intent(mBoundFunfManager, NameValueDatabaseService.class);
    i.setAction(DatabaseService.ACTION_RECORD);
    i.putExtras(b);
    mBoundFunfManager.startService(i);

}

From source file:com.google.cloud.backend.config.ConfigurationServlet.java

License:Apache License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    // process request
    JsonObject jsonResponse = new JsonObject();
    String mode = req.getParameter(PARAM_OPERATION);

    try {//  www  .j  a va 2s.c  o m
        if (!XSRFTokenUtility.verifyToken(configMgr.getSecretKey(), mode, req.getParameter(PARAM_TOKEN))) {
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    } catch (NoSuchAlgorithmException e) {
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }

    if (PARAM_OPERATION_READ.equals(mode)) {
        readConfig(jsonResponse);
    } else if (PARAM_OPERATION_SAVE.equals(mode)) {
        saveConfig(req, jsonResponse);
    } else if (PARAM_OPERATION_PUSHMSG.equals(mode)) {
        sendPushMessage(req, jsonResponse);
    } else if (PARAM_OPERATION_CLEAR_SUBSCRIPTIONS.equals(mode)) {
        clearAllSubscriptions(jsonResponse);
    } else {
        throw new IllegalArgumentException("No such operation: " + mode);
    }

    // write response
    resp.setContentType("application/json");
    resp.setStatus(200);
    resp.getWriter().println(jsonResponse.toString());
    resp.getWriter().flush();
    resp.flushBuffer();
}

From source file:com.google.cloud.solutions.sampleapps.orchestration.orchestrator.server.GceInstanceCreator.java

License:Open Source License

/**
 * Makes the payload for creating a new disk.
 *
 * @param diskName the name of the disk.
 * @return the payload for the POST request to create a new disk.
 *//*from w w  w  .  j a  v a 2s.  co m*/
private String createPayload_disk(String diskName, Map<String, String> configProperties) {
    JsonObject json = new JsonObject();
    json.addProperty("kind", "compute#disk");
    json.addProperty("name", diskName);
    json.addProperty("zone", ConfigProperties.urlPrefixWithProjectAndZone);
    json.addProperty("description", "Persistent boot disk.");
    json.addProperty("sourceSnapshot", ConfigProperties.urlPrefixWithProject + "/global/snapshots/"
            + configProperties.get("snapshotName"));
    String payload = json.toString();
    return payload;
}

From source file:com.google.cloud.solutions.sampleapps.orchestration.orchestrator.server.GceInstanceCreator.java

License:Open Source License

/**
 * Makes the payload for creating an instance.
 *
 * @param instanceName the name of the instance.
 * @return the payload for the POST request to create a new instance.
 *//*from  ww  w. j  a v a  2  s  . c o m*/
String createPayload_instance(String instanceName, String bootDiskName, Map<String, String> configProperties) {
    JsonObject json = new JsonObject();
    json.addProperty("kind", "compute#instance");
    json.addProperty("name", instanceName);
    json.addProperty("machineType", ConfigProperties.urlPrefixWithProjectAndZone + "/machineTypes/"
            + configProperties.get("machineType"));

    JsonObject disksElem = new JsonObject();
    disksElem.addProperty("kind", "compute#attachedDisk");
    disksElem.addProperty("boot", true);
    disksElem.addProperty("type", "PERSISTENT");
    disksElem.addProperty("mode", "READ_WRITE");
    disksElem.addProperty("deviceName", bootDiskName);
    disksElem.addProperty("zone", ConfigProperties.urlPrefixWithProjectAndZone);
    disksElem.addProperty("source", ConfigProperties.urlPrefixWithProjectAndZone + "/disks/" + bootDiskName);

    JsonArray jsonAr = new JsonArray();
    jsonAr.add(disksElem);
    json.add("disks", jsonAr);

    JsonObject networkInterfacesObj = new JsonObject();
    networkInterfacesObj.addProperty("kind", "compute#instanceNetworkInterface");
    networkInterfacesObj.addProperty("network",
            ConfigProperties.urlPrefixWithProject + "/global/networks/default");

    JsonObject accessConfigsObj = new JsonObject();
    accessConfigsObj.addProperty("name", "External NAT");
    accessConfigsObj.addProperty("type", "ONE_TO_ONE_NAT");
    JsonArray accessConfigsAr = new JsonArray();
    accessConfigsAr.add(accessConfigsObj);
    networkInterfacesObj.add("accessConfigs", accessConfigsAr);

    JsonArray networkInterfacesAr = new JsonArray();
    networkInterfacesAr.add(networkInterfacesObj);
    json.add("networkInterfaces", networkInterfacesAr);

    JsonObject serviceAccountsObj = new JsonObject();
    serviceAccountsObj.addProperty("kind", "compute#serviceAccount");
    serviceAccountsObj.addProperty("email", "default");
    JsonArray scopesAr = new JsonArray();
    scopesAr.add(new JsonPrimitive("https://www.googleapis.com/auth/userinfo.email"));
    scopesAr.add(new JsonPrimitive("https://www.googleapis.com/auth/compute"));
    scopesAr.add(new JsonPrimitive("https://www.googleapis.com/auth/devstorage.full_control"));
    serviceAccountsObj.add("scopes", scopesAr);
    JsonArray serviceAccountsAr = new JsonArray();
    serviceAccountsAr.add(serviceAccountsObj);
    json.add("serviceAccounts", serviceAccountsAr);

    JsonObject metadataObj = new JsonObject();

    JsonArray mdItemsAr = new JsonArray();
    JsonObject mdItemsObj = new JsonObject();
    mdItemsObj.addProperty("key", "startup-script-url");
    mdItemsObj.addProperty("value", configProperties.get("startupScript"));
    mdItemsAr.add(mdItemsObj);
    metadataObj.add("items", mdItemsAr);
    json.add("metadata", metadataObj);
    String payload = json.toString();
    return payload;
}