Example usage for com.google.gson JsonParser parse

List of usage examples for com.google.gson JsonParser parse

Introduction

In this page you can find the example usage for com.google.gson JsonParser parse.

Prototype

@Deprecated
public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException 

Source Link

Usage

From source file:at.tugraz.kmi.medokyservice.fca.util.ImportExport.java

License:Open Source License

public static void main(String[] args) {
    try {//from   ww  w .  java 2 s.  com
        ImportExport ie = new ImportExport(args);
        File io = new File(ie.file);
        if (ie.export) {
            BufferedWriter out = new BufferedWriter(new FileWriter(io, false));
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            JsonParser jp = new JsonParser();
            JsonElement je = jp.parse(ie.export());
            out.write(gson.toJson(je));
            out.close();
        } else {
            BufferedReader in = new BufferedReader(new FileReader(io));
            ie.imPort(new JsonParser().parse(in).getAsJsonObject());
            in.close();
        }
    } catch (Exception e) {
        System.err.println("Error: " + e.getLocalizedMessage());
        e.printStackTrace();
    }
}

From source file:automatizacionrp.obtenerParametros.java

public static Parametros obtenerParametros() {
    log.info("Inicia proceso de obtencin de parmetros");
    try {/*from   ww  w . j  a v a2  s  .  c  o m*/
        pdi = Servicio.queryapp("SELECT  conf.json_config , pe.id_plan_ejecucion , "
                + "jo.job FROM public.config as conf, public.plan_ejecuciones as pe , "
                + "public.pasos_plan_ejecucion as ppe , public.jobs as jo WHERE conf.activo=true "
                + "and elemento='pdi' and pe.id_job=jo.id_job and pe.id_plan_ejecucion=ppe.id_plan_ejecucion "
                + "and ppe.status_plan='en espera' and ppe.activo=true and pe.timestamp_planificacion in "
                + "(SELECT min(pe.timestamp_planificacion) FROM public.config as conf, "
                + "public.plan_ejecuciones as pe , public.pasos_plan_ejecucion as ppe "
                + "WHERE conf.activo=true and elemento='pdi'and pe.id_plan_ejecucion=ppe.id_plan_ejecucion "
                + "and ppe.status_plan='en espera' and ppe.activo=true) and pe.timestamp_planificacion::timestamp <= now()::timestamp LIMIT 1;");

    } catch (Exception e) {
        // TODO Auto-generated catch block
        log.error("Excepcin obteniendo parmetros pdi 1 :");
        log.error(e);
        pdi = "";
    }
    if (pdi.length() <= 2) {
        log.info("No existe planificacion pendiente");
        return param;
    }
    aux = "";
    pdi = pdi.substring(1, pdi.length() - 1);
    JsonParser parser = new JsonParser();
    JsonElement elementObject;
    elementObject = parser.parse(pdi);
    tipo = elementObject.getAsJsonObject().get("job").getAsString();
    id = elementObject.getAsJsonObject().get("id_plan_ejecucion").getAsString();

    try {
        cluster = Servicio.queryapp("SELECT  conf.json_config , pe.id_plan_ejecucion , "
                + "jo.job FROM public.config as conf, public.plan_ejecuciones as pe , "
                + "public.pasos_plan_ejecucion as ppe , public.jobs as jo WHERE conf.activo=true "
                + "and elemento='cluster' and pe.id_job=jo.id_job and pe.id_plan_ejecucion=ppe.id_plan_ejecucion "
                + "and ppe.status_plan='en espera' and ppe.activo=true and pe.timestamp_planificacion in "
                + "(SELECT min(pe.timestamp_planificacion) FROM public.config as conf, "
                + "public.plan_ejecuciones as pe , public.pasos_plan_ejecucion as ppe "
                + "WHERE conf.activo=true and elemento='cluster'and pe.id_plan_ejecucion=ppe.id_plan_ejecucion "
                + "and ppe.status_plan='en espera' and ppe.activo=true) and pe.timestamp_planificacion::timestamp <= now()::timestamp limit 1;");

        bd_pys = Servicio.queryapp("SELECT  conf.json_config , pe.id_plan_ejecucion , jo.job "
                + "FROM public.config as conf, public.plan_ejecuciones as pe , public.pasos_plan_ejecucion as ppe, "
                + "public.jobs as jo WHERE conf.activo=true and elemento='bd_pys' and pe.id_job=jo.id_job "
                + "and pe.id_plan_ejecucion=ppe.id_plan_ejecucion and ppe.status_plan='en espera' and ppe.activo=true "
                + "and pe.timestamp_planificacion in (SELECT min(pe.timestamp_planificacion) FROM public.config as conf,"
                + "public.plan_ejecuciones as pe , public.pasos_plan_ejecucion as ppe WHERE conf.activo=true "
                + "and elemento='bd_pys'and pe.id_plan_ejecucion=ppe.id_plan_ejecucion and ppe.status_plan='en espera' and ppe.activo=true) "
                + "and pe.timestamp_planificacion::timestamp <= now()::timestamp limit 1;");

        tienda = Servicio.queryapp(
                "SELECT t.tienda,t.host_bd_oracle,t.usuario_bd_oracle,t.pass_usuario_bd_oracle,t.bd_oracle\n"
                        + "  FROM public.plan_ejecuciones as pe,public.tiendas as t\n"
                        + "  where pe.id_plan_ejecucion=" + id + " and pe.id_tienda=t.id_tienda;");

    } catch (Exception e) {
        log.error("Excepcin obteniendo parmetros cluster , bd_pys y tienda :");
        log.error(e);
        tienda = "";
        cluster = "";
        bd_pys = "";
    }
    bandera = true;

    if (pdi.length() > 2) {
        if (existeCampo.existeCampo(pdi, "valor")) {
            aux = elementObject.getAsJsonObject().get("valor").getAsString();
            param.setTransformaciones(aux);
        }
        if (existeCampo.existeCampo(pdi, "timestamp_inicio_ejec")) {
            aux = elementObject.getAsJsonObject().get("timestamp_inicio_ejec").getAsString();
            param.setTimestampIni(aux);
        }
        if (existeCampo.existeCampo(pdi, "timestamp_fin_ejec")) {
            aux = elementObject.getAsJsonObject().get("timestamp_fin_ejec").getAsString();
            param.setTimestampFin(aux);
        }
        if (existeCampo.existeCampo(pdi, "id_plan_ejecucion")) {
            aux = elementObject.getAsJsonObject().get("id_plan_ejecucion").getAsString();
            param.setIdplanEjec(aux);
        }
        pdi = elementObject.getAsJsonObject().get("json_config").getAsString();
        elementObject = parser.parse(pdi);
        if (existeCampo.existeCampo(pdi, "directorio_pdi")) {
            aux = elementObject.getAsJsonObject().get("directorio_pdi").getAsString();
            param.setDirPDI(aux);
        }
        if (existeCampo.existeCampo(pdi, "repositorio")) {
            aux = elementObject.getAsJsonObject().get("repositorio").getAsString();
            param.setRepositorio(aux);
        }
        if (existeCampo.existeCampo(pdi, "usuario_repositorio")) {
            aux = elementObject.getAsJsonObject().get("usuario_repositorio").getAsString();
            param.setUsuarioRepositorio(aux);
        }
        if (existeCampo.existeCampo(pdi, "password")) {
            aux = elementObject.getAsJsonObject().get("password").getAsString();
            param.setPassusuarioRepo(aux);
        }
        if (existeCampo.existeCampo(pdi, "directorio_logs")) {
            aux = elementObject.getAsJsonObject().get("directorio_logs").getAsString();
            param.setDirLogs(aux);
        }
        if (existeCampo.existeCampo(pdi, "nivel_logs")) {
            aux = elementObject.getAsJsonObject().get("nivel_logs").getAsString();
            param.setNivelLogs(aux);
        }
        param.setNombreJob(tipo);

        if (bandera) {
            if (existeCampo.existeCampo(pdi, "directorio_job_ci")) {
                aux = elementObject.getAsJsonObject().get("directorio_job_ci").getAsString();
                param.setDirEjecucion(aux);
            }
        } else {
            if (existeCampo.existeCampo(pdi, "directorio_job_m")) {
                aux = elementObject.getAsJsonObject().get("directorio_job_m").getAsString();
                param.setDirEjecucion(aux);
            }
        }

        param.setJobModo("CARGA");
    } else {
        log.warn("No se obtuvieron los valores del PDI");
    }
    if (cluster.length() > 2) {
        aux = "";
        cluster = cluster.substring(1, cluster.length() - 1);
        elementObject = parser.parse(cluster);
        cluster = elementObject.getAsJsonObject().get("json_config").getAsString();
        if (existeCampo.existeCampo(cluster, "nodos")) {
            elementObject = parser.parse(cluster);
            cluster = elementObject.getAsJsonObject().get("nodos").toString();
            cluster = cluster.substring(1, cluster.length() - 1);
            StringTokenizer st = new StringTokenizer(cluster, "}");
            cluster = st.nextToken() + "}";
            elementObject = parser.parse(cluster);
            if (existeCampo.existeCampo(cluster, "host")) {
                aux = elementObject.getAsJsonObject().get("host").getAsString();
                param.setHostbdCassandra(aux);
            }
            if (existeCampo.existeCampo(cluster, "columnFamily")) {
                aux = elementObject.getAsJsonObject().get("columnFamily").getAsString();
                param.setColumnFamily(aux);
            }
            if (existeCampo.existeCampo(cluster, "keyspace")) {
                aux = elementObject.getAsJsonObject().get("keyspace").getAsString();
                param.setKeyspace(aux);
            }
        }
    } else {
        log.warn("No se obtuvieron los valores del cluster");
    }
    if (bd_pys.length() > 2) {
        aux = "";
        bd_pys = bd_pys.substring(1, bd_pys.length() - 1);
        elementObject = parser.parse(bd_pys);
        bd_pys = elementObject.getAsJsonObject().get("json_config").getAsString();
        elementObject = parser.parse(bd_pys);
        if (existeCampo.existeCampo(bd_pys, "host")) {
            aux = elementObject.getAsJsonObject().get("host").getAsString();
            param.setHostbdApp(aux);
        }
        if (existeCampo.existeCampo(bd_pys, "bd")) {
            aux = elementObject.getAsJsonObject().get("bd").getAsString();
            param.setBdApp(aux);
        }
        if (existeCampo.existeCampo(bd_pys, "usuario")) {
            aux = elementObject.getAsJsonObject().get("usuario").getAsString();
            param.setUsuariobdApp(aux);
        }
        if (existeCampo.existeCampo(bd_pys, "password")) {
            aux = elementObject.getAsJsonObject().get("password").getAsString();
            param.setPassusuariobdApp(aux);
        }
    } else {
        log.warn("No se obtuvieron los valores de bd_pys");
    }
    if (tienda.length() > 2) {
        aux = "";
        tienda = tienda.substring(1, tienda.length() - 1);
        elementObject = parser.parse(tienda);

        if (existeCampo.existeCampo(tienda, "usuario_bd_oracle")) {
            aux = elementObject.getAsJsonObject().get("usuario_bd_oracle").getAsString();
            param.setUsuariobdOracle(aux);
        }
        if (existeCampo.existeCampo(tienda, "pass_usuario_bd_oracle")) {
            aux = elementObject.getAsJsonObject().get("pass_usuario_bd_oracle").getAsString();
            param.setPassusuariobdOracle(aux);
        }
        if (existeCampo.existeCampo(tienda, "host_bd_oracle")) {
            aux = elementObject.getAsJsonObject().get("host_bd_oracle").getAsString();
            param.setHostbdOracle(aux);
        }
        if (existeCampo.existeCampo(tienda, "bd_oracle")) {
            aux = elementObject.getAsJsonObject().get("bd_oracle").getAsString();
            param.setBdOracle(aux);
        }
    } else {
        log.warn("No se obtuvieron los valores de las tiendas");
    }
    param.setTipo(tipo);
    return param;
}

