Example usage for org.json.simple JSONObject get

List of usage examples for org.json.simple JSONObject get

Introduction

In this page you can find the example usage for org.json.simple JSONObject get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.rylinaux.plugman.util.BukGetUtil.java

/**
 * Check if the installed plugin version is up-to-date with the DBO version.
 *
 * @param pluginName the plugin name.//from w w w .  j a v  a2  s  .com
 * @return the reflective UpdateResult.
 */
public static UpdateResult checkUpToDate(String pluginName) {

    String pluginSlug = BukGetUtil.getPluginSlug(pluginName);

    if (pluginSlug == null || pluginSlug.isEmpty()) {
        return new UpdateResult(UpdateResult.ResultType.INVALID_PLUGIN);
    }

    JSONObject json = BukGetUtil.getPluginData(pluginSlug);
    JSONArray versions = (JSONArray) json.get("versions");

    if (versions.size() == 0) {
        return new UpdateResult(UpdateResult.ResultType.INVALID_PLUGIN);
    }

    JSONObject latest = (JSONObject) versions.get(0);

    String currentVersion = PluginUtil.getPluginVersion(pluginName);
    String latestVersion = (String) latest.get("version");

    if (currentVersion == null) {
        return new UpdateResult(UpdateResult.ResultType.NOT_INSTALLED, currentVersion, latestVersion);
    } else if (currentVersion.equalsIgnoreCase(latestVersion)) {
        return new UpdateResult(UpdateResult.ResultType.UP_TO_DATE, currentVersion, latestVersion);
    } else {
        return new UpdateResult(UpdateResult.ResultType.OUT_OF_DATE, currentVersion, latestVersion);
    }

}

From source file:eg.nileu.cis.nilestore.main.HttpDealer.java

/**
 * Put./*from   w  ww  .ja v  a 2  s. c  o  m*/
 * 
 * @param filepath
 *            the filepath
 * @param url
 *            the url
 * @throws ClientProtocolException
 *             the client protocol exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void put(String filepath, String url) throws ClientProtocolException, IOException {
    url = url + (url.endsWith("/") ? "" : "/") + "upload?t=json";
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File(filepath);
    final double filesize = file.length();

    ContentBody fbody = new FileBodyProgress(file, new ProgressListener() {

        @Override
        public void transfered(long bytes, float rate) {
            int percent = (int) ((bytes / filesize) * 100);
            String bar = ProgressUtils.progressBar("Uploading file to the gateway : ", percent, rate);
            System.err.print("\r" + bar);
            if (percent == 100) {
                System.err.println();
                System.err.println("wait the gateway is processing and saving your file");
            }
        }
    });

    entity.addPart("File", fbody);

    post.setEntity(entity);

    HttpResponse response = client.execute(post);

    if (response != null) {
        System.err.println(response.getStatusLine());
        HttpEntity ht = response.getEntity();
        String json = EntityUtils.toString(ht);
        JSONParser parser = new JSONParser();
        try {
            JSONObject obj = (JSONObject) parser.parse(json);
            System.out.println(obj.get("cap"));
        } catch (ParseException e) {
            System.err.println("Error during parsing the response: " + e.getMessage());
            System.exit(-1);
        }
    } else {
        System.err.println("Error: response = null");
    }

    client.getConnectionManager().shutdown();
}

From source file:me.timothy.ddd.quests.Quest_GantJewels.java

public static Quest_GantJewels fromObject(QuestManager qM, JSONObject jObj) {
    Quest_GantJewels result = new Quest_GantJewels(qM);
    result.reallyAccepted = jObj.get("reallyAccepted") == Boolean.TRUE;
    return result;
}

From source file:io.github.casnix.spawnerdropper.SpawnerStack.java

