Example usage for com.google.gson JsonObject getAsJsonObject

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

Introduction

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

Prototype

public JsonObject getAsJsonObject(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonObject.

Usage

From source file:PanicDetect.java

License:Apache License

private void listRegex() {
    try {//from  www.  j  a  v a2  s .  c  om
        String result = RunnerRepository.getRPCClient()
                .execute("panicDetectConfig", new Object[] { RunnerRepository.getUser(), "list" }).toString();
        JsonElement jelement = new JsonParser().parse(result);
        JsonObject main = jelement.getAsJsonObject();
        JsonObject regex = main.getAsJsonObject(RunnerRepository.getUser());
        Iterator<Map.Entry<String, JsonElement>> iter = regex.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, JsonElement> n = iter.next();
            String id = n.getKey();
            JsonElement content = n.getValue();
            JsonObject ob = content.getAsJsonObject();
            String exp = ob.get("expression").getAsString();
            String en = ob.get("enabled").getAsString();
            MyPanel panel = new MyPanel(exp, Boolean.parseBoolean(en), id);
            addPanel(panel);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:apim.restful.importexport.utils.APIImportUtil.java

License:Open Source License

/**
 * This method imports an API/*ww w. j a  v  a  2s . c  o  m*/
 *
 * @param pathToArchive            location of the extracted folder of the API
 * @param currentUser              the current logged in user
 * @param isDefaultProviderAllowed decision to keep or replace the provider
 * @throws APIImportException     if there is an error in importing an API
 */
public static void importAPI(String pathToArchive, String currentUser, boolean isDefaultProviderAllowed)
        throws APIImportException {

    API importedApi;

    // If the original provider is preserved,
    if (isDefaultProviderAllowed) {

        FileInputStream inputStream = null;
        BufferedReader bufferedReader = null;

        try {
            inputStream = new FileInputStream(pathToArchive + APIImportExportConstants.JSON_FILE_LOCATION);
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            importedApi = new Gson().fromJson(bufferedReader, API.class);
        } catch (FileNotFoundException e) {
            log.error("Error in locating api.json file. ", e);
            throw new APIImportException("Error in locating api.json file. " + e.getMessage());
        } finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(bufferedReader);
        }
    } else {

        String pathToJSONFile = pathToArchive + APIImportExportConstants.JSON_FILE_LOCATION;

        try {
            String jsonContent = FileUtils.readFileToString(new File(pathToJSONFile));
            JsonElement configElement = new JsonParser().parse(jsonContent);
            JsonObject configObject = configElement.getAsJsonObject();

            //locate the "providerName" within the "id" and set it as the current user
            JsonObject apiId = configObject.getAsJsonObject(APIImportExportConstants.ID_ELEMENT);
            apiId.addProperty(APIImportExportConstants.PROVIDER_ELEMENT,
                    APIUtil.replaceEmailDomain(currentUser));
            importedApi = new Gson().fromJson(configElement, API.class);

        } catch (IOException e) {
            log.error("Error in setting API provider to logged in user. ", e);
            throw new APIImportException("Error in setting API provider to logged in user. " + e.getMessage());
        }
    }

    Set<Tier> allowedTiers;
    Set<Tier> unsupportedTiersList;

    try {
        allowedTiers = provider.getTiers();
    } catch (APIManagementException e) {
        log.error("Error in retrieving tiers of the provider. ", e);
        throw new APIImportException("Error in retrieving tiers of the provider. " + e.getMessage());
    }

    if (!(allowedTiers.isEmpty())) {
        unsupportedTiersList = Sets.difference(importedApi.getAvailableTiers(), allowedTiers);

        //If at least one unsupported tier is found, it should be removed before adding API
        if (!(unsupportedTiersList.isEmpty())) {
            for (Tier unsupportedTier : unsupportedTiersList) {

                //Process is continued with a warning and only supported tiers are added to the importer API
                log.warn("Tier name : " + unsupportedTier.getName() + " is not supported.");
            }

            //Remove the unsupported tiers before adding the API
            importedApi.removeAvailableTiers(unsupportedTiersList);
        }
    }

    try {
        int tenantId = APIUtil.getTenantId(currentUser);
        provider.addAPI(importedApi);
        addSwaggerDefinition(importedApi, pathToArchive, tenantId);
    } catch (APIManagementException e) {
        //Error is logged and APIImportException is thrown because adding API and swagger are mandatory steps
        log.error("Error in adding API to the provider. ", e);
        throw new APIImportException("Error in adding API to the provider. " + e.getMessage());
    }
    //Since Image, documents, sequences and WSDL are optional, exceptions are logged and ignored in implementation
    addAPIImage(pathToArchive, importedApi);
    addAPIDocuments(pathToArchive, importedApi);
    addAPISequences(pathToArchive, importedApi, currentUser);
    addAPIWsdl(pathToArchive, importedApi, currentUser);

}

From source file:application.Genius.java

License:Open Source License

public static ArrayList<Lyrics> search(String query) {
    ArrayList<Lyrics> results = new ArrayList<>();
    query = Normalizer.normalize(query, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+",
            "");// w ww  . j  a  v a  2 s . co m
    JsonObject response = null;
    try {
        URL queryURL = new URL(
                String.format("http://api.genius.com/search?q=%s", URLEncoder.encode(query, "UTF-8")));
        Connection connection = Jsoup.connect(queryURL.toExternalForm())
                .header("Authorization", "Bearer " + Keys.GENIUS).ignoreContentType(true);
        Document document = connection.userAgent(USER_AGENT).get();
        response = new JsonParser().parse(document.text()).getAsJsonObject();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (response == null || response.getAsJsonObject("meta").get("status").getAsInt() != 200)
        return results;
    JsonArray hits = response.getAsJsonObject("response").getAsJsonArray("hits");

    int processed = 0;
    while (processed < hits.size()) {
        JsonObject song = hits.get(processed).getAsJsonObject().getAsJsonObject("result");
        String artist = song.getAsJsonObject("primary_artist").get("name").getAsString();
        String title = song.get("title").getAsString();
        String url = "http://genius.com/songs/" + song.get("id").getAsString();
        Lyrics l = new Lyrics();
        l.mArtist = artist;
        l.mTitle = title;
        l.mSourceUrl = url;
        l.mSource = "Genius";
        results.add(l);
        processed++;
    }
    return results;
}

From source file:at.yawk.buycraft.BuycraftApiImpl.java

License:Mozilla Public License

@Override
public InfoResponse info(String port, String onlineMode, String playerLimit, String version)
        throws IOException {
    Objects.requireNonNull(port);
    Objects.requireNonNull(onlineMode);
    Objects.requireNonNull(playerLimit);
    Objects.requireNonNull(version);
    JsonObject object = get("info",
            new URIBuilder().setParameter("serverPort", port).setParameter("onlineMode", onlineMode)
                    .setParameter("playersMax", playerLimit).setParameter("version", version));
    JsonObject payload = object.getAsJsonObject("payload");
    return new InfoResponse(payload.get("latestVersion").getAsDouble(),
            payload.get("latestDownload").getAsString(), payload.get("serverId").getAsInt(),
            payload.get("serverCurrency").getAsString(), payload.get("serverName").getAsString(),
            payload.get("serverStore").getAsString(), payload.get("updateUsernameInterval").getAsInt(),
            payload.get("onlineMode").getAsBoolean());
}

From source file:at.yawk.buycraft.BuycraftApiImpl.java

License:Mozilla Public License

@Override
public PendingResponse pending() throws IOException {
    JsonObject object = get("pendingUsers");
    List<String> pending = new ArrayList<>();
    JsonObject payload = object.getAsJsonObject("payload");
    payload.getAsJsonArray("pendingPlayers").forEach(ele -> pending.add(ele.getAsString()));
    return new PendingResponse(Collections.unmodifiableCollection(pending),
            payload.get("offlineCommands").getAsBoolean());
}

From source file:at.yawk.buycraft.BuycraftApiImpl.java

License:Mozilla Public License

@Override
public List<Command> commands(String players, String offlineCommands, String offlineCommandLimit)
        throws IOException {
    JsonObject object = get("commands",
            new URIBuilder().setParameter("do", "lookup").setParameter("users", players)
                    .setParameter("offlineCommands", offlineCommands)
                    .setParameter("offlineCommandLimit", offlineCommandLimit));
    List<Command> commands = new ArrayList<>();
    object.getAsJsonObject("payload").getAsJsonArray("commands").forEach(ele -> {
        JsonObject entry = ele.getAsJsonObject();
        Command command = new Command(entry.get("id").getAsInt(), entry.get("ign").getAsString(),
                entry.get("uuid").getAsString(), entry.get("command").getAsString(),
                entry.get("requireOnline").getAsBoolean(), entry.get("requireInventorySlot").getAsInt(),
                entry.get("delay").getAsInt());
        commands.add(command);//  www . j  ava  2 s  . c  o m
    });
    return commands;
}

From source file:bean.EJBean.java

License:Open Source License

public Edificio getEdificio(String id) {

    client = ClientBuilder.newClient();//from w ww.  j av  a2 s  . co m
    String edificio = client.target(baseURI).path("edificios").path(id).request(MediaType.APPLICATION_JSON)
            .get(String.class);
    client.close();

    /// Deserializar///

    GsonBuilder gsonBuilder = new GsonBuilder();

    JsonDeserializer<Edificio> deserializer = new JsonDeserializer<Edificio>() {

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

            Edificio e = new Edificio();

            e.setIdedificio(jsonObject.get("idedificio").getAsString());

            if (jsonObject.has("nombreen")) {
                e.setNombreen(jsonObject.get("nombreen").getAsString());
            }
            if (jsonObject.has("nombrevl")) {
                e.setNombrevl(jsonObject.get("nombrevl").getAsString());
            }
            if (jsonObject.has("nombrees")) {
                e.setNombrees(jsonObject.get("nombrees").getAsString());
            }
            if (jsonObject.has("direccion")) {
                e.setDireccion(jsonObject.get("direccion").getAsString());
            }
            if (jsonObject.has("telefono")) {
                e.setTelefono(jsonObject.get("telefono").getAsString());
            }
            if (jsonObject.has("enlace")) {
                e.setEnlace(jsonObject.get("enlace").getAsString());
            }
            e.setXano(jsonObject.get("xano").getAsString());
            e.setTopleft(jsonObject.get("topleft").getAsString());
            e.setTopright(jsonObject.get("topright").getAsString());
            e.setBottomleft(jsonObject.get("bottomleft").getAsString());

            // System.out.println("Deserializer: Edi Obj: "+e.toString());

            List<Usuario> lu = new ArrayList<Usuario>();
            JsonArray usuariosArray = jsonObject.getAsJsonArray("usuarios");
            for (JsonElement usuario : usuariosArray) {
                Usuario u = new Usuario();
                JsonObject usuarioObj = usuario.getAsJsonObject();
                u.setUsuario(usuarioObj.get("usuario").getAsString());
                lu.add(u);
            }
            // System.out.println("Deserializer: usu Obj: "+e.toString());

            e.setUsuarios(lu);
            // System.out.println("Deserializer: usu Obj: " + e.getUsuarios().size());
            List<Plano> lp = new ArrayList<Plano>();
            JsonArray planoArray = jsonObject.getAsJsonArray("planos");
            for (JsonElement plano : planoArray) {
                Plano p = new Plano();
                PlanoPK pk = new PlanoPK();
                JsonObject planoObj = plano.getAsJsonObject();
                pk.setIdedificio(e.getIdedificio());
                pk.setIdplano(planoObj.get("idplano").getAsString());
                p.setId(pk);
                p.setEnlace(planoObj.get("enlace").getAsString());
                p.setNivel(planoObj.get("nivel").getAsInt());
                Edificio edAux = new Edificio();
                edAux.setIdedificio(edAux.getIdedificio());
                p.setEdificio(edAux);

                lp.add(p);
            }

            e.setPlanos(lp);

            JsonObject coordenadaObj = jsonObject.getAsJsonObject("coordenada");
            Coordenada coordenada = new Coordenada();
            coordenada.setIdcoordenada(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setDescripcion(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setLatitud(coordenadaObj.get("latitud").getAsDouble());
            coordenada.setLongitud(coordenadaObj.get("longitud").getAsDouble());

            e.setCoordenada(coordenada);

            return e;
        }

    };
    gsonBuilder.registerTypeAdapter(Edificio.class, deserializer);

    System.out.println("GSON" + edificio);

    Gson customGson = gsonBuilder.create();
    Edificio jsonToEdificio = customGson.fromJson(edificio, Edificio.class);
    System.out.print("Size users EJB: " + jsonToEdificio.getUsuarios().size());

    return jsonToEdificio;
}

From source file:bean.EJBean.java

License:Open Source License

public Espacio getEspacio(String id) {
    client = ClientBuilder.newClient();/*from  w  w  w  . j  av  a  2s .co  m*/
    String espacio = client.target(baseURI).path("espacios").path(id).request(MediaType.APPLICATION_JSON)
            .get(String.class);
    client.close();

    /// Deserializar///

    //      System.out.println(espacio);

    GsonBuilder gsonBuilder = new GsonBuilder();

    JsonDeserializer<Espacio> deserializer = new JsonDeserializer<Espacio>() {

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

            Espacio e = new Espacio();

            e.setIdespacio(jsonObject.get("idespacio").getAsString());

            if (jsonObject.has("nombreen")) {
                e.setNombreen(jsonObject.get("nombreen").getAsString());
            }
            if (jsonObject.has("nombrevl")) {
                e.setNombrevl(jsonObject.get("nombrevl").getAsString());
            }
            if (jsonObject.has("nombrees")) {
                e.setNombrees(jsonObject.get("nombrees").getAsString());
            }
            if (jsonObject.has("bloque")) {
                e.setBloque(jsonObject.get("bloque").getAsString());
            }
            if (jsonObject.has("piso")) {
                e.setPiso(jsonObject.get("piso").getAsInt());
            }
            if (jsonObject.has("tipo")) {
                e.setTipo(jsonObject.get("tipo").getAsString());
            }
            e.setVisibilidad(jsonObject.get("visibilidad").getAsBoolean());
            if (jsonObject.has("boundingbox")) {
                e.setBoundingbox(jsonObject.get("boundingbox").getAsString());
            }

            // System.out.println("Deserializer: Edi Obj: "+e.toString());
            JsonObject edificioObj = jsonObject.getAsJsonObject("edificio");
            Edificio edificio = new Edificio();
            edificio.setIdedificio(edificioObj.get("idedificio").getAsString());

            e.setEdificio(edificio);

            List<Panorama> lp = new ArrayList<Panorama>();
            JsonArray panoArray = jsonObject.getAsJsonArray("panoramas");
            for (JsonElement pano : panoArray) {
                Panorama p = new Panorama();
                JsonObject panoObj = pano.getAsJsonObject();
                p.setIdpanorama(panoObj.get("idpanorama").getAsString());
                p.setEnlace(panoObj.get("enlace").getAsString());
                lp.add(p);
            }

            e.setPanoramas(lp);

            JsonObject coordenadaObj = jsonObject.getAsJsonObject("coordenada");
            Coordenada coordenada = new Coordenada();
            coordenada.setIdcoordenada(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setDescripcion(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setLatitud(coordenadaObj.get("latitud").getAsDouble());
            coordenada.setLongitud(coordenadaObj.get("longitud").getAsDouble());

            e.setCoordenada(coordenada);

            if (jsonObject.has("profesores")) {
                List<Profesor> lprof = new ArrayList<Profesor>();
                JsonArray profArray = jsonObject.getAsJsonArray("profesores");
                for (JsonElement prof : profArray) {
                    Profesor p = new Profesor();
                    JsonObject profObj = prof.getAsJsonObject();
                    p.setIdprofesor(profObj.get("idprofesor").getAsString());
                    p.setUsuario(profObj.get("usuario").getAsString());
                    p.setVisibilidad(profObj.get("visibilidad").getAsBoolean());

                    lprof.add(p);
                }

                e.setProfesores(lprof);
            }

            return e;
        }

    };
    gsonBuilder.registerTypeAdapter(Espacio.class, deserializer);

    // System.out.println("GSON"+espacio);

    Gson customGson = gsonBuilder.create();
    Espacio jsonToEspacio = customGson.fromJson(espacio, Espacio.class);

    return jsonToEspacio;
}

From source file:bean.EJBean.java

License:Open Source License

public List<Espacio> getEspaciosFromEdificio(String id) {

    client = ClientBuilder.newClient();//from ww w.  ja v a 2 s.  com
    String espaciosJSON = client.target(baseURI).path("edificios").path(id).path("espacios")
            .request(MediaType.APPLICATION_JSON).get(String.class);
    client.close();

    GsonBuilder gsonBuilder = new GsonBuilder();

    JsonDeserializer<Espacio> deserializer = new JsonDeserializer<Espacio>() {

        @Override
        public Espacio deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
            JsonObject jsonObject = json.getAsJsonObject();

            Espacio e = new Espacio();

            // System.out.println("HOLA "+jsonObject.get("bloque").getAsString());

            e.setIdespacio(jsonObject.get("idespacio").getAsString());
            e.setNombrees(jsonObject.get("nombrees").getAsString());
            // e.setNombreen(jsonObject.get("nombreen").getAsString());
            // e.setNombrevl(jsonObject.get("nombrevl").getAsString());
            e.setBloque(jsonObject.get("bloque").getAsString());
            e.setBoundingbox(jsonObject.get("boundingbox").getAsString());
            e.setPiso(jsonObject.get("piso").getAsInt());
            e.setTipo(jsonObject.get("tipo").getAsString());
            e.setVisibilidad(jsonObject.get("visibilidad").getAsBoolean());

            JsonObject coordenadaObj = jsonObject.getAsJsonObject("coordenada");
            Coordenada coordenada = new Coordenada();
            coordenada.setIdcoordenada(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setDescripcion(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setLatitud(coordenadaObj.get("latitud").getAsDouble());
            coordenada.setLongitud(coordenadaObj.get("longitud").getAsDouble());
            e.setCoordenada(coordenada);

            JsonObject edificioObj = jsonObject.getAsJsonObject("edificio");
            Edificio edificio = new Edificio();
            edificio.setIdedificio(edificioObj.get("idedificio").getAsString());
            /*
             * edificio.setNombrees(edificioObj.get("nombrees").getAsString());
             * edificio.setNombreen(edificioObj.get("nombreen").getAsString());
             * edificio.setNombrevl(edificioObj.get("nombrevl").getAsString());
             * edificio.setEnlace(edificioObj.get("enlace").getAsString());
             * edificio.setXano(edificioObj.get("xano").getAsString());
             * edificio.setTopleft(edificioObj.get("topleft").getAsString());
             * edificio.setTopright(edificioObj.get("topright").getAsString());
             * edificio.setBottomleft(edificioObj.get("bottomleft").getAsString());
             */
            e.setEdificio(edificio);

            List<Panorama> lu = new ArrayList<Panorama>();
            JsonArray panoramaArray = jsonObject.getAsJsonArray("panoramas");
            for (JsonElement panorama : panoramaArray) {
                Panorama p = new Panorama();

                JsonObject panoramaObj = panorama.getAsJsonObject();

                p.setIdpanorama(panoramaObj.get("idpanorama").getAsString());
                p.setEnlace(panoramaObj.get("enlace").getAsString());
                if (panoramaObj.has("panorama")) {
                    p.setPanorama(panoramaObj.get("panorama").getAsInt());
                }

                lu.add(p);
            }

            e.setPanoramas(lu);

            List<Profesor> lp = new ArrayList<Profesor>();
            if (jsonObject.has("profesores")) {
                JsonArray profesorArray = jsonObject.getAsJsonArray("profesores");
                for (JsonElement profesor : profesorArray) {
                    Profesor p = new Profesor();

                    JsonObject profesorObj = profesor.getAsJsonObject();
                    p.setIdprofesor(profesorObj.get("idprofesor").getAsString());
                    p.setUsuario(profesorObj.get("usuario").getAsString());
                    p.setVisibilidad(profesorObj.get("visibilidad").getAsBoolean());
                    lp.add(p);
                }
            }
            e.setProfesores(lp);

            return e;
        }

    };
    gsonBuilder.registerTypeAdapter(Espacio.class, deserializer);

    Type listType = new TypeToken<List<Espacio>>() {
    }.getType();

    Gson customGson = gsonBuilder.create();
    List<Espacio> jsonToEspacios = customGson.fromJson(espaciosJSON, listType);

    // System.out.println("Success Espacio: "+ jsonToEspacios.size());

    return jsonToEspacios;

}

From source file:br.unicamp.cst.bindings.soar.SOARPlugin.java

License:Open Source License

public void addBranchToJson(String newBranch, JsonObject json, double value) {
    String[] newNodes = newBranch.split("\\.");
    JsonObject temp;// = new JsonObject();

    if (newNodes.length > 1) {
        if (json.has(newNodes[0])) {
            addBranchToJson(newBranch.substring(newNodes[0].length() + 1), json.getAsJsonObject(newNodes[0]),
                    value);//from w  w  w . j a v a 2 s . c o m
        } else {
            temp = createJsonFromString(newBranch.substring(newNodes[0].length() + 1), value);
            json.add(newNodes[0], temp);
        }
    } else {
        json.addProperty(newNodes[0], value);
    }
}