Example usage for com.google.gson JsonElement getAsInt

List of usage examples for com.google.gson JsonElement getAsInt

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsInt.

Prototype

public int getAsInt() 

Source Link

Document

convenience method to get this element as a primitive integer value.

Usage

From source file:de.baydev.hueemulator.network.resources.service.SensorService.java

License:Open Source License

public List<HueResponse> updateConfig(String id, String data) {
    HueSensor sensor = manager.getItems().get(id);
    List<HueResponse> responses = new ArrayList<>();

    if (sensor != null) {

        HueSensorConfig item = sensor.getConfig();

        JsonUtil.toJsonObject(data).entrySet().forEach(k -> {

            JsonElement val = k.getValue();
            switch (k.getKey()) {
            case "battery":
                item.setBattery(val.getAsInt());
                responses.addAll(/*from w w w.  j a va2  s.co  m*/
                        responseSimpleSuccess("/sensors/ " + id + "/config/battery", item.getBattery()));
                break;
            case "lat":
                item.setLatitude(val.getAsString());
                responses.addAll(responseSimpleSuccess("/sensors/ " + id + "/config/lat", item.getLatitude()));
                break;
            case "long":
                item.setLongitude(val.getAsString());
                responses
                        .addAll(responseSimpleSuccess("/sensors/ " + id + "/config/long", item.getLongitude()));
                break;
            case "on":
                item.setOn(val.getAsBoolean());
                responses.addAll(responseSimpleSuccess("/sensors/ " + id + "/config/on", item.getOn()));
                break;
            case "reachable":
                item.setReachable(val.getAsBoolean());
                responses.addAll(
                        responseSimpleSuccess("/sensors/ " + id + "/config/reachable", item.getReachable()));
                break;
            case "sunriseoffset":
                item.setSunriseoffset(val.getAsInt());
                responses.addAll(responseSimpleSuccess("/sensors/ " + id + "/config/sunriseoffset",
                        item.getSunriseoffset()));
                break;
            case "sunsetoffset":
                item.setSunsetoffset(val.getAsInt());
                responses.addAll(responseSimpleSuccess("/sensors/ " + id + "/config/sunsetoffset",
                        item.getSunsetoffset()));
                break;
            default:

            }
        });

        sensor.setConfig(item);
        manager.onChange(id, sensor);

    }

    return responses;
}

From source file:de.baydev.hueemulator.network.resources.service.ServiceUtils.java

License:Open Source License