public static boolean TakeSpawnerOutOfService(String spawnerType) {
    // Read ./SpawnerDropper.SpawnerStack.json into a string

    // get the value of JSON->{spawnerType} and subtract 1 to it unless it is 0.
    // If it's zero, return false

    // Write file back to disk
    try {/*from  w w w  .ja  v a  2 s  .  c  om*/
        // Read entire ./SpawnerDropper.SpawnerStack.json into a string
        String spawnerStack = new String(
                Files.readAllBytes(Paths.get("./plugins/SpawnerDropper/SpawnerStack.json")));

        // get the value of JSON->{spawnerType}
        JSONParser parser = new JSONParser();

        Object obj = parser.parse(spawnerStack);

        JSONObject jsonObj = (JSONObject) obj;

        long numberInService = (Long) jsonObj.get(spawnerType);

        if (numberInService <= 0) {
            return false;
        } else {
            //            System.out.println("[SD DBG MSG] TSOOS numberInServer("+numberInService+")");

            numberInService -= 1;
            jsonObj.put(spawnerType, new Long(numberInService));

            FileWriter file = new FileWriter("./plugins/SpawnerDropper/SpawnerStack.json");
            file.write(jsonObj.toJSONString());
            file.flush();
            file.close();

            return true;
        }
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[SpawnerDropper] Caught ParseException in TakeSpawnerOutOfService(String)");
        e.printStackTrace();

        return false;
    } catch (FileNotFoundException e) {
        Bukkit.getLogger()
                .warning("[SpawnerDropper] Could not find ./plugins/SpawnerDropper/SpawnerStack.json");
        e.printStackTrace();

        return false;
    } catch (IOException e) {
        Bukkit.getLogger().warning("[SpawnerDropper] Caught IOException in TakeSpawnerOutOfService(String)");
        e.printStackTrace();

        return false;
    }
}

From source file:msuresh.raftdistdb.TestAtomix.java

private static void InitPortNumber() {
    try {/* w w w .  j  a v a  2 s.co  m*/
        File f = new File(Constants.STATE_LOCATION + "global.info");
        if (!f.exists()) {
            RaftCluster.createDefaultGlobal();
        }
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(new FileReader(Constants.STATE_LOCATION + "global.info"));
        JSONObject jsonObject = (JSONObject) obj;
        Long a = (Long) jsonObject.get("currentCount");
        portId = a.intValue();
    } catch (Exception e) {
        System.out.println(e.toString());
    }
}

From source file:mp3downloader.ZingSearch.java

private static ArrayList<Song> readSongsFromContent(String content) throws ParseException {
    ArrayList<Song> songs = new ArrayList<Song>();
    JSONParser parser = new JSONParser();

    JSONObject obj = (JSONObject) parser.parse(content);
    JSONArray items = (JSONArray) obj.get("Data");

    for (int i = 0; i < items.size(); i++) {
        JSONObject item = (JSONObject) items.get(i);
        String id = (String) item.get("ID");
        String title = (String) item.get("Title");
        String performer = (String) item.get("Artist");
        String thumbnail = (String) item.get("ArtistAvatar");
        String source = "";
        if (item.get("LinkDownload320") != null) {
            source = (String) item.get("LinkDownload320");
        } else if (item.get("LinkDownload128") != null) {
            source = (String) item.get("LinkDownload128");
        }//from ww  w. j  a  v  a 2s. c  o  m
        String type = "mp3";
        Song song = new Song(id, title, performer, source, thumbnail, type);
        songs.add(song);
    }
    return songs;
}

From source file:com.iti.request.NearbyService.java

public static List<Address> getNearby(String x, String y, String r, String type) throws IOException {

    String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?v=3&location=";
    url = url.concat(x);/*  w w w  . ja  v a2 s  . co m*/
    url = url.concat("%2C");
    url = url.concat(y);
    url = url.concat("&radius=");
    url = url.concat(r);
    url = url.concat("&types=");
    url = url.concat(type);
    url = url.concat("&key=AIzaSyAmsScw_ynzyQf32_KSGjbGiej7VN2rL7g");

    String result = httpGet(url);

    Object obj = JSONValue.parse(result.toString());
    JSONObject jsonObj = (JSONObject) obj;
    JSONArray resultsArray = (JSONArray) jsonObj.get("results");
    Iterator i = resultsArray.iterator();

    ArrayList<Address> addresses = new ArrayList<Address>();

    while (i.hasNext()) {

        JSONObject jsonResult = (JSONObject) i.next();
        String name = (String) jsonResult.get("name");
        String vicinity = (String) jsonResult.get("vicinity");

        System.out.println(name);

        Address address = new Address();
        address.setName(name);
        address.setVicinity(vicinity);

        addresses.add(address);

    }

    return addresses;
}

