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.talend.repository.hcatalog.service.HCatalogServiceUtil.java

public static void main(String[] args) {
    // WebClient client =
    // WebClient.create("http://talend-hdp-all:50111/templeton/v1/ddl/database/talend?user.name=ycbai");
    WebClient client = WebClient.create("http://talend-hdp-all:50111?user.name=ycbai");
    String path = "templeton/v1/ddl/database/" + "talend" + "/table/tablename";
    client.path(path);/* w  w w.  j a  va  2s.  c om*/
    client.accept("application/json");
    Response response = client.get();
    InputStream inputStream = (InputStream) response.getEntity();
    try {
        String input = IOUtils.toString(inputStream);
        JSONObject jsonObject = (JSONObject) JSONValue.parse(input);
        // JSONArray tables = (JSONArray) jsonObject.get("tables");
        JSONArray columns = (JSONArray) jsonObject.get("columns");
        Iterator iterator = columns.iterator();
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println(next);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.topicquests.solr.agents.merge.SolrMergeEngine.java

public void studyDocument(String jsonString) {
    log.logDebug("SolrMergeEngine.studyDocument " + jsonString);
    System.out.println(jsonString);
    tracer.trace(0, jsonString);/* ww w  . j  a  v  a  2 s . c o  m*/
    Map<String, Object> o = new HashMap<String, Object>();
    try {
        JSONObject jo = (JSONObject) parser.parse(jsonString);
        String locator = (String) jo.get(ITopicQuestsOntology.LOCATOR_PROPERTY);
        // are we busy looking at this puppy
        synchronized (nodesInMerge) {
            if (nodesInMerge.contains(locator))
                return;
        }
        //TODO dump the JSONObject to this map
        Iterator<String> itr = jo.keySet().iterator();
        Object vo;
        String key;

        while (itr.hasNext()) {
            key = itr.next();
            vo = jo.get(key);
            if (vo instanceof String)
                o.put(key, vo);
            else if (vo instanceof JSONArray) {
                JSONArray ja = (JSONArray) vo;
                Iterator<String> jitr = ja.iterator();
                List<String> vl = new ArrayList<String>();
                while (jitr.hasNext())
                    vl.add(jitr.next());
                o.put(key, vl);
            }
        }
    } catch (Exception e) {
        agentEnvironment.logError(e.getMessage(), e);
        e.printStackTrace();
        return; //we cannot study this document
    }
    //should not try to merge tuples
    Object isTuple = o.get(ITopicQuestsOntology.TUPLE_SUBJECT_PROPERTY);
    //should not have an isVirtual property
    Object isVirtual = o.get(ITopicQuestsOntology.IS_VIRTUAL_PROXY);
    //should not have a mergeTuple property
    Object hasVirtual = o.get(ITopicQuestsOntology.MERGE_TUPLE_PROPERTY);
    //which nodeType?
    String typ = (String) o.get(ITopicQuestsOntology.INSTANCE_OF_PROPERTY_TYPE);
    boolean ismerge = false;
    if (typ != null)
        ismerge = (typ.equals(ITopicQuestsOntology.MERGE_ASSERTION_TYPE)
                || typ.equals(ITopicQuestsOntology.POSSIBLE_MERGE_ASSERTIONTYPE)
                || typ.equals(ITopicQuestsOntology.UNMERGE_ASSERTION_TYPE));
    // we do not merge virtual proxies or merge assertion tuples
    log.logDebug(
            "SolrMergeEngine.studyDocument-1 " + isVirtual + " " + hasVirtual + " " + ismerge + " " + isTuple);

    if (isVirtual == null && hasVirtual == null && !ismerge && isTuple == null) {
        INode node = new Node(o);
        TopicMergePortfolio pf = new TopicMergePortfolio(agentEnvironment, this);
        pf.studyNode(node);

        //poof! It's gone. That's a threaded activity
        //Trust me: it will be back!
    }
}

From source file:org.wikipedia.nirvana.nirvanabot.MockNirvanaBot.java

private List<ExpectedQuery> parseQueries(JSONArray jsonQueries) {
    Iterator<?> it = jsonQueries.iterator();
    List<ExpectedQuery> queries = new ArrayList<>();
    while (it.hasNext()) {
        JSONObject queryJson = (JSONObject) it.next();
        ExpectedQuery query = new ExpectedQuery(readStringList(queryJson, "contains"));
        queries.add(query);//from  w w  w  .ja  va 2 s . c o  m
    }
    return queries;
}

From source file:org.wikipedia.nirvana.nirvanabot.MockNirvanaBot.java

private List<EditInfoMinimal> parseEdits(JSONArray jsonEdits) {
    Iterator<?> it = jsonEdits.iterator();
    List<EditInfoMinimal> edits = new ArrayList<>();
    while (it.hasNext()) {
        JSONObject editInfoJson = (JSONObject) it.next();
        EditInfoMinimal edit = new EditInfoMinimal((String) editInfoJson.get("title"),
                readMultiLineString(editInfoJson, "text"), (int) (long) (Long) editInfoJson.get("section"));
        edits.add(edit);//from w ww  .j a  v a2 s.c  o  m
    }
    return edits;
}

From source file:org.wikipedia.nirvana.nirvanabot.MockNirvanaBot.java

private List<String> parseMultilineStringArray(JSONArray jsonResponces) {
    List<String> list = new ArrayList<String>();
    Iterator<?> it = jsonResponces.iterator();
    while (it.hasNext()) {
        String val = parseMultiLineString(it.next());
        list.add(val);
    }//from  w w  w. j  av a  2  s  .c  om
    return list;
}

From source file:org.wikipedia.nirvana.nirvanabot.MockNirvanaBot.java

private void readWiki(MockNirvanaWiki wiki, JSONObject wikiJson) {
    JSONArray transcludesJsonList = (JSONArray) wikiJson.get("whatTranscludesHere");
    if (transcludesJsonList != null) {
        Iterator<?> it = transcludesJsonList.iterator();
        while (it.hasNext()) {
            JSONObject transcludesJson = (JSONObject) it.next();
            wiki.mockWhatTranscludesHere((String) transcludesJson.get("title"),
                    ((String) transcludesJson.get("list")).split(","));
        }//from   ww w  .  j a  v  a 2  s  .  c  o m
    }
    JSONArray nsIdJsonList = (JSONArray) wikiJson.get("namespaceIdentifier");
    if (nsIdJsonList != null) {
        Iterator<?> it = nsIdJsonList.iterator();
        while (it.hasNext()) {
            JSONObject nsIdJson = (JSONObject) it.next();
            //System.out.println("ns num type: "+ nsIdJson.get("number").getClass());
            wiki.mockNamespaceIdentifier((Long) nsIdJson.get("number"), (String) nsIdJson.get("id"));
        }
    }
    JSONArray pageTextJsonList = (JSONArray) wikiJson.get("pageText");
    if (pageTextJsonList != null) {
        Iterator<?> it = pageTextJsonList.iterator();
        while (it.hasNext()) {
            JSONObject pageTextJson = (JSONObject) it.next();
            wiki.mockPageText((String) pageTextJson.get("title"), readMultiLineString(pageTextJson, "text"));
        }
    }

    JSONArray firstRevJsonList = (JSONArray) wikiJson.get("firstRevision");
    if (firstRevJsonList != null) {
        Iterator<?> it = firstRevJsonList.iterator();
        while (it.hasNext()) {
            JSONObject revisionJson = (JSONObject) it.next();
            wiki.mockFirstRevision((String) revisionJson.get("title"), parseRevision(wiki, revisionJson));
        }
    }

    JSONArray pageTemplatesJsonList = (JSONArray) wikiJson.get("templates");
    if (pageTemplatesJsonList != null) {
        Iterator<?> it = pageTemplatesJsonList.iterator();
        while (it.hasNext()) {
            JSONObject pageTemplatesJson = (JSONObject) it.next();
            wiki.mockPageTemplates((String) pageTemplatesJson.get("title"),
                    readStringList(pageTemplatesJson, "templates"));
        }
    }
}

From source file:org.wikipedia.nirvana.nirvanabot.MockNirvanaBot.java

private String parseMultiLineString(Object object) {
    if (object instanceof String) {
        return (String) object;
    } else {/*from www.  j a v  a 2 s. c  o m*/
        JSONArray list = (JSONArray) object;
        StringBuilder b = new StringBuilder();
        Iterator<?> it = list.iterator();
        while (it.hasNext()) {
            String str = (String) it.next();
            b.append(str).append("\n");
        }
        // Remove last "\n"
        if (b.length() > 0) {
            b.setLength(b.length() - 1);
        }
        return b.toString();
    }
}

From source file:org.wikipedia.nirvana.nirvanabot.MockNirvanaBot.java

private List<String> readStringList(JSONObject jsonObject, String name) {
    JSONArray list = (JSONArray) jsonObject.get(name);
    Iterator<?> it = list.iterator();
    List<String> result = new ArrayList<String>();
    while (it.hasNext()) {
        result.add((String) it.next());
    }/* www. j ava 2 s .  co  m*/
    return result;
}

From source file:org.wso2.carbon.apimgt.sciquest.keymanager.APIManagerOAuthClient.java

/**
 * This method validates the access token with external OAuth Server
 *
 * @param accessToken - the token which need to be validated
 * @return an {@code AccessTokenInfo} having token validation meta data
 * @throws APIManagementException// www . j  av  a2  s  .  co  m
 */

public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
    AccessTokenInfo tokenInfo = new AccessTokenInfo();
    tokenInfo.setAccessToken(accessToken);

    KeyManagerConfiguration config = KeyManagerHolder.getKeyManagerInstance().getKeyManagerConfiguration();

    String introspectionURL = config.getParameter(ClientConstants.INTROSPECTION_URL);
    String introspectionConsumerKey = config.getParameter(ClientConstants.INTROSPECTION_CK);
    String introspectionConsumerSecret = config.getParameter(ClientConstants.INTROSPECTION_CS);
    String encodedSecret = Base64
            .encode(new String(introspectionConsumerKey + ":" + introspectionConsumerSecret).getBytes());

    BufferedReader reader = null;

    try {
        URIBuilder uriBuilder = new URIBuilder(introspectionURL);
        uriBuilder.addParameter("access_token", accessToken);
        uriBuilder.build();

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        HttpClient client = new DefaultHttpClient();

        httpGet.setHeader("Authorization", "Basic " + encodedSecret);
        HttpResponse response = client.execute(httpGet);
        int responseCode = response.getStatusLine().getStatusCode();

        if (log.isDebugEnabled()) {
            log.debug("HTTP Response code for Token Validation from external OAuth Server: " + responseCode);
        }

        // Response Format from OAuth 2 Server

        /*{
        "audience":"MappedClient",
            "scopes":[
                "test"
            ],
            "principal":{
                "name":"mappedclient",
                "roles":[
                
                ],
                "groups":[
                
                ],
                "adminPrincipal":false,
                "attributes":{
                
                }
            },
            "expires_in":1433059160531
        }*/

        HttpEntity entity = response.getEntity();
        JSONObject parsedObject;
        reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));

        if (HttpStatus.SC_OK == responseCode) {
            //pass bufferReader object  and get read it and retrieve  the parsedJson object
            parsedObject = getParsedObjectByReader(reader);
            if (parsedObject != null) {
                Object principal = parsedObject.get("principal");

                if (principal == null) {
                    tokenInfo.setTokenValid(false);
                    return tokenInfo;
                }
                Map principalMap = (Map) principal;
                String clientId = (String) principalMap.get("name");
                Long expiryTimeString = (Long) parsedObject.get("expires_in");

                // Returning false if mandatory attributes are missing.
                if (clientId == null || expiryTimeString == null) {
                    tokenInfo.setTokenValid(false);
                    tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_EXPIRED);
                    return tokenInfo;
                }

                long currentTime = System.currentTimeMillis();
                long expiryTime = expiryTimeString;
                if (expiryTime > currentTime) {
                    tokenInfo.setTokenValid(true);
                    tokenInfo.setConsumerKey(clientId);
                    tokenInfo.setValidityPeriod(expiryTime - currentTime);
                    // Considering Current Time as the issued time.
                    tokenInfo.setIssuedTime(currentTime);
                    JSONArray scopesArray = (JSONArray) parsedObject.get("scopes");

                    if (log.isDebugEnabled()) {
                        StringBuilder tokens = new StringBuilder("[");
                        Iterator iterator = scopesArray.iterator();
                        while (iterator.hasNext()) {
                            tokens.append(iterator.next());
                            if (iterator.hasNext()) {
                                tokens.append(", ");
                            }
                        }
                        tokens.append("]");

                        log.debug("Tokens " + tokens);
                    }

                    if (scopesArray != null && !scopesArray.isEmpty()) {

                        String[] scopes = new String[scopesArray.size()];
                        for (int i = 0; i < scopes.length; i++) {
                            scopes[i] = (String) scopesArray.get(i);
                        }
                        tokenInfo.setScope(scopes);
                    }

                    JSONObject jso = new JSONObject();
                    jso.putAll(principalMap);
                    tokenInfo.setEndUserName(jso.toString());

                    if (log.isDebugEnabled()) {
                        log.debug("Token Response Principle : " + jso.toJSONString());
                    }
                } else {
                    tokenInfo.setTokenValid(false);
                    tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_EXPIRED);
                    return tokenInfo;
                }

            } else {
                log.error("Invalid Token " + accessToken);
                tokenInfo.setTokenValid(false);
                tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
                return tokenInfo;
            }
        } //for other HTTP error codes we just pass generic message.
        else {
            log.error("Invalid Token " + accessToken);
            tokenInfo.setTokenValid(false);
            tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_ACCESS_TOKEN_INACTIVE);
            return tokenInfo;
        }

    } catch (UnsupportedEncodingException e) {
        handleException("The Character Encoding is not supported. " + e.getMessage(), e);
    } catch (ClientProtocolException e) {
        handleException(
                "HTTP request error has occurred while sending request  to OAuth Provider. " + e.getMessage(),
                e);
    } catch (IOException e) {
        handleException("Error has occurred while reading or closing buffer reader. " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        handleException("Error occurred while building URL with params." + e.getMessage(), e);
    } catch (ParseException e) {
        handleException("Error while parsing response json " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    return tokenInfo;
}

From source file:org.wso2.carbon.appmgt.mdm.wso2emm.ApplicationOperationsImpl.java

/**
 *
 * @param applicationOperationDevice holds the information needs to retrieve device list
 * @return List of devices//from ww w  . j a  v  a 2  s  . co  m
 */

public List<Device> getDevices(ApplicationOperationDevice applicationOperationDevice) {

    HashMap<String, String> configProperties = applicationOperationDevice.getConfigParams();

    String serverURL = configProperties.get(Constants.PROPERTY_SERVER_URL);
    String authUser = configProperties.get(Constants.PROPERTY_AUTH_USER);
    String authPass = configProperties.get(Constants.PROPERTY_AUTH_PASS);

    List<Device> devices = new ArrayList<>();

    HttpClient httpClient = AppManagerUtil.getHttpClient(serverURL);
    int tenantId = applicationOperationDevice.getTenantId();
    String[] params = applicationOperationDevice.getParams();
    HttpGet getMethod = new HttpGet(serverURL + String.format(Constants.API_DEVICE_LIST, tenantId, params[0]));
    getMethod.setHeader(Constants.RestConstants.AUTHORIZATION, Constants.RestConstants.BASIC
            + new String(Base64.encodeBase64((authUser + ":" + authPass).getBytes())));
    try {
        HttpResponse response = httpClient.execute(getMethod);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            String responseString = "";
            if (entity != null) {
                responseString = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity);
            }

            JSONArray devicesArray = (JSONArray) new JSONValue().parse(responseString);
            if (log.isDebugEnabled())
                log.debug("Devices Received" + devicesArray.toJSONString());
            Iterator<JSONObject> iterator = devicesArray.iterator();
            while (iterator.hasNext()) {
                JSONObject deviceObj = iterator.next();
                Device device = new Device();
                device.setId(deviceObj.get("id").toString());
                JSONObject properties = (JSONObject) new JSONValue()
                        .parse(deviceObj.get("properties").toString());
                device.setName(properties.get("device").toString());
                device.setModel(properties.get("model").toString());
                if ("1".equals(deviceObj.get("platform_id").toString())) {
                    device.setPlatform("android");
                } else if ("2".equals(deviceObj.get("platform_id").toString())) {
                    device.setPlatform("ios");
                } else if ("3".equals(deviceObj.get("platform_id").toString())) {
                    device.setPlatform("ios");
                } else if ("4".equals(deviceObj.get("platform_id").toString())) {
                    device.setPlatform("ios");
                }
                device.setImage(
                        String.format(configProperties.get("ImageURL"), properties.get("model").toString()));
                device.setType("mobileDevice");
                device.setPlatformVersion("0");
                devices.add(device);

            }
        }
    } catch (IOException e) {
        String errorMessage = "Error while getting the device list from WSO2 EMM";
        if (log.isDebugEnabled()) {
            log.error(errorMessage, e);
        } else {
            log.error(errorMessage);
        }
    }
    return devices;
}