Example usage for com.google.gson JsonObject getAsJsonPrimitive

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

Introduction

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

Prototype

public JsonPrimitive getAsJsonPrimitive(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonPrimitive element.

Usage

From source file:com.cloudant.http.interceptors.CookieInterceptor.java

License:Open Source License

private boolean sessionHasStarted(InputStream responseStream) {
    try {//from  ww  w  .j  av  a  2s.  c  o  m
        //check the response body
        Gson gson = new Gson();
        JsonObject jsonResponse = gson.fromJson(new InputStreamReader(responseStream, "UTF-8"),
                JsonObject.class);

        // only check for ok:true, https://issues.apache.org/jira/browse/COUCHDB-1356
        // means we cannot check that the name returned is the one we sent.
        return jsonResponse != null && jsonResponse.has("ok") && jsonResponse.get("ok").isJsonPrimitive()
                && jsonResponse.getAsJsonPrimitive("ok").isBoolean()
                && jsonResponse.getAsJsonPrimitive("ok").getAsBoolean();
    } catch (UnsupportedEncodingException e) {
        //UTF-8 should be supported on all JVMs
        throw new RuntimeException(e);
    }
}

From source file:com.continusec.client.VerifiableLog.java

License:Apache License

/**
 * Get an inclusion proof for a given item for a specific tree size. Most clients will commonly use {@link #verifyInclusion(LogTreeHead,MerkleTreeLeaf)} instead.
 * @param treeSize the tree size for which the inclusion proof should be returned. This is usually as returned by {@link #getTreeHead(int)}.getTreeSize().
 * @param leaf the entry for which the inclusion proof should be returned. Note that {@link AddEntryResponse} and {@link VerifiableEntry} both implement {@link MerkleTreeLeaf}.
 * @return a log inclusion proof object that can be verified against a given tree hash.
 * @throws ContinusecException upon error
 *///from ww  w . j  av a 2  s  .  co m
public LogInclusionProof getInclusionProof(int treeSize, MerkleTreeLeaf leaf) throws ContinusecException {
    try {
        byte[] mtlHash = leaf.getLeafHash();
        JsonObject e = new JsonParser()
                .parse(new String(
                        this.client.makeRequest("GET",
                                this.path + "/tree/" + treeSize + "/inclusion/h/"
                                        + Hex.encodeHexString(mtlHash),
                                null, null).data,
                        "UTF-8"))
                .getAsJsonObject();
        return new LogInclusionProof(e.getAsJsonPrimitive("tree_size").getAsInt(), mtlHash,
                e.get("leaf_index").getAsInt(), jsonArrayToAuditProof(e.getAsJsonArray("proof")));
    } catch (UnsupportedEncodingException e) {
        throw new ContinusecException(e);
    }
}

From source file:com.continusec.client.VerifiableLog.java

License:Apache License

/**
 * Get an inclusion proof for a specified tree size and leaf index. This is not used by typical clients,
 * however it can be useful for audit operations and debugging tools. Typical clients will use {@link #verifyInclusion(LogTreeHead,MerkleTreeLeaf)}.
 * @param treeSize the tree size on which to base the proof.
 * @param leafIndex the leaf index for which to retrieve the inclusion proof.
 * @return a partially filled in LogInclusionProof (note it will not include the MerkleTreeLeaf hash for the item).
 * @throws ContinusecException upon error
 *//*from  ww  w .j av a  2  s  . c  o m*/
public LogInclusionProof getInclusionProofByIndex(int treeSize, int leafIndex) throws ContinusecException {
    try {
        JsonObject e = new JsonParser()
                .parse(new String(
                        this.client.makeRequest("GET",
                                this.path + "/tree/" + treeSize + "/inclusion/" + leafIndex, null, null).data,
                        "UTF-8"))
                .getAsJsonObject();
        return new LogInclusionProof(e.getAsJsonPrimitive("tree_size").getAsInt(), null,
                e.get("leaf_index").getAsInt(), jsonArrayToAuditProof(e.getAsJsonArray("proof")));
    } catch (UnsupportedEncodingException e) {
        throw new ContinusecException(e);
    }
}

From source file:com.continusec.client.VerifiableLog.java

License:Apache License

/**
 * ConsistencyProof returns an audit path which contains the set of Merkle Subtree hashes
 * that demonstrate how the root hash is calculated for both the first and second tree sizes.
 * @param firstSize the size of the first tree.
 * @param secondSize the size of the second tree.
 * @return a log consistency proof object that must be verified.
 * @throws ContinusecException upon error
 *//*www  .  j a  v  a  2s.co  m*/
public LogConsistencyProof getConsistencyProof(int firstSize, int secondSize) throws ContinusecException {
    try {
        JsonObject e = new JsonParser().parse(new String(this.client.makeRequest("GET",
                this.path + "/tree/" + secondSize + "/consistency/" + firstSize, null, null).data, "UTF-8"))
                .getAsJsonObject();
        return new LogConsistencyProof(e.getAsJsonPrimitive("first_tree_size").getAsInt(),
                e.getAsJsonPrimitive("second_tree_size").getAsInt(),
                jsonArrayToAuditProof(e.getAsJsonArray("proof")));
    } catch (UnsupportedEncodingException e) {
        throw new ContinusecException(e);
    }
}

From source file:com.elasticrtc.tutorial.one2many.ws.CallHandler.java

License:Apache License

private synchronized void presenter(final WebSocketSession session, JsonObject jsonMessage) throws IOException {
    if (presenterUserSession == null) {
        presenterUserSession = new UserSession(session);

        pipeline = kurento.createMediaPipeline();
        presenterUserSession.setWebRtcEndpoint(new WebRtcEndpoint.Builder(pipeline).build());

        WebRtcEndpoint presenterWebRtc = presenterUserSession.getWebRtcEndpoint();

        presenterWebRtc.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {

            @Override/*from w  w  w  .j  av a2s .c o  m*/
            public void onEvent(IceCandidateFoundEvent event) {
                JsonObject response = new JsonObject();
                response.addProperty("id", "iceCandidate");
                response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
                try {
                    synchronized (session) {
                        session.sendMessage(new TextMessage(response.toString()));
                    }
                } catch (IOException e) {
                    log.debug(e.getMessage());
                }
            }
        });

        String sdpOffer = jsonMessage.getAsJsonPrimitive("sdpOffer").getAsString();
        String sdpAnswer = presenterWebRtc.processOffer(sdpOffer);

        JsonObject response = new JsonObject();
        response.addProperty("id", "presenterResponse");
        response.addProperty("response", "accepted");
        response.addProperty("sdpAnswer", sdpAnswer);

        synchronized (session) {
            presenterUserSession.sendMessage(response);
        }
        presenterWebRtc.gatherCandidates();

    } else {
        JsonObject response = new JsonObject();
        response.addProperty("id", "presenterResponse");
        response.addProperty("response", "rejected");
        response.addProperty("message", "Another user is currently acting as sender. Try again later ...");
        session.sendMessage(new TextMessage(response.toString()));
    }
}

