Example usage for org.json.simple JSONArray get

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

Introduction

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

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:hoot.services.nativeInterfaces.ProcessStreamInterface.java

/**
 * @param cmd/*from   w  w  w.j  av a 2s  .c  om*/
 * @return
 */
private String[] createBashScriptCmdArray(JSONObject cmd) {
    ArrayList<String> execCmd = new ArrayList<String>();

    try {
        execCmd.add("bash");
        execCmd.add(coreScriptPath + "/" + (String) cmd.get("exec"));
        JSONArray params = (JSONArray) cmd.get("params");
        int nParams = params.size();
        for (int i = 0; i < nParams; i++) {
            JSONObject param = (JSONObject) params.get(i);
            Iterator iter = param.entrySet().iterator();

            String arg = "";
            String key = "";
            while (iter.hasNext()) {
                Map.Entry mEntry = (Map.Entry) iter.next();
                key = (String) mEntry.getKey();
                arg = (String) mEntry.getValue();
            }
            execCmd.add(arg);

        }
        if (cmd.get("jobId") != null) {
            String jobid = cmd.get("jobId").toString();
            execCmd.add(jobid);
        }
    } catch (Exception ex) {
        log.error("Failed to parse job params. Reason: " + ex.getMessage());
    }

    Object[] objectArray = execCmd.toArray();
    return Arrays.copyOf(objectArray, objectArray.length, String[].class);
}

From source file:hoot.services.nativeInterfaces.ProcessStreamInterface.java

/**
 * Creates command for make file script based call if exectype = "make"
 * output looks like make -f [some makefile] [any argument make file uses]
 *
 * @param cmd// ww w.  j a v a  2 s .c  o m
 * @return
 */
private String[] createScriptCmdArray(JSONObject cmd) {
    ArrayList<String> execCmd = new ArrayList<String>();

    try {
        execCmd.add("make");
        execCmd.add("-f");
        execCmd.add(coreScriptPath + "/" + (String) cmd.get("exec"));
        JSONArray params = (JSONArray) cmd.get("params");
        int nParams = params.size();
        for (int i = 0; i < nParams; i++) {
            JSONObject param = (JSONObject) params.get(i);
            Iterator iter = param.entrySet().iterator();

            String arg = "";
            String key = "";
            while (iter.hasNext()) {
                Map.Entry mEntry = (Map.Entry) iter.next();
                key = (String) mEntry.getKey();
                arg = (String) mEntry.getValue();
            }

            execCmd.add(key + "=" + arg + "");

        }
        String jobid = cmd.get("jobId").toString();
        execCmd.add("jobid=" + jobid);
        execCmd.add("DB_URL=" + dbUrl);
    } catch (Exception ex) {
        log.error("Failed to parse job params. Reason: " + ex.getMessage());
    }

    Object[] objectArray = execCmd.toArray();
    return Arrays.copyOf(objectArray, objectArray.length, String[].class);
}

From source file:cc.pinel.mangue.ui.ChaptersPanel.java

/**
 * Loads all chapters from the given manga.
 * //from   w  w  w.j  a  va  2s .  c  om
 * @param manga the manga
 */
public void loadChapters(final Manga manga) {
    if (this.manga != null && this.manga.getId().equals(manga.getId()))
        return;

    this.manga = manga;
    rememberManga();

    new StorageHandler(main.getContext(), "Loading mangas...") {
        /**
         * {@inheritDoc}
         */
        public void handleRun() throws Exception {
            final String lastChapterNumber = new StateStorage(main.getContext()).getChapter(manga.getId());

            final ConnectivityHandler handler = new ConnectivityHandler(main.getContext(),
                    "Loading chapters...") {
                /**
                 * {@inheritDoc}
                 */
                public void handleConnected() throws Exception {
                    JSONParser parser = new JSONParser();
                    JSONArray chapters = (JSONArray) parser
                            .parse(IOUtils.toString(new URL(manga.getAllChaptersLink()).openStream()));

                    chaptersPages.removeAllItems();
                    for (int i = chapters.size() - 1; i >= 0; i--) {
                        JSONObject chapter = (JSONObject) chapters.get(i);
                        String chapterNumber = chapter.get("chapter").toString();
                        String chapterName = StringUtils.unescapeHtml(chapter.get("chapter_name").toString());
                        String chapterTitle = chapterNumber
                                + (chapterName != null && chapterName.length() != 0 ? ": " + chapterName : "");

                        final KWTSelectableLabel chapterLabel = new KWTSelectableLabel(chapterTitle);
                        chapterLabel.setName(chapterNumber);
                        chapterLabel.setFocusable(true);
                        chapterLabel.setEnabled(true);
                        chapterLabel.addActionListener(chapterListener);

                        // last read chapter
                        if (lastChapterNumber != null && chapterNumber.equals(lastChapterNumber))
                            highlightLabel(chapterLabel);

                        chaptersPages.addItem(chapterLabel);
                    }

                    EventQueue.invokeAndWait(new Runnable() {
                        public void run() {
                            chaptersPages.first();

                            requestFocus();
                            repaint();
                        }
                    });
                }
            };

            main.getContext().getConnectivity().submitSingleAttemptConnectivityRequest(handler, true);
        }
    }.start();
}

