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.juniform.JUniformPackerJSON.java

@Override
public JUniformObject toUniformObjectFromObject(Object object) {
    if (object == null) {
        return JUniformObject.OBJECT_NIL;
    } else if (object instanceof JSONObject) {
        JSONObject jsonMap = (JSONObject) object;
        Map<Object, Object> map = new HashMap<>();
        Iterator it = jsonMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            map.put(pair.getKey(), this.toUniformObjectFromObject(pair.getValue()));
        }/*from  w  w w. j  a va2 s.c o m*/
        return new JUniformObject(map);

    } else if (object instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) object;
        ArrayList<Object> array = new ArrayList<>();
        @SuppressWarnings("unchecked")
        Iterator<Object> it = jsonArray.iterator();
        while (it.hasNext()) {
            array.add(this.toUniformObjectFromObject(it.next()));
        }
        return new JUniformObject(array);
    } else {
        return new JUniformObject(object);
    }
}

From source file:de.hstsoft.sdeep.NoteManager.java

public void loadNotes() throws IOException, ParseException {

    File file = new File(directory + FILENAME);
    if (file.exists()) {

        Reader reader = new BufferedReader(new FileReader(file));
        JSONParser jsonParser = new JSONParser();
        JSONObject json = (JSONObject) jsonParser.parse(reader);
        reader.close();/*w ww. ja  v a2  s .  c o m*/

        int version = Integer.parseInt(json.get("version").toString());
        if (VERSION != version) {
            System.out.println("Can not load Notes. invalid version.");
        }

        JSONArray notesArray = (JSONArray) json.get("notes");

        this.notes = new ArrayList<>();
        @SuppressWarnings("rawtypes")
        Iterator iterator = notesArray.iterator();
        while (iterator.hasNext()) {
            JSONObject noteJson = (JSONObject) iterator.next();
            Note note = Note.fromJson(noteJson);
            notes.add(note);
        }
    }

}

From source file:com.netflix.dyno.connectionpool.impl.lb.TokenMapSupplierImpl.java

List<HostToken> parseTokenListFromJson(String json) {

    List<HostToken> hostTokens = new ArrayList<HostToken>();

    JSONParser parser = new JSONParser();
    try {//from  w  w w .  ja va  2 s. c o m
        JSONArray arr = (JSONArray) parser.parse(json);

        Iterator<?> iter = arr.iterator();
        while (iter.hasNext()) {

            Object item = iter.next();
            if (!(item instanceof JSONObject)) {
                continue;
            }
            JSONObject jItem = (JSONObject) item;

            Long token = Long.parseLong((String) jItem.get("token"));
            String hostname = (String) jItem.get("hostname");
            String zone = (String) jItem.get("zone");

            Host host = new Host(hostname, port, Status.Up).setRack(zone);
            HostToken hostToken = new HostToken(token, host);
            hostTokens.add(hostToken);
        }

    } catch (ParseException e) {
        Logger.error("Failed to parse json response: " + json, e);
        throw new RuntimeException(e);
    }

    return hostTokens;
}

From source file:data.GoogleBooksWS.java