From source file:com.elasticrtc.tutorial.one2many.ws.CallHandler.java

License:Apache License

private synchronized void viewer(final WebSocketSession session, JsonObject jsonMessage) throws IOException {
    if (presenterUserSession == null || presenterUserSession.getWebRtcEndpoint() == null) {
        JsonObject response = new JsonObject();
        response.addProperty("id", "viewerResponse");
        response.addProperty("response", "rejected");
        response.addProperty("message", "No active sender now. Become sender or . Try again later ...");
        session.sendMessage(new TextMessage(response.toString()));
    } else {//  w  w w  . j  a  v  a2  s  . com
        if (viewers.containsKey(session.getId())) {
            JsonObject response = new JsonObject();
            response.addProperty("id", "viewerResponse");
            response.addProperty("response", "rejected");
            response.addProperty("message", "You are already viewing in this session. "
                    + "Use a different browser to add additional viewers.");
            session.sendMessage(new TextMessage(response.toString()));
            return;
        }
        UserSession viewer = new UserSession(session);
        viewers.put(session.getId(), viewer);

        WebRtcEndpoint nextWebRtc = new WebRtcEndpoint.Builder(pipeline).build();

        nextWebRtc.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {

            @Override
            public void onEvent(IceCandidateFoundEvent event) {
                JsonObject response = new JsonObject();
                response.addProperty("id", "iceCandidate");
                response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
                try {
                    synchronized (session) {
                        session.sendMessage(new TextMessage(response.toString()));
                    }
                } catch (IOException e) {
                    log.debug(e.getMessage());
                }
            }
        });

        viewer.setWebRtcEndpoint(nextWebRtc);
        presenterUserSession.getWebRtcEndpoint().connect(nextWebRtc);
        String sdpOffer = jsonMessage.getAsJsonPrimitive("sdpOffer").getAsString();
        String sdpAnswer = nextWebRtc.processOffer(sdpOffer);

        JsonObject response = new JsonObject();
        response.addProperty("id", "viewerResponse");
        response.addProperty("response", "accepted");
        response.addProperty("sdpAnswer", sdpAnswer);

        synchronized (session) {
            viewer.sendMessage(response);
        }
        nextWebRtc.gatherCandidates();
    }
}

