Example usage for org.json.simple JSONValue parse

List of usage examples for org.json.simple JSONValue parse

Introduction

In this page you can find the example usage for org.json.simple JSONValue parse.

Prototype

public static Object parse(String s) 

Source Link

Usage

From source file:com.drevelopment.couponcodes.bukkit.updater.Updater.java

/**
 * Make a connection to the BukkitDev API and request the newest file's details.
 *
 * @return true if successful.//  w  w w .  j a  v a 2 s .  c  o m
 */
private boolean read() {
    try {
        final URLConnection conn = this.url.openConnection();
        conn.setConnectTimeout(5000);

        if (this.apiKey != null) {
            conn.addRequestProperty("X-API-Key", this.apiKey);
        }
        conn.addRequestProperty("User-Agent", Updater.USER_AGENT);

        conn.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.isEmpty()) {
            this.plugin.getLogger()
                    .warning("The updater could not find any files for the project id " + this.id);
            this.result = UpdateResult.FAIL_BADID;
            return false;
        }

        JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1);
        this.versionName = (String) latestUpdate.get(Updater.TITLE_VALUE);
        this.versionLink = (String) latestUpdate.get(Updater.LINK_VALUE);
        this.versionType = (String) latestUpdate.get(Updater.TYPE_VALUE);
        this.versionGameVersion = (String) latestUpdate.get(Updater.VERSION_VALUE);

        return true;
    } catch (final IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            this.plugin.getLogger()
                    .severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
            this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct.");
            this.result = UpdateResult.FAIL_APIKEY;
        } else {
            this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating.");
            this.plugin.getLogger().severe(
                    "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
            this.result = UpdateResult.FAIL_DBO;
        }
        this.plugin.getLogger().log(Level.SEVERE, null, e);
        return false;
    }
}

From source file:fr.bmartel.bboxapi.BboxApi.java

/**
 * /*www  . j  av  a2  s .c o m*/
 * Retrieve all hosts
 * 
 * @param listener
 *            listener for request result / failure
 * 
 * @return true if request has been successfully initiated
 */
@Override
public boolean getHosts(final IHostsListener listener) {

    ClientSocket clientSocket = new ClientSocket("gestionbbox.lan", 80);

    clientSocket.addClientSocketEventListener(new IHttpClientListener() {

        @Override
        public void onIncomingHttpFrame(HttpFrame frame, HttpStates httpStates, IClientSocket clientSocket) {

            if (httpStates == HttpStates.HTTP_FRAME_OK && frame.isHttpResponseFrame()) {

                // this is data coming from the server
                if (frame.getStatusCode() == 200) {

                    String data = new String(frame.getBody().getBytes());

                    JSONArray obj = (JSONArray) JSONValue.parse(data);

                    if (obj.size() > 0) {

                        JSONObject item = (JSONObject) obj.get(0);
                        if (item.containsKey("hosts")) {

                            JSONObject sub_item = (JSONObject) item.get("hosts");

                            if (sub_item.containsKey("list")) {

                                JSONArray hostList = (JSONArray) sub_item.get("list");

                                List<Host> hostObjectList = new ArrayList<Host>();

                                for (int i = 0; i < hostList.size(); i++) {

                                    JSONObject hostEntry = (JSONObject) hostList.get(i);

                                    if (hostEntry.containsKey("id") && hostEntry.containsKey("hostname")
                                            && hostEntry.containsKey("macaddress")
                                            && hostEntry.containsKey("ipaddress")
                                            && hostEntry.containsKey("type") && hostEntry.containsKey("link")
                                            && hostEntry.containsKey("devicetype")
                                            && hostEntry.containsKey("firstseen")
                                            && hostEntry.containsKey("lastseen")
                                            && hostEntry.containsKey("lease")
                                            && hostEntry.containsKey("active")) {

                                        int id = Integer.parseInt(hostEntry.get("id").toString());
                                        String hostname = hostEntry.get("hostname").toString();
                                        String macaddress = hostEntry.get("macaddress").toString();
                                        String ipaddress = hostEntry.get("ipaddress").toString();
                                        String type = hostEntry.get("type").toString();
                                        String link = hostEntry.get("link").toString();
                                        String devicetype = hostEntry.get("devicetype").toString();
                                        String firstseen = hostEntry.get("firstseen").toString();
                                        String lastseen = hostEntry.get("lastseen").toString();
                                        int lease = Integer.parseInt(hostEntry.get("lease").toString());

                                        boolean active = (Integer
                                                .parseInt(hostEntry.get("active").toString()) == 0) ? false
                                                        : true;

                                        hostObjectList.add(new Host(id, hostname, macaddress, ipaddress, type,
                                                link, devicetype, firstseen, lastseen, lease, active));
                                    }
                                }
                                listener.onHostsReceived(hostObjectList);
                                clientSocket.closeSocket();
                                return;
                            }
                        }
                    }

                }
                listener.onHostsFailure();
                clientSocket.closeSocket();
            }
        }

        @Override
        public void onSocketError() {

            listener.onHostsFailure();

        }
    });

    HashMap<String, String> headers = new HashMap<String, String>();

    headers.put("Accept", "*/*");
    headers.put("Host", "gestionbbox.lan");
    headers.put("Cookie", token_header);
    HttpFrame frameRequest = new HttpFrame(HttpMethod.GET_REQUEST, new HttpVersion(1, 1), headers,
            "/api/v1/hosts", new ListOfBytes(""));

    clientSocket.write(frameRequest.toString().getBytes());

    return false;
}