public RequestResponse parseState(HueState state, String path, String data) {

    List<HueResponse> responses = new ArrayList<>();

    try {//from w  ww  . j  av  a2  s  . c  om

        JsonUtil.toJsonObject(data).entrySet().forEach(k -> {

            String key = k.getKey();
            JsonElement val = k.getValue();

            switch (key) {
            case "on":
                state.setOn(k.getValue().getAsBoolean());
                responses.addAll(responseSimpleSuccess(path + "/on", state.getOn()));
                break;
            case "bri":
                state.setBri(k.getValue().getAsInt());
                responses.addAll(responseSimpleSuccess(path + "/bri", state.getBri()));
                break;
            case "xy":
                if (val.getAsJsonArray().size() == 2) {
                    Float[] newXy = JsonUtil.fromJson(k.getValue().toString(), Float[].class);
                    if (newXy[0] >= 0 && newXy[0] <= 1.0 && newXy[1] >= 0 && newXy[1] <= 1.0) {
                        state.setXy(newXy);
                        state.setColormode("xy");
                        responses.addAll(responseSimpleSuccess(path + "/xy", state.getXy()));
                    }
                }
                break;

            case "bri_inc":
                state.setBri(state.getBri() + val.getAsInt());
                responses.addAll(responseSimpleSuccess(path + "/bri", state.getBri()));
                break;

            case "ct":
                state.setCt(val.getAsInt());
                state.setColormode("ct");
                responses.addAll(responseSimpleSuccess(path + "/ct", state.getCt()));
                break;
            case "hue":
                state.setHue(val.getAsInt());
                state.setColormode("hs");
                responses.addAll(responseSimpleSuccess(path + "/hue", state.getHue()));
                break;
            case "sat":
                state.setSat(val.getAsInt());
                state.setColormode("hs");
                responses.addAll(responseSimpleSuccess(path + "/sat", state.getSat()));
                break;
            case "alert":
                state.setAlert(val.getAsString());
                responses.addAll(responseSimpleSuccess(path + "/alert", state.getAlert()));
                break;
            case "effect":
                state.setEffect(val.getAsString());
                responses.addAll(responseSimpleSuccess(path + "/effect", state.getEffect()));
                break;
            case "sat_inc":
                state.setSat(state.getSat() + val.getAsInt());
                responses.addAll(responseSimpleSuccess(path + "/sat", state.getSat()));
                break;
            case "colormode":
                state.setColormode(val.getAsString());
                responses.addAll(responseSimpleSuccess(path + "/colormode", state.getColormode()));
                break;
            case "hue_inc":
                state.setHue(state.getHue() + val.getAsInt());
                responses.addAll(responseSimpleSuccess(path + "/hue", state.getHue()));
                break;
            case "ct_inc":
                state.setCt(state.getCt() + val.getAsInt());
                responses.addAll(responseSimpleSuccess(path + "/ct", state.getCt()));
                break;
            case "xy_inc":

                Float[] newXy = JsonUtil.fromJson(val.getAsString(), Float[].class);
                Float[] calcXy = { state.getXy()[0] + newXy[0], state.getXy()[1] + newXy[1] };
                if (calcXy[0] >= 0 && calcXy[0] <= 1.0 && calcXy[1] >= 0 && calcXy[1] <= 1.0) {
                    state.setXy(calcXy);
                    state.setColormode("xy");
                    responses.addAll(responseSimpleSuccess(path + "/xy", state.getXy()));
                }
                break;
            case "scene":
                state.setScene(val.getAsString());
                responses.addAll(responseSimpleSuccess(path + "/scene", state.getScene()));

                break;
            }
        });

    } catch (Exception ex) {
        LOGGER.log(Level.WARNING, "IOException called while getting Group Data", ex);
    }

    return new RequestResponse(state, responses);
}

From source file:de.lespace.apprtc.WebSocketRTCClient.java

License:Open Source License

