Example usage for org.json.simple JSONArray iterator

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

Introduction

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

Prototype

public Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this list in proper sequence.

Usage

From source file:com.healthcit.analytics.utils.ExcelExportUtils.java

@SuppressWarnings("unchecked")
public static void streamVisualizationDataAsExcelFormat(OutputStream out, JSONObject data) {
    // Get the array of columns
    JSONArray jsonColumnArray = (JSONArray) data.get(COLUMNS_JSON_KEY);

    String[] excelColumnArray = new String[jsonColumnArray.size()];

    for (int index = 0; index < excelColumnArray.length; ++index) {
        excelColumnArray[index] = (String) ((JSONObject) jsonColumnArray.get(index)).get(LABEL_JSON_KEY);
    }//from   w  ww. j a v a 2 s. c  o  m

    // Get the array of rows
    JSONArray jsonRowArray = (JSONArray) data.get(ROWS_JSON_KEY);

    JSONArray excelRowArray = new JSONArray();

    Iterator<JSONObject> jsonRowIterator = jsonRowArray.iterator();

    while (jsonRowIterator.hasNext()) {
        JSONArray rowCell = (JSONArray) jsonRowIterator.next().get(ROWCELL_JSON_KEY);

        JSONObject excelRowObj = new JSONObject();

        for (int index = 0; index < rowCell.size(); ++index) {

            excelRowObj.put(excelColumnArray[index],
                    ((JSONObject) rowCell.get(index)).get(ROWCELLVALUE_JSON_KEY));
        }

        excelRowArray.add(excelRowObj);
    }

    // build the Excel outputstream
    Json2Excel.build(out, excelRowArray.toJSONString(), excelColumnArray);
}

From source file:br.com.RatosDePC.Brpp.compiler.BrppCompiler.java

