Example usage for com.google.gson JsonElement getAsString

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

Introduction

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

Prototype

public String getAsString() 

Source Link

Document

convenience method to get this element as a string value.

Usage

From source file:co.cask.cdap.internal.app.MapReduceSpecificationCodec.java

License:Apache License

@Override
public MapReduceSpecification deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObj = json.getAsJsonObject();

    String className = jsonObj.get("className").getAsString();
    String name = jsonObj.get("name").getAsString();
    String description = jsonObj.get("description").getAsString();
    int mapperMemoryMB = jsonObj.get("mapperMemoryMB").getAsInt();
    int reducerMemoryMB = jsonObj.get("reducerMemoryMB").getAsInt();
    JsonElement inputDataSetElem = jsonObj.get("inputDataSet");
    String inputDataSet = inputDataSetElem == null ? null : inputDataSetElem.getAsString();
    JsonElement outputDataSetElem = jsonObj.get("outputDataSet");
    String outputDataSet = outputDataSetElem == null ? null : outputDataSetElem.getAsString();

    Set<String> dataSets = deserializeSet(jsonObj.get("datasets"), context, String.class);
    Map<String, String> properties = deserializeMap(jsonObj.get("properties"), context, String.class);

    return new DefaultMapReduceSpecification(className, name, description, inputDataSet, outputDataSet,
            dataSets, properties, mapperMemoryMB, reducerMemoryMB);
}

From source file:co.cask.cdap.internal.app.runtime.artifact.ArtifactRangeCodec.java

License:Apache License

@Override
public ArtifactRange deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    try {/*from w  ww .j av  a 2 s  . com*/
        return ArtifactRange.parse(json.getAsString());
    } catch (InvalidArtifactRangeException e) {
        throw new JsonParseException(e);
    }
}

From source file:co.cask.cdap.notifications.NotificationFeedInfoDeserializer.java

License:Apache License

@Override
public NotificationFeedInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject obj = json.getAsJsonObject();

    String category = obj.get("category").getAsString();
    JsonElement descriptionElement = obj.get("description");
    String description = descriptionElement == null ? "" : descriptionElement.getAsString();

    String namespace;/*  w ww  . j  a v  a 2s  .  com*/
    String feed;
    JsonElement namespaceElement = obj.get("namespace");
    // this means its the old Id.NotificationFeed object where namespace is something like "namespace":{"id":"default"}
    if (namespaceElement.isJsonObject()) {
        namespace = namespaceElement.getAsJsonObject().get("id").getAsString();
        feed = obj.get("name").getAsString();
    } else {
        namespace = namespaceElement.getAsString();
        feed = obj.get("feed").getAsString();
    }

    return new NotificationFeedInfo(namespace, category, feed, description);
}

From source file:co.cask.cdap.proto.codec.EntityIdTypeAdapter.java

License:Apache License

@Override
public EntityId deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject map = json.getAsJsonObject();
    JsonElement entityTypeJson = map.get("entity");
    if (entityTypeJson == null) {
        throw new JsonParseException("Expected entity in EntityId JSON");
    }/*from   w w  w  .  ja v a  2s  .  c  o  m*/

    String entityTypeString = entityTypeJson.getAsString();
    EntityType type = EntityType.valueOf(entityTypeString);
    if (type == null) {
        throw new JsonParseException("Invalid entity: " + entityTypeString);
    }

    return context.deserialize(json, type.getIdClass());
}

From source file:co.cask.cdap.proto.codec.IdTypeAdapter.java

License:Apache License

@Override
public Id deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject map = json.getAsJsonObject();
    JsonElement elementTypeJson = map.get("elementType");
    if (elementTypeJson == null) {
        throw new JsonParseException("Expected elementType in Id JSON");
    }//from  ww w.ja  v  a  2 s.c  o m

    String elementTypeString = elementTypeJson.getAsString();
    EntityType type = EntityType.valueOf(elementTypeString);
    if (type == null) {
        throw new JsonParseException("Invalid elementType: " + elementTypeString);
    }

    return context.deserialize(json, type.getIdClass());
}