From source file:com.sforce.cd.apexUnit.client.codeCoverage.CodeCoverageComputer.java

/**
 * This method is not used currently Calculate code coverage results for the
 * Apex classes using Tooling API's This method is intended to provide code
 * coverage at method level for each class . This indicates which exact
 * method needs more coverage/*from   w  ww  .  j  a v a2  s .c om*/
 * 
 * @return
 */
public void calculateCodeCoverageUsingToolingAPI(String classArrayAsStringForQuery) {
    int classCounter = 0;
    String relativeServiceURL = "/services/data/v" + SUPPORTED_VERSION + "/tooling";
    String soqlcc = QueryConstructor.getClassLevelCodeCoverage(classArrayAsStringForQuery);
    LOG.debug("OAuthTokenGenerator.getOrgToken() : " + OAuthTokenGenerator.getOrgToken());
    JSONObject responseJsonObject = null;
    responseJsonObject = WebServiceInvoker.doGet(relativeServiceURL, soqlcc, OAuthTokenGenerator.getOrgToken());

    if (responseJsonObject != null) {
        String responseStr = responseJsonObject.toJSONString();
        LOG.debug(responseStr);
        JSONArray recordObject = (JSONArray) responseJsonObject.get("records");
        for (int i = 0; i < recordObject.size(); ++i) {
            classCounter++;
            // The object below is one record from the ApexCodeCoverage
            // object
            JSONObject rec = (JSONObject) recordObject.get(i);

            int coveredLines = Integer.valueOf((String) rec.get("NumLinesCovered").toString());
            int unCoveredLines = Integer.valueOf((String) rec.get("NumLinesUncovered").toString());
            // ApexTestClassId - The ID of the test class.
            String apexTestClassID = (String) rec.get("ApexTestClassId").toString();
            // ApexClassOrTriggerId - The ID of the class or trigger under
            // test.
            String apexClassorTriggerId = (String) rec.get("ApexClassOrTriggerId").toString();
            String testMethodName = (String) rec.get("TestMethodName").toString();
            LOG.info("Record number # " + classCounter + " : coveredLines : " + coveredLines
                    + " : unCoveredLines : " + unCoveredLines + " : apexTestClassID : " + apexTestClassID
                    + " : apexClassorTriggerId : " + apexClassorTriggerId + " : testMethodName : "
                    + testMethodName);

        }

    }
}

From source file:com.tremolosecurity.provisioning.core.providers.SugarCRM.java

@Override
public User findUser(String userID, Set<String> attributes, Map<String, Object> request)
        throws ProvisioningException {

    try {/*w ww  .  java 2  s .  c o  m*/

        String sessionId = sugarLogin();
        Gson gson = new Gson();

        SugarGetEntryList sgel = new SugarGetEntryList();
        sgel.setSession(sessionId);
        sgel.setModule_name("Contacts");
        StringBuffer b = new StringBuffer();
        b.append(
                "contacts.id in (SELECT eabr.bean_id FROM email_addr_bean_rel eabr JOIN email_addresses ea ON (ea.id = eabr.email_address_id) WHERE eabr.deleted=0 AND ea.email_address = '")
                .append(userID).append("')");
        sgel.setQuery(b.toString());
        sgel.setOrder_by("");
        sgel.setOffset(0);
        ArrayList<String> reqFields = new ArrayList<String>();
        reqFields.add("id");
        sgel.setSelect_fields(reqFields);
        sgel.setMax_results(-1);
        sgel.setDeleted(false);
        sgel.setLink_name_to_fields_array(new HashMap<String, List<String>>());

        String searchJson = gson.toJson(sgel);

        String respJSON = execJson(searchJson, "get_entry_list");

        JSONObject jsonObj = (JSONObject) JSONValue.parse(respJSON);
        JSONArray jsonArray = (JSONArray) jsonObj.get("entry_list");
        String id = (String) ((JSONObject) jsonArray.get(0)).get("id");

        SugarGetEntry sge = new SugarGetEntry();
        sge.setId(id);
        sge.setSession(sessionId);
        sge.setSelect_fields(new ArrayList<String>());
        sge.setModule_name("Contacts");
        sge.setLink_name_to_fields_array(new HashMap<String, List<String>>());
        searchJson = gson.toJson(sge);
        respJSON = execJson(searchJson, "get_entry");
        //System.out.println(respJSON);
        SugarEntrySet res = gson.fromJson(respJSON, SugarEntrySet.class);

        User user = new User(userID);

        SugarContactEntry sce = res.getEntry_list().get(0);
        for (String attrName : sce.getName_value_list().keySet()) {
            NVP nvp = sce.getName_value_list().get(attrName);

            if (attributes.size() > 0 && !attributes.contains(nvp.getName())) {
                continue;
            }

            if (nvp.getValue() != null && !nvp.getValue().isEmpty()) {
                Attribute attr = new Attribute(nvp.getName(), nvp.getValue());
                user.getAttribs().put(nvp.getName(), attr);
            }
        }

        return user;

    } catch (Exception e) {
        throw new ProvisioningException("Could not find user", e);
    }
}

