Example usage for com.google.gson JsonObject remove

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

Introduction

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

Prototype

public JsonElement remove(String property) 

Source Link

Document

Removes the property from this JsonObject .

Usage

From source file:org.iti.agrimarket.util.LazySerializerForUser.java

/**
 * This method is responsible for the serialization operation for the unit
 * objects depending on the language requested it ignores the other
 * language's fields//w  w w  . j  a v  a  2  s  . c  o  m
 *
 * @param t
 * @param type
 * @param jsc
 * @return
 */
@Override
public JsonElement serialize(User t, Type type, JsonSerializationContext jsc) {
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    JsonObject jObj = (JsonObject) gson.toJsonTree(t);

    jObj.remove("mail");
    jObj.remove("mobile");
    jObj.remove("registrationChannel");
    jObj.remove("lat");
    jObj.remove("long_");
    jObj.remove("governerate");
    jObj.remove("imageUrl");
    jObj.remove("ratesAverage");
    jObj.remove("loggedIn");
    jObj.remove("image");
    jObj.remove("userDatas");
    jObj.remove("products");
    jObj.remove("userPlantsPlants");
    jObj.remove("userOfferProductFixeds");
    jObj.remove("histories");
    jObj.remove("userRatesUsersForRatedId");
    jObj.remove("userRatesUsersForRaterId");

    return jObj;
}

From source file:org.iti.agrimarket.util.SerializerForCategory.java

/**
 * This method is responsible for the serialization operation for the category objects depending on the language requested
 * it ignores the other language's fields
 * @param t//from w  w  w .  java 2 s  .  co m
 * @param type
 * @param jsc
 * @return 
 */
@Override
public JsonElement serialize(Category t, Type type, JsonSerializationContext jsc) {
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    JsonObject jObj = (JsonObject) gson.toJsonTree(t);

    if (language.equals("ar")) {
        jObj.remove("nameEn");
    } else if (language.equals("en")) {

        jObj.remove("nameAr");
    }

    return jObj;
}

From source file:org.iti.agrimarket.util.SerializerForProduct.java

/**
 * This method is responsible for the serialization operation for the product objects depending on the language requested
 * it ignores the other language's fields
 * @param t/*w ww  .  jav a  2  s  .  c o  m*/
 * @param type
 * @param jsc
 * @return 
 */
@Override
public JsonElement serialize(Product t, Type type, JsonSerializationContext jsc) {
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    JsonObject jObj = (JsonObject) gson.toJsonTree(t);

    if (language.equals("ar")) {
        jObj.remove("nameEn");
    } else if (language.equals("en")) {

        jObj.remove("nameAr");
    }

    return jObj;
}

From source file:org.iti.agrimarket.util.SerializerForUnit.java

/**
 * This method is responsible for the serialization operation for the unit objects depending on the language requested
 * it ignores the other language's fields
 * @param t//from  ww w. j a va 2 s.c o  m
 * @param type
 * @param jsc
 * @return 
 */
@Override
public JsonElement serialize(Unit t, Type type, JsonSerializationContext jsc) {
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    JsonObject jObj = (JsonObject) gson.toJsonTree(t);

    if (language.equals("ar")) {
        jObj.remove("nameEn");
    } else if (language.equals("en")) {

        jObj.remove("nameAr");
    }

    return jObj;
}

From source file:org.jboss.weld.logging.LogMessageIndexDiff.java

License:Apache License

private boolean areMessagesEqual(JsonObject msg1, JsonObject msg2) {
    List<String> suppressions = extractSuppressions(msg1);
    suppressions.addAll(extractSuppressions(msg2));
    if (!suppressions.isEmpty()) {
        // Make a copy of JSON representations first
        JsonParser parser = new JsonParser();
        msg1 = parser.parse(msg1.toString()).getAsJsonObject();
        msg2 = parser.parse(msg2.toString()).getAsJsonObject();
        msg1.remove(SUPPRESSIONS);
        msg2.remove(SUPPRESSIONS);//from  www . j a  va  2s .  co  m
        // Then remove all suppressed members
        // E.g. for @SuppressWarnings("weldlog:msg-value") we'd like to remove msgObj.msg.value
        for (String suppression : suppressions) {
            String[] suppressionParts = suppression.substring(SUPPRESS_WARNINGS_PREFIX.length()).split("-");
            removeSuppressedMember(msg1, suppressionParts);
            removeSuppressedMember(msg2, suppressionParts);
        }
    }
    return msg1.equals(msg2);
}