From source file:badminton.common.Util.JsonUtil.java

License:Open Source License

/**
 * json?list//from w w w .j a v a 2 s .  c o m
 * 
 * @param json
 * @param tClass
 * @param <T>
 * @return
 */
public static <T> List<T> toList(final String json, final Class<T> tClass) {
    final List<T> result = Lists.newArrayList();

    if (StringUtils.isNotBlank(json)) {
        final JsonParser parser = new JsonParser();
        final JsonArray jsonArray = parser.parse(json).getAsJsonArray();
        jsonArray.forEach(node -> {
            final T cse = GSON.fromJson(node, tClass);
            result.add(cse);
        });
    }

    return result;
}

From source file:be.iminds.iot.dianne.dataset.DatasetConfigurator.java

License:Open Source License

private void parseDatasetConfiguration(File f) {
    try {/*from  w w  w.j av  a2 s .  c o m*/
        // parse any adapter configurations from JSON and apply config?
        JsonParser parser = new JsonParser();
        JsonObject json = parser.parse(new JsonReader(new FileReader(f))).getAsJsonObject();

        String name = json.get("name").getAsString();
        if (name == null)
            return; // should have a name

        Hashtable<String, Object> props = new Hashtable<>();

        String dir = f.getParentFile().getAbsolutePath();
        props.put("dir", dir);

        String pid = null;

        if (json.has("adapter")) {
            String adapter = json.get("adapter").getAsString();
            pid = adapter.contains(".") ? adapter : "be.iminds.iot.dianne.dataset.adapters." + adapter;
            // in case of adapter, set Dataset target: the dataset it is adapting
            String dataset = json.get("dataset").getAsString();
            props.put("Dataset.target", "(name=" + dataset + ")");
        } else if (json.has("type")) {
            String type = json.get("type").getAsString();
            pid = "be.iminds.iot.dianne.dataset." + type;
        } else {
            // some hard coded pids
            if (name.startsWith("MNIST")) {
                pid = "be.iminds.iot.dianne.dataset.MNIST";
            } else if (name.startsWith("CIFAR-100")) {
                pid = "be.iminds.iot.dianne.dataset.CIFAR100";
            } else if (name.startsWith("CIFAR-10")) {
                pid = "be.iminds.iot.dianne.dataset.CIFAR10";
            } else if (name.startsWith("STL-10")) {
                pid = "be.iminds.iot.dianne.dataset.STL10";
            } else if (name.startsWith("SVHN")) {
                pid = "be.iminds.iot.dianne.dataset.SVHN";
            } else if (name.equalsIgnoreCase("ImageNetValidation")) {
                pid = "be.iminds.iot.dianne.dataset.ImageNet.validation";
            } else if (name.equalsIgnoreCase("ImageNetTraining")) {
                pid = "be.iminds.iot.dianne.dataset.ImageNet.training";
            } else {
                pid = "be.iminds.iot.dianne.dataset." + name;
            }
        }

        // set an aiolos instance id using the dataset name to treat
        // equally named datasets as single instance in the network
        props.put("aiolos.instance.id", name);
        // combine all offered interfaces (might be SequenceDataset or ExperiencePool)
        props.put("aiolos.combine", "*");

        // TODO use object conversion from JSON here?
        Configuration config = ca.createFactoryConfiguration(pid, null);
        json.entrySet().stream().forEach(e -> {
            if (e.getValue().isJsonArray()) {
                JsonArray a = e.getValue().getAsJsonArray();
                String[] val = new String[a.size()];
                for (int i = 0; i < val.length; i++) {
                    val[i] = a.get(i).getAsString();
                }
                props.put(e.getKey(), val);
            } else {
                props.put(e.getKey(), e.getValue().getAsString());
            }
        });
        config.update(props);
    } catch (Exception e) {
        System.err.println("Error parsing Dataset config file: " + f.getAbsolutePath());
        e.printStackTrace();
    }
}