From source file:de.fhg.fokus.odp.middleware.ckan.CKANGatewayUtil.java

/**
 * Returns a list of the most popular tags.
 * /*  ww w . j  a va  2  s . c  o  m*/
 * @param numberOfTags
 *            the number of popular tags to return.
 * @return the most popular tags or null if an error occurred.
 */
@SuppressWarnings("unchecked")
public static JSONArray getMostPopularTags(int numberOfTags) {
    // check the parameters
    if (numberOfTags <= 0) {
        return null;
    }

    // the JSON array to return
    JSONArray toReturn = new JSONArray();

    // prepare the REST API call
    String RESTcall = "api/tag_counts";

    try {
        String tagListString = connectorInstance.restCall(RESTcall);

        if (tagListString == null) {
            log.log(Level.SEVERE, "Failed to realize api call \"" + url + RESTcall + "\" !!!");
            return null;
        }

        // parse the JSON string and obtain an array of JSON objects
        Object obj = JSONValue.parse(tagListString);
        JSONArray array = (JSONArray) obj;

        HashMap<String, Long> map = new HashMap<String, Long>();

        // fill unsorted HashMap with all keys and values
        for (Object tag : array) {
            JSONArray tagArray = (JSONArray) tag;
            map.put((String) tagArray.get(0), (Long) tagArray.get(1));
        }

        // call sortHashMapByValues
        HashMap<String, Long> sortedHashMap = sortHashMapByValues(map);

        // calculate number of return array size
        if (sortedHashMap.size() < numberOfTags) {
            numberOfTags = sortedHashMap.size();
        }

        // iterate over n fields and fill toReturn
        if (sortedHashMap.size() >= numberOfTags) {
            List<String> mapKeys = new ArrayList<String>(sortedHashMap.keySet());
            Iterator<String> keyIt = mapKeys.iterator();
            int i = 0;
            while (keyIt.hasNext() && i < numberOfTags) {
                String key = keyIt.next();
                // (key, (Long) sortedHashMap.get(key));
                JSONObject tag = new JSONObject();
                tag.put("count", sortedHashMap.get(key));
                tag.put("tag_name", key);
                toReturn.add(tag);
                i++;
            }
        }
    }
    // catch potential exceptions
    catch (MalformedURLException e) {
        log.log(Level.SEVERE, "Malformed URL \"" + url + RESTcall + "\" !!!");
        return null;
    } catch (IOException e) {
        return null;
    }

    return toReturn;
}

From source file:alexaactions.SmartThingsAgent.java

String getById(String path, String id) {
    String devices_json = get(path);

    System.out.println(devices_json);

    JSONParser parser = new JSONParser();
    Object obj = null;//  w w w .  j  a v  a  2s . c o m
    JSONObject device;
    JSONArray arr;

    // the whole purpose of this code is to determine if the id is valid
    try {
        obj = parser.parse(devices_json);
    } catch (ParseException ex) {
        Logger.getLogger(SmartThingsTemperatureDevices.class.getName()).log(Level.SEVERE, null, ex);
    }

    arr = (JSONArray) obj;
    if (arr != null) {
        int i, j;

        for (i = 0; i < arr.size(); i++) {
            device = (JSONObject) arr.get(i);
            String d_id = (String) device.get("id");
            if (d_id == null ? id == null : d_id.equals(id)) {
                for (j = 0; j < endpoints.size(); j++) {
                    JSONObject e = (JSONObject) endpoints.get(j);
                    String url = (String) e.get("uri") + "/" + path + "/" + d_id;
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Authorization", "Bearer " + access_token);

                    return smartthings.get(url, headers);
                }
            }
        }
    }
    return null;
}