From source file:org.jboss.weld.logging.LogMessageIndexDiff.java

License:Apache License

private Set<String> getCollisions(JsonObject msg1, JsonObject msg2) {
    List<String> suppressions = extractSuppressions(msg1);
    suppressions.addAll(extractSuppressions(msg2));
    if (!suppressions.isEmpty()) {
        // Make a copy of JSON representations first
        JsonParser parser = new JsonParser();
        msg1 = parser.parse(msg1.toString()).getAsJsonObject();
        msg2 = parser.parse(msg2.toString()).getAsJsonObject();
        msg1.remove(SUPPRESSIONS);
        msg2.remove(SUPPRESSIONS);//from  w  w  w  . ja  va  2 s  .  c  o m
        // Then remove all suppressed members
        // E.g. for @SuppressWarnings("weldlog:msg-value") we'd like to remove msgObj.msg.value
        for (String suppression : suppressions) {
            String[] suppressionParts = suppression.substring(SUPPRESS_WARNINGS_PREFIX.length()).split("-");
            removeSuppressedMember(msg1, suppressionParts);
            removeSuppressedMember(msg2, suppressionParts);
        }
    }
    Set<String> collisions = new HashSet<>();
    for (Entry<String, JsonElement> entry : msg1.entrySet()) {
        JsonElement msg2Value = msg2.get(entry.getKey());
        if (!entry.getValue().equals(msg2Value)) {
            if (entry.getValue().isJsonObject() && msg2Value.isJsonObject()) {
                Set<String> nestedCollisions = getCollisions(entry.getValue().getAsJsonObject(),
                        msg2Value.getAsJsonObject());
                for (String nested : nestedCollisions) {
                    collisions.add(entry.getKey().toLowerCase() + "-" + nested);
                }
            } else {
                collisions.add(entry.getKey());
            }
        }
    }
    return collisions;
}

From source file:org.jboss.weld.logging.LogMessageIndexDiff.java

License:Apache License

private void removeSuppressedMember(JsonObject msg, String[] suppressionParts) {
    JsonObject last = findLastJsonObject(msg, suppressionParts);
    if (last != null) {
        last.remove(suppressionParts[suppressionParts.length - 1]);
    }/*from  w w  w  .  j  av a2 s.  co  m*/
}

From source file:org.json.other.server.Base64JsonRpcExecutor.java

License:Apache License

