Example usage for com.google.gson JsonObject get

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

Introduction

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

Prototype

public JsonElement get(String memberName) 

Source Link

Document

Returns the member with the specified name.

Usage

From source file:algorithmi.models.TypeUser.java

License:Apache License

public TypeUser(String data) {

    //Transforma a string recebida pelo pedido http para json
    JsonParser jsonParser = new JsonParser();
    JsonObject UserType = (JsonObject) jsonParser.parse(data);

    //Exibe os dados, em formato json
    System.out.println(UserType.entrySet());
    /**/* w w w . java 2 s . c o m*/
     *
     * Revalidar TUDO, formatos, campos vazios, TUDO!!
     *
     */
    validateData();
    //Associa os dados ao objecto UserType
    this.id_Type = UserType.getAsInt(); //ir buscar o max id da bd + 1 
    this.name = UserType.get("name").getAsString();
    //       
}

From source file:algorithmi.models.User.java

License:Apache License

public User(String data) {

    //Transforma a string recebida pelo pedido http para json
    JsonParser jsonParser = new JsonParser();
    JsonObject user = (JsonObject) jsonParser.parse(data);
    //Exibe os dados, em formato json
    System.out.println(user.entrySet());
    /**//from   w w  w . jav  a  2 s  .co m
     *
     * Revalidar TUDO, formatos, campos vazios, TUDO!!
     *
     */
    validateData();
    //Associa os dados ao objecto User
    this._id = 123; //ir buscar o max id da bd + 1 
    this.name = user.get("name").getAsString();
    //        this.password = user.get("password").getAsString();
    this.imgB64 = user.get("imgB64").getAsString();
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    df.setLenient(false);
    Date dt;
    try {
        dt = df.parse(user.get("dateBirth").getAsString());
    } catch (ParseException ex) {
        dt = new Date();
    }
    this.dateBirth = dt;
    this.email = user.get("email").getAsString();
    this.type = 3;//Definir o tipo de utilizador, como  registo, dever ser do tipo aluno
}

From source file:algorithmi.models.UserCourse.java

License:Apache License

public UserCourse(String data) {

    //Transforma a string recebida pelo pedido http para json
    JsonParser jsonParser = new JsonParser();
    JsonObject UserCourse = (JsonObject) jsonParser.parse(data);
    //Exibe os dados, em formato json
    System.out.println(UserCourse.entrySet());
    /**//from  w  w  w  .j  a v  a2 s.c  o m
     *
     * Revalidar TUDO, formatos, campos vazios, TUDO!!
     *
     */
    validateData();
    //Associa os dados ao objecto UserCourse
    this.user = UserCourse.get("_id").getAsInt();
    ; //ir buscar o max id da bd + 1 
    this.course = UserCourse.get("codCourse").getAsInt();

}

From source file:allout58.mods.techtree.tree.ItemStackGSON.java

License:Open Source License

@Override
public ItemStack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final JsonObject obj = json.getAsJsonObject();
    final String name = obj.get("name").getAsString();
    final Item it = (Item) Item.itemRegistry.getObject(name);
    final int meta = obj.get("meta").getAsInt();
    return new ItemStack(it, 1, meta);
}

From source file:allout58.mods.techtree.tree.TechNodeGSON.java

License:Open Source License

@Override
public TechNode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final JsonObject obj = json.getAsJsonObject();
    final int id = obj.get("id").getAsInt();
    final String name = obj.get("name").getAsString();
    final int science = obj.get("scienceRequired").getAsInt();
    final String description = obj.get("description").getAsString();
    final ItemStack[] items = context.deserialize(obj.get("lockedItems"), ItemStack[].class);

    final TechNode node = new TechNode(id);
    //        ItemStack[] items = new ItemStack[] { new ItemStack(Items.apple), new ItemStack(Items.arrow), new ItemStack(Items.bow) };
    node.setup(name, science, description, items);

    final JsonArray jsonParentArray = obj.getAsJsonArray("parents");
    for (int i = 0; i < jsonParentArray.size(); i++) {
        node.addParentNode(jsonParentArray.get(i).getAsInt());
    }// ww w.java  2 s .  co  m

    return node;
}