@Override
public void onWebSocketMessage(final String msg) {
    //    try {// ww w . ja v  a  2  s  .  c  o  m
    Message message = GsonWrapper.getGson().fromJson(msg, Message.class);
    //      JSONObject json = new JSONObject(msg);

    AppConfig params = message.getParams();
    if (params != null) {
        Log.i(TAG, "Got appConfig" + msg + " parsing into roomParameters");
        //this.roomParametersFetcher.parseAppConfig(msg);

        Log.i(TAG, "app config: " + msg);
        try {
            //          JSONObject appConfig = new JSONObject(msg);

            String result = message.getResult();
            Log.i(TAG, "client debug ");
            if (!result.equals("SUCCESS")) {
                return;
            }

            //          String params = appConfig.getString("params");
            //          appConfig = new JSONObject(params);
            LinkedList<PeerConnection.IceServer> iceServers = iceServersFromPCConfigJSON(params.getPcConfig());

            AppRTCClient.SignalingParameters signalingParameters = new SignalingParameters(iceServers);

            wsClient.register(connectionParameters.from);
        } catch (JSONException e) {
            signalingEvents.onChannelError("app config JSON parsing error: " + e.toString());
        }
        return;
    }

    //            if (socketState != WebSocketConnectionState.REGISTERED && socketState != WebSocketConnectionState.CONNECTED){
    //                Log.e(TAG, "websocket still in non registered state.");
    //                return;
    //            }
    JsonElement typeJson = message.getType();

    if (typeJson == null || message.getData() == null || typeJson.getAsString().length() != 0) {
        return;
    }

    String id = "";
    String response = "";

    MessageType type = MessageType.valueOf("" + typeJson.getAsInt());
    MessageData data = message.getData();
    switch (type) {
    case CUSTOMER_LOGIN:
        //user register
        //            JSONObject userT = json.getJSONObject("data");
        userId = data.getUserId();
        //            userId = userT.getInt("userId");
        //            userName = userT.getString("name");
        userName = data.getName().getAsString();
        //make call;
        socketState = WebSocketConnectionState.REGISTERED;
        makeCall();
        break;

    case AGENT_INFO_CUSTOMER:
        agentData = message.getData();
        break;

    case HAVE_MESSAGE:
        signalingEvents.onMessageCome(data);
        break;

    case MESSAGE:
        conversationId = message.getData().getConversationId();
        signalingEvents.onConversationReady();
        break;

    case RESPONSE_AGENT_MISS_CHAT_TO_CUSTOMER:
        signalingEvents.onAgentMissedChat();
        break;

    case VIDEO_CALL: //video call processing
        //            JSONObject dataO = json.getJSONObject("data");
        processVideoCall(message);
        break;

    case AGENT_END_CONVERSATION_CUSTOMER:
        signalingEvents.onAgentEndConversation();
        break;

    case RESPONSE_SERVICE_LIST:
        signalingEvents.onServiceListResponse(data.getServices());
        break;
    }
    /*
    if(json.has("id")) id = json.getString("id");
            
    if(id.equals("registerResponse")){
            
        response = json.getString("response"); //TODO if not accepted what todo?
        String message = json.getString("message");
            
        if(response.equals("accepted"))      {
            socketState = WebSocketConnectionState.REGISTERED;
        }
            
        else if(response.equals("rejected"))      {
            signalingEvents.onChannelError("register rejected: " + message);
        }
            
        else if(response.equals("skipped")) {
            signalingEvents.onChannelError("register rejected: " + message);                                                                       // Log.e(TAG, "registration was skipped because: "+message);
        }
    }
            
    if(id.equals("registeredUsers")){
        response = json.getString("response");
        signalingEvents.onUserListUpdate(response);
    }
            
    if(id.equals("callResponse")){
        response = json.getString("response");
            
        if(response.startsWith("rejected")) {
            Log.d(TAG, "call got rejected: "+response);
            signalingEvents.onChannelClose();
        }else{
            Log.d(TAG, "sending sdpAnswer: "+response);
            SessionDescription sdp = new SessionDescription(
                    SessionDescription.Type.ANSWER,json.getString("sdpAnswer"));
            
            signalingEvents.onRemoteDescription(sdp);
        }
    }
    if(id.equals("callScreenResponse")){
        response = json.getString("response");
            
        if(response.startsWith("rejected")) {
            Log.d(TAG, "call got rejected: "+response);
            signalingEvents.onChannelScreenClose();
        }else{
            Log.d(TAG, "sending sdpAnswer: "+response);
            SessionDescription sdp = new SessionDescription(
                    SessionDescription.Type.ANSWER,json.getString("sdpAnswer"));
            
            signalingEvents.onRemoteScreenDescription(sdp);
        }
    }
            
    if(id.equals("incomingCall")){
        Log.d(TAG, "incomingCall "+json.toString());
        signalingEvents.onIncomingCall(json.getString("from"));
    }
            
    if(id.equals("incomingScreenCall")){
        Log.d(TAG, "incomingScreenCall "+json.toString());
        signalingEvents.onIncomingScreenCall(json);
    }
            
    if(id.equals("startCommunication")){
        Log.d(TAG, "startCommunication "+json.toString());
        SessionDescription sdp = new SessionDescription(SessionDescription.Type.ANSWER,json.getString("sdpAnswer"));
        signalingEvents.onStartCommunication(sdp);
    }
    if(id.equals("startScreenCommunication")){
        Log.d(TAG, "startScreenCommunication "+json.toString());
        SessionDescription sdp = new SessionDescription(SessionDescription.Type.ANSWER,json.getString("sdpAnswer"));
           // signalingEvents.onStartScreenCommunication(sdp); //remove if not needed!
        signalingEvents.onStartScreenCommunication(sdp);
    }
    if(id.equals("stopCommunication")){
        Log.d(TAG, "stopCommunication "+json.toString());
        signalingEvents.onChannelClose();
    }
    if(id.equals("stopScreenCommunication")){
        Log.d(TAG, "stopCommunication "+json.toString());
        signalingEvents.onChannelScreenClose();
    }
    if(id.equals("iceCandidateScreen")){
            
        JSONObject candidateJson = json.getJSONObject("candidate");
            
        IceCandidate candidate = new IceCandidate(
                candidateJson.getString("sdpMid"),
                candidateJson.getInt("sdpMLineIndex"),
                candidateJson.getString("candidate"));
            
        signalingEvents.onRemoteScreenIceCandidate(candidate);
            
    }
    if(id.equals("iceCandidate")){
        Log.d(TAG, "iceCandidate "+json.toString());
            
        JSONObject candidateJson = json.getJSONObject("candidate");
            
        IceCandidate candidate = new IceCandidate(
                candidateJson.getString("sdpMid"),
                candidateJson.getInt("sdpMLineIndex"),
                candidateJson.getString("candidate"));
            
        signalingEvents.onRemoteIceCandidate(candidate);
    }
            
    if (id.equals("stop")) {
        signalingEvents.onChannelClose();
    }
    if (id.equals("stopScreen")) {
        signalingEvents.onChannelScreenClose();
    }
    */
    //    } catch (JSONException e) {
    //      reportError("WebSocket message JSON parsing error: " + e.toString());
    //    }
}

