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:io.kodokojo.endpoint.dto.WebSocketMessageGsonAdapter.java

License:Open Source License

@Override
public WebSocketMessage deserialize(JsonElement input, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject json = (JsonObject) input;
    JsonPrimitive jsonEntity = json.getAsJsonPrimitive("entity");
    if (jsonEntity == null) {
        throw new JsonParseException("entity attribute expected.");
    }//from  w w  w.j  ava 2 s .c  o m
    String entity = jsonEntity.getAsString();
    JsonPrimitive jsonAction = json.getAsJsonPrimitive("action");
    if (jsonAction == null) {
        throw new JsonParseException("action attribute expected.");
    }
    String action = jsonAction.getAsString();
    JsonObject jsonData = json.getAsJsonObject("data");
    if (jsonData == null) {
        throw new JsonParseException("data attribute expected.");
    }

    return new WebSocketMessage(entity, action, jsonData);
}

From source file:io.kodokojo.endpoint.UserSparkEndpoint.java

License:Open Source License

@Override
public void configure() {
    post(BASE_API + "/user/:id", JSON_CONTENT_TYPE, ((request, response) -> {
        String identifier = request.params(":id");
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Try to create user with id {}", identifier);
        }/*from  w w  w.j a v  a 2  s.c  o  m*/
        if (userStore.identifierExpectedNewUser(identifier)) {
            JsonParser parser = new JsonParser();
            JsonObject json = (JsonObject) parser.parse(request.body());
            String email = json.getAsJsonPrimitive("email").getAsString();

            String username = email.substring(0, email.lastIndexOf("@"));
            User userByUsername = userStore.getUserByUsername(username);
            if (userByUsername != null) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Trying to create user {} from email '{}' who already exist.", username,
                            email);
                }
                halt(409);
                return "";
            }

            String entityName = email;
            if (json.has("entity") && StringUtils.isNotBlank(json.getAsJsonPrimitive("entity").getAsString())) {
                entityName = json.getAsJsonPrimitive("entity").getAsString();
            }

            String password = new BigInteger(130, new SecureRandom()).toString(32);
            KeyPair keyPair = RSAUtils.generateRsaKeyPair();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

            User user = new User(identifier, username, username, email, password,
                    RSAUtils.encodePublicKey((RSAPublicKey) keyPair.getPublic(), email));

            String entityId = null;
            SimpleCredential credential = extractCredential(request);
            if (credential != null) {
                User userRequester = userAuthenticator.authenticate(credential);
                if (userRequester != null) {
                    entityId = entityStore.getEntityIdOfUserId(userRequester.getIdentifier());
                }
            }
            if (entityId == null) {
                Entity entity = new Entity(entityName, user);
                entityId = entityStore.addEntity(entity);
            }
            entityStore.addUserToEntity(identifier, entityId);

            user = new User(identifier, entityId, username, username, email, password, user.getSshPublicKey());

            if (userStore.addUser(user)) {

                response.status(201);
                StringWriter sw = new StringWriter();
                RSAUtils.writeRsaPrivateKey(privateKey, sw);
                response.header("Location", "/user/" + user.getIdentifier());
                UserCreationDto userCreationDto = new UserCreationDto(user, sw.toString());

                if (emailSender != null) {
                    List<String> cc = null;
                    if (credential != null) {
                        User userRequester = userAuthenticator.authenticate(credential);
                        if (userRequester != null) {
                            cc = Collections.singletonList(userRequester.getEmail());
                        }
                    }
                    String content = "<h1>Welcome on Kodo Kojo</h1>\n"
                            + "<p>You will find all information which is bind to your account '"
                            + userCreationDto.getUsername() + "'.</p>\n" + "\n" + "<p>Password : <b>"
                            + userCreationDto.getPassword() + "</b></p>\n"
                            + "<p>Your SSH private key generated:\n" + "<br />\n"
                            + userCreationDto.getPrivateKey() + "\n" + "</p>\n"
                            + "<p>Your SSH public key generated:\n" + "<br />\n"
                            + userCreationDto.getSshPublicKey() + "\n" + "</p>";
                    emailSender.send(Collections.singletonList(userCreationDto.getEmail()), null, cc,
                            "User creation on Kodo Kojo " + userCreationDto.getName(), content, true);
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Mail with user data send to {}.", userCreationDto.getEmail());
                        if (LOGGER.isTraceEnabled()) {
                            LOGGER.trace("Email to {} content : \n {}", userCreationDto.getEmail(), content);
                        }
                    }
                }

                return userCreationDto;
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("The UserStore not abel to add following user {}.", user.toString());
            }
            halt(428);
            return "";
        } else {
            halt(412);
            return "";
        }
    }), jsonResponseTransformer);

    post(BASE_API + "/user", JSON_CONTENT_TYPE, (request, response) -> {
        String res = userStore.generateId();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Generate id : {}", res);
        }
        return res;
    });

    get(BASE_API + "/user", JSON_CONTENT_TYPE, (request, response) -> {
        SimpleCredential credential = extractCredential(request);
        if (credential != null) {
            User user = userStore.getUserByUsername(credential.getUsername());
            if (user == null) {
                halt(404);
                return "";
            }
            return getUserDto(user);
        }
        halt(401);
        return "";
    }, jsonResponseTransformer);

    get(BASE_API + "/user/:id", JSON_CONTENT_TYPE, (request, response) -> {
        SimpleCredential credential = extractCredential(request);
        String identifier = request.params(":id");
        User requestUser = userStore.getUserByUsername(credential.getUsername());
        User user = userStore.getUserByIdentifier(identifier);
        if (user != null) {
            if (user.getEntityIdentifier().equals(requestUser.getEntityIdentifier())) {
                if (!user.getUsername().equals(credential.getUsername())) {
                    user = new User(user.getIdentifier(), user.getName(), user.getUsername(), user.getEmail(),
                            "", user.getSshPublicKey());
                }
                return getUserDto(user);
            }
            halt(403, "You aren't in same entity.");
            return "";
        }
        halt(404);
        return "";
    }, jsonResponseTransformer);
}