@Override
public void parse(String tekst) throws Exception {

    //List<Book> lista=new ArrayList<>();

    JSONParser parser = new JSONParser();
    Object obj = parser.parse(tekst);
    JSONObject jsonObject = (JSONObject) obj;
    if (prvi) {//  w w w. j a  v  a2s  .c om
        int brojRezultata = Integer.parseInt(jsonObject.get("totalItems") + "");
        ukupanBrojStrana = brojRezultata / RESULTS_PER_PAGE + 1;
        System.out.println("Broj strana" + ukupanBrojStrana);
        prvi = false;
    }

    System.out.println("Trenutni broj strane " + trenutniBrojStrane);
    JSONArray niz = (JSONArray) jsonObject.get("items");
    if (niz == null) {
        kraj = true;
    } else {
        Iterator iterator = niz.iterator();
        while (iterator.hasNext()) {
            Book b = new Book();
            b.setUri(URIGenerator.generateUri(b));
            JSONObject book = (JSONObject) iterator.next();
            b.setTitle((String) ((JSONObject) book.get("volumeInfo")).get("title"));
            JSONArray autori = (JSONArray) ((JSONObject) book.get("volumeInfo")).get("authors");
            if (autori != null) {
                Iterator it = autori.iterator();
                while (it.hasNext()) {
                    Person p = new Person();
                    p.setUri(URIGenerator.generateUri(p));
                    p.setName((String) it.next());
                    b.getAuthors().add(p);
                }
            } else {
                System.out.println("Autori su null");
            }
            Organization o = new Organization();
            o.setUri(URIGenerator.generateUri(o));
            o.setName((String) ((JSONObject) book.get("volumeInfo")).get("publisher"));
            b.setPublisher(o);
            String date = (String) ((JSONObject) book.get("volumeInfo")).get("publishedDate");
            System.out.println(date);
            b.setDatePublished(date);

            String description = (String) ((JSONObject) book.get("volumeInfo")).get("description");
            b.setDescription(description);

            Object brStr = ((JSONObject) book.get("volumeInfo")).get("pageCount");
            if (brStr != null) {
                long broj = Long.parseLong(brStr.toString());
                b.setNumberOfPages((int) broj);
            }

            JSONArray identifiers = (JSONArray) ((JSONObject) book.get("volumeInfo"))
                    .get("industryIdentifiers");
            if (identifiers != null) {
                for (int i = 0; i < identifiers.size(); i++) {
                    JSONObject identifier = (JSONObject) identifiers.get(i);
                    if ("ISBN_13".equals((String) identifier.get("type"))) {
                        b.setIsbn((String) identifier.get("identifier"));
                    }
                }
            }
            //b.setIsbn((String) ((JSONObject) ((JSONArray)((JSONObject)book.get("volumeInfo")).get("industryIdentifiers")).get(1)).get("identifier"));

            lista.add(b);

        }

        if (trenutniBrojStrane < ukupanBrojStrana) {
            trenutniBrojStrane++;
        } else {
            kraj = true;
        }
    }
}

From source file:it.polimi.diceH2020.plugin.control.JSonReader.java