From source file:de.sanandrew.mods.sanlib.lib.util.JsonUtils.java

License:Creative Commons License

public static int getIntVal(JsonElement json) {
    if (json == null || json.isJsonNull()) {
        throw new JsonSyntaxException("Json cannot be null");
    }/*from  w  w w .  j  a  v a  2 s.c  o m*/

    if (!json.isJsonPrimitive()) {
        throw new JsonSyntaxException("Expected value to be a primitive");
    }

    return json.getAsInt();
}

From source file:de.sanandrew.mods.sanlib.lib.util.JsonUtils.java

License:Creative Commons License

public static int getIntVal(JsonElement json, int defVal) {
    if (json == null || !json.isJsonPrimitive()) {
        return defVal;
    }/*w ww  .j  av a2s.  c  o m*/

    return json.getAsInt();
}

From source file:de.unistuttgart.ipvs.pmp.apps.vhike.ctrl.Controller.java

License:Apache License

/**
 * Announce a trip to the web servprintStackTraceice
 * /*from  w  w w  .  jav  a2s. com*/
 * @param session_id
 * @param destination
 * @return TRIP_STATUS_ANNOUNCED, TRIP_STATUS_OPEN_TRIP,STATUS_ERROR
 */
public int announceTrip(final String session_id, final String destination, final float current_lat,
        final float current_lon, final int avail_seats, Date date) {
    Log.i(this, session_id + ", " + destination + ", " + current_lat + ", " + current_lat + ", " + avail_seats);
    String ret = "";
    try {
        if (date == null) {
            ret = this.ws.announceTrip(session_id, destination, current_lat, current_lon, avail_seats, 0);
        } else {
            System.out.println("DATE: " + DateFormat.getDateTimeInstance().format(date.getTime()));
            ret = this.ws.announceTrip(session_id, destination, current_lat, current_lon, avail_seats,
                    date.getTime());
        }
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    JsonObject object = this.parser.parse(ret).getAsJsonObject();

    int tripId = -1;
    JsonElement status = object.get("status");

    if (object != null && object.get(ERROR) == null && status != null) {
        JsonElement id = object.get("id");
        if (status.getAsString().equals("announced") && id != null) {
            tripId = id.getAsInt();
            Model.getInstance().setTripId(tripId);
            Log.d(TAG, String.valueOf(Model.getInstance().getTripId()));
            return Constants.STATUS_SUCCESS;
        }
        if (status.getAsString().equals("open_trip_exists")) {
            return Constants.TRIP_STATUS_OPEN_TRIP;
        }
    } else {
        setError(object);
        return Constants.STATUS_ERROR;
    }
    return Constants.STATUS_ERROR;

}

From source file:de.unistuttgart.ipvs.pmp.apps.vhike.tools.JSonRequestReader.java

License:Apache License

/**
 * Announce a trip to the web service/*from  w w w .jav a 2 s .  c  o m*/
 * 
 * @return true if succeeded
 */
public static String announceTrip(String session_id, String destination, float current_lat, float current_lon,
        int avail_seats, Date date) {
    listToParse.clear();
    listToParse.add(new ParamObject("sid", session_id, false));

    listToParse.add(new ParamObject("destination", destination, true));
    listToParse.add(new ParamObject("avail_seats", String.valueOf(avail_seats), true));
    if (date != null) {
        listToParse.add(new ParamObject("date", String.valueOf(date.getTime()), true));
    }
    if (current_lat < Constants.COORDINATE_INVALID) {
        listToParse.add(new ParamObject("current_lat", String.valueOf(current_lat), true));
    }
    if (current_lon < Constants.COORDINATE_INVALID) {
        listToParse.add(new ParamObject("current_lon", String.valueOf(current_lon), true));
    }

    JsonObject object = null;
    try {
        object = JSonRequestProvider.doRequest(listToParse, "trip_announce.php");
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    int tripId = -1;
    JsonElement status = object.get("status");
    if (object != null && object.get(ERROR) == null && status != null) {
        JsonElement id = object.get("id");
        if (status.getAsString().equals("announced") && id != null) {
            tripId = id.getAsInt();
            Model.getInstance().setTripId(tripId);
            Log.d(TAG, String.valueOf(Model.getInstance().getTripId()));
        }
        return status.getAsString();
    } else {
        setError(object);
        return ERROR;
    }
}

From source file:edu.jhuapl.dorset.agents.ResponseCodeDeserializer.java

License:Open Source License

@Override
public Code deserialize(JsonElement element, Type type, JsonDeserializationContext ctx)
        throws JsonParseException {
    return Code.fromValue(element.getAsInt());
}

From source file:edu.mit.media.funf.probe.builtin.SensorProbe.java

License:Open Source License

protected int getSensorDelay(String specifiedSensorDelay) {
    int sensorDelay = -1;
    JsonElement el = getGson().toJsonTree(specifiedSensorDelay);
    if (!el.isJsonNull()) {
        try {//from  w ww  .j a  v  a  2  s . c om
            int sensorDelayInt = el.getAsInt();
            if (sensorDelayInt == SensorManager.SENSOR_DELAY_FASTEST
                    || sensorDelayInt == SensorManager.SENSOR_DELAY_GAME
                    || sensorDelayInt == SensorManager.SENSOR_DELAY_UI
                    || sensorDelayInt == SensorManager.SENSOR_DELAY_NORMAL) {
                sensorDelay = sensorDelayInt;
            }
        } catch (NumberFormatException e) {
        } catch (ClassCastException e) {
        } catch (IllegalStateException e) {
        }
    }

    if (sensorDelay < 0) {
        try {
            String sensorDelayString = el.getAsString().toUpperCase().replace("SENSOR_DELAY_", "");
            if (SENSOR_DELAY_FASTEST.equals(sensorDelayString)) {
                sensorDelay = SensorManager.SENSOR_DELAY_FASTEST;
            } else if (SENSOR_DELAY_GAME.equals(sensorDelayString)) {
                sensorDelay = SensorManager.SENSOR_DELAY_GAME;
            } else if (SENSOR_DELAY_UI.equals(sensorDelayString)) {
                sensorDelay = SensorManager.SENSOR_DELAY_UI;
            } else if (SENSOR_DELAY_NORMAL.equals(sensorDelayString)) {
                sensorDelay = SensorManager.SENSOR_DELAY_NORMAL;
            }
        } catch (ClassCastException cce) {
            Log.w(LogUtil.TAG, "Unknown sensor delay value: " + specifiedSensorDelay);
        }
    }

    if (sensorDelay < 0) {
        sensorDelay = SensorManager.SENSOR_DELAY_FASTEST;
    }

    return sensorDelay;
}

From source file:ee.ria.xroad.asyncdb.messagequeue.JsonUtils.java

License:Open Source License

static int getIntPropertyValue(JsonObject jsonObject, String memberName) {
    JsonElement jsonElement = jsonObject.get(memberName);

    if (jsonElement == null) {
        return 0;
    }// w w w.  j a v  a  2  s .  c om
    return jsonElement.getAsInt();
}