From source file:co.cask.cdap.proto.codec.MapReduceSpecificationCodec.java

License:Apache License

@Override
public MapReduceSpecification deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObj = json.getAsJsonObject();

    String className = jsonObj.get("className").getAsString();
    String name = jsonObj.get("name").getAsString();
    String description = jsonObj.get("description").getAsString();
    Resources driverResources = deserializeResources(jsonObj, "driver", context);
    Resources mapperResources = deserializeResources(jsonObj, "mapper", context);
    Resources reducerResources = deserializeResources(jsonObj, "reducer", context);
    JsonElement inputDataSetElem = jsonObj.get("inputDataSet");
    String inputDataSet = inputDataSetElem == null ? null : inputDataSetElem.getAsString();
    JsonElement outputDataSetElem = jsonObj.get("outputDataSet");
    String outputDataSet = outputDataSetElem == null ? null : outputDataSetElem.getAsString();

    Set<String> dataSets = deserializeSet(jsonObj.get("datasets"), context, String.class);
    Map<String, String> properties = deserializeMap(jsonObj.get("properties"), context, String.class);
    return new MapReduceSpecification(className, name, description, inputDataSet, outputDataSet, dataSets,
            properties, driverResources, mapperResources, reducerResources);
}

From source file:co.com.powersoft.lab.databaselab.controller.MaquinaGeneralServlet.java

/**
 * Metodo que permite insertar//  w ww  .j av a2s  . c om
 *
 * @autor Leonardo Solano
 * @param request contiene los datos pasados por AJAX
 * @param response contiene 1 si fue exitoso, 2 si ya existe o 0 si no fue
 * exitoso
 * @exception IOException
 */
public void agregarMaquinaGeneral(HttpServletRequest request, HttpServletResponse response) throws IOException {

    //Nombre de la operacin
    String OPERACION = OperationConstants.AGREGAR_MAQUINA_GENERAL;

    int resp = 0;

    try {

        //Objetos JSON
        String jsonElementos = request.getParameter("jsonElementos") == null ? "{}"
                : request.getParameter("jsonElementos");

        //Validamos que no sea vacio
        if (jsonElementos != null && !jsonElementos.equals("{}")) {

            Gson gson = new Gson();
            JsonObject result = gson.fromJson(jsonElementos, JsonElement.class).getAsJsonObject();
            //Nombre del prefijo del formulario
            String prefijo = "maquina_";

            String idPlanta = request.getParameter("idPlanta") == null ? "0"
                    : HashEncripter.getInstance().desencrypterKey(request.getParameter("idPlanta"));

            //Validamos que exista un idPlanta
            if (!idPlanta.equals("0")) {
                JsonArray arrayCodigo = (JsonArray) result.get(prefijo + "codigo");
                JsonArray arrayNombre = (JsonArray) result.get(prefijo + "nombre");
                JsonArray arrayReferencia = (JsonArray) result.get(prefijo + "referencia");
                JsonArray arrayIdsLineaGeneral = (JsonArray) result.get("idNewLineaGeneral");

                //Organizamos el objeto a agregar
                MaquinaGeneral maquinaGeneral = new MaquinaGeneral();
                for (int i = 0; i < arrayCodigo.size(); i++) {
                    maquinaGeneral.setCodigo(
                            arrayCodigo.get(i).getAsString().isEmpty() ? "" : arrayCodigo.get(i).getAsString());
                    maquinaGeneral.setNombre(
                            arrayNombre.get(i).getAsString().isEmpty() ? "" : arrayNombre.get(i).getAsString());
                    maquinaGeneral.setReferencia(arrayReferencia.get(i).getAsString().isEmpty() ? ""
                            : arrayReferencia.get(i).getAsString());

                    //Planta General
                    PlantaGeneral plantaGeneral = new PlantaGeneral();
                    plantaGeneral.setId(Integer.parseInt(idPlanta));
                    maquinaGeneral.setPlantaGeneral(plantaGeneral);

                    //LineaGeneral asociadas
                    List<LineaGeneral> listaLineaGeneral = new ArrayList<>();

                    if (arrayIdsLineaGeneral != null) {
                        for (JsonElement idLineaGeneral : arrayIdsLineaGeneral) {
                            //Validamos si el codigo es valido
                            if (!idLineaGeneral.getAsString().isEmpty()) {
                                String id = HashEncripter.getInstance()
                                        .desencrypterKey(idLineaGeneral.getAsString());
                                LineaGeneral lineaGeneral = new LineaGeneral(Integer.parseInt(id));
                                listaLineaGeneral.add(lineaGeneral);
                            }
                        }
                    }
                    maquinaGeneral.setListaLineasGeneral(listaLineaGeneral);
                }

                //Agregamos el objeto a la BD
                resp = ServiceFactory.getInstance().getServiceBeanLab().agregarMaquinaGeneral(usuario,
                        maquinaGeneral);
            }
        }

        //Retornamos la respuesta al JSP
        respuestaServer(response, resp);

    } catch (NumberFormatException | JsonSyntaxException | NamingException e) {
        //Retornamos la respuesta al JSP
        respuestaServer(response, resp);
        logger.error(ErrorUtil.getInstance().getErrorData(e, OPERACION, INFO_ADICIONAL), e);
    } catch (Exception e) {
        logger.error(ErrorUtil.getInstance().getErrorData(e, OPERACION, INFO_ADICIONAL), e);
    }
}

