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:com.bedatadriven.rebar.appcache.server.DefaultSelectionServlet.java

License:Apache License

private String computePermutation(HttpServletRequest req, JsonArray permutationMap) throws ServletException {

    Map<String, String> properties = computeProperties(req);
    Set<String> matches = new HashSet<>();

    for (int i = 0; i != permutationMap.size(); ++i) {
        JsonObject permutation = (JsonObject) permutationMap.get(i);
        if (matches(properties, permutation)) {
            matches.add(permutation.get("permutation").getAsString());
        }/*w w  w  . j av a 2s.  c  om*/
    }

    if (matches.size() == 1) {
        return matches.iterator().next();
    } else {
        return null;
    }
}

From source file:com.bedatadriven.rebar.appcache.server.DefaultSelectionServlet.java

License:Apache License

private boolean matches(Map<String, String> properties, JsonObject permutation) {
    String strongName = permutation.get("permutation").getAsString();
    JsonObject permProperties = permutation.getAsJsonObject("properties");
    for (Map.Entry<String, JsonElement> property : permProperties.entrySet()) {
        String expected = property.getValue().getAsString();
        String actual = properties.get(property.getKey());
        if (actual != null && !expected.equals(actual)) {
            logger.finest("Rejecting " + strongName + ", expected property '" + property.getValue() + "' "
                    + "with value '" + expected + "', found '" + actual + "'");
            return false;
        }/*from  w ww .  j ava  2  s  .c  o m*/
    }
    return true;
}

From source file:com.bekwam.resignator.model.ConfigurationJSONAdapter.java

License:Apache License

