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:de.ingrid.external.gemet.GEMETMapper.java

/**
 * Map concepts to TreeTerms and add to given TreeTerm as parents or
 * children.//from  w w w.j  a va2  s  . c  o  m
 * 
 * @param node
 *            TreeTerm where to add other TreeTerms
 * @param concepts
 *            concepts added as TreeTerms
 * @param addAsParent
 *            true=add as parents, false= add as children
 * @return the given node for further processing
 */
private TreeTerm addToTreeTerm(TreeTerm node, JSONArray concepts, boolean addAsParent) {
    TreeTerm termToAdd = null;
    Iterator<JSONObject> iterator = concepts.iterator();
    while (iterator.hasNext()) {
        termToAdd = new TreeTermImpl();
        mapToTerm(iterator.next(), termToAdd);
        if (addAsParent)
            addParentTerm(node, termToAdd);
        else
            addChildTerm(node, termToAdd);
    }

    return node;
}

From source file:com.deem.zkui.controller.Login.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Login Post Action!");
    try {//from   w w w .  ja v a2s  .  c o 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;

        // We're going to read this from the env
        String userenv = null;
        String passenv = null;
        String roleenv = null;

        try {
            userenv = System.getenv(ZKUI_USERNAME);
            passenv = System.getenv(ZKUI_PASSWORD);
            roleenv = System.getenv(ZKUI_ROLE);
        } catch (NullPointerException | SecurityException ex) {
            logger.error("Couldn't read credentials from env, default to ldap...");
        }

        logger.info(String.format("User env: %s, user: %s", userenv, username));

        if (userenv == null || passenv == null) {
            logger.info("Thar be no environment variables set.");
            //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");
                    }
                }
            }
        } else {
            authenticated = (username.equals(userenv) && password.equals(passenv));
            role = roleenv;
        }

        if (authenticated) {
            logger.info("Login successful: " + 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.ftl.html");
        }

    } catch (ParseException | TemplateException ex) {
        logger.error(Arrays.toString(ex.getStackTrace()));
        ServletUtil.INSTANCE.renderError(request, response, ex.getMessage());
    }
}

From source file:luceneprueba.utils.Review.java

public List<Review> getListByJson(JSONArray reviews) {
    List<Review> reviewsList = new ArrayList();
    Iterator i = reviews.iterator();

    JSONObject json;//from  w  ww .j  av a2s  .  c o m
    int date;
    double puntaje;
    List<String> topics = new ArrayList();
    double[] clas1 = new double[3];
    double[] clas2 = new double[3];
    Iterator j;

    while (i.hasNext()) {
        json = (JSONObject) i.next();
        date = (int) json.get("fecha");
        puntaje = (double) json.get("score");
        j = (Iterator) json.get("topicos");
        while (j.hasNext()) {
            topics.add((String) j.next());
        }
        j = (Iterator) json.get("clasificador1");
        int count = 0;
        while (j.hasNext()) {
            clas1[count] = (double) j.next();
            count++;
        }
        j = (Iterator) json.get("clasificador2");
        count = 0;
        while (j.hasNext()) {
            clas2[count] = (double) j.next();
            count++;
        }
        //reviewsList.add(new Review(date, puntaje, topics, clas1, clas2));
    }

    return reviewsList;
}

From source file:Controladora.ConexionAPI.java