From source file:co.com.powersoft.lab.databaselab.controller.MaquinaGeneralServlet.java

/**
 * Metodo que permite modificar//from  w  ww  .  j av  a  2 s .com
 *
 * @autor Leonardo Solano
 * @param request contiene los datos pasados por AJAX
 * @param response contiene 1 si fue exitoso o 0 si no lo fue
 * @exception IOException
 */
public void modificarMaquinaGeneral(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    //Nombre de la operacin
    String OPERACION = OperationConstants.MODIFICAR_MAQUINA_GENERAL;

    int resp = 0;

    try {
        //Objetos JSON
        String jsonElementos = request.getParameter("jsonElementos") == null ? "{}"
                : request.getParameter("jsonElementos");

        //Validamos que no sea vacio
        if (jsonElementos != null && !jsonElementos.equals("{}")) {

            Gson gson = new Gson();
            JsonObject result = gson.fromJson(jsonElementos, JsonElement.class).getAsJsonObject();
            //Nombre del prefijo del formulario
            String prefijo = "maquina_";

            JsonArray arrayIdMaquina = (JsonArray) result.get(prefijo + "idMaquina");
            JsonArray arrayCodigo = (JsonArray) result.get(prefijo + "codigo");
            JsonArray arrayNombre = (JsonArray) result.get(prefijo + "nombre");
            JsonArray arrayReferencia = (JsonArray) result.get(prefijo + "referencia");
            JsonArray arrayIdPlantaGeneral = (JsonArray) result.get(prefijo + "idPlantaNew");
            JsonArray arrayIdsLineaGeneral = (JsonArray) result.get("idNewLineaGeneral");

            //Organizamos el objeto a agregar
            MaquinaGeneral maquinaGeneral = new MaquinaGeneral();
            for (int i = 0; i < arrayIdMaquina.size(); i++) {
                maquinaGeneral.setId(Integer.parseInt(
                        HashEncripter.getInstance().desencrypterKey(arrayIdMaquina.get(i).getAsString())));
                maquinaGeneral.setCodigo(
                        arrayCodigo.get(i).getAsString().isEmpty() ? "" : arrayCodigo.get(i).getAsString());
                maquinaGeneral.setNombre(
                        arrayNombre.get(i).getAsString().isEmpty() ? "" : arrayNombre.get(i).getAsString());
                maquinaGeneral.setReferencia(arrayReferencia.get(i).getAsString().isEmpty() ? ""
                        : arrayReferencia.get(i).getAsString());

                //Planta General
                PlantaGeneral plantaGeneral = new PlantaGeneral();
                plantaGeneral.setId(Integer.parseInt(HashEncripter.getInstance()
                        .desencrypterKey(arrayIdPlantaGeneral.get(i).getAsString())));
                maquinaGeneral.setPlantaGeneral(plantaGeneral);

                //LineaGeneral asociadas
                List<LineaGeneral> listaLineaGeneral = new ArrayList<>();

                if (arrayIdsLineaGeneral != null) {
                    for (JsonElement idLineaGeneral : arrayIdsLineaGeneral) {
                        //Validamos si el codigo es valido
                        if (!idLineaGeneral.getAsString().isEmpty()) {
                            String id = HashEncripter.getInstance()
                                    .desencrypterKey(idLineaGeneral.getAsString());
                            LineaGeneral lineaGeneral = new LineaGeneral(Integer.parseInt(id));
                            listaLineaGeneral.add(lineaGeneral);
                        }
                    }
                }
                maquinaGeneral.setListaLineasGeneral(listaLineaGeneral);
            }

            //Modificamos el objeto a la BD
            resp = ServiceFactory.getInstance().getServiceBeanLab().modificarMaquinaGeneral(usuario,
                    maquinaGeneral);
        }

        //Retornamos la respuesta al JSP
        respuestaServer(response, resp);

    } catch (NumberFormatException | JsonSyntaxException | NamingException e) {
        //Retornamos la respuesta al JSP
        respuestaServer(response, resp);
        logger.error(ErrorUtil.getInstance().getErrorData(e, OPERACION, INFO_ADICIONAL), e);
    } catch (Exception e) {
        //Retornamos la respuesta al JSP
        respuestaServer(response, resp);
        logger.error(ErrorUtil.getInstance().getErrorData(e, OPERACION, INFO_ADICIONAL), e);
    }
}