From source file:alexaactions.SmartThingsAgent.java

String getByLabel(String path, String label) {
    String devices_json = get(path);

    System.out.println(devices_json);

    JSONParser parser = new JSONParser();
    Object obj = null;/*  ww  w  .  jav a 2  s  .  c  o  m*/
    JSONObject device;
    JSONArray arr;

    // the whole purpose of this code is to determine if the id is valid
    try {
        obj = parser.parse(devices_json);
    } catch (ParseException ex) {
        Logger.getLogger(SmartThingsTemperatureDevices.class.getName()).log(Level.SEVERE, null, ex);
    }

    arr = (JSONArray) obj;
    if (arr != null) {
        int i, j;

        for (i = 0; i < arr.size(); i++) {
            device = (JSONObject) arr.get(i);
            String d_label = (String) device.get("label");
            String d_id = (String) device.get("id");
            if (d_label == null ? label == null : d_label.equals(label)) {
                for (j = 0; j < endpoints.size(); j++) {
                    JSONObject e = (JSONObject) endpoints.get(j);
                    String url = (String) e.get("uri") + "/" + path + "/" + d_id;
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Authorization", "Bearer " + access_token);

                    return smartthings.get(url, headers);
                }
            }
        }
    }
    return null;
}

From source file:moderation.Moderate.java

public List getInstapost() throws SQLException {
    List savedpost = getSavedList(album_id);
    List posts = new ArrayList();
    try {//  w  w w.  j  a  v  a 2  s .  c o  m
        String access_token = new Api().getInsta_token();
        String tagname = this.hash;
        String url = "https://api.instagram.com/v1/tags/" + tagname + "/media/recent?access_token="
                + access_token + "&count=50";
        System.out.println(url);
        try {
            String genreJson = IOUtils.toString(new URL(url));
            JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
            String data = "";
            JSONArray genreArray = (JSONArray) genreJsonObject.get("data");
            JSONObject pagination = (JSONObject) genreJsonObject.get("pagination");
            this.instanext = (String) pagination.get("next_url");

            if (genreArray.size() > 0) {
                for (int i = 0; i < genreArray.size(); i++) {
                    JSONObject firstGenre = (JSONObject) genreArray.get(i);
                    PostModel post = new PostModel();
                    post.setAlbum_id(this.album_id);
                    //parameter

                    // post_id   
                    if (firstGenre.get("id") != null) {
                        post.setPost_id(firstGenre.get("id").toString());
                        if (savedpost.contains(firstGenre.get("id")))
                            post.setStatus("old");
                        else
                            post.setStatus("new");
                    }
                    //post_creation time    
                    if (firstGenre.get("created_time") != null)
                        post.setPost_time(firstGenre.get("created_time").toString());
                    // post type  
                    if (firstGenre.get("type") != null)
                        post.setType(firstGenre.get("type").toString());

                    // post link

                    if (firstGenre.get("link") != null)
                        post.setLink(firstGenre.get("link").toString());
                    // sender details name, id, pic 

                    if (firstGenre.get("user") != null) {
                        JSONObject user = (JSONObject) firstGenre.get("user");
                        post.setSender_id((String) user.get("id"));
                        post.setSender_name((String) user.get("full_name"));
                        post.setSender_pic((String) user.get("profile_picture"));

                    }

                    //post message

                    JSONObject caption = (JSONObject) firstGenre.get("caption");
                    if (caption != null)
                        post.setCaption_text(URLEncoder.encode((String) caption.get("text"), "UTF-8"));

                    boolean ispic = false;
                    String pic = "";
                    if (firstGenre.get("type").toString().equalsIgnoreCase("image")) {
                        ispic = true;
                        JSONObject images = (JSONObject) firstGenre.get("images");
                        if (images != null) {
                            JSONObject low_resolution = (JSONObject) images.get("low_resolution");
                            JSONObject standard_resolution = (JSONObject) images.get("standard_resolution");
                            post.setImage_low((String) low_resolution.get("url"));
                            post.setImage_standard((String) standard_resolution.get("url"));
                            //  out.println("<br/>original="+post_message+"<br/>encoded="+post_messageencode);
                            post.setParam("post_id=" + post.getPost_id() + "&album_id=" + post.getAlbum_id()
                                    + "&type=" + post.getType() + "&post_time=" + post.getPost_time() + "&link="
                                    + post.getLink() + "&pic_low=" + post.getImage_low() + "&pic_standard="
                                    + post.getImage_standard() + "&post_message=" + post.getCaption_text()
                                    + "&sender_name=" + post.getSender_name() + "&sender_id="
                                    + post.getSender_id() + "&sender_pic=" + post.getSender_pic());

                        }
                    }

                    if (ispic == true)
                        posts.add(post);
                }

            }

        } catch (IOException | ParseException e) {
            System.err.println("Exception occure in getInstapost inner try catch" + e);
        }

    } catch (Exception e) {
        System.err.println("Exception in getinstapost method main try-catch" + e);
    }

    return posts;
}