public List<Usuario> sendGetListaUsuarios(String token) {
    httpClient = null; // Objeto a travs del cual realizamos las peticiones
    request = null; // Objeto para realizar las peticiines HTTP GET o POST
    status = 0; // Cdigo de la respuesta HTTP
    reader = null; // Se usa para leer la respuesta a la peticin
    line = null; // Se usa para leer cada una de las lineas de texto de la respuesta

    List<Usuario> listaauxiliar = new ArrayList<Usuario>();
    Usuario usuario = new Usuario();

    // Instanciamos el objeto
    httpClient = new HttpClient();
    // Invocamos por GET
    String url = "http://localhost:8090/api/usuarios/";
    request = new GetMethod(url);
    // Aadimos los parmetros que deseemos a la peticin 
    request.setRequestHeader("token", token);
    try {/*from w w w  .  ja va  2s. co  m*/
        // Leemos el cdigo de la respuesta HTTP que nos devuelve el servidor
        status = httpClient.executeMethod(request);
        // Vemos si la peticin se ha realizado satisfactoriamente
        if (status != HttpStatus.SC_OK) {
            System.out.println("Error\t" + request.getStatusCode() + "\t" + request.getStatusText() + "\t"
                    + request.getStatusLine());
        } else {
            // Leemos el contenido de la respuesta y realizamos el tratamiento de la misma.
            // En nuestro caso, simplemente mostramos el resultado por la salida estndar
            reader = new BufferedReader(
                    new InputStreamReader(request.getResponseBodyAsStream(), request.getResponseCharSet()));

            JSONParser parser = new JSONParser();

            JSONValue jsonvalue = new JSONValue();

            String tkn = null;

            System.out.println("entro AL WHILE");

            listaauxiliar = null;
            line = reader.readLine();
            while (line != null) {
                System.out.println(line);

                System.out.println("uno");
                // JSONObject jso = (JSONObject) parser.parse(line);
                JSONArray jo = (JSONArray) jsonvalue.parse(line);
                //(JSONArray) jso.get("");
                System.out.println("antes de iterar");
                Iterator<String> iterator = jo.iterator();
                System.out.println("depues de iterar");
                while (iterator.hasNext()) {
                    System.out.println("Entro al while iterador");
                    System.out.println(iterator.next());
                }
                System.out.println("SALIO al while iterador");
                /*usuario.setMail((String) jo.get("mail"));
                usuario.setNombre((String) jo.get("nombre"));
                usuario.setUsuario((String) jo.get("usuario"));
                listaauxiliar.add(usuario);
                        
                System.out.println((String) jo.get("mail"));
                System.out.println((String) jo.get("nombre"));
                System.out.println((String) jo.get("usuario"));*/

                line = reader.readLine();
            }
        }
    } catch (Exception ex) {
        System.err.println("Error\t: " + ex.getMessage());

        ex.printStackTrace();
    } finally {
        // Liberamos la conexin. (Tambin libera los stream asociados)
        request.releaseConnection();
    }
    return listaauxiliar;
}

From source file:br.com.RatosDePC.Brpp.IDEui.CodeDocument.java

private void processKeywords() {
    JSONArray Keywords = JSONUtils.getKeywords();
    @SuppressWarnings("unchecked")
    Iterator<JSONObject> iterator = Keywords.iterator();
    while (iterator.hasNext()) {
        JSONObject key = iterator.next();
        String highType = (String) key.get("highlight-type");
        if (!highType.equals("null")) {
            int type = Integer.parseInt(highType);
            switch (type) {
            case 1:
                KEYWORDS_1 = KEYWORDS_1.concat(((String) key.get("highlight")).trim() + "|");
                break;
            case 2:
                KEYWORDS_2 = KEYWORDS_2.concat(((String) key.get("highlight")).trim() + "|");
                break;
            case 3:
                KEYWORDS_3 = KEYWORDS_3.concat(((String) key.get("highlight")).trim() + "|");
                break;
            case 4:
                KEYWORDS_4 = KEYWORDS_4.concat(((String) key.get("highlight")).trim() + "|");
                break;
            }//  ww  w  .j a v  a2  s  .  com
        }
    }

    KEYWORDS_4 = KEYWORDS_4.concat(KeywordManagerUtils.getKey());
    KEYWORDS_3 = KEYWORDS_3.concat(KeywordManagerUtils.getKeyTwo());
    KEYWORDS_1 = KEYWORDS_1.substring(0, KEYWORDS_1.length() - 1).concat(")");
    KEYWORDS_2 = KEYWORDS_2.substring(0, KEYWORDS_2.length() - 1).concat(")");
    if (KEYWORDS_3.contains("||"))
        KEYWORDS_3 = KEYWORDS_3.replace("||", "|");
    if (KEYWORDS_4.contains("||"))
        KEYWORDS_4 = KEYWORDS_4.replace("||", "|");
    KEYWORDS_3 = KEYWORDS_3.endsWith("|") ? KEYWORDS_3.substring(0, KEYWORDS_3.length() - 1).concat(")")
            : KEYWORDS_3.concat(")");
    KEYWORDS_4 = KEYWORDS_4.endsWith("|") ? KEYWORDS_4.substring(0, KEYWORDS_4.length() - 1).concat(")")
            : KEYWORDS_4.concat(")");
}