From source file:co.edu.uniandes.csw.miso4204.reward.service.RewardService.java

License:MIT License

@POST
@Path("/save")
public RewardDTO saveReward(@Context HttpHeaders httpHeaders, RewardDTO reward) {
    try {// w w w .j a v a 2 s.  c o m
        String path = new File(".").getCanonicalPath();
    } catch (Exception e) {
    }
    String token = httpHeaders.getRequestHeader("X_REST_USER").get(0);
    ClientConfig config = new ClientConfig();
    Client client = ClientBuilder.newClient(config);

    String entity = client.target(URL_SERVICIO).path(reward.getBuyerId().toString())
            .request(MediaType.APPLICATION_JSON).header("X_REST_USER", token).get(String.class);

    System.out.println(entity);
    JsonParser parser = new JsonParser();
    JsonObject object = (JsonObject) parser.parse(entity);
    JsonElement column = object.get("id");
    String id = column.getAsString();
    System.out.println(id);
    reward.setBuyerId(Long.parseLong(id));
    createReward(reward);
    return reward;
}

From source file:co.forsaken.projectindigo.utils.mojangtokens.DateTypeAdapter.java

License:Open Source License

@Override
public Date deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    if (!(json instanceof JsonPrimitive)) {
        throw new JsonParseException("The date " + json + " is not a string!");
    }//from   w  w w. java 2 s.c  om
    if (type != Date.class) {
        throw new IllegalArgumentException(getClass() + " cannot deserialize to " + type);
    }
    String value = json.getAsString();
    synchronized (enUsFormat) {
        try {
            return enUsFormat.parse(value);
        } catch (ParseException e) {
            try {
                return iso8601Format.parse(value);
            } catch (ParseException e2) {
                try {
                    String tmp = value.replace("Z", "+00:00");
                    return iso8601Format.parse(tmp.substring(0, 22) + tmp.substring(23));
                } catch (ParseException e3) {
                    throw new JsonSyntaxException("Invalid date " + value, e3);
                }
            }
        }
    }
}