From source file:iphonestalker.util.FindMyIPhoneReader.java

public String connect(String username, String password) {

    numDevices = 0;//w  w w  .  j  a v  a 2s. c o m

    // Setup HTTP parameters
    HttpParams params = new BasicHttpParams();
    params.setParameter("http.useragent", "Find iPhone/1.1 MeKit (iPhone: iPhone OS/4.2.1)");
    client = new DefaultHttpClient(params);

    // Construct the post
    post = new HttpPost("https://fmipmobile.me.com/fmipservice/device/" + username);
    post.addHeader("X-Client-Uuid", "0000000000000000000000000000000000000000");
    post.addHeader("X-Client-Name", "My iPhone");
    Header[] headers = { new BasicHeader("X-Apple-Find-Api-Ver", "2.0"),
            new BasicHeader("X-Apple-Authscheme", "UserIdGuest"),
            new BasicHeader("X-Apple-Realm-Support", "1.0"),
            new BasicHeader("Content-Type", "application/json; charset=utf-8"),
            new BasicHeader("Accept-Language", "en-us"), new BasicHeader("Pragma", "no-cache"),
            new BasicHeader("Connection", "keep-alive"), new BasicHeader("Authorization",
                    "Basic " + new String(Base64.encodeBase64((username + ":" + password).getBytes()))) };
    post.setHeaders(headers);

    HttpResponse response = null;
    try {
        // Execute
        response = client.execute(post);

        // We should get a redirect
        if (response.getStatusLine().getStatusCode() == 330) {
            String newHost = (((Header[]) response.getHeaders("X-Apple-MME-Host"))[0]).getValue();
            try {
                post.setURI(new URI("https://" + newHost + "/fmipservice/device/" + username + "/initClient"));
            } catch (URISyntaxException ex) {
                logger.log(Level.SEVERE, null, ex);
                return "Couldn't post URI: " + ex;
            }

            // Dump the data so we can execute a new post
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            JSONObject object = (JSONObject) JSONValue.parse(reader);

            // This post should get us our data
            response = client.execute(post);
            reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

            // Read the data
            object = (JSONObject) JSONValue.parse(reader);
            JSONArray array = ((JSONArray) object.get("content"));
            numDevices = array.size();

            // Setup the route data
            iPhoneRouteList = new ArrayList<IPhoneRoute>();

            for (int i = 0; i < numDevices; i++) {
                // Get the device data
                object = (JSONObject) array.get(i);
                IPhoneLocation iPhoneLocation = getLocation(object);

                // Add route data
                IPhoneRoute iPhoneRoute = new IPhoneRoute();
                String modelDisplayName = (String) object.get("modelDisplayName");
                String deviceModelName = (String) object.get("deviceModel");
                String name = (String) object.get("name");

                Calendar cal = Calendar.getInstance();
                cal.setTimeInMillis(System.currentTimeMillis());
                iPhoneRoute.name = "[FMI #" + (i + 1) + "]" + name + ":" + modelDisplayName + " "
                        + deviceModelName;
                iPhoneRoute.lastBackupDate = cal.getTime();
                iPhoneRoute.setFMI(true);

                if (iPhoneLocation != null) {
                    iPhoneRoute.addLocation(iPhoneLocation);
                }
                iPhoneRouteList.add(iPhoneRoute);
            }

        } else {
            logger.log(Level.WARNING, "Couldn\'t retrieve iPhone data: " + response.getStatusLine().toString());
            return "Couldn't retrieve iPhone data: " + response.getStatusLine().toString();
        }
    } catch (ClientProtocolException ex) {
        logger.log(Level.SEVERE, null, ex);
        return "Couldn't retrieve iPhone data: " + ex;
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
        return "Couldn't retrieve iPhone data: " + ex;
    }

    return null;
}