From source file:de.ingrid.external.gemet.GEMETMapper.java

public List<RelatedTerm> mapToRelatedTerms(JSONArray jsonArray, ConceptRelation conceptRelation) {
    List<RelatedTerm> resultList = new ArrayList<RelatedTerm>();

    Iterator<JSONObject> iterator = jsonArray.iterator();
    while (iterator.hasNext()) {
        resultList.add(mapToRelatedTerm(iterator.next(), conceptRelation));
    }//  w ww  .j av a 2 s .c o  m

    return resultList;
}

From source file:com.albert.javatest.JavaTestExample.java

@Ignore
@Test//from w  ww. ja v  a 2s.c o  m
public void testJacksonStream() {
    log.entering("OnekeyTAI", "loading Properties ...");

    JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(new FileReader("C:\\Projects\\sts-351-osap\\AlbertWeb\\src\\file.json"));

        JSONObject jsonObject = (JSONObject) obj;

        String name = (String) jsonObject.get("name");
        System.out.println(name);

        long age = (Long) jsonObject.get("age");
        System.out.println(age);

        // loop array
        JSONArray msg = (JSONArray) jsonObject.get("messages");
        Iterator<String> iterator = msg.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:net.gtl.movieanalytics.data.InfoStore.java

private void readJsonFile(String path) {
    JSONParser parser = new JSONParser();

    try {/*from   w  w w . j  a v a2 s.  c om*/
        JSONObject root = (JSONObject) parser.parse(new FileReader(path));
        double testRecordPercentage = (Double) root.get("testRecordPercentage");
        this.setTestRecordPercentage(testRecordPercentage);

        JSONArray tolerances = (JSONArray) root.get("errorToleranceRate");

        double errorToleranceRate[] = new double[tolerances.size()];
        Iterator<Double> iter = tolerances.iterator();
        int i = 0;
        while (iter.hasNext()) {
            errorToleranceRate[i] = iter.next();
            i++;
        }
        this.setErrorToleranceRate(errorToleranceRate);
        String tableName = (String) root.get("tableName");
        this.setTableName(tableName);
        String sourceTableName = (String) root.get("sourceTableName");
        this.setSourceTableName(sourceTableName);
        String resultFieldName = (String) root.get("resultFieldName");
        this.setResultFieldName(resultFieldName);

        JSONObject tdObj = (JSONObject) root.get("testDataSource");
        boolean isNew = (Boolean) tdObj.get("newGenerated");
        String tdPath = (String) tdObj.get("saveToFilePath");
        if ((tdPath == null) || (tdPath.equals(""))) {
            isNew = true;
        }
        this.setNewGeneratedTestDataSet(isNew);
        this.setTestDataSetIdFilePath(tdPath);

        String dbHost = (String) root.get("dbHost");
        this.setDbHost(dbHost);

        JSONArray features = (JSONArray) root.get("features");
        Iterator<JSONObject> iterator = features.iterator();
        while (iterator.hasNext()) {
            JSONObject featureObj = iterator.next();
            String name = (String) featureObj.get("name");
            String type = (String) featureObj.get("type");
            DBFieldType fType = DBFieldType.valueOf(type);
            int subNum = ((Long) featureObj.get("subNum")).intValue();

            FeatureDimension feature = new FeatureDimension(fType, name, subNum);
            this.addFeature(feature);
        }

        JSONArray fm = (JSONArray) root.get("featuresInModel");
        List<Feature> featuresInModel = new ArrayList<Feature>();
        Iterator<JSONObject> iterS = fm.iterator();
        while (iterS.hasNext()) {
            JSONObject currentFeature = iterS.next();
            Boolean isEnabled = (Boolean) currentFeature.get("enabled");
            if ((isEnabled != null) && (isEnabled.booleanValue() == false)) {
                continue;
            }

            String featureName = (String) currentFeature.get("name");
            Feature feature = new Feature(featureName);

            JSONArray functions = (JSONArray) currentFeature.get("functions");
            if (functions != null) {
                List<FeatureFunction> functionList = new ArrayList<FeatureFunction>();
                Iterator<JSONObject> funs = functions.iterator();
                while (funs.hasNext()) {
                    JSONObject function = funs.next();
                    String functionName = (String) function.get("name");
                    FeatureFunction featureFunction = new FeatureFunction(functionName);
                    JSONArray args = (JSONArray) function.get("arguments");

                    if ((args != null) && (args.size() > 0)) {
                        double arguments[] = new double[tolerances.size()];
                        Iterator<Double> iterA = args.iterator();
                        i = 0;
                        while (iterA.hasNext()) {
                            arguments[i] = iterA.next();
                            i++;
                        }
                        featureFunction.setArguments(arguments);
                    }
                    functionList.add(featureFunction);
                }
                feature.setFunctions(functionList);
            }
            featuresInModel.add(feature);
        }

        this.setFeaturesInModel(featuresInModel);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:eu.seaclouds.platform.discoverer.crawler.CloudTypes.java

private void crawlPaasOfferings() {
    JSONObject resp;//from   w w  w .  j  ava 2s .c  o m
    Iterator<String> it;

    /* paas section */
    String paasQuery = "https://cloudharmony.com/api/services?" + "api-key=" + API_KEY + "&"
            + "serviceTypes=paas";
    resp = (JSONObject) query(paasQuery);
    JSONArray paases = (JSONArray) resp.get("ids");
    it = paases.iterator();
    while (it.hasNext()) {
        try {
            String serviceId = it.next();
            CloudHarmonyService chService = getService(serviceId, CloudTypes.PAAS);
            generateOfferings(chService);
        } catch (Exception e) {
            log.warn(e.getMessage());
        }
    }
}

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

private void loadDatabase(Locale lang) throws IOException, ParseException {
    // Get the POS pattern file and parse it.

    InputStreamReader is = FileSystem.getInputStreamReaderFromPath(posDatabasePaths.get(lang));

    BufferedReader reader = new BufferedReader(is);
    Object obj = (new JSONParser()).parse(reader);
    JSONObject fileblock = (JSONObject) obj;
    JSONArray pagesBlock = (JSONArray) fileblock.get("languages");

    // Find the required language in the specified file
    Iterator<JSONObject> iterator = pagesBlock.iterator();
    JSONObject languageBlock = null;/*from  w w  w  .  j  ava2s . c  o  m*/
    while (iterator.hasNext()) {
        languageBlock = (iterator.next());
        String currLanguage = (String) languageBlock.get("language");
        if (currLanguage.equals(lang.getLanguage())) {
            break;
        }
    }

    // If the language is not supported by the database, stop the execution.
    if (languageBlock == null) {
        throw new NullPointerException(
                "Language " + lang.getLanguage() + " not found in file " + posDatabasePaths.get(lang));
    }

    JSONArray patternBlock = (JSONArray) languageBlock.get("patterns");

    Iterator<JSONObject> patternIterator = patternBlock.iterator();

    // put the patterns in the hashmap
    while (patternIterator.hasNext()) {
        JSONObject pattern = (patternIterator.next());
        String POSpattern = (String) pattern.get("pattern");
        validPosPatterns.add(POSpattern);
    }
}