From source file:com.firmansyah.imam.sewa.kendaraan.FormUser.java

public void showDataUserById(int id) throws ParseException {
    try {//  ww w  . j  ava2  s. c o  m
        getDataURL dataurl = new getDataURL();

        String url = Path.serverURL + "/user/show/" + id;

        String data = dataurl.getData(url);

        Object obj = JSONValue.parse(data);
        JSONArray dataArray = (JSONArray) obj;

        JSONObject getData = (JSONObject) dataArray.get(0);

        Object nama = getData.get("nama");
        Object username = getData.get("username");
        Object id_pelanggan = getData.get("id");
        Object status = getData.get("status");

        if (status.equals("0")) {
            btnAktif.setText("Aktifkan");
        } else {
            btnAktif.setText("Non Aktifkan");
        }

        inputNama.setText((String) nama);
        inputUsername.setText((String) username);
        inputIdUser.setText((String) id_pelanggan.toString());

        btnTambah.setEnabled(false);
        btnUbah.setEnabled(true);
        btnHapus.setEnabled(true);
        btnAktif.setEnabled(true);

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

From source file:net.milkbowl.vault.Vault.java

public double updateCheck(double currentVersion) {
    try {//from  ww  w .  j a v  a2s.c  o  m
        URL url = new URL("https://api.curseforge.com/servermods/files?projectids=33184");
        URLConnection conn = url.openConnection();
        conn.setReadTimeout(5000);
        conn.addRequestProperty("User-Agent", "Vault Update Checker");
        conn.setDoOutput(true);
        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();
        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            this.getLogger().warning("No files found, or Feed URL is bad.");
            return currentVersion;
        }
        // Pull the last version from the JSON
        newVersionTitle = ((String) ((JSONObject) array.get(array.size() - 1)).get("name")).replace("Vault", "")
                .trim();
        return Double.valueOf(newVersionTitle.replaceFirst("\\.", "").trim());
    } catch (Exception e) {
        log.info("There was an issue attempting to check for the latest version.");
    }
    return currentVersion;
}

From source file:net.emotivecloud.scheduler.drp4ost.DRP4OST.java

private boolean existsImage(String imageID) {
    boolean exists = false;

    //Get the Response Content in a String
    String images = oStackClient.getAllImages();

    // Parsing the JSON response to get all the images
    JSONObject allImages = (JSONObject) JSONValue.parse(images);
    JSONArray jsonImages = (JSONArray) allImages.get("images");

    for (int i = 0; i < jsonImages.size(); ++i) {
        JSONObject image = (JSONObject) jsonImages.get(i);
        String tmpImgID = image.get("name").toString();
        if (tmpImgID.equals(imageID)) {
            exists = true;//from w  w w  . j a v a 2 s.  co m
            break;
        }
    }
    return exists;
}

From source file:net.emotivecloud.scheduler.drp4ost.OStackClient.java

public String createFlavor(EmotiveOVF ovf) {

    String apiAddress = ":8774/v2/" + OS_TENANT_ID + "/flavors";
    String flavorID = null;//from  ww  w . j a  v a2s  . co  m

    System.out.println("DRP4OST>OStackClient.createFlavor(): entra en createFlavor");

    // Mandatory OpenStack's Flavor attributes
    //        name: The name for the flavor.
    //        ram: The amount of RAM, in MBs, for the flavor.
    //        vcpus: The virtual CPUs, in a whole integer amount, for the flavor.
    //        disk: The amount of disk space, in GBs, for the flavor.
    //        id: The ID, a unique integer value, for the flavor.

    String name = ovf.getId();
    Object ram = ovf.getMemoryMB();
    Object vcpus = ovf.getCPUsNumber();
    Map<String, OVFDisk> allDisks = ovf.getDisks();
    long size = Long.parseLong(this.IMG_DEFAULT_DISK_SIZE);
    String diskSize = this.IMG_DEFAULT_DISK_SIZE;

    // Get the DISK's section
    for (OVFDisk ovfDisk : allDisks.values()) {
        if (ovfDisk.getHref().contains(ovf.getBaseImage())) {
            size = ovfDisk.getCapacityMB() / 1024;
            System.out.println("DRP4OST>OStackClient.createFlavor(): size(" + ovfDisk.getCapacityMB()
                    + " / 1024)=" + size + "");

            if (size <= 1 || size < Long.parseLong(this.IMG_DEFAULT_DISK_SIZE)) {
                diskSize = this.IMG_DEFAULT_DISK_SIZE;
            }
        }
    }

    // If the VM already has Flavor, update it. Necessary to delete & create 
    // because OpenStack does not permit to update flavors
    // Cannot delete flavors that are already in use by another 
    if (this.activeInstancesWithFlavor(name) > 0) {
        String myFlavorID = this.getFlavorID(name);
        System.out.println(
                "DRP4OST-OStackClient.createFlavor(): Flavor used by running VM, cannot be updated, this flavor will be used myFlavorID="
                        + myFlavorID);
        return myFlavorID;
    } else if (this.existsFlavor(name) && this.activeInstancesWithFlavor(name) == 0) {
        System.out
                .println("DRP4OST-OStackClient.createFlavor(): Update obligates to delete the Flavor flavorID="
                        + this.getFlavorID(name));
        this.deleteFlavor(name);
    } else {
        System.out.println("DRP4OST-OStackClient.createFlavor(): ELSE, name=" + name + ", myFlavorID="
                + this.getFlavorID(name));
    }

    String flavorPattern = "{" + "     \"flavor\": {" + "     \"disk\": %s," + "     \"vcpus\": %s, "
            + "     \"ram\": %s," + "     \"name\": \"%s\"," + "     \"id\": \"%s\","
            + "     \"OS-FLV-EXT-DATA:ephemeral\": %s" + "     }" + "}";

    // OS-FLV-EXT-DATA:ephemeral has to be "2", otherwise it does'nt works
    String flavor = String.format(flavorPattern, diskSize, vcpus, ram, name, name, "2");

    //Instantiate an HttpClient
    HttpClient client = new DefaultHttpClient();
    try {
        //Instantiate a POST HTTP method
        HttpPost request = new HttpPost(this.drpHost + apiAddress);
        request.setHeader("X-Auth-Token", this.token);
        request.setHeader("Content-type", "application/json");
        request.setHeader("Accept", "application/json");
        request.setHeader("User-Agent", "python-novaclient");
        request.setHeader("X-Auth-Project-Id", this.OS_TENANT_NAME);

        StringEntity se = new StringEntity(flavor);
        request.setEntity(se);

        //Execute the request, obtain a Response
        HttpResponse response = client.execute(request);
        System.out.println("DRP4OST>OStackClient.createFlavor(), response=" + response);

        //If the response is not OK, throw an exception
        if (response.getStatusLine().getStatusCode() != 200) {
            System.out.println("DRP4OST>OStackClient.createFlavor");
            throw new DRPOSTException(response.getStatusLine().getReasonPhrase(), StatusCodes.BAD_REQUEST);
        }

        //Get the Response Content in a String
        String responseContent = IOUtils.toString(response.getEntity().getContent());
        System.out.println("DRP4OST>OStackClient.createFlavor, responseContent=" + responseContent);

        // Parsing the JSON response to get the flavor ID
        JSONObject jo = (JSONObject) JSONValue.parse(responseContent);
        jo = (JSONObject) jo.get("flavor");
        flavorID = jo.get("id").toString();
        System.out.println("DRP4OST>OStackClient.createFlavor, flavorID=" + flavorID);

    } catch (IOException ex) {

        throw new DRPOSTException("Exception creating the Flavor", StatusCodes.BAD_REQUEST);
    }
    //        return "2";
    return flavorID;
}

From source file:net.emotivecloud.scheduler.drp4ost.DRP4OST.java

private OVFWrapper[] getAllServersWrappers() {
    ArrayList<OVFWrapper> wrappers = new ArrayList<OVFWrapper>();
    String servers = oStackClient.getAllServers();

    JSONObject allServers = (JSONObject) JSONValue.parse(servers);
    JSONArray jsonServers = (JSONArray) allServers.get("servers");

    for (int i = 0; i < jsonServers.size(); ++i) {
        JSONObject server = (JSONObject) jsonServers.get(i);
        OVFWrapper wTmp = this.parse(server.toString());
        wrappers.add(wTmp);//from ww w .  j  av  a2  s.  com
    }

    OVFWrapper vms[] = wrappers.toArray(new OVFWrapper[wrappers.size()]);

    return vms;
}

From source file:com.treasure_data.client.bulkimport.BulkImportClientAdaptorImpl.java

private DeletePartResult doDeletePart(DeletePartRequest request) throws ClientException {
    request.setCredentials(client.getTreasureDataCredentials());
    validator.validateCredentials(client, request);

    String jsonData = null;//from  w ww .j av  a2  s  . com
    int code = 0;
    String message = null;
    try {
        conn = createConnection();

        // send request
        String path = String.format(HttpURL.V3_DELETE_PART, HttpConnectionImpl.e(request.getSessionName()),
                HttpConnectionImpl.e(request.getPartID()));
        Map<String, String> header = new HashMap<String, String>();
        setUserAgentHeader(header);
        Map<String, String> params = null;
        conn.doPostRequest(request, path, header, params);

        // receive response code
        code = conn.getResponseCode();
        message = conn.getResponseMessage();
        if (code != HttpURLConnection.HTTP_OK) {
            String errMessage = conn.getErrorMessage();
            LOG.severe(HttpClientException.toMessage("Delete part failed", message, code));
            LOG.severe(errMessage);
            throw new HttpClientException("Delete part failed", message + ", detail = " + errMessage, code);
        }

        // receive response body
        jsonData = conn.getResponseBody();
        validator.validateJSONData(jsonData);
    } catch (IOException e) {
        LOG.throwing(getClass().getName(), "deletePart", e);
        LOG.severe(HttpClientException.toMessage(e.getMessage(), message, code));
        throw new HttpClientException("Delete part failed", message, code, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // parse JSON data {"name":"sess01"}
    @SuppressWarnings("unchecked")
    Map<String, String> map = (Map<String, String>) JSONValue.parse(jsonData);
    validator.validateJavaObject(jsonData, map);

    return new DeletePartResult(request.getSession());
}

From source file:net.emotivecloud.scheduler.drp4ost.OStackClient.java

/**
 * Gets all the identifiers of the VMs running on this project
 *
 * @return all the identifiers of the VMs running on this project
 *//*  ww w. ja  v a 2s .com*/
public ArrayList<String> getAllVMsIDs() {
    String apiAddress = ":8774/v2/" + this.OS_TENANT_ID + "/servers";
    ArrayList<String> vmsIDsList = new ArrayList<String>();

    //Instantiate an HttpClient
    HttpClient client = new DefaultHttpClient();
    try {
        //Instantiate a GET HTTP method
        HttpGet request = new HttpGet(this.drpHost + apiAddress);
        request.setHeader("X-Auth-Token", this.token);

        //Execute the request, obtain a Response
        HttpResponse response = client.execute(request);
        //Get the Response Content in a String

        String responseContent = IOUtils.toString(response.getEntity().getContent());
        // Parsing the JSON response to get all the flavors
        JSONObject allServers = (JSONObject) JSONValue.parse(responseContent);
        JSONArray jsonServers = (JSONArray) allServers.get("servers");

        for (int i = 0; i < jsonServers.size(); ++i) {
            JSONObject flavor = (JSONObject) jsonServers.get(i);
            String vmID = flavor.get("id").toString();
            vmsIDsList.add("" + vmID);
        }

    } catch (IOException ex) {
        throw new DRPOSTException("IO Exception getting IDs from the VMs", StatusCodes.BAD_REQUEST);
    } catch (Exception e) {
        throw new DRPOSTException("Exception getting IDs from the VMs", StatusCodes.BAD_REQUEST);
    }
    return vmsIDsList;

}