From source file:be.iminds.iot.dianne.jsonrpc.DianneRequestHandler.java

License:Open Source License

@Override
public void handleRequest(JsonReader reader, JsonWriter writer) throws IOException {
    try {/*from w w w. ja va 2s.c o  m*/
        JsonParser parser = new JsonParser();
        JsonObject request = parser.parse(reader).getAsJsonObject();
        handleRequest(request, writer);
    } catch (JsonParseException e) {
        e.printStackTrace();
        writeError(writer, null, -32700, "Parse error");
    } catch (IllegalStateException e) {
        // this happens when the client closes the socket and reader returns null
        throw new IOException(e);
    }
}

From source file:be.uantwerpen.dc.studyassistant.StudyAssistant.java

private ArrayList<Environment> getEnvironmentResources() {
    URL url = null;/*from  w  w w  .  j ava  2  s  . c o m*/
    try {
        //url = new URL("https://192.168.2.33:8443/logs");
        url = new URL("https://demo3407181.mockable.io/logs");

    } catch (MalformedURLException ex) {
        Logger.getLogger(StudyAssistant.class.getName()).log(Level.SEVERE, null, ex);
    }

    String jstring = null;
    try {
        jstring = NetworkUtility.request(url, false, false);
    } catch (Exception ex) {
        Logger.getLogger(StudyAssistant.class.getName()).log(Level.SEVERE, null, ex);
    }

    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
    JsonParser parser = new JsonParser();
    JsonArray jArray = parser.parse(jstring).getAsJsonArray();

    ArrayList<Environment> lcs = new ArrayList<Environment>();

    for (JsonElement obj : jArray) {
        Environment cse = gson.fromJson(obj, Environment.class);
        lcs.add(cse);
    }

    return lcs;
}