From source file:io.kodokojo.endpoint.WebSocketEntryPoint.java

License:Open Source License

@OnWebSocketMessage
public void message(Session session, String message) throws IOException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Receive following message: {}", message);
    }//from   w w w.  java 2 s. c om
    LOGGER.info("Receive following message: {}", message);
    UserSession userSession = sessionIsValidated(session);
    if (userSession == null) {
        Long connectDate = sessions.get(session);
        long delta = (connectDate + USER_VALIDATION_TIMEOUT) - System.currentTimeMillis();
        if (delta < 0) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Session of user wait for to many times....");
            }
            session.close(); // To late to connect.
        } else {
            Gson gson = localGson.get();
            WebSocketMessage webSocketMessage = gson.fromJson(message, WebSocketMessage.class);
            JsonObject data = null;
            if ("user".equals(webSocketMessage.getEntity())
                    && "authentication".equals(webSocketMessage.getAction())
                    && webSocketMessage.getData().has("authorization")) {
                data = webSocketMessage.getData();
                String encodedAutorization = data.getAsJsonPrimitive("authorization").getAsString();
                if (encodedAutorization.startsWith("Basic ")) {
                    String encodedCredentials = encodedAutorization.substring("Basic ".length());
                    String decoded = new String(Base64.getDecoder().decode(encodedCredentials));
                    String[] credentials = decoded.split(":");
                    if (credentials.length != 2) {
                        sessions.remove(session);
                        session.close(1008, "Authorization value in data mal formatted");
                    } else {
                        User user = userStore.getUserByUsername(credentials[0]);
                        if (user == null) {
                            sessions.remove(session);
                            session.close(4401, "Invalid credentials for user '" + credentials[0] + "'.");
                        } else {
                            if (user.getPassword().equals(credentials[1])) {
                                userConnectedSession.put(user.getIdentifier(), new UserSession(session, user));
                                sessions.remove(session);
                                JsonObject dataValidate = new JsonObject();
                                dataValidate.addProperty("message", "success");
                                dataValidate.addProperty("identifier", user.getIdentifier());
                                WebSocketMessage response = new WebSocketMessage("user", "authentication",
                                        dataValidate);
                                String responseStr = gson.toJson(response);
                                session.getRemote().sendString(responseStr);
                                if (LOGGER.isDebugEnabled()) {
                                    LOGGER.debug("Send following message to user {} : {}", user.getUsername(),
                                            responseStr);
                                }
                                LOGGER.info("Send welcome message to user {} : {}", user.getUsername(),
                                        responseStr);
                            } else {
                                sessions.remove(session);
                                session.close(4401, "Invalid credentials.");

                            }
                        }
                    }
                } else {
                    sessions.remove(session);
                    session.close(1008,
                            "Authentication value in data attribute mal formatted : " + data.toString());
                }
            } else {
                sessions.remove(session);
                session.close();
            }
        }
    } else {
        userSession.setLastActivityDate(System.currentTimeMillis());
        LOGGER.debug("Receive following message from user '{}'.", userSession.getUser().getName());
    }
}