From source file:com.elasticrtc.tutorial.one2one.ws.CallHandler.java

License:Apache License

private void register(WebSocketSession session, JsonObject jsonMessage) throws IOException {
    String name = jsonMessage.getAsJsonPrimitive("name").getAsString();

    UserSession caller = new UserSession(session, name);
    String responseMsg = "accepted";
    if (name.isEmpty()) {
        responseMsg = "rejected: empty user name";
    } else if (registry.exists(name)) {
        responseMsg = "rejected: user '" + name + "' already registered";
    } else {/*  ww  w.  ja  v a  2  s  . com*/
        registry.register(caller);
    }

    JsonObject response = new JsonObject();
    response.addProperty("id", "registerResponse");
    response.addProperty("response", responseMsg);
    caller.sendMessage(response);
}

From source file:com.elasticrtc.tutorial.one2one.ws.CallHandler.java

License:Apache License

private void call(UserSession caller, JsonObject jsonMessage) throws IOException {
    String to = jsonMessage.get("to").getAsString();
    String from = jsonMessage.get("from").getAsString();
    JsonObject response = new JsonObject();

    if (registry.exists(to)) {
        caller.setSdpOffer(jsonMessage.getAsJsonPrimitive("sdpOffer").getAsString());
        caller.setCallingTo(to);// ww w . j a  v  a2  s. c  om

        response.addProperty("id", "incomingCall");
        response.addProperty("from", from);

        UserSession callee = registry.getByName(to);
        callee.sendMessage(response);
        callee.setCallingFrom(from);
    } else {
        response.addProperty("id", "callResponse");
        response.addProperty("response", "rejected: user '" + to + "' is not registered");

        caller.sendMessage(response);
    }
}

From source file:com.example.sabeeh.helloworld.AuthService.java

License:Apache License

/***
 * Pulls the user ID and token out of a json object from the server
 * @param jsonObject/*w w w .  j  a v a  2s  .c  o  m*/
 */
public void setUserAndSaveData(JsonObject jsonObject) {
    String userId = jsonObject.getAsJsonPrimitive("userId").getAsString();
    String token = jsonObject.getAsJsonPrimitive("token").getAsString();
    setUserData(userId, token);
    saveUserData(userId, token);
    /*SharedPreferences prefs =  mContext.getSharedPreferences(SHAREDPREFFILE, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(USERIDPREF, mClient.getCurrentUser().getUserId());
    editor.putString(TOKENPREF, mClient.getCurrentUser().getAuthenticationToken());
    editor.commit();*/

}

From source file:com.github.cc007.headsweeper.controller.HeadSweeperGame.java

License:Open Source License

public HeadSweeperGame(JsonObject input, Plugin plugin) {

    this.plugin = plugin;

    x = input.getAsJsonPrimitive("x").getAsInt();
    y = input.getAsJsonPrimitive("y").getAsInt();
    z = input.getAsJsonPrimitive("z").getAsInt();

    game = new MineSweeper(true);
    game.deserialize(input.getAsJsonObject("game"));

    world = null;/*from   ww w .  j  av a2  s. co  m*/

    try {
        UUID worldUID = UUID.fromString(input.getAsJsonPrimitive("world").getAsString());
        world = Bukkit.getServer().getWorld(worldUID);
    } catch (IllegalArgumentException e) {
        world = Bukkit.getServer().getWorld(input.getAsJsonPrimitive("world").getAsString());
    }

    initMetaData();
}