From source file:be.uantwerpen.dc.studyassistant.StudyAssistant.java

private Environment getLastEnvironmentRecord() {
    URL url = null;/*  www .ja  v a 2  s .  c o m*/
    try {
        //url = new URL("https://192.168.2.33:8443/log");
        url = new URL("https://demo3407181.mockable.io/log");
    } catch (MalformedURLException ex) {
        Logger.getLogger(StudyAssistant.class.getName()).log(Level.SEVERE, null, ex);
    }

    String jstring = null;
    try {
        jstring = NetworkUtility.request(url, false, false);
    } catch (Exception ex) {
        Logger.getLogger(StudyAssistant.class.getName()).log(Level.SEVERE, null, ex);
    }

    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
    JsonParser parser = new JsonParser();
    JsonArray jArray = parser.parse(jstring).getAsJsonArray();

    ArrayList<Environment> lcs = new ArrayList<Environment>();

    for (JsonElement obj : jArray) {
        Environment cse = gson.fromJson(obj, Environment.class);
        lcs.add(cse);
    }

    return lcs.get(0);

}

From source file:blockplus.transport.VirtualClient.java

License:Open Source License

@Override
public void onMessage(final String message) {
    final JsonParser jsonParser = new JsonParser();
    final JsonObject jsonObject = jsonParser.parse(message).getAsJsonObject();
    final String type = jsonObject.get("type").getAsString();
    if (type.equals("game")) {
        final JsonObject data = jsonObject.get("data").getAsJsonObject();
        final int k = data.get("players").getAsInt();
        this.color = Colors.values()[k - 1].toString();
    }//from  w w w  . j av a 2 s. c  o m
    if (type.equals("update")) {
        final JsonObject data = jsonObject.get("data").getAsJsonObject();

        //            System.out.println(data);

        final String color = data.get("color").getAsString();
        if (color.equals(this.color)) {
            if (data.get("isTerminal").getAsBoolean()) {
                System.out.println("Game Over");
            } else {

                final Colors side = Colors.valueOf(this.color);

                final BoardEncoding boardEncoding = new BoardEncoding();
                final Board board = boardEncoding.decode(data.get("board").getAsJsonObject());

                //                    final OptionsEncoding optionsEncoding = new OptionsEncoding();
                //                    final Options options = optionsEncoding.decode(data.get("options").getAsJsonObject());

                final SidesEncoding sidesEncoding = new SidesEncoding();
                final Sides sides = sidesEncoding.decode(data.get("pieces").getAsJsonObject());

                final Context context = new Context(side, sides, board);
                final AI3 ai = new AI3();

                //                    final IPosition position = this.testAI(side, board, options);
                //                    final Set<IPosition> positions = this.moveSupplier(options, position);

                System.out.println();
                System.out.println(side);
                final Set<IPosition> positions = ai.get(context);

                final JsonArray jsonArray = new JsonArray();
                for (final IPosition iPosition : positions)
                    jsonArray.add(new JsonPrimitive(20 * iPosition.row() + iPosition.column() % 20)); // TODO !!!

                final MoveSubmit moveSubmit = new MoveSubmit(jsonArray);

                try {
                    this.send(moveSubmit);
                } catch (final Exception e) {
                }
            }
        }
    }
}