public void read() {
    // read the json file
    FileReader reader;/*  w  ww .  java  2 s . c  om*/

    try {
        reader = new FileReader(filePath);

        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
        provider = (String) jsonObject.get("provider");
        JSONArray lang = (JSONArray) jsonObject.get("lstSolutions");
        Iterator<?> i = lang.iterator();

        // take each value from the json array separately
        while (i.hasNext()) {
            JSONObject innerObj = (JSONObject) i.next();
            String idClass = (String) innerObj.get("id");
            long numVm = (long) innerObj.get("numberVM");
            JSONObject jsonOb = (JSONObject) innerObj.get("typeVMselected");
            String type = (String) jsonOb.get("id");
            this.classNumVM.put(idClass, numVm);
            this.classTypeVM.put(idClass, type);
            this.classes.add(idClass);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:net.phyloviz.nj.json.NJItemFactory.java

private Map<Integer, NJUnionNode> createUnions(JSONArray union, Map<Integer, NJLeafNode> leafs) {
    int size = leafs.size();
    HashMap<Integer, NJUnionNode> unions = new HashMap(size);
    for (Iterator<JSONObject> it = union.iterator(); it.hasNext();) {
        JSONObject l = it.next();/*from  ww w  . ja va2 s  .com*/
        Integer id = (int) (long) l.get("id");
        Integer nl = (int) (long) l.get("left");
        Integer nr = (int) (long) l.get("right");
        float dl = (float) (double) l.get("distanceLeft");
        float dr = (float) (double) l.get("distanceRight");

        NodeType node1 = nl >= size ? unions.get(nl) : leafs.get(nl);
        NodeType node2 = nr >= size ? unions.get(nr) : leafs.get(nr);
        unions.put(id, new NJUnionNode(node1, dl, node2, dr, size, 0, null, id));
    }
    return unions;
}

From source file:com.martin.zkedit.controller.Login.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Login Post Action!");
    try {//from   www. j  a  va 2s .  co m
        Properties globalProps = (Properties) getServletContext().getAttribute("globalProps");
        Map<String, Object> templateParam = new HashMap<>();
        HttpSession session = request.getSession(true);
        session.setMaxInactiveInterval(Integer.valueOf(globalProps.getProperty("sessionTimeout")));
        //TODO: Implement custom authentication logic if required.
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String role = null;
        Boolean authenticated = false;
        //if ldap is provided then it overrides roleset.
        if (globalProps.getProperty("ldapAuth").equals("true")) {
            authenticated = new LdapAuth().authenticateUser(globalProps.getProperty("ldapUrl"), username,
                    password, globalProps.getProperty("ldapDomain"));
            if (authenticated) {
                JSONArray jsonRoleSet = (JSONArray) ((JSONObject) new JSONParser()
                        .parse(globalProps.getProperty("ldapRoleSet"))).get("users");
                for (Iterator it = jsonRoleSet.iterator(); it.hasNext();) {
                    JSONObject jsonUser = (JSONObject) it.next();
                    if (jsonUser.get("username") != null && jsonUser.get("username").equals("*")) {
                        role = (String) jsonUser.get("role");
                    }
                    if (jsonUser.get("username") != null && jsonUser.get("username").equals(username)) {
                        role = (String) jsonUser.get("role");
                    }
                }
                if (role == null) {
                    role = ZooKeeperUtil.ROLE_USER;
                }

            }
        } else {
            JSONArray jsonRoleSet = (JSONArray) ((JSONObject) new JSONParser()
                    .parse(globalProps.getProperty("userSet"))).get("users");
            for (Iterator it = jsonRoleSet.iterator(); it.hasNext();) {
                JSONObject jsonUser = (JSONObject) it.next();
                if (jsonUser.get("username").equals(username) && jsonUser.get("password").equals(password)) {
                    authenticated = true;
                    role = (String) jsonUser.get("role");
                }
            }
        }
        if (authenticated) {
            logger.info("Login successfull: " + username);
            session.setAttribute("authName", username);
            session.setAttribute("authRole", role);
            response.sendRedirect("/home");
        } else {
            session.setAttribute("flashMsg", "Invalid Login");
            ServletUtil.INSTANCE.renderHtml(request, response, templateParam, "login.html.ftl");
        }

    } catch (ParseException | TemplateException ex) {
        ServletUtil.INSTANCE.renderError(request, response, ex.getMessage());
    }
}

From source file:msgclient.ServerConnection.java

public ArrayList<String> lookupUsers() {
    ArrayList<String> result = new ArrayList<String>();

    JSONObject jsonObject = makeGetToServer(USERLOOKUP_PATH);
    if (jsonObject == null) {
        return null;
    }//from w  w  w .j a  v a2  s  . c o m

    try {
        long numUsers = (long) jsonObject.get("numUsers");
        if (numUsers <= 0) {
            return result;
        }

        JSONArray users = (JSONArray) jsonObject.get("users");
        Iterator<String> iterator = users.iterator();
        while (iterator.hasNext()) {
            String nextUser = iterator.next();
            result.add(nextUser);
        }
    } catch (Exception e) {
        // Some kind of problem
        return null;
    }

    return result;
}

From source file:it.uniud.ailab.dcore.annotation.annotators.TagMeTokenAnnotator.java

/**
 * The method that actually does the job: it tags a text string with
 * Wikipedia page titles when needed, and puts the result in a convenient
 * HashMap./*  w w w. j a  v  a2 s. c  o m*/
 * 
 * @param text the text to tag
 * @param lang the language of the text
 * @return an hashmap with the substrings of the input text and their matching
 * Wikipedia page
 */
private HashMap<String, String> tagSentence(String text, String lang) {
    HashMap<String, String> output = new HashMap();
    HttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(tagmeEndpoint);
    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("text", text));
    params.add(new BasicNameValuePair("key", apiKey));
    params.add(new BasicNameValuePair("lang", lang));
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new AnnotationException(this, "Encoding error while building TAGME request URL", e);
    }

    try {
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity respEntity = response.getEntity();

        if (respEntity != null) {
            // EntityUtils to get the response content
            String content = EntityUtils.toString(respEntity);
            Object obj = parser.parse(content);
            JSONObject queryblock = (JSONObject) obj;
            JSONArray annotationBlock = (JSONArray) queryblock.get("annotations");
            Iterator<JSONObject> iterator = annotationBlock.iterator();
            while (iterator.hasNext()) {
                JSONObject tag = (iterator.next());
                Float rho = Float.parseFloat((String) tag.get("rho"));
                if (rho > 0.15) {
                    String spot = (String) tag.get("spot");
                    String lemma = (String) tag.get("title");
                    output.put(spot, lemma);
                }

            }

        }
    } catch (ClientProtocolException e) {
        throw new AnnotationException(this, "Fail while querying TAGME", e);
    } catch (IOException e) {
        throw new AnnotationException(this, "Fail querying TAGME", e);
    } catch (ParseException e) {
        throw new AnnotationException(this, "Fail while parsing TAGME json", e);
    }
    return output;
}