@Override
public Configuration deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {

    if (logger.isDebugEnabled()) {
        logger.debug("[DESERIALIZE]");
    }//from  ww  w .j a  va  2  s . c o  m

    JsonObject obj = (JsonObject) jsonElement;

    JsonElement apElement = obj.get("activeProfile");
    String ap = "";
    if (apElement != null) {
        ap = apElement.getAsString();
    }

    JsonElement jdkElem = obj.get("jdkHome");
    String jdkHome = "";
    if (jdkElem != null) {
        jdkHome = jdkElem.getAsString();
    }

    JsonElement hpElem = obj.get("hashedPassword");
    String hp = "";
    if (hpElem != null) {
        hp = hpElem.getAsString();
    }

    JsonElement ludElem = obj.get("lastUpdatedDate");
    String lud = "";
    LocalDateTime lastUpdatedDate = null;
    if (ludElem != null) {
        lud = ludElem.getAsString();
        if (StringUtils.isNotEmpty(lud)) {
            lastUpdatedDate = LocalDateTime.parse(lud, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        }
    }

    JsonArray recentProfiles = obj.getAsJsonArray("recentProfiles");
    JsonArray profiles = obj.getAsJsonArray("profiles");

    if (logger.isDebugEnabled()) {
        logger.debug("[DESERIALIZE] rp={}, ap={}, jdkHome={}, keytool={}, profiles={}",
                recentProfiles.toString(), ap, jdkHome, profiles.toString());
    }

    Configuration conf = new Configuration();
    conf.setActiveProfile(Optional.of(ap));
    conf.setJDKHome(Optional.of(jdkHome));
    conf.getRecentProfiles().addAll(deserializeRecentProfiles(recentProfiles));
    conf.getProfiles().addAll(deserializeProfiles(profiles));
    conf.setHashedPassword(Optional.of(hp));
    conf.setLastUpdatedDateTime(Optional.ofNullable(lastUpdatedDate));
    return conf;
}

From source file:com.bekwam.resignator.model.ConfigurationJSONAdapter.java

License:Apache License

private List<Profile> deserializeProfiles(JsonArray profiles) {

    List<Profile> ps = new ArrayList<>();

    for (JsonElement e : profiles) {

        JsonObject profileObj = (JsonObject) e;
        String profileName = profileObj.get("profileName").getAsString();

        Boolean rs = Boolean.FALSE;
        if (profileObj.get("replaceSignatures") != null) {
            rs = profileObj.get("replaceSignatures").getAsBoolean();
        }/*from   w  ww.  j a va  2  s . c om*/

        SigningArgumentsType argsType = SigningArgumentsType.JAR;
        if (profileObj.get("argsType") != null) {
            String at = profileObj.get("argsType").getAsString();
            if (StringUtils.equalsIgnoreCase(at, String.valueOf(SigningArgumentsType.FOLDER))) {
                argsType = SigningArgumentsType.FOLDER;
            }
        }

        Profile p = new Profile(profileName, rs, argsType);

        //
        // SourceFile part
        //
        JsonObject sourceObj = profileObj.getAsJsonObject("sourceFile");
        if (sourceObj != null) {
            JsonElement sfe = sourceObj.get("fileName");
            if (sfe != null) {
                SourceFile sf = new SourceFile(sfe.getAsString());
                p.setSourceFile(Optional.of(sf));
            }
        }

        //
        // TargetFile part
        //
        JsonObject targetObj = profileObj.getAsJsonObject("targetFile");
        if (sourceObj != null) {
            JsonElement tfe = targetObj.get("fileName");
            if (tfe != null) {
                TargetFile tf = new TargetFile(tfe.getAsString());
                p.setTargetFile(Optional.of(tf));
            }
        }

        //
        // JarsignerConfig part
        //
        JsonObject jcObj = profileObj.getAsJsonObject("jarsignerConfig");
        if (jcObj != null) {

            String alias = "";
            String storepass = "";
            String keypass = "";
            String keystore = "";
            Boolean verbose = false;

            JsonElement ae = jcObj.get("alias");
            if (ae != null) {
                alias = ae.getAsString();
            }

            JsonElement spe = jcObj.get("storepass");
            if (spe != null) {
                storepass = spe.getAsString();
            }

            JsonElement kpe = jcObj.get("keypass");
            if (kpe != null) {
                keypass = kpe.getAsString();
            }

            JsonElement kse = jcObj.get("keystore");
            if (kse != null) {
                keystore = kse.getAsString();
            }

            JsonElement ve = jcObj.get("verbose");
            if (ve != null) {
                verbose = ve.getAsBoolean();
            }

            JarsignerConfig jc = new JarsignerConfig(alias, "", "", keystore, verbose);
            jc.setEncryptedKeypass(keypass);
            jc.setEncryptedStorepass(storepass);

            p.setJarsignerConfig(Optional.of(jc));
        }

        ps.add(p);
    }

    return ps;
}

From source file:com.betafase.mcmanager.api.SpigotUpdateChecker.java

@Override
public UpdateInfo checkUpdate() {
    ServerRequest r = new ServerRequest("resources/" + spigot_id + "/versions?sort=-name");
    JsonElement e = r.getAsJsonElement();
    if (e.isJsonArray()) {
        JsonObject current = e.getAsJsonArray().get(0).getAsJsonObject();
        String version = current.get("name").getAsString();
        if (!version.equalsIgnoreCase(plugin.getDescription().getVersion())) {
            UpdateInfo info = new UpdateInfo(plugin, null, version, "8Update found via SpigotUpdater",
                    current.has("url") ? current.get("url").getAsString() : null) {
                @Override//from  w  w  w  .j av a 2 s  . com
                public void performUpdate(Player notifier) {
                    SpigetPlugin d = new SpigetPlugin(spigot_id);
                    d.loadInformation();
                    if (d.hasDirectDownload()) {
                        notifier.sendMessage(
                                "aCached Download from spiget.org found. Downloading directly...");
                        d.downloadDirectly(notifier, "plugins/" + getJarName());
                    } else if (d.isExternalDownload()) {
                        notifier.sendMessage(
                                "clError elThis Plugin has an external download. You must download it manually: "
                                        + d.getDownloadURL());
                    } else {
                        notifier.sendMessage("aDownload started. Please wait...");
                        notifier.performCommand("wget plugins " + d.getDownloadURL());
                    }
                }

            };
            return info;
        }
    } else {
        System.out.println("Could not check update for " + plugin.getName() + " : " + r.getAsString());
    }
    return null;
}

From source file:com.betafase.mcmanager.utils.spiget.PluginInfoRequest.java

public SpigetPlugin[] getPlugins() {
    try {//from ww w.  ja va2 s.  co  m
        JsonArray a = getAsJsonElement().getAsJsonArray();
        ArrayList<SpigetPlugin> list = new ArrayList<>();
        for (JsonElement e : a.getAsJsonArray()) {
            JsonObject o = e.getAsJsonObject();
            int id = o.get("id").getAsInt();
            SpigetPlugin pl = new SpigetPlugin(id);
            list.add(pl);
        }
        return list.toArray(new SpigetPlugin[list.size()]);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return new SpigetPlugin[0];
}

From source file:com.betafase.mcmanager.utils.spiget.SpigetPlugin.java

public void loadInformation() {
    author = new AuthorNameRequest(id).getName();
    ServerRequest r = new ServerRequest("resources/" + id);
    JsonObject o = r.getAsJsonObject();
    name = o.get("name").getAsString();
    if (name.length() > 60) {
        name = name.substring(0, 60);//  ww  w . ja  v  a2  s .c  om
    }
    tag = o.get("tag").getAsString();
    JsonObject file = o.getAsJsonObject("file");
    external = file.get("type").getAsString().equalsIgnoreCase("external");
    file_size = file.get("size").getAsDouble() + " " + file.get("sizeUnit").getAsString();
    download_url = "https://spigotmc.org/" + file.get("url").getAsString();
    JsonObject ro = o.getAsJsonObject("rating");
    rating = ro.get("average").getAsDouble() + " / 5 (" + ro.get("count") + " reviews)";
    downloads = o.get("downloads").getAsInt();
    last_update = Utils.makeDateReadable(o.get("updateDate").getAsLong() * 1000);
}

From source file:com.betafase.mcmanager.utils.Updater.java

License:Creative Commons License

public boolean hasUpdate() {
    try {//from   w  w w  . j  av a2 s.c  om
        PluginDescriptionFile f = plugin.getDescription();
        URL obj = new URL("https://api.betafase.com/plugins/" + f.getName() + "/version");
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setInstanceFollowRedirects(true);

        int responseCode = con.getResponseCode();
        System.out.println("[" + plugin.getName() + "] Checking for updates");
        if (responseCode != 200) {
            System.out.println("[" + plugin.getName() + "] Response Code : " + responseCode);
            return false;
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        inputLine = response.toString();
        if (inputLine == null) {
            throw new IOException("Could not read Data");
        }
        JsonElement element = new JsonParser().parse(inputLine);
        JsonObject object = element.getAsJsonObject();
        newVersion = object.get("version").getAsString();
        currentVersion = f.getVersion();
        if (!newVersion.equalsIgnoreCase(currentVersion)) {
            newTitle = object.get("title").getAsString();
            newDescription_en = object.get("description_en").getAsString();
            System.out.println("[" + plugin.getName() + "] An Update was found: v" + newVersion);
            return true;
        }
        System.out.println("[" + plugin.getName() + "] You are running the lastest version.");
        return false;
    } catch (Exception ex) {
        System.out.println("[" + plugin.getName() + "] Failed to check for updates: " + ex.getMessage());
        ex.printStackTrace();
        return false;
    }
}

From source file:com.bicitools.ws.ConsumeServicios.java

public static RespuestaJson consumeTiempoDist(Object st) {
    RespuestaNuevoJson out = new RespuestaNuevoJson();
    RespuestaJson output = new RespuestaJson();
    try {// w  w w .j av a 2 s. c  om

        ClientConfig clientConfig = new DefaultClientConfig();
        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
        Client client = Client.create(clientConfig);
        WebResource webResource = client.resource(
                "http://localhost:8080/bicitoolsRU/webresources/myresource/ObtenerDistanciaTiempoRuta");

        ClientResponse response = webResource.accept("application/json").type("application/json")
                .post(ClientResponse.class, st);

        if (response.getStatus() != 200) {
            output = ConstruyeRespuesta.construyeRespuestaFalla("Fallo 200");

        }
        String json = response.getEntity(String.class);
        Gson gson = new Gson();

        JsonParser jParser = new JsonParser();
        JsonObject jObject = (JsonObject) jParser.parse(json);

        JsonElement elem = jObject.get("codigo");
        JsonElement elem2 = jObject.get("valor");
        JsonElement elem3 = jObject.get("data");
        JsonElement elem4 = jObject.get("descripcion");
        JsonObject jObjectInterno = (JsonObject) jParser.parse(elem3.toString());

        JsonElement elem5 = jObjectInterno.get("tiempo");
        JsonElement elem6 = jObjectInterno.get("distancia");

        TiempoDistanciaInfo t = new TiempoDistanciaInfo(elem5.toString(), elem6.toString());
        ArrayList datos = new ArrayList();

        //RespuestaNuevoJson info = gson.fromJson(json, RespuestaNuevoJson.class);
        //System.out.println("");
        output.setCodigo(Integer.parseInt(elem.toString()));
        output.setValor(elem2.toString());
        output.setDescripcion(elem4.toString());
        datos.add(t);
        output.setDatos(datos);
        output.setDescripcion(out.getDescripcion());

    } catch (Exception e) {
        output = ConstruyeRespuesta.construyeRespuestaFalla(e.getMessage());
        e.printStackTrace();
    }
    return output;
}

From source file:com.bigtester.ate.tcg.controller.PredictionIOTrainer.java

License:Apache License

/**
 * Quert entity.//from   w  ww .j  a  v  a 2 s . c  o m
 *
 * @param record the record
 * @return the user input training record
 * @throws ExecutionException the execution exception
 * @throws InterruptedException the interrupted exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static UserInputTrainingRecord queryEntity(UserInputTrainingRecord record)
        throws ExecutionException, InterruptedException, IOException {
    EngineClient client = new EngineClient(ENGINESERVERURL);

    JsonObject jObj = client.sendQuery(ImmutableMap.<String, Object>of("text", record.getInputMLHtmlCode()));
    client.close();
    String cat = jObj.get("category").getAsString();
    if (null == cat)
        cat = "";
    record.setPioPredictLabelResult(cat);
    Double con = jObj.get("confidence").getAsDouble();
    if (null == con)
        con = 0.0;
    record.setPioPredictConfidence(con);

    return record;
}