From source file:at.ac.tuwien.dsg.smartcom.integration.JSONConverter.java

private static String[][] parsePeerInfoResults(JSONObject json) {
    if (json.containsKey("results")) {
        JSONArray array = (JSONArray) json.get("results");

        if (array.size() == 0) {
            return null;
        }/*from  ww  w .j  a v  a 2 s.  c o m*/

        List<String[]> outerList = new ArrayList<>();
        for (Object o : array) {
            JSONArray innerArray = (JSONArray) o;
            List<String> valueList = new ArrayList<>();

            for (Object ob : innerArray) {
                try {
                    valueList.add(parseToString(ob));
                } catch (ConverterException e) {
                    return null;
                }
            }
            outerList.add(valueList.toArray(new String[valueList.size()]));
        }

        return outerList.toArray(new String[outerList.size()][]);
    } else {
        return null;
    }
}

From source file:com.criticalsoftware.mobics.presentation.util.GeolocationUtil.java

public static List<PlaceDTO> getAddressFromText(String address) throws UnsupportedEncodingException {

    List<PlaceDTO> results = new ArrayList<PlaceDTO>();

    address = URLEncoder.encode(address, Configuration.INSTANCE.getUriEnconding());

    String url = MessageFormat.format(SEARCH_URL, Configuration.INSTANCE.getGeolocationServer(), address,
            Configuration.INSTANCE.getGeolocationServerAllowedCountries(),
            Configuration.INSTANCE.getMaxResults());
    HttpMethod method = new GetMethod(url);
    try {/*from ww  w .  java2  s. c  o  m*/
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Making search location call to: {}", url);
        }
        int statusCode = new HttpClient().executeMethod(method);

        if (statusCode == HttpStatus.SC_OK) {
            byte[] responseBody = readResponse(method);
            JSONArray jsonArray = (JSONArray) new JSONParser().parse(new String(responseBody));
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace(jsonArray.toJSONString());
            }

            @SuppressWarnings("unchecked")
            Iterator<JSONObject> it = jsonArray.iterator();
            while (it.hasNext()) {
                JSONObject place = it.next();
                results.add(new PlaceDTO((String) place.get(DISPLAY_NAME), (String) place.get(LATITUDE_NAME),
                        (String) place.get(LONGITUDE_NAME)));
            }

        } else {
            LOGGER.warn("Recived a HTTP status {}. Response was not good from {}", statusCode, url);
        }
    } catch (HttpException e) {
        LOGGER.error("Error while making call.", e);
    } catch (IOException e) {
        LOGGER.error("Error while reading the response.", e);
    } catch (ParseException e) {
        LOGGER.error("Error while parsing json response.", e);
    }

    return results;
}

From source file:me.cybermaxke.merchants.v16r3.SUtil.java

private static void apply(Object element, Data data) {
    if (!(element instanceof JSONObject) && !(element instanceof JSONArray)) {
        return;/*  w w w  .  j a v  a2 s  .c  o m*/
    }

    ChatColor lastColor0 = data.lastColor;
    Set<ChatColor> lastStyles0 = Sets.newHashSet(data.lastStyles);

    if (element instanceof JSONObject) {
        JSONObject object = (JSONObject) element;
        if (object.containsKey("color")) {
            ChatColor color = lookupColors.get(object.get("color"));

            if (color != null) {
                if (data.lastColor != color) {
                    data.builder.append(color);
                }
            }
        }
        for (Entry<String, ChatColor> style : lookupStyles.entrySet()) {
            String key = style.getKey();
            ChatColor value = style.getValue();

            if (object.containsKey(key)) {
                if (data.lastStyles.add(value)) {
                    data.builder.append(value);
                }
            } else {
                data.lastStyles.remove(value);
            }
        }
        if (object.containsKey("extra")) {
            apply(object.get("extra"), data);
        }
    } else if (element instanceof JSONArray) {
        JSONArray array = (JSONArray) element;
        for (Object object0 : array) {
            apply(object0, data);
        }
    }

    data.lastColor = lastColor0;
    data.lastStyles = lastStyles0;
}