From source file:ambari.interaction.NodeController.java

public static ArrayList<ComponentInformation> getListOfNodes() throws Exception {
    String url = "http://127.0.0.1:8080/api/v1/clusters/mycluster/services/HDFS/components/DATANODE?fields=host_components/HostRoles/desired_admin_state,host_components/HostRoles/state";
    String responseJson = HttpURLConnectionExample.sendGet(url);
    System.out.print(responseJson);
    JsonParser jsonParser = new JsonParser();
    JsonElement jsonTree = jsonParser.parse(responseJson);
    ArrayList<ComponentInformation> listOfCompoents = new ArrayList<ComponentInformation>();

    if (jsonTree.isJsonObject()) {
        JsonObject jsonObject = jsonTree.getAsJsonObject();
        JsonElement hostComponents = jsonObject.get("host_components");

        if (hostComponents.isJsonArray()) {
            JsonArray hostComponentsJsonArray = hostComponents.getAsJsonArray();
            System.out.println("\nStart");
            System.out.println(hostComponentsJsonArray);

            for (int i = 0; i < hostComponentsJsonArray.size(); i++) {
                JsonElement hostComponentsElem = hostComponentsJsonArray.get(i);

                if (hostComponentsElem.isJsonObject()) {
                    JsonObject jsonObjectElem = hostComponentsElem.getAsJsonObject();
                    JsonElement hostRolesElem = jsonObjectElem.get("HostRoles");

                    if (hostRolesElem.isJsonObject()) {
                        JsonObject hostRolesObjs = hostRolesElem.getAsJsonObject();
                        JsonElement componentNameElem = hostRolesObjs.get("component_name");
                        JsonElement hostNameElem = hostRolesObjs.get("host_name");
                        JsonElement stateElem = hostRolesObjs.get("state");

                        listOfCompoents.add(new ComponentInformation(componentNameElem.toString(),
                                hostNameElem.toString(), stateElem.toString()));
                    }/*from w ww  .ja v a  2s.c  o m*/
                }
            }
        }
    }

    return listOfCompoents;
}

From source file:angularBeans.realtime.RealTimeInvoker.java

License:Open Source License

public void process(@Observes @DataReceivedEvent RealTimeDataReceiveEvent event) {

    JsonObject jObj = event.getData();
    String UID = jObj.get("session").getAsString();
    String beanName = jObj.get("service").getAsString();
    String method = jObj.get("method").getAsString();
    long reqId = jObj.get("reqId").getAsLong();
    JsonObject paramsObj = jObj.get("params").getAsJsonObject();

    NGSessionScopeContext.setCurrentContext(UID);

    if (reqId == 0) {
        return;/*from   ww w.  j a v  a  2  s .com*/
    }

    Object bean = locator.lookup(beanName, UID);

    remoteInvoker.realTimeInvoke(bean, method, paramsObj, event, reqId, UID);

}

From source file:angularBeans.remote.InvocationHandler.java

License:LGPL