public static boolean compile(String path) {
    setFile(FileUtils.getBrinodirectory() + System.getProperty("file.separator") + "Arduino");
    setFile(getFile()//from   w w w.  j a  v  a 2 s .  c  o m
            .concat(path.substring(path.lastIndexOf(System.getProperty("file.separator")), path.length() - 5)));
    setFile(getFile()
            .concat(path.substring(path.lastIndexOf(System.getProperty("file.separator")), path.length() - 4)));
    setFile(getFile().concat("ino"));
    File ino = new File(getFile());
    if (!ino.exists()) {
        try {
            ino.getParentFile().mkdirs();
            ino.createNewFile();
        } catch (IOException e) {

        }
    }
    try {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        String code = new String(encoded);
        JSONArray Keywords = JSONUtils.getKeywords();
        @SuppressWarnings("unchecked")
        Iterator<JSONObject> iterator = Keywords.iterator();
        while (iterator.hasNext()) {
            JSONObject key = iterator.next();
            String arg = (String) key.get("arg");
            if (arg.equals("false")) {
                code = code.replace((String) key.get("translate"), (String) key.get("arduino"));
            } else {
                code = code.replaceAll((String) key.get("translate"), (String) key.get("arduino"));
            }
        }

        try (FileWriter file = new FileWriter(getFile())) {
            file.write(code);
        }
        System.out.println(code);
        return true;

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;

}

From source file:eu.ebbitsproject.peoplemanager.utils.HttpUtils.java

public static String findPerson(String errorType, String location) {

    CloseableHttpClient httpClient = HttpClients.createDefault();

    String url = PropertiesUtils.getProperty("uiapp.address");

    HttpPost httpPost = new HttpPost(url);

    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("action", "find-persons"));
    String properties = "demo-e1:competence=" + errorType + ",demo-e1:area-responsibility=" + location;
    String pmProperties = "available=true";
    nvps.add(new BasicNameValuePair("properties", properties));
    nvps.add(new BasicNameValuePair("pmProperties", pmProperties));

    try {//  www .  j a v  a 2  s  .  co m
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, ex);
    }

    CloseableHttpResponse response = null;
    String personJSON = null;
    try {
        response = httpClient.execute(httpPost);
        personJSON = EntityUtils.toString(response.getEntity());
        System.out.println("######## PersonJSON: " + personJSON);
    } catch (IOException e) {
        Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    if (personJSON != null) {
        JSONArray persons = (JSONArray) JSONValue.parse(personJSON);
        Iterator<JSONObject> i = persons.iterator();
        if (i.hasNext()) {
            JSONObject o = i.next();
            return o.get("id").toString();
        }
    }

    return personJSON;
}

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);/*from   w  w  w  . java 2  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:luceneindexdemo.LuceneIndexDemo.java

public static void missOperation(String type)
        throws FileNotFoundException, IOException, org.json.simple.parser.ParseException, SQLException {
    //JSONObject jsObject=new JSONObject();
    System.out.println("this brings out all your connection with the person you miss");
    String query = "match (n:People)-[r:KNOWS]-(b:People) where n.name='" + user + "' and r.relType='" + type
            + "' return filter(x in n.interest where x in b.interest) as common,b.name";
    Connection con = DriverManager.getConnection("jdbc:neo4j://localhost:7474/");
    ResultSet rs = con.createStatement().executeQuery(query);
    JSONParser jsParser = new JSONParser();
    FileReader freReader = new FileReader("/home/rishav12/NetBeansProjects/LuceneIndexDemo/location.json");
    JSONObject jsono = (JSONObject) jsParser.parse(freReader);
    JSONArray jslocArray = (JSONArray) jsono.get("CHENNAI");
    int count = 0;
    while (rs.next()) {
        System.out.println(rs.getString("b.name"));
        String searchQuery = "start n=node:restaurant('withinDistance:[" + jslocArray.get(0) + ","
                + jslocArray.get(1) + ",13.5]') where ";
        JSONArray jsArray = (JSONArray) jsParser.parse(rs.getString("common"));
        Iterator<JSONArray> iterJsArray = jsArray.iterator();

        count++;// w ww .  j  a  v  a  2s  . c om
        int k = 0;
        int flag = 0;
        while (iterJsArray.hasNext()) {
            flag = 1;
            if (k == 0) {
                searchQuery = searchQuery + "n.type='" + iterJsArray.next() + "'";
                k = k + 1;

            } else
                searchQuery = searchQuery + " or n.type='" + iterJsArray.next() + "'";
        }

        if (flag == 1) {
            searchQuery += " return n.name,n.type";
            ResultSet commonInterest = con.createStatement().executeQuery(searchQuery);
            System.out.println("Sir based on your common interests with " + rs.getString("b.name")
                    + " \ni will plan out something nearby you");
            while (commonInterest.next()) {
                System.out
                        .println(commonInterest.getString("n.name") + " " + commonInterest.getString("n.type"));
            }
        } else {
            System.err.println("you do not seem to share any common interest with" + rs.getString("b.name"));
        }

    }
    return;

}

From source file:com.modeln.batam.connector.wrapper.ReportEntry.java

@SuppressWarnings("unchecked")
public static ReportEntry fromJSON(JSONObject obj) {
    String id = (String) obj.get("id");
    String name = (String) obj.get("name");
    String buildId = (String) obj.get("build_id");
    String buildName = (String) obj.get("build_name");
    String description = (String) obj.get("description");
    String startDate = (String) obj.get("start_date");
    String endDate = (String) obj.get("end_date");
    String status = (String) obj.get("status");

    List<String> logs = new ArrayList<String>();
    JSONArray logsArray = (JSONArray) obj.get("logs");
    if (logsArray != null) {
        for (Iterator<String> it = logsArray.iterator(); it.hasNext();) {
            String log = (String) it.next();
            logs.add(log);/*from   w  w w .ja v  a 2  s . c o  m*/
        }
    }
    boolean isCustomFormatEnabled = (Boolean) obj.get("isCustomFormatEnabled") == null ? false
            : (Boolean) obj.get("isCustomFormatEnabled");
    String customFormat = (String) obj.get("customFormat");
    String customEntry = (String) obj.get("customEntry");
    return new ReportEntry(id, name, buildId, buildName, description,
            startDate == null ? null : new Date(Long.valueOf(startDate)),
            endDate == null ? null : new Date(Long.valueOf(endDate)), status, logs, isCustomFormatEnabled,
            customFormat, customEntry);
}