From source file:io.motown.operatorapi.json.gson.deserializer.AddressTypeAdapterDeserializer.java

License:Apache License

@Override
public Address deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) {
    JsonObject obj;

    try {//  ww w  .  j a v a 2  s . c  o  m
        obj = jsonElement.getAsJsonObject();
        if (obj == null) {
            return null;
        }
    } catch (ClassCastException | IllegalStateException e) {
        throw new JsonParseException("Address must be a JSON object", e);
    }

    String addressLine1 = obj.getAsJsonPrimitive("addressLine1").getAsString();
    String city = obj.getAsJsonPrimitive("city").getAsString();
    String country = obj.getAsJsonPrimitive("country").getAsString();

    JsonPrimitive addressLine2Obj = obj.getAsJsonPrimitive("addressLine2"),
            postalCodeObj = obj.getAsJsonPrimitive("postalCode"), regionObj = obj.getAsJsonPrimitive("region");

    String addressLine2 = addressLine2Obj != null ? addressLine2Obj.getAsString() : "";
    String postalCode = postalCodeObj != null ? postalCodeObj.getAsString() : "";
    String region = regionObj != null ? regionObj.getAsString() : "";

    return new Address(addressLine1, addressLine2, postalCode, city, region, country);
}

From source file:io.motown.operatorapi.json.gson.deserializer.CoordinatesTypeAdapterDeserializer.java

License:Apache License

@Override
public Coordinates deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) {
    JsonObject obj;

    try {/*from ww w .  ja  va  2 s.com*/
        obj = jsonElement.getAsJsonObject();
        if (obj == null) {
            return null;
        }
    } catch (ClassCastException | IllegalStateException e) {
        throw new JsonParseException("Coordinates must be a JSON object", e);
    }

    double latitude = obj.getAsJsonPrimitive("latitude").getAsDouble();
    double longitude = obj.getAsJsonPrimitive("longitude").getAsDouble();

    return new Coordinates(latitude, longitude);
}

From source file:io.motown.operatorapi.json.gson.deserializer.OpeningTimeTypeAdapterDeserializer.java

License:Apache License

@Override
public OpeningTime deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) {
    JsonObject obj;

    try {/*from   w  ww  .ja  v  a 2 s.c  om*/
        obj = jsonElement.getAsJsonObject();
        if (obj == null) {
            return null;
        }
    } catch (ClassCastException | IllegalStateException e) {
        throw new JsonParseException("OpeningTime must be a valid JSON object", e);
    }

    Day day = Day.fromValue(obj.getAsJsonPrimitive("day").getAsString());
    String timeStartStr = obj.getAsJsonPrimitive("timeStart").getAsString();
    String timeStopStr = obj.getAsJsonPrimitive("timeStop").getAsString();

    TimeOfDay timeStart;
    TimeOfDay timeStop;

    Matcher start = TIME_OF_DAY.matcher(timeStartStr);
    Matcher stop = TIME_OF_DAY.matcher(timeStopStr);
    if (start.matches() && stop.matches()) {
        timeStart = new TimeOfDay(Integer.parseInt(start.group(HOUR_GROUP)),
                Integer.parseInt(start.group(MINUTES_GROUP)));
        timeStop = new TimeOfDay(Integer.parseInt(stop.group(HOUR_GROUP)),
                Integer.parseInt(stop.group(MINUTES_GROUP)));
    } else {
        throw new JsonParseException("timeStart and timeStop must be a valid 24-hour time (00:00 - 23:59)");
    }

    return new OpeningTime(day, timeStart, timeStop);
}

From source file:io.motown.operatorapi.json.gson.deserializer.TextualTokenTypeAdapterDeserializer.java

License:Apache License