private void genericInvoke(Object service, String methodName, JsonObject params, Map<String, Object> returns,
        long reqID, String UID, HttpServletRequest request)

        throws SecurityException, ClassNotFoundException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, NoSuchMethodException {

    Object mainReturn = null;/*  w ww .j  a va 2  s . c  o m*/
    Method m = null;
    JsonElement argsElem = params.get("args");

    if (reqID > 0) {
        returns.put("reqId", reqID);
    }
    if (argsElem != null) {

        JsonArray args = params.get("args").getAsJsonArray();

        for (Method mt : service.getClass().getMethods()) {

            if (mt.getName().equals(methodName)) {
                m = mt;
                Type[] parameters = mt.getParameterTypes();

                if (parameters.length == args.size()) {

                    List<Object> argsValues = new ArrayList<>();

                    for (int i = 0; i < parameters.length; i++) {

                        Class typeClass;

                        String typeString = ((parameters[i]).toString());

                        if (typeString.startsWith("interface")) {

                            typeString = typeString.substring(10);
                            typeClass = Class.forName(typeString);
                        } else {
                            if (typeString.startsWith("class")) {

                                typeString = typeString.substring(6);
                                typeClass = Class.forName(typeString);
                            } else {
                                typeClass = builtInMap.get(typeString);
                            }
                        }

                        JsonElement element = args.get(i);

                        if (element.isJsonPrimitive()) {

                            String val = element.getAsString();

                            argsValues.add(CommonUtils.convertFromString(val, typeClass));

                        } else if (element.isJsonArray()) {

                            JsonArray arr = element.getAsJsonArray();

                            argsValues.add(util.deserialise(arrayTypesMap.get(typeString), arr));

                        } else {

                            argsValues.add(util.deserialise(typeClass, element));
                        }
                    }

                    if (!CommonUtils.isGetter(mt)) {
                        update(service, params);
                    }

                    try {
                        mainReturn = mt.invoke(service, argsValues.toArray());
                    } catch (Exception e) {
                        handleException(mt, e);
                        e.printStackTrace();
                    }
                }
            }
        }
    } else {

        for (Method mt : service.getClass().getMethods()) {

            if (mt.getName().equals(methodName)) {

                Type[] parameters = mt.getParameterTypes();

                // handling methods that took HttpServletRequest as parameter

                if (parameters.length == 1) {

                    //                   if(mt.getParameters()[0].getType()==HttpServletRequest.class)   
                    //                    {
                    //                      System.out.println("hehe...");
                    //                      mt.invoke(service, request);
                    //                  
                    //                    }

                } else {
                    if (!CommonUtils.isGetter(m)) {
                        update(service, params);
                    }
                    mainReturn = mt.invoke(service);
                }

            }
        }

    }

    ModelQueryImpl qImpl = (ModelQueryImpl) modelQueryFactory.get(service.getClass());

    Map<String, Object> scMap = new HashMap<>(qImpl.getData());

    returns.putAll(scMap);

    qImpl.getData().clear();

    if (!modelQueryFactory.getRootScope().getRootScopeMap().isEmpty()) {
        returns.put("rootScope", new HashMap<>(modelQueryFactory.getRootScope().getRootScopeMap()));
        modelQueryFactory.getRootScope().getRootScopeMap().clear();
    }

    String[] updates = null;

    if (m.isAnnotationPresent(NGReturn.class)) {

        if (mainReturn == null)
            mainReturn = "";

        NGReturn ngReturn = m.getAnnotation(NGReturn.class);
        updates = ngReturn.updates();

        if (ngReturn.model().length() > 0) {
            returns.put(ngReturn.model(), mainReturn);
            Map<String, String> binding = new HashMap<>();

            binding.put("boundTo", ngReturn.model());

            mainReturn = binding;
        }
    }

    if (m.isAnnotationPresent(NGPostConstruct.class)) {
        NGPostConstruct ngPostConstruct = m.getAnnotation(NGPostConstruct.class);
        updates = ngPostConstruct.updates();

    }

    if (updates != null) {
        if ((updates.length == 1) && (updates[0].equals("*"))) {

            List<String> upd = new ArrayList<>();
            for (Method met : service.getClass().getDeclaredMethods()) {

                if (CommonUtils.isGetter(met)) {

                    String fieldName = (met.getName()).substring(3);
                    String firstCar = fieldName.substring(0, 1);
                    upd.add((firstCar.toLowerCase() + fieldName.substring(1)));

                }
            }

            updates = new String[upd.size()];

            for (int i = 0; i < upd.size(); i++) {
                updates[i] = upd.get(i);
            }
        }
    }

    if (updates != null) {
        for (String up : updates) {

            String getterName = GETTER_PREFIX + up.substring(0, 1).toUpperCase() + up.substring(1);
            Method getter;
            try {
                getter = service.getClass().getMethod(getterName);
            } catch (NoSuchMethodException e) {
                getter = service.getClass()
                        .getMethod((getterName.replace(GETTER_PREFIX, BOOLEAN_GETTER_PREFIX)));
            }

            Object result = getter.invoke(service);
            returns.put(up, result);

        }
    }

    returns.put("mainReturn", mainReturn);

    if (!logger.getLogPool().isEmpty()) {
        returns.put("log", logger.getLogPool().toArray());
        logger.getLogPool().clear();
    }
}