From source file:model.Post_store.java

public static List<String> getpostcomments(int id) {

    JSONParser parser = new JSONParser();
    List<String> comments = new ArrayList<>();

    try {//  ww w  . j av a2 s  . c om

        Object obj = parser.parse(new FileReader(root + "posts/" + id + ".json"));

        JSONObject jsonObject = (JSONObject) obj;

        JSONArray Jcomments = (JSONArray) jsonObject.get("comments");
        if (Jcomments != null) {
            Iterator<String> iterator = Jcomments.iterator();
            while (iterator.hasNext()) {
                comments.add(iterator.next());
            }
        }

    } catch (FileNotFoundException e) {
        System.out.println(e);
    } catch (IOException e) {
        System.out.println(e);
    } catch (ParseException e) {
        System.out.println(e);
    }

    return comments;

}

From source file:model.Post_store.java

public static List<String> getpostUAcomments(int id) {

    JSONParser parser = new JSONParser();
    List<String> UA_comments = new ArrayList<>();

    try {//from ww  w  . j a va 2s.co  m

        Object obj = parser.parse(new FileReader(root + "posts/" + id + ".json"));

        JSONObject jsonObject = (JSONObject) obj;

        JSONArray JUAcomments = (JSONArray) jsonObject.get("UA_comments");
        if (JUAcomments != null) {
            Iterator<String> iterator = JUAcomments.iterator();
            while (iterator.hasNext()) {
                UA_comments.add(iterator.next());
            }
        }

    } catch (FileNotFoundException e) {
        System.out.println(e);
    } catch (IOException e) {
        System.out.println(e);
    } catch (ParseException e) {
        System.out.println(e);
    }

    return UA_comments;

}

From source file:com.jts.rest.profileservice.utils.RestServiceHelper.java

/**
 * Gets the recent challenges and splits them to active and past challenges
 * Maximum 3 past challenges and all active challenges will be returned
 * @param sessionId//from  w  w  w . j  a  v a  2s.  c o m
 * @param username
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static JSONObject getProcessedChallengesM2(String sessionId, String username)
        throws MalformedURLException, IOException {
    JSONArray recentChallenges = getRecentParticipantChallengesByUsername(sessionId, username);
    JSONArray activeChallenges = new JSONArray();
    JSONArray pastChallenges = new JSONArray();

    Iterator<JSONObject> iterator = recentChallenges.iterator();
    while (iterator.hasNext()) {
        JSONObject participantChallenge = iterator.next();
        JSONObject challenge = (JSONObject) participantChallenge.get("Challenge__r");
        if (challenge.get("Status__c").equals(PSContants.STATUS_CREATED)) { //active challenge
            activeChallenges.add(participantChallenge);
            JSONArray categories = getCategoriesByChallenge(sessionId,
                    (String) participantChallenge.get("Challenge__c"));
            participantChallenge.put("categories", categories);
        } else { //past challenges
            if (pastChallenges.size() < 3) {
                pastChallenges.add(participantChallenge);
                JSONArray categories = getCategoriesByChallenge(sessionId,
                        (String) participantChallenge.get("Challenge__c"));
                participantChallenge.put("categories", categories);
            }
        }
    }
    JSONObject challenges = new JSONObject();
    challenges.put("activeChallenges", activeChallenges);
    challenges.put("pastChallenges", pastChallenges);
    challenges.put("totalChallenges", getChallengeCountByUser(sessionId, username));
    return challenges;
}

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 {//w  w  w .ja  v a  2 s. c  om
        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;
}