private void sendError(JsonRpcServerTransport transport, JsonObject resp, Integer code, String message,
        String data) {/*  w w  w . ja  va  2 s  .  c  o m*/
    JsonObject error = new JsonObject();
    if (code != null) {
        error.addProperty("code", code);
    }

    if (message != null) {
        error.addProperty("message", message);
    }

    if (data != null) {
        error.addProperty("data", data);
    }

    resp.add("error", error);
    resp.remove("result");
    String responseData = resp.toString();

    try {
        transport.writeResponse(responseData);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.json.rpc.server.InjectingJsonRpcExecutor.java

License:Apache License

private void sendError(JsonRpcServerTransport transport, JsonObject resp, Integer code, String message,
        String data) {/*w  w w. j  a va 2  s .c  o  m*/
    JsonObject error = new JsonObject();
    if (code != null) {
        error.addProperty("code", code);
    }

    if (message != null) {
        error.addProperty("message", message);
    }

    if (data != null) {
        error.addProperty("data", data);
    }

    resp.add("error", error);
    resp.remove("result");
    String responseData = resp.toString();

    LOG.debug("JSON-RPC error <<  {}", responseData);
    try {
        transport.writeResponse(responseData);
    } catch (Exception e) {
        LOG.error("unable to write error response : " + responseData, e);
    }
}

From source file:org.matrix.androidsdk.call.MXJingleCall.java

License:Apache License

/**
 * create the local stream/*from w w  w.  j ava  2 s  . co m*/
 */
private void createLocalStream() {
    Log.d(LOG_TAG, "## createLocalStream(): IN");

    // check there is at least one stream to start a call
    if ((null == mLocalVideoTrack) && (null == mLocalAudioTrack)) {
        Log.d(LOG_TAG, "## createLocalStream(): CALL_ERROR_CALL_INIT_FAILED");

        dispatchOnCallError(CALL_ERROR_CALL_INIT_FAILED);
        hangup("no_stream");
        terminate(IMXCall.END_CALL_REASON_UNDEFINED);
        return;
    }

    // create our local stream to add our audio and video tracks
    mLocalMediaStream = mPeerConnectionFactory.createLocalMediaStream("ARDAMS");
    // add video track to local stream
    if (null != mLocalVideoTrack) {
        mLocalMediaStream.addTrack(mLocalVideoTrack);
    }
    // add audio track to local stream
    if (null != mLocalAudioTrack) {
        mLocalMediaStream.addTrack(mLocalAudioTrack);
    }

    // build ICE servers list
    ArrayList<PeerConnection.IceServer> iceServers = new ArrayList<>();

    if (null != mTurnServer) {
        try {
            String username = null;
            String password = null;
            JsonObject object = mTurnServer.getAsJsonObject();

            if (object.has("username")) {
                username = object.get("username").getAsString();
            }

            if (object.has("password")) {
                password = object.get("password").getAsString();
            }

            JsonArray uris = object.get("uris").getAsJsonArray();

            for (int index = 0; index < uris.size(); index++) {
                String url = uris.get(index).getAsString();

                if ((null != username) && (null != password)) {
                    iceServers.add(new PeerConnection.IceServer(url, username, password));
                } else {
                    iceServers.add(new PeerConnection.IceServer(url));
                }
            }
        } catch (Exception e) {
            Log.e(LOG_TAG,
                    "## createLocalStream(): Exception in ICE servers list Msg=" + e.getLocalizedMessage());
        }
    }

    // define at least on server
    if (iceServers.size() == 0) {
        iceServers.add(new PeerConnection.IceServer("stun:stun.l.google.com:19302"));
    }

    // define constraints
    MediaConstraints pcConstraints = new MediaConstraints();
    pcConstraints.optional.add(new MediaConstraints.KeyValuePair("RtpDataChannels", "true"));

    // start connecting to the other peer by creating the peer connection
    mPeerConnection = mPeerConnectionFactory.createPeerConnection(iceServers, pcConstraints,
            new PeerConnection.Observer() {
                @Override
                public void onSignalingChange(PeerConnection.SignalingState signalingState) {
                    Log.d(LOG_TAG, "## mPeerConnection creation: onSignalingChange state=" + signalingState);
                }

                @Override
                public void onIceConnectionChange(final PeerConnection.IceConnectionState iceConnectionState) {
                    Log.d(LOG_TAG, "## mPeerConnection creation: onIceConnectionChange " + iceConnectionState);
                    mUIThreadHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (iceConnectionState == PeerConnection.IceConnectionState.CONNECTED) {
                                if ((null != mLocalVideoTrack) && mUsingLargeLocalRenderer && isVideo()) {
                                    mLocalVideoTrack.setEnabled(false);
                                    VideoRendererGui.remove(mLargeLocalRendererCallbacks);
                                    mLocalVideoTrack.removeRenderer(mLargeLocalRenderer);

                                    // in conference call, there is no local preview,
                                    // the local attendee video is sent by the server among the others conference attendees.
                                    if (!isConference()) {
                                        // add local preview, only for 1:1 call
                                        mLocalVideoTrack.addRenderer(mSmallLocalRenderer);
                                    }

                                    listenPreviewUpdate();

                                    mLocalVideoTrack.setEnabled(true);
                                    mUsingLargeLocalRenderer = false;

                                    mCallView.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (null != mCallView) {
                                                mCallView.invalidate();
                                            }
                                        }
                                    });
                                }

                                dispatchOnStateDidChange(IMXCall.CALL_STATE_CONNECTED);
                            }
                            // theses states are ignored
                            // only the matrix hangup event is managed
                            /*else if (iceConnectionState == PeerConnection.IceConnectionState.DISCONNECTED) {
                                // TODO warn the user ?
                                hangup(null);
                            } else if (iceConnectionState == PeerConnection.IceConnectionState.CLOSED) {
                                // TODO warn the user ?
                                terminate();
                            }*/
                            else if (iceConnectionState == PeerConnection.IceConnectionState.FAILED) {
                                dispatchOnCallError(CALL_ERROR_ICE_FAILED);
                                hangup("ice_failed");
                            }
                        }
                    });
                }

                @Override
                public void onIceConnectionReceivingChange(boolean var1) {
                    Log.d(LOG_TAG, "## mPeerConnection creation: onIceConnectionReceivingChange " + var1);
                }

                @Override
                public void onIceGatheringChange(PeerConnection.IceGatheringState iceGatheringState) {
                    Log.d(LOG_TAG, "## mPeerConnection creation: onIceGatheringChange " + iceGatheringState);
                }

                @Override
                public void onIceCandidate(final IceCandidate iceCandidate) {
                    Log.d(LOG_TAG, "## mPeerConnection creation: onIceCandidate " + iceCandidate);

                    mUIThreadHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (!isCallEnded()) {
                                JsonObject content = new JsonObject();
                                content.addProperty("version", 0);
                                content.addProperty("call_id", mCallId);

                                JsonArray candidates = new JsonArray();
                                JsonObject cand = new JsonObject();
                                cand.addProperty("sdpMLineIndex", iceCandidate.sdpMLineIndex);
                                cand.addProperty("sdpMid", iceCandidate.sdpMid);
                                cand.addProperty("candidate", iceCandidate.sdp);
                                candidates.add(cand);
                                content.add("candidates", candidates);

                                boolean addIt = true;

                                // merge candidates
                                if (mPendingEvents.size() > 0) {
                                    try {
                                        Event lastEvent = mPendingEvents.get(mPendingEvents.size() - 1);

                                        if (TextUtils.equals(lastEvent.getType(),
                                                Event.EVENT_TYPE_CALL_CANDIDATES)) {
                                            // return the content cast as a JsonObject
                                            // it is not a copy
                                            JsonObject lastContent = lastEvent.getContentAsJsonObject();

                                            JsonArray lastContentCandidates = lastContent.get("candidates")
                                                    .getAsJsonArray();
                                            JsonArray newContentCandidates = content.get("candidates")
                                                    .getAsJsonArray();

                                            Log.d(LOG_TAG,
                                                    "Merge candidates from " + lastContentCandidates.size()
                                                            + " to " + (lastContentCandidates.size()
                                                                    + newContentCandidates.size() + " items."));

                                            lastContentCandidates.addAll(newContentCandidates);

                                            // replace the candidates list
                                            lastContent.remove("candidates");
                                            lastContent.add("candidates", lastContentCandidates);

                                            // don't need to save anything, lastContent is a reference not a copy

                                            addIt = false;
                                        }
                                    } catch (Exception e) {
                                        Log.e(LOG_TAG,
                                                "## createLocalStream(): createPeerConnection - onIceCandidate() Exception Msg="
                                                        + e.getMessage());
                                    }
                                }

                                if (addIt) {
                                    Event event = new Event(Event.EVENT_TYPE_CALL_CANDIDATES, content,
                                            mSession.getCredentials().userId, mCallSignalingRoom.getRoomId());

                                    mPendingEvents.add(event);
                                    sendNextEvent();
                                }
                            }
                        }
                    });
                }

                @Override
                public void onAddStream(final MediaStream mediaStream) {
                    Log.d(LOG_TAG, "## mPeerConnection creation: onAddStream " + mediaStream);

                    mUIThreadHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if ((mediaStream.videoTracks.size() == 1) && !isCallEnded()) {
                                mRemoteVideoTrack = mediaStream.videoTracks.get(0);
                                mRemoteVideoTrack.setEnabled(true);
                                mRemoteVideoTrack.addRenderer(mLargeRemoteRenderer);
                            }
                        }
                    });
                }

                @Override
                public void onRemoveStream(final MediaStream mediaStream) {
                    Log.d(LOG_TAG, "## mPeerConnection creation: onRemoveStream " + mediaStream);

                    mUIThreadHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (null != mRemoteVideoTrack) {
                                mRemoteVideoTrack.dispose();
                                mRemoteVideoTrack = null;
                                mediaStream.videoTracks.get(0).dispose();
                            }
                        }
                    });

                }

                @Override
                public void onDataChannel(DataChannel dataChannel) {
                    Log.d(LOG_TAG, "## mPeerConnection creation: onDataChannel " + dataChannel);
                }

                @Override
                public void onRenegotiationNeeded() {
                    Log.d(LOG_TAG, "## mPeerConnection creation: onRenegotiationNeeded");
                }
            });

    // send our local video and audio stream to make it seen by the other part
    mPeerConnection.addStream(mLocalMediaStream);

    MediaConstraints constraints = new MediaConstraints();
    constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
    constraints.mandatory
            .add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", isVideo() ? "true" : "false"));

    // call createOffer only for outgoing calls
    if (!isIncoming()) {
        Log.d(LOG_TAG, "## createLocalStream(): !isIncoming() -> createOffer");

        mPeerConnection.createOffer(new SdpObserver() {
            @Override
            public void onCreateSuccess(SessionDescription sessionDescription) {
                Log.d(LOG_TAG, "createOffer onCreateSuccess");

                final SessionDescription sdp = new SessionDescription(sessionDescription.type,
                        sessionDescription.description);

                mUIThreadHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (mPeerConnection != null) {
                            // must be done to before sending the invitation message
                            mPeerConnection.setLocalDescription(new SdpObserver() {
                                @Override
                                public void onCreateSuccess(SessionDescription sessionDescription) {
                                    Log.d(LOG_TAG, "setLocalDescription onCreateSuccess");
                                }

                                @Override
                                public void onSetSuccess() {
                                    Log.d(LOG_TAG, "setLocalDescription onSetSuccess");
                                    sendInvite(sdp);
                                    dispatchOnStateDidChange(IMXCall.CALL_STATE_INVITE_SENT);
                                }

                                @Override
                                public void onCreateFailure(String s) {
                                    Log.e(LOG_TAG, "setLocalDescription onCreateFailure " + s);
                                    dispatchOnCallError(CALL_ERROR_CAMERA_INIT_FAILED);
                                    hangup(null);
                                }

                                @Override
                                public void onSetFailure(String s) {
                                    Log.e(LOG_TAG, "setLocalDescription onSetFailure " + s);
                                    dispatchOnCallError(CALL_ERROR_CAMERA_INIT_FAILED);
                                    hangup(null);
                                }
                            }, sdp);
                        }
                    }
                });
            }

            @Override
            public void onSetSuccess() {
                Log.d(LOG_TAG, "createOffer onSetSuccess");
            }

            @Override
            public void onCreateFailure(String s) {
                Log.d(LOG_TAG, "createOffer onCreateFailure " + s);
                dispatchOnCallError(CALL_ERROR_CAMERA_INIT_FAILED);
            }

            @Override
            public void onSetFailure(String s) {
                Log.d(LOG_TAG, "createOffer onSetFailure " + s);
                dispatchOnCallError(CALL_ERROR_CAMERA_INIT_FAILED);
            }
        }, constraints);

        dispatchOnStateDidChange(IMXCall.CALL_STATE_WAIT_CREATE_OFFER);
    }
}