From source file:angularBeans.remote.OneWayEndPoint.java

License:Open Source License

private Object process(HttpServletRequest request) {

    String fullPath = request.getRequestURI();
    fullPath = (fullPath.substring(fullPath.indexOf("/service/") + 9));

    String parts[] = fullPath.split("/");

    String beanName = parts[0];//from  w w w . ja va 2  s  . c o  m
    String method = parts[1];

    String params = request.getParameter("params");

    if (request.getMethod().equals("POST")) {
        try {
            StringBuilder buffer = new StringBuilder();
            BufferedReader reader;

            reader = request.getReader();

            String line;

            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            params = buffer.toString();
            // System.out.println(params);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    JsonObject paramsObj = util.parse(params);

    String UID = (paramsObj.get("sessionUID")).getAsString();

    NGSessionScopeContext.setCurrentContext(UID);

    receiveEvents.fire(new OneWayDataReceivedEvent(paramsObj));

    Object result = remoteInvoker.invoke(locator.lookup(beanName, UID), method, paramsObj, UID);

    String jsonResponse = util.getJson(result);

    // System.out.println(jsonResponse);

    return jsonResponse;
}

From source file:angularBeans.remote.RealTimeEndPoint.java

License:Open Source License

@Override
public void init() throws ServletException {
    SockJsServer server = AngularBeansServletContextListener.sockJsServer;
    // Various options can be set on the server, such as:
    // echoServer.options.responseLimit = 4 * 1024;

    // server.options.
    // onConnection is the main entry point for handling SockJS connections
    server.onConnection(new SockJsServer.OnConnectionHandler() {

        @Override//from   w ww. jav a  2  s. c  om
        public void handle(final SockJsConnection connection) {

            // logger.info("session opened");
            // onData gets called when a client sends data to the server
            connection.onData(new SockJsConnection.OnDataHandler() {
                @Override
                public void handle(String message) {

                    JsonObject jObj = CommonUtils.parse(message).getAsJsonObject();
                    String UID = null;

                    if (jObj.get("session") == null) {
                        UID = SessionMapper.getHTTPSessionID(connection.id);
                    } else {
                        UID = jObj.get("session").getAsString();
                        SessionMapper.getSessionsMap().put(UID, new HashSet<String>());

                    }
                    SessionMapper.getSessionsMap().get(UID).add(connection.id);

                    RealTimeDataReceivedEvent ev = new RealTimeDataReceivedEvent(connection, jObj);

                    ev.setConnection(connection);
                    ev.setSessionId(UID);
                    NGSessionScopeContext.setCurrentContext(UID);

                    String service = jObj.get("service").getAsString();

                    if (service.equals("ping")) {

                        sessionOpenEvent.fire(ev);
                        logger.info("AngularBeans-client: " + UID);

                    } else {

                        receiveEvents.fire(ev);

                    }

                    // connection.write(message);
                }
            });

            // onClose gets called when a client disconnects
            connection.onClose(new SockJsConnection.OnCloseHandler() {
                @Override
                public void handle() {

                    getServletContext().log("Realtime client disconnected..");
                }
            });
        }
    });

    server.options.websocket = true;

    setServer(server);

    // Don't forget to call super.init() to wire everything up
    super.init();

}