@Override
public TextualToken deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
    JsonObject obj;
    String token;//from   ww w .j a v  a2  s. c  o  m

    try {
        obj = json.getAsJsonObject();
    } catch (ClassCastException | IllegalStateException e) {
        throw new JsonParseException("TextualToken must be a JSON object", e);
    }

    try {
        token = obj.getAsJsonPrimitive(TOKEN_MEMBER) != null
                ? obj.getAsJsonPrimitive(TOKEN_MEMBER).getAsString()
                : "";
    } catch (ClassCastException | IllegalStateException e) {
        throw new JsonParseException("token must be a JSON string", e);
    }

    try {
        JsonPrimitive authenticationStatus = obj.getAsJsonPrimitive("status");
        if (authenticationStatus != null) {
            String status = authenticationStatus.getAsString();
            return new TextualToken(token, IdentifyingToken.AuthenticationStatus.valueOf(status));
        }
    } catch (ClassCastException | IllegalStateException e) {
        throw new JsonParseException("status must be a JSON string", e);
    }

    return new TextualToken(token);
}

From source file:io.urmia.md.model.job.JobStatus.java

License:Open Source License

public JobStatus(String json, Stats stats) {

    JsonObject rootObj = parser.parse(json).getAsJsonObject();

    this.id = rootObj.getAsJsonPrimitive("id").getAsString();
    this.phases = JobDefinition.Phase.fromJsonArray(rootObj.getAsJsonArray("phases"));

    this.timeCreated = fromISO8601ToMillis(rootObj.getAsJsonPrimitive("timeCreated").getAsString());
    this.timeDone = fromISO8601ToMillis(rootObj.getAsJsonPrimitive("timeDone").getAsString());
    this.timeArchiveStarted = fromISO8601ToMillis(
            rootObj.getAsJsonPrimitive("timeArchiveStarted").getAsString());
    this.timeArchiveDone = fromISO8601ToMillis(rootObj.getAsJsonPrimitive("timeArchiveDone").getAsString());

    this.stats = stats;
}

From source file:io.webfolder.cdp.session.WSAdapter.java

License:Open Source License

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void onTextMessage(final WebSocket websocket, final String data) throws Exception {
    executor.execute(() -> {// w w w .j a va  2s .c o m
        log.debug(data);
        JsonElement json = gson.fromJson(data, JsonElement.class);
        JsonObject object = json.getAsJsonObject();
        JsonElement idElement = object.get("id");
        if (idElement != null) {
            String id = idElement.getAsString();
            if (id != null) {
                int valId = (int) parseDouble(id);
                WSContext context = contextList.get(valId);
                if (context != null) {
                    JsonObject error = object.getAsJsonObject("error");
                    if (error != null) {
                        int code = (int) error.getAsJsonPrimitive("code").getAsDouble();
                        String message = error.getAsJsonPrimitive("message").getAsString();
                        context.setError(new CommandException(code, message));
                    } else {
                        context.setData(json);
                    }
                }
            }
        } else {
            JsonElement method = object.get("method");
            if (method != null && method.isJsonPrimitive()) {
                String eventName = method.getAsString();
                if ("Inspector.detached".equals(eventName) && session != null) {
                    if (session != null) {
                        Thread thread = new Thread(new TerminateSession(session, object));
                        thread.setName("cdp4j-terminate");
                        thread.setDaemon(true);
                        thread.start();
                        session = null;
                    }
                } else {
                    Events event = events.get(eventName);
                    if (event != null) {
                        JsonElement params = object.get("params");
                        Object value = gson.fromJson(params, event.klass);
                        for (EventListener next : eventListeners) {
                            executor.execute(() -> {
                                next.onEvent(event, value);
                            });
                        }
                    }
                }
            }
        }
    });
}

From source file:io.winterdev.server.SmsManager.java

public boolean sendSms(String num, String text) {

    try {//from  w  ww  .  j av  a 2  s.  c o  m
        JsonObject response = ApiGetter.get("https://rest.nexmo.com/sms/json?api_key=" + Private.NEXMO_KEY
                + "&api_secret=" + Private.NEXMO_SECRET + "&to=" + num + "&text=" + text + "&from="
                + Private.NEXMO_NUMBER);
        JsonObject messages = response.getAsJsonArray("messages").get(0).getAsJsonObject();
        JsonPrimitive status = messages.getAsJsonPrimitive("status");
        if (status.getAsString().equalsIgnoreCase("0"))
            return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}