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.flipkart.android.proteus.parser.Attributes.java

License:Apache License

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

    JsonObject output = new JsonObject();
    JsonObject priorities = new JsonObject();
    Map<Integer, String> map = new HashMap<>();

    Field[] fields = Priority.class.getFields();
    for (Field field : fields) {
        if (field.getName().equals("value")) {
            continue;
        }/*from ww w  .j  a  v  a 2  s. c o m*/
        Priority priority = (Priority) Priority.class.getField(field.getName()).get(new Priority(0));
        priorities.addProperty(field.getName(), priority.value);
        map.put(priority.value, field.getName());
    }

    JsonObject attributes = new JsonObject();
    Class<?>[] list = Attributes.class.getDeclaredClasses();
    for (Class type : list) {
        if (type.equals(Attribute.class)) {
            continue;
        }
        for (Field field : type.getFields()) {
            Attribute attribute = (Attribute) type.getField(field.getName()).get(null);
            JsonObject value = new JsonObject();
            value.addProperty("priority", map.get(attribute.getPriority().value));
            attributes.add(attribute.getName(), value);
        }
    }

    output.add("all", attributes);
    output.add("priority", priorities);

    System.out.println(output.toString());
}

From source file:com.geoxp.oss.servlet.GetOSSRSAServlet.java

License:Apache License

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JsonObject json = new JsonObject();

    json.addProperty("exponent", OSS.getSessionRSAPublicKey().getPublicExponent().toString(10));
    json.addProperty("modulus", OSS.getSessionRSAPublicKey().getModulus().toString(10));

    response.setContentType("application/json");
    response.getWriter().print(json.toString());
}

From source file:com.github.abilityapi.abilityapi.external.Metrics.java

License:Open Source License

/**
 * Sends the data to the bStats server.//from  ww w.  j a va2s.com
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JsonObject data) throws Exception {
    Validate.notNull(data, "Data cannot be null");
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}

From source file:com.github.achatain.nopasswordauthentication.utils.ServletResponseUtils.java

License:Open Source License

public static void writeJsonResponse(HttpServletResponse resp, JsonObject json) throws IOException {
    Preconditions.checkArgument(json != null, "Json argument should not be null");
    resp.setContentType(JSON_TYPE);/*from   w w w .ja v a2 s. c  om*/
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.getWriter().write(json.toString());
}

From source file:com.github.cc007.headsweeper.HeadSweeper.java

License:Open Source License

/**
 * Save the currently available games to a json file
 *///from  www  . j a v  a2 s .  c o  m
public void saveGames() {
    File file = new File(getDataFolder(), "sweeperGames.json");
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            getLogger().log(Level.SEVERE, "Couldn't create sweeperGames.json");
        }
    }

    JsonObject json = controller.serialize();
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, false))) {
        writer.write(json.toString());
        writer.flush();
    } catch (IOException ex) {
        getLogger().log(Level.SEVERE, "Couldn't write to sweeperGames.json");
    }
}

From source file:com.github.messenger4j.profile.GreetingsProfileResponse.java

License:Apache License

public static GreetingsProfileResponse fromJson(JsonObject jsonObject) throws MessengerIOException {
    JsonArray dataArray = getArray(jsonObject, "data");
    if (isJsonArrayEmpty(dataArray)) {
        return new GreetingsProfileResponse(jsonObject.toString());
    }// w ww.j  a va  2s .  co m

    JsonArray greetingsJsonArray = getArray(dataArray.get(0).getAsJsonObject(), "greeting");
    if (isJsonArrayEmpty(greetingsJsonArray)) {
        return new GreetingsProfileResponse(jsonObject.toString());
    }

    return new GreetingsProfileResponse(jsonObject.toString(),
            new Gson().fromJson(greetingsJsonArray, Greeting[].class));
}

From source file:com.github.xose.persona.verifier.VerifyResultParser.java

License:Apache License

public final static String toJSONString(VerifyResult input) {
    JsonObject result = new JsonObject();
    result.addProperty("status", input.getStatus().toString());
    if (VerifyResult.Status.OKAY.equals(input.getStatus())) {
        result.addProperty("email", input.getEmail());
        result.addProperty("audience", input.getAudience());
        result.addProperty("expires", input.getExpires().getTime());
        result.addProperty("issuer", input.getIssuer());
    } else if (VerifyResult.Status.FAILURE.equals(input.getStatus())) {
        result.addProperty("reason", input.getReason());
    }/*from  w ww  .ja v a2s .co  m*/
    return result.toString();
}

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

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String id = requireParameter(req, Params.ID);
    JsonObject toRtn = new JsonObject();
    try {//www  .  java2  s.  co m
        Long startRev = Long.parseLong(requireParameter(req, Params.START_REVISION));
        String endRevString = optionalParameter(req, Params.END_REVISION, null);
        Long endRev = endRevString == null ? null : Long.parseLong(endRevString);
        fetchDeltas(toRtn, new ObjectId(id), startRev - 1, endRev);
    } 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);
    }

    RpcUtil.writeJsonResult(req, resp, toRtn.toString());
}

From source file:com.goodow.realtime.server.rpc.RevisionHandler.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String key = requireParameter(req, Constants.Params.ID);

    ConnectResult result;//from w ww.  jav  a 2  s.co m
    try {
        result = slobFacilities.getSlobStore().reconnect(new ObjectId(key), null);
    } 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 obj = new JsonObject();
    obj.addProperty(Constants.Params.REVISION, result.getVersion());

    RpcUtil.writeJsonResult(req, resp, obj.toString());
}

From source file:com.goodow.realtime.server.rpc.SaveHandler.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);
    JsonObject payload = new JsonParser().parse(RpcUtil.readRequestBody(req)).getAsJsonObject();
    long version = payload.get(Params.REVISION).getAsLong();
    String changes = payload.get(Params.CHANGES).toString();

    ObjectId id = new ObjectId(key);
    Session session = new Session(context.get().getAccountInfo().getUserId(), sid);
    long resultingVersion;
    if (version == 0) {
        JsonArray jsonArray = new JsonParser().parse(changes).getAsJsonArray();
        List<Delta<String>> deltas = new ArrayList<Delta<String>>(jsonArray.size());
        for (JsonElement e : jsonArray) {
            deltas.add(new Delta<String>(session, e.toString()));
        }//from   www .java  2 s  . c  o m
        loader.create(id, deltas);
        resultingVersion = deltas.size();
    } else {
        ServerMutateRequest mutateRequest = new ServerMutateRequest();
        mutateRequest.setSession(new ObjectSession(id, session));
        mutateRequest.setVersion(version);
        mutateRequest.setDeltas(changes);

        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);
        }
        resultingVersion = res.getResultingVersion();
    }

    JsonObject json = new JsonObject();
    json.addProperty(Constants.Params.REVISION, resultingVersion);
    RpcUtil.writeJsonResult(req, resp, json.toString());
}