From source file:blusunrize.immersiveengineering.client.models.ModelData.java

public static JsonObject asJsonObject(Map<String, String> map) {
    JsonObject ret = new JsonObject();
    JsonParser parser = new JsonParser();
    for (Entry<String, String> e : map.entrySet()) {
        ret.add(e.getKey(), parser.parse(e.getValue()));
    }/* w ww .  ja v a 2  s . c  o m*/
    return ret;
}

From source file:blusunrize.immersiveengineering.client.models.multilayer.MultiLayerModel.java

@Nonnull
@Override//from   w  w  w.  j  av a  2 s.  com
public IModel process(ImmutableMap<String, String> customData) {
    Map<BlockRenderLayer, List<ModelData>> newSubs = new HashMap<>();
    JsonParser parser = new JsonParser();
    Map<String, String> unused = new HashMap<>();
    for (String layerStr : customData.keySet())
        if (LAYERS_BY_NAME.containsKey(layerStr)) {

            BlockRenderLayer layer = LAYERS_BY_NAME.get(layerStr);
            JsonElement ele = parser.parse(customData.get(layerStr));
            if (ele.isJsonObject()) {
                ModelData data = ModelData.fromJson(ele.getAsJsonObject(), ImmutableList.of(),
                        ImmutableMap.of());
                newSubs.put(layer, ImmutableList.of(data));
            } else if (ele.isJsonArray()) {
                JsonArray array = ele.getAsJsonArray();
                List<ModelData> models = new ArrayList<>();
                for (JsonElement subEle : array)
                    if (subEle.isJsonObject())
                        models.add(ModelData.fromJson(ele.getAsJsonObject(), ImmutableList.of(),
                                ImmutableMap.of()));
                newSubs.put(layer, models);
            }
        } else
            unused.put(layerStr, customData.get(layerStr));
    JsonObject unusedJson = ModelData.asJsonObject(unused);
    for (Entry<BlockRenderLayer, List<ModelData>> entry : newSubs.entrySet())
        for (ModelData d : entry.getValue())
            for (Entry<String, JsonElement> entryJ : unusedJson.entrySet())
                if (!d.data.has(entryJ.getKey()))
                    d.data.add(entryJ.getKey(), entryJ.getValue());
    if (!newSubs.equals(subModels))
        return new MultiLayerModel(newSubs);
    return this;
}