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:org.alfresco.web.extensibility.SlingshotEvaluatorUtil.java

/**
 * Determines whether or not the current user is a member of the supplied group.
 *
 * @param context RequestContext/* w ww .j a v a  2s . c o m*/
 * @param groups List<String>
 * @param memberOfAllGroups boolean
 * @return boolean
 */
@SuppressWarnings({ "rawtypes" })
public boolean isMemberOfGroups(RequestContext context, List<String> groups, boolean memberOfAllGroups) {
    // Initialise the default result to be null... we're intentionally using a Boolean object over boolean
    // primitive to give us access to the third value of null. This allows us to determine whether or not
    // any membership information has actually been processed (e.g. when NO groups have been specified).
    Boolean isMember = null;

    // We're going to store GROUP membership in the HttpSession as this changes infrequently but will be
    // accessing SITE membership for every request. Surf will ensure that requests are cached for each
    // page so we are not making the same request more than once per page. Site membership can change more
    // frequently so we need to be sure that the information we have is up-to-date.
    HttpSession session = ServletUtil.getSession();
    org.json.simple.JSONArray groupsList = null;
    String GROUP_MEMBERSHIPS = "AlfGroupMembershipsKey";

    // Get the current site
    String currentSite = getSite(context);

    boolean externalAuth = false;
    RemoteConfigElement config = (RemoteConfigElement) context.getServiceRegistry().getConfigService()
            .getConfig("Remote").getConfigElement("remote");
    if (config != null) {
        EndpointDescriptor descriptor = config.getEndpointDescriptor(AlfrescoUserFactory.ALFRESCO_ENDPOINT_ID);
        if (descriptor != null) {
            externalAuth = descriptor.getExternalAuth();
        }
    }

    // Get all the group membership first so that we don't perform this operation multiple times... check
    // the HttpSession and if it's not already available then make a request for it and cache it for future
    // reference. Note that we're ONLY caching the current users membership information.
    Object _cachedGroupMemberships = session.getAttribute(GROUP_MEMBERSHIPS);
    if (_cachedGroupMemberships instanceof org.json.simple.JSONArray) {
        groupsList = (org.json.simple.JSONArray) _cachedGroupMemberships;
    } else {
        try {
            // Get the Site membership information...
            CredentialVault cv = context.getCredentialVault();
            if (cv != null) {
                Credentials creds = cv.retrieve(AlfrescoUserFactory.ALFRESCO_ENDPOINT_ID);
                // Check for external authentication
                // MNT-11857
                if (creds == null && !externalAuth) {
                    // User is not logged in anymore
                    return false;
                }
                String userName = (String) session.getAttribute(UserFactory.SESSION_ATTRIBUTE_KEY_USER_ID);
                Connector connector = context.getServiceRegistry().getConnectorService().getConnector(
                        SlingshotUserFactory.ALFRESCO_ENDPOINT_ID, userName, ServletUtil.getSession());
                Response res = connector
                        .call("/api/people/" + URLEncoder.encode(context.getUserId()) + "?groups=true");
                if (res.getStatus().getCode() == Status.STATUS_OK) {
                    String response = res.getResponse();
                    org.json.simple.parser.JSONParser p = new org.json.simple.parser.JSONParser();
                    Object o2 = p.parse(response);
                    if (o2 instanceof org.json.simple.JSONObject) {
                        org.json.simple.JSONObject jsonRes = (org.json.simple.JSONObject) o2;
                        groupsList = (org.json.simple.JSONArray) jsonRes.get("groups");
                        session.setAttribute(GROUP_MEMBERSHIPS, groupsList);
                    }
                }
            }
        } catch (ConnectorServiceException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    // Work through the supplied list of groups to determine whether or not the current user is a member of them...
    for (String groupName : groups) {
        boolean isMemberOfCurrentGroup = false;
        if (groupName != null) {
            // If the requested groupName begins with "Site" then this indicates that we are looking
            // for a site specific group such as "SiteConsumer" and we therefore need to modify the
            // group name to reflect the current site. If we are not currently viewing a site then
            // we will automatically indicate that the user is not a member (how can they be a member
            // of the current site if they're not in a site?) and move onto the next group...
            if (groupName.startsWith("Site")) {
                if (currentSite == null) {
                    isMember = false;
                } else {
                    // We're going to rely on URI tokens to determine if we're viewing a site - it's the
                    // best data available from the RequestContext.
                    try {
                        CredentialVault cv = context.getCredentialVault();
                        if (cv != null) {
                            Credentials creds = cv.retrieve(AlfrescoUserFactory.ALFRESCO_ENDPOINT_ID);
                            if (creds == null && !externalAuth) {
                                // User is not logged in anymore
                                return false;
                            }
                            String userName = (String) session
                                    .getAttribute(UserFactory.SESSION_ATTRIBUTE_KEY_USER_ID);
                            Connector connector = context.getServiceRegistry().getConnectorService()
                                    .getConnector(AlfrescoUserFactory.ALFRESCO_ENDPOINT_ID, userName,
                                            ServletUtil.getSession());
                            Response res = connector.call("/api/sites/" + currentSite + "/memberships/"
                                    + URLEncoder.encode(context.getUserId()));
                            if (res.getStatus().getCode() == Status.STATUS_OK) {
                                String response = res.getResponse();
                                org.json.simple.parser.JSONParser p = new org.json.simple.parser.JSONParser();
                                Object o2 = p.parse(response);
                                if (o2 instanceof org.json.simple.JSONObject) {
                                    org.json.simple.JSONObject jsonRes = (org.json.simple.JSONObject) o2;
                                    String siteMembership = (String) jsonRes.get("role");
                                    isMemberOfCurrentGroup = siteMembership.equals(groupName);
                                }
                            } else {
                                // When the user is NOT a member of the site the request will actually return a 404 (rather than a 200)
                                // so on any request that fails we will assume they are not a member of the site.
                                isMemberOfCurrentGroup = false;
                            }
                        }
                    } catch (ConnectorServiceException e) {
                        e.printStackTrace();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            } else if (groupsList != null) {
                // Check for regular GROUP membership... all non-site groups MUST begin "GROUP"...
                Iterator i = groupsList.iterator();
                while (i.hasNext()) {
                    org.json.simple.JSONObject group = (org.json.simple.JSONObject) i.next();
                    String currGroupName = group.get("itemName").toString();
                    if (currGroupName.equals(groupName)) {
                        isMemberOfCurrentGroup = true;
                        break;
                    }
                }
            }
        }

        // Handle the requested membership logic and make a quick exit if possible...
        if (memberOfAllGroups) {
            isMember = (isMember == null) ? isMemberOfCurrentGroup : isMember && isMemberOfCurrentGroup;
            if (!isMember) {
                // Break out of the main loop if the user must be a member of all groups and is not
                // a member of at least one of them. There is no point in checking the remaining groups
                break;
            }
        } else {
            isMember = (isMember == null) ? isMemberOfCurrentGroup : isMember || isMemberOfCurrentGroup;
            if (isMember) {
                // Break out of the main loop if the user is a member of at least one group as that
                // is all that is required.
                break;
            }
        }
    }
    return isMember;
}

From source file:org.apache.commons.validator.TestValidator.java

public static void main(String[] args) throws IOException, ParseException {
    System.out.println(GenericValidator.isEmail("abc"));
    FileReader reader = new FileReader(
            Thread.currentThread().getContextClassLoader().getResource("student.json").getPath());
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(reader);

    JSONObject jsonObject = (JSONObject) obj;

    String name = (String) jsonObject.get("studentForm");
    System.out.println(name);//from www.  j  a va2s .c  o  m

    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());
    }
    /* JsonParser parser = new JsonParser();
     JsonElement element = parser.parse(reader);
     JsonObject json = element.getAsJsonObject();
     System.out.println(json.get("name"));*/

}

From source file:org.apache.sqoop.tools.tool.RepositoryDumpTool.java

private JSONObject addConnectorName(JSONObject json) {
    ConnectorManager connectorManager = ConnectorManager.getInstance();

    JSONArray results = (JSONArray) json.get(JsonBean.ALL);

    Iterator<JSONObject> iterator = results.iterator();

    while (iterator.hasNext()) {
        JSONObject result = iterator.next();
        Long connectorId = (Long) result.get(JSONConstants.CONNECTOR_ID);
        result.put(JSONConstants.CONNECTOR_NAME,
                connectorManager.getConnectorConfigurable(connectorId).getUniqueName());
    }/*ww w. java2s  .com*/

    return json;
}

From source file:org.apache.usergrid.chop.webapp.coordinator.rest.UploadResource.java

@SuppressWarnings("unchecked")
@POST/*www .j  av  a2s.c  o  m*/
@Path("/results")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public Response uploadResults(MimeMultipart multipart) throws Exception {
    String runId = multipart.getBodyPart(RestParams.RUN_ID).getContent().toString();
    LOG.debug("extracted {} = {}", RestParams.RUN_ID, runId);

    InputStream in = multipart.getBodyPart(RestParams.CONTENT).getInputStream();

    JSONObject object = (JSONObject) new JSONParser().parse(new InputStreamReader(in));
    JSONArray runResults = (JSONArray) object.get("runResults");
    Iterator<JSONObject> iterator = runResults.iterator();

    //noinspection WhileLoopReplaceableByForEach
    while (iterator.hasNext()) {
        JSONObject jsonResult = iterator.next();

        BasicRunResult runResult = new BasicRunResult(runId, Util.getInt(jsonResult, "runCount"),
                Util.getInt(jsonResult, "runTime"), Util.getInt(jsonResult, "ignoreCount"),
                Util.getInt(jsonResult, "failureCount"));

        if (runResultDao.save(runResult)) {
            LOG.info("Saved run result: {}", runResult);
        }
    }

    return Response.status(Response.Status.CREATED).entity("TRUE").build();
}

From source file:org.apache.wink.rest.ClockinResource.java

@Path(PATH_DATABASE_EDIT)
@POST/*from w  w w .  jav  a 2 s  .co m*/
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response editData(@QueryParam("table") String table, String obj) {

    Status status = Response.Status.NO_CONTENT;
    Connection con = null;
    String result = null;
    OraclePreparedStatement stmt = null;
    try {

        //prevent sql injection
        String sqlStatement = null;
        try {
            System.out.println("table: " + table);
            DATABASE_TABLES.valueOf(table.toLowerCase());
            System.out.println("Table exists. Mapping to table now.");
        } catch (IllegalArgumentException e) {
            throw new Exception("Table does not exist in the database.");
        }

        JSONObject jsonObject = (JSONObject) new JSONParser().parse(obj);
        System.out.println("jsonObject.toJSONString() " + jsonObject.toJSONString());

        //parse column names
        JSONArray colNames = (JSONArray) jsonObject.get("columnNames");
        Iterator<String> iter = colNames.iterator();
        sqlStatement = "UPDATE " + table + " set ";
        while (iter.hasNext()) {
            sqlStatement += (String) iter.next() + " = ?";
            if (iter.hasNext()) {
                sqlStatement += ", ";
            }
        }

        //connect to database via connection pool
        DatabaseConnectionPool dbpool = DatabaseConnectionPool.getInstance();
        con = dbpool.getConnection();

        JSONArray colData = (JSONArray) jsonObject.get("columnData");
        sqlStatement += " where ID = '" + colData.get(0) + "'";

        stmt = (OraclePreparedStatement) con.prepareStatement(sqlStatement);
        System.out.println("sqlStatement " + sqlStatement);

        //parse update data
        Iterator<String> iterData = colData.iterator();
        int countPlace = 1;
        while (iterData.hasNext()) {
            String d = iterData.next();
            try {
                System.out.println("Trying: " + d);
                int di = Integer.parseInt(d);
                stmt.setInt(countPlace, di);
            } catch (NumberFormatException nfe) {
                System.out.println("Not an integer...");
                stmt.setString(countPlace, d);
            }
            countPlace++;
        }
        int i = stmt.executeUpdate();

        if (i <= 0) {
            status = Response.Status.BAD_REQUEST;
        } else {
            status = Response.Status.OK;
        }
    } catch (ParseException pe) {
        System.out.println("Catching parse exception: " + pe.getMessage());
        status = Response.Status.INTERNAL_SERVER_ERROR;
        result = pe.getMessage();
    } catch (Exception e) {
        System.out.println("Catching exception: " + e.getMessage());
        status = Response.Status.INTERNAL_SERVER_ERROR;
        result = e.getMessage();
    } finally {
        //step5 close the connection object
        try {
            con.close();
        } catch (Exception e) {
            System.out.println("Finally: " + e.getMessage());
        }
    }
    if (result == null) {
        result = "{\"Data\":\"Ok\"}";
    }
    return Response.status(status).entity(result).header("Content-Type", "application/json").build();
}

From source file:org.apache.wink.rest.ClockinResource.java

@Path(PATH_DATABASE_ADD)
@POST/*from   w ww.java 2 s .  co m*/
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response addData(@QueryParam("table") String table, String obj) {

    Status status = Response.Status.NO_CONTENT;
    Connection con = null;
    String result = null;
    OraclePreparedStatement stmt = null;
    try {

        //prevent sql injection
        String sqlStatement = null;
        try {
            System.out.println("table: " + table);
            DATABASE_TABLES.valueOf(table.toLowerCase());
            System.out.println("Table exists. Mapping to table now.");
        } catch (IllegalArgumentException e) {
            throw new Exception("Table does not exist in the database.");
        }

        JSONObject jsonObject = (JSONObject) new JSONParser().parse(obj);
        System.out.println("jsonObject.toJSONString() " + jsonObject.toJSONString());

        //parse column names
        JSONArray colNames = (JSONArray) jsonObject.get("columnNames");
        Iterator<String> iter = colNames.iterator();

        /*
            INSERT INTO worked_shifts(start_time,scheduled_shift_ID,employee_ID, location_ID)
              VALUES ('20-NOV-16 15:54:30','1','1','1');
         */
        sqlStatement = "INSERT INTO " + table + "(";
        String paramSpace = "";
        while (iter.hasNext()) {
            sqlStatement += (String) iter.next();
            paramSpace += "?";
            if (iter.hasNext()) {
                sqlStatement += ", ";
                paramSpace += ", ";
            }
        }
        sqlStatement += ") VALUES (" + paramSpace + ")";

        //connect to database via connection pool
        DatabaseConnectionPool dbpool = DatabaseConnectionPool.getInstance();
        con = dbpool.getConnection();

        JSONArray colData = (JSONArray) jsonObject.get("columnData");

        stmt = (OraclePreparedStatement) con.prepareStatement(sqlStatement);
        System.out.println("sqlStatement " + sqlStatement);

        //parse update data
        Iterator<String> iterData = colData.iterator();
        int countPlace = 1;
        while (iterData.hasNext()) {
            String d = iterData.next();
            try {
                System.out.println("Trying: " + d);
                int di = Integer.parseInt(d);
                stmt.setInt(countPlace, di);
            } catch (NumberFormatException nfe) {
                System.out.println("Not an integer...");
                stmt.setString(countPlace, d);
            }
            countPlace++;
        }
        int i = stmt.executeUpdate();

        if (i <= 0) {
            status = Response.Status.BAD_REQUEST;
        } else {
            status = Response.Status.OK;
        }
    } catch (ParseException pe) {
        System.out.println("Catching parse exception: " + pe.getMessage());
        status = Response.Status.INTERNAL_SERVER_ERROR;
        result = pe.getMessage();
    } catch (Exception e) {
        System.out.println("Catching exception: " + e.getMessage());
        status = Response.Status.INTERNAL_SERVER_ERROR;
        result = e.getMessage();
    } finally {
        //step5 close the connection object
        try {
            con.close();
        } catch (Exception e) {
            System.out.println("Finally: " + e.getMessage());
        }
    }
    if (result == null) {
        result = "{\"Data\":\"Ok\"}";
    }
    return Response.status(status).entity(result).header("Content-Type", "application/json").build();
}

From source file:org.bgbm.biovel.drf.checklist.BgbmEditClient.java

private void buildTaxonIdList(List<TnrMsg.Query> queryList, String response) throws DRFChecklistException {

    JSONParser parser = new JSONParser();
    Object obj;// w w w.  j  a va2 s.  c  om
    try {
        obj = parser.parse(response);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new DRFChecklistException(e);
    } catch (org.json.simple.parser.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new DRFChecklistException(e);
    }

    JSONArray jsonArray = (JSONArray) obj;
    if (jsonArray.size() != queryList.size()) {
        throw new DRFChecklistException("Query and Response lists have different lengths");
    }

    Iterator<JSONObject> itrNameMsgs = jsonArray.iterator();
    Iterator<TnrMsg.Query> itrQuery = queryList.iterator();

    while (itrNameMsgs.hasNext() && itrQuery.hasNext()) {
        Query query = itrQuery.next();
        JSONArray responseArray = (JSONArray) itrNameMsgs.next().get("response");
        if (responseArray != null) {
            Iterator<JSONObject> resIterator = responseArray.iterator();
            while (resIterator.hasNext()) {
                JSONObject res = resIterator.next();
                JSONArray accTaxonUuidArray = (JSONArray) res.get("acceptedTaxonUuids");
                Iterator<String> atIterator = accTaxonUuidArray.iterator();
                while (atIterator.hasNext()) {
                    String accTaxonId = atIterator.next();
                    taxonIdQueryMap.put(accTaxonId, query);
                }
            }
        }
    }
}

From source file:org.bgbm.biovel.drf.checklist.BgbmEditClient.java

private void updateQueriesWithResponse(String response, ServiceProviderInfo ci) throws DRFChecklistException {
    JSONParser parser = new JSONParser();
    Object obj;//from   w  w  w.j  a  v  a 2  s. c  o m
    try {
        obj = parser.parse(response);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new DRFChecklistException(e);
    } catch (org.json.simple.parser.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new DRFChecklistException(e);
    }

    JSONArray jsonArray = (JSONArray) obj;
    Iterator<JSONObject> itrTaxonMsgs = jsonArray.iterator();

    while (itrTaxonMsgs.hasNext()) {
        JSONObject taxonInfo = (JSONObject) itrTaxonMsgs.next();
        JSONObject taxonResponse = (JSONObject) taxonInfo.get("response");
        JSONObject taxon = (JSONObject) taxonResponse.get("taxon");
        JSONArray relatedTaxa = (JSONArray) taxonResponse.get("relatedTaxa");

        JSONObject taxonRequest = (JSONObject) taxonInfo.get("request");
        String taxonUuid = (String) taxonRequest.get("taxonUuid");

        if (taxon != null) {
            TnrResponse tnrResponse = new TnrResponse();
            tnrResponse.setChecklist(ci.getLabel());
            tnrResponse.setChecklistUrl(ci.getUrl());
            AcceptedName accName = generateAccName(taxon);
            tnrResponse.setAcceptedName(accName);
            generateSynonyms(relatedTaxa, tnrResponse);
            Query query = taxonIdQueryMap.get(taxonUuid);
            if (query != null) {
                query.getTnrResponse().add(tnrResponse);
            }
        }
    }
}

From source file:org.bgbm.biovel.drf.checklist.BgbmEditClient.java

private void generateSynonyms(JSONArray relatedTaxa, TnrResponse tnrResponse) {

    Iterator<JSONObject> itrSynonyms = relatedTaxa.iterator();
    while (itrSynonyms.hasNext()) {

        JSONObject synonymjs = (JSONObject) itrSynonyms.next();
        String status = (String) synonymjs.get("taxonStatus");
        if (status != null && status.equals("synonym")) {
            TnrResponse.Synonym synonym = new Synonym();
            TaxonNameType taxonName = new TaxonNameType();
            NameType name = new NameType();

            String resName = (String) synonymjs.get("name");
            name.setNameComplete(resName);
            NameParser ecatParser = new NameParser();
            String nameCanonical = ecatParser.parseToCanonical(resName);
            name.setNameCanonical(nameCanonical);
            name.setNameStatus((String) synonymjs.get("taxonStatus"));

            taxonName.setRank((String) synonymjs.get("rank"));
            taxonName.setName(name);//from www. java2s  .c o  m

            synonym.setTaxonName(taxonName);

            JSONObject sourcejs = (JSONObject) synonymjs.get("source");
            String sourceUrl = (String) sourcejs.get("url");
            String sourceDatasetID = (String) sourcejs.get("datasetID");
            String sourceDatasetName = (String) sourcejs.get("datasetName");
            String sourceName = "";

            SourceType source = new SourceType();
            source.setDatasetID(sourceDatasetID);
            source.setDatasetName(sourceDatasetName);
            source.setName(sourceName);
            source.setUrl(sourceUrl);
            synonym.setSource(source);

            JSONObject scrutinyjs = (JSONObject) synonymjs.get("taxonomicScrutiny");
            String accordingTo = (String) scrutinyjs.get("accordingTo");
            String modified = (String) scrutinyjs.get("modified");

            ScrutinyType scrutiny = new ScrutinyType();
            scrutiny.setAccordingTo(accordingTo);
            scrutiny.setModified(modified);
            synonym.setScrutiny(scrutiny);

            tnrResponse.getSynonym().add(synonym);
        }
    }
}

From source file:org.dragonet.net.translator.Translator_v0_11.java

public String translateChatMessage(JSONObject jsonObj) {
    StringBuilder sbuilder = new StringBuilder();
    if (jsonObj.containsKey("text")) {
        if (jsonObj.containsKey("color")) {
            try {
                sbuilder.append(MCColor.valueOf((String) jsonObj.get("color")).getPECode().toUpperCase());
            } catch (IllegalArgumentException e) {
            }/* w w w  .j  a va2 s. c om*/
        }
        sbuilder.append(((String) jsonObj.get("text")));
    }
    if (jsonObj.containsKey("extra")) {
        if (jsonObj.get("extra") instanceof LinkedList) {
            LinkedList<JSONObject> jsonList = (LinkedList<JSONObject>) jsonObj.get("extra");
            for (JSONObject obj : jsonList) {
                if (obj.containsKey("text")) {
                    if (obj.containsKey("color")) {
                        try {
                            sbuilder.append(
                                    MCColor.valueOf((String) obj.get("color")).getPECode().toUpperCase());
                        } catch (IllegalArgumentException e) {
                        }
                    }
                    sbuilder.append((String) obj.get("text"));
                }
            }
        } else if (jsonObj.get("extra") instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) jsonObj.get("extra");
            if (jsonArray.size() > 0) {
                for (Iterator it = jsonArray.iterator(); it.hasNext();) {
                    Object obj = it.next();
                    if (((JSONObject) obj).containsKey("text")) {
                        if (((JSONObject) obj).containsKey("color")) {
                            try {
                                sbuilder.append(MCColor.valueOf((String) ((JSONObject) obj).get("color"))
                                        .getPECode().toUpperCase());
                            } catch (IllegalArgumentException e) {
                            }
                        }
                        sbuilder.append((String) ((JSONObject) obj).get("text"));
                    }
                }
            }
        }
    }
    return sbuilder.toString();
}