Search in sources :

Example 21 with ParseException

use of org.json.simple.parser.ParseException in project Rubicon by Rubicon-Bot.

the class MojangUtil method fetchName.

private String fetchName(String playername) {
    HttpRequestBuilder request = new HttpRequestBuilder("https://api.mojang.com/users/profiles/minecraft/" + playername, RequestType.GET);
    RequestResponse response = null;
    try {
        response = request.sendRequest();
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (response.getResponseCode() != 200)
        return null;
    JSONObject json = null;
    try {
        json = (JSONObject) parser.parse(response.getResponseMessage());
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return json.get("name").toString();
}
Also used : JSONObject(org.json.simple.JSONObject) HttpRequestBuilder(de.foryasee.httprequest.HttpRequestBuilder) RequestResponse(de.foryasee.httprequest.RequestResponse) ParseException(org.json.simple.parser.ParseException) ParseException(org.json.simple.parser.ParseException)

Example 22 with ParseException

use of org.json.simple.parser.ParseException in project elephant-bird by twitter.

the class LzoJsonRecordReader method decodeLineToJson.

public static boolean decodeLineToJson(JSONParser parser, Text line, MapWritable value) {
    try {
        JSONObject jsonObj = (JSONObject) parser.parse(line.toString());
        if (jsonObj != null) {
            for (Object key : jsonObj.keySet()) {
                Text mapKey = new Text(key.toString());
                Text mapValue = new Text();
                if (jsonObj.get(key) != null) {
                    mapValue.set(jsonObj.get(key).toString());
                }
                value.put(mapKey, mapValue);
            }
        } else {
            // JSONParser#parse(String) may return a null reference, e.g. when
            // the input parameter is the string "null".  A single line with
            // "null" is not valid JSON though.
            LOG.warn("Could not json-decode string: " + line);
            return false;
        }
        return true;
    } catch (ParseException e) {
        LOG.warn("Could not json-decode string: " + line, e);
        return false;
    } catch (NumberFormatException e) {
        LOG.warn("Could not parse field into number: " + line, e);
        return false;
    }
}
Also used : JSONObject(org.json.simple.JSONObject) JSONObject(org.json.simple.JSONObject) Text(org.apache.hadoop.io.Text) ParseException(org.json.simple.parser.ParseException)

Example 23 with ParseException

use of org.json.simple.parser.ParseException in project airavata by apache.

the class OAuthTokenRetrievalClient method retrieveAccessToken.

/**
 * Retrieve the OAuth Access token via the specified grant type.
 * @param consumerId
 * @param consumerSecret
 * @param userName
 * @param password
 * @param grantType
 * @return
 * @throws SecurityException
 */
public String retrieveAccessToken(String consumerId, String consumerSecret, String userName, String password, int grantType) throws AiravataSecurityException {
    HttpPost postMethod = null;
    try {
        // initialize trust store to handle SSL handshake with WSO2 IS properly.
        TrustStoreManager trustStoreManager = new TrustStoreManager();
        SSLContext sslContext = trustStoreManager.initializeTrustStoreManager(Properties.TRUST_STORE_PATH, Properties.TRUST_STORE_PASSWORD);
        // create https scheme with the trust store
        org.apache.http.conn.ssl.SSLSocketFactory sf = new org.apache.http.conn.ssl.SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, Properties.authzServerPort);
        HttpClient httpClient = new DefaultHttpClient();
        // set the https scheme in the httpclient
        httpClient.getConnectionManager().getSchemeRegistry().register(httpsScheme);
        postMethod = new HttpPost(Properties.oauthTokenEndPointURL);
        // build the HTTP request with relevant params for resource owner credential grant type
        String authInfo = consumerId + ":" + consumerSecret;
        String authHeader = new String(Base64.encodeBase64(authInfo.getBytes()));
        postMethod.setHeader("Content-Type", "application/x-www-form-urlencoded");
        postMethod.setHeader("Authorization", "Basic " + authHeader);
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        if (grantType == 1) {
            urlParameters.add(new BasicNameValuePair("grant_type", "password"));
            urlParameters.add(new BasicNameValuePair("username", userName));
            urlParameters.add(new BasicNameValuePair("password", password));
        } else if (grantType == 2) {
            urlParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
        }
        postMethod.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse response = httpClient.execute(postMethod);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuilder result = new StringBuilder();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        JSONParser parser = new JSONParser();
        JSONObject jsonObject = (JSONObject) parser.parse(result.toString());
        return (String) jsonObject.get("access_token");
    } catch (ClientProtocolException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } catch (IOException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } catch (ParseException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) Scheme(org.apache.http.conn.scheme.Scheme) ArrayList(java.util.ArrayList) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) InputStreamReader(java.io.InputStreamReader) HttpResponse(org.apache.http.HttpResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SSLContext(javax.net.ssl.SSLContext) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) JSONObject(org.json.simple.JSONObject) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BufferedReader(java.io.BufferedReader) TrustStoreManager(org.apache.airavata.security.util.TrustStoreManager) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException)

Example 24 with ParseException

use of org.json.simple.parser.ParseException in project herd by FINRAOS.

the class UrlHelper method parseJsonObjectFromUrl.

/**
 * Reads JSON from a specified URL.
 *
 * @param url the url
 *
 * @return the JSON object
 */