From source file:ch.trustserv.soundbox.plugins.portals.jamendoplugin.JamendoPlugin.java

/**
 *
 * @param searchString/*w  ww.  ja  va  2 s. c  om*/
 * @return
 */
@Override
public Object searchSong(final String searchString) {

    URI link = null;
    try {
        link = new URI("http://api.jamendo.com/get2/id+name+album_name+"
                + "artist_name+duration/track/json/track_album+album_artist"
                + "?order=searchweight_desc&n=all&searchquery=" + searchString.replaceAll(" ", "%20"));
    } catch (URISyntaxException ex) {
        Logger.getLogger(JamendoPlugin.class.getName()).log(Level.SEVERE, null, ex);
    }
    HttpGet get = new HttpGet(link);
    HttpClient client = new DefaultHttpClient();
    Dictionary l = new Hashtable<>();
    ArrayList songArrayList = new ArrayList();
    JSONParser parser = new JSONParser();
    Object obj = null;
    try {
        HttpEntity entity = client.execute(get).getEntity();
        String entityAsString = EntityUtils.toString(entity);
        entity.getContent().close();
        if (entityAsString.isEmpty()) // something went wrong...
        {
            return null;
        }
        obj = parser.parse(entityAsString);

    } catch (IOException | IllegalStateException | ParseException | org.json.simple.parser.ParseException ex) {
        Logger.getLogger(JamendoPlugin.class.getName()).log(Level.SEVERE, null, ex);
    }

    JSONArray songs = (JSONArray) obj;
    Iterator iter = songs.iterator();
    JSONObject rawSong = null;
    while (iter.hasNext()) {
        try {
            rawSong = (JSONObject) parser.parse(iter.next().toString());
        } catch (org.json.simple.parser.ParseException ex) {
            Logger.getLogger(JamendoPlugin.class.getName()).log(Level.SEVERE, null, ex);
        }

        JamendoSong song = new JamendoSong(rawSong);
        songArrayList.add(song);
    }

    l.put("songList", songArrayList);
    l.put("portalName", "Jamendo");
    ServiceReference ref = cx.getServiceReference(EventAdmin.class.getName());
    if (ref != null) {
        EventAdmin eventAdmin = (EventAdmin) cx.getService(ref);
        Event reportGeneratedEvent = new Event(FOUNDSONG, l);

        eventAdmin.sendEvent(reportGeneratedEvent);
    }
    return null;
}