public JSONObject parseJsonObjectFromUrl(String url) {
    try {
        // Get proxy information.
        Proxy proxy;
        String httpProxyHost = configurationHelper.getProperty(ConfigurationValue.HTTP_PROXY_HOST);
        Integer httpProxyPort = configurationHelper.getProperty(ConfigurationValue.HTTP_PROXY_PORT, Integer.class);
        if (StringUtils.isNotBlank(httpProxyHost) && httpProxyPort != null) {
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort));
        } else {
            proxy = Proxy.NO_PROXY;
        }
        // Open an input stream as per specified URL.
        InputStream inputStream = urlOperations.openStream(new URL(url), proxy);
        try {
            // Parse the JSON object from the input stream.
            JSONParser jsonParser = new JSONParser();
            return (JSONObject) jsonParser.parse(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        } catch (ParseException e) {
            throw new IllegalArgumentException(String.format("Failed to parse JSON object from the URL: url=\"%s\"", url), e);
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        throw new IllegalArgumentException(String.format("Failed to read JSON from the URL: url=\"%s\"", url), e);
    }
}
Also used : Proxy(java.net.Proxy) JSONObject(org.json.simple.JSONObject) InputStreamReader(java.io.InputStreamReader) InetSocketAddress(java.net.InetSocketAddress) InputStream(java.io.InputStream) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) IOException(java.io.IOException) URL(java.net.URL)

Example 25 with ParseException

use of org.json.simple.parser.ParseException in project spatial-portal by AtlasOfLivingAustralia.

the class PhylogeneticDiversityComposer method fillPDTreeList.

private void fillPDTreeList() {
    JSONArray ja = null;
    String url = CommonData.getSettings().getProperty(CommonData.PHYLOLIST_URL) + "/phylo/getExpertTrees";
    JSONParser jp = new JSONParser();
    try {
        ja = (JSONArray) jp.parse(Util.readUrl(url));
    } catch (ParseException e) {
        LOGGER.error("failed to parse getExpertTrees");
    }
    if (ja == null || ja.size() == 0) {
        Events.echoEvent("onClose", this, null);
        getMapComposer().showMessage("Phylogenetic diversity tool is currently unavailable.");
        return;
    }
    trees = new Object[ja.size()];
    header = new ArrayList<String>();
    // restrict header to what is in the zul
    for (Component c : getFellow(StringConstants.TREES_HEADER).getChildren()) {
        header.add(c.getId().substring(3));
    }
    int row = 0;
    for (int i = 0; i < ja.size(); i++) {
        JSONObject j = (JSONObject) ja.get(i);
        Map<String, String> pdrow = new HashMap<String, String>();
        for (Object o : j.keySet()) {
            String key = (String) o;
            if (j.containsKey(key) && j.get(key) != null) {
                pdrow.put(key, j.get(key).toString());
            } else {
                pdrow.put(key, null);
            }
        }
        trees[row] = pdrow;
        row++;
    }
    treesList.setModel(new ListModelArray(trees, false));
    treesList.setItemRenderer(new ListitemRenderer() {

        public void render(Listitem li, Object data, int itemIdx) {
            Map<String, String> map = (Map<String, String>) data;
            for (int i = 0; i < header.size(); i++) {
                String value = map.get(header.get(i));
                if (value == null) {
                    value = "";
                }
                if ("treeViewUrl".equalsIgnoreCase(header.get(i))) {
                    Html img = new Html("<i class='icon-info-sign'></i>");
                    img.setAttribute("link", value.isEmpty() ? CommonData.getSettings().getProperty(CommonData.PHYLOLIST_URL) : value);
                    Listcell lc = new Listcell();
                    lc.setParent(li);
                    img.setParent(lc);
                    img.addEventListener(StringConstants.ONCLICK, new EventListener() {

                        @Override
                        public void onEvent(Event event) throws Exception {
                            // re-toggle the checked flag
                            Listitem li = (Listitem) event.getTarget().getParent().getParent();
                            li.getListbox().toggleItemSelection(li);
                            String metadata = (String) event.getTarget().getAttribute("link");
                            getMapComposer().activateLink(metadata, "Metadata", false);
                        }
                    });
                } else {
                    Listcell lc = new Listcell(value);
                    lc.setParent(li);
                }
            }
        }
    });
    treesList.setMultiple(true);
}
Also used : HashMap(java.util.HashMap) JSONArray(org.json.simple.JSONArray) JSONObject(org.json.simple.JSONObject) Event(org.zkoss.zk.ui.event.Event) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException) EventListener(org.zkoss.zk.ui.event.EventListener) Component(org.zkoss.zk.ui.Component) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

ParseException (org.json.simple.parser.ParseException)258 JSONObject (org.json.simple.JSONObject)191 JSONParser (org.json.simple.parser.JSONParser)185 JSONArray (org.json.simple.JSONArray)84 IOException (java.io.IOException)71 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)50 HashMap (java.util.HashMap)41 ArrayList (java.util.ArrayList)34 Map (java.util.Map)23 HashSet (java.util.HashSet)18 API (org.wso2.carbon.apimgt.api.model.API)18 BufferedReader (java.io.BufferedReader)13 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)13 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)13 List (java.util.List)12 File (java.io.File)11 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)11 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)11 InputStreamReader (java.io.InputStreamReader)10 URL (java.net.URL)10