Example usage for org.json.simple JSONObject keySet

List of usage examples for org.json.simple JSONObject keySet

Introduction

In this page you can find the example usage for org.json.simple JSONObject keySet.

Prototype

Set<K> keySet();

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:com.ibm.bluemix.samples.PostgreSQLReportedErrors.java

/**
 * Establishes a connection to the database
 * //  ww w  .j  av a  2s  .  c  o m
 * @return the established connection
 * 
 * @throws Exception
 *          a custom exception thrown if no postgresql service URL was found
 */
public static Connection getConnection() throws Exception {
    Map<String, String> env = System.getenv();

    if (env.containsKey("VCAP_SERVICES")) {
        // we are running on cloud foundry, let's grab the service details from vcap_services
        JSONParser parser = new JSONParser();
        JSONObject vcap = (JSONObject) parser.parse(env.get("VCAP_SERVICES"));
        JSONObject service = null;

        // We don't know exactly what the service is called, but it will contain "postgresql"
        for (Object key : vcap.keySet()) {
            String keyStr = (String) key;
            if (keyStr.toLowerCase().contains("postgresql")) {
                service = (JSONObject) ((JSONArray) vcap.get(keyStr)).get(0);
                break;
            }
        }

        if (service != null) {
            JSONObject creds = (JSONObject) service.get("credentials");
            String name = (String) creds.get("name");
            String host = (String) creds.get("host");
            Long port = (Long) creds.get("port");
            String user = (String) creds.get("user");
            String password = (String) creds.get("password");

            String url = "jdbc:postgresql://" + host + ":" + port + "/" + name;

            return DriverManager.getConnection(url, user, password);
        }
    }
    throw new Exception(
            "No PostgreSQL service URL found. Make sure you have bound the correct services to your app.");
}

From source file:com.sforce.cd.apexUnit.client.codeCoverage.WebServiceInvoker.java

public static JSONObject doGet(String relativeServiceURL, String accessToken) {

    LOG.debug("relativeServiceURL in doGet method:" + relativeServiceURL);
    HttpClient httpclient = new HttpClient();
    GetMethod get = null;//from  w ww  . j av a  2 s  .  c  o  m

    String authorizationServerURL = CommandLineArguments.getOrgUrl() + relativeServiceURL;
    get = new GetMethod(authorizationServerURL);
    get.addRequestHeader("Content-Type", "application/json");
    get.setRequestHeader("Authorization", "Bearer " + accessToken);
    LOG.debug("Start GET operation for the url..." + authorizationServerURL);
    InputStream instream = null;
    try {
        instream = executeHTTPMethod(httpclient, get, authorizationServerURL);
        LOG.debug("done with get operation");

        JSONObject json = (JSONObject) JSONValue.parse(new InputStreamReader(instream));
        LOG.debug("is json null? :" + json == null ? "true" : "false");
        if (json != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("ToolingApi.get response: " + json.toString());
                Set<String> keys = castSet(String.class, json.keySet());
                Iterator<String> jsonKeyIter = keys.iterator();
                LOG.debug("Response for the GET method: ");
                while (jsonKeyIter.hasNext()) {
                    String key = jsonKeyIter.next();
                    LOG.debug("key : " + key + ". Value :  " + json.get(key) + "\n");
                    // TODO if query results are too large, only 1st batch
                    // of results
                    // are returned. Need to use the identifier in an
                    // additional query
                    // to retrieve rest of the next batch of results

                    if (key.equals("nextRecordsUrl")) {
                        // fire query to the value for this key
                        // doGet((String) json.get(key), accessToken);
                        try {
                            authorizationServerURL = CommandLineArguments.getOrgUrl() + (String) json.get(key);
                            get.setURI(new URI(authorizationServerURL, false));
                            instream = executeHTTPMethod(httpclient, get, authorizationServerURL);
                            JSONObject newJson = (JSONObject) JSONValue.parse(new InputStreamReader(instream));
                            if (newJson != null) {
                                Set<String> newKeys = castSet(String.class, json.keySet());
                                Iterator<String> newJsonKeyIter = newKeys.iterator();
                                while (newJsonKeyIter.hasNext()) {
                                    String newKey = newJsonKeyIter.next();
                                    json.put(newKey, newJson.get(newKey));
                                    LOG.debug("newkey : " + newKey + ". NewValue :  " + newJson.get(newKey)
                                            + "\n");
                                }
                            }

                        } catch (URIException e) {
                            ApexUnitUtils.shutDownWithDebugLog(e,
                                    "URI exception while fetching subsequent batch of result");
                        }
                    }

                }
            }
        }
        return json;
    } finally {
        get.releaseConnection();
        try {
            if (instream != null) {
                instream.close();

            }
        } catch (IOException e) {
            ApexUnitUtils.shutDownWithDebugLog(e,
                    "Encountered IO exception when closing the stream after reading response from the get method. The error says: "
                            + e.getMessage());
        }
    }
}

From source file:edu.isi.techknacq.topics.readinglist.ReadDocumentkey.java

public void Readfile() {
    try {/*from  w  w w  .  j av a  2s  .c  o  m*/
        JSONParser parser = new JSONParser();
        JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(filename));
        for (Object key : jsonObject.keySet()) {
            JSONObject documentInfo = (JSONObject) jsonObject.get(key);
            String author = (String) documentInfo.get("author");
            String title = (String) documentInfo.get("title");
            docMap.put((String) key, "author: " + author + ", title: " + title);
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ReadDocumentkey.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ReadDocumentkey.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(ReadDocumentkey.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.polopoly.tools.minifier.FileMapConstructor.java

public Map<String, List<String>> decodeFiles(String json) throws BadJsonException {

    Map<String, List<String>> result = new HashMap<String, List<String>>();
    JSONParser parser = new JSONParser();
    try {/*from  ww w  . ja  va  2 s .co  m*/
        Object parsed = parser.parse(json);
        if (parsed instanceof JSONObject) {
            JSONObject fileMap = (JSONObject) parsed;
            for (Object fileObj : fileMap.keySet()) {
                String filename = fileObj.toString();
                Object parsedArray = fileMap.get(fileObj);
                if (parsedArray instanceof JSONArray) {
                    result.put(filename, getFilesFromMap((JSONArray) parsedArray));
                }
            }
        } else {
            throw new BadJsonException("Top level object not a string");
        }
    } catch (ParseException e) {
        throw new BadJsonException(e);
    }
    return result;
}

From source file:com.justgiving.raven.kissmetrics.schema.KissmetricsJsonToSchemaMapper.java

@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
    String s = value.toString();//from ww  w.  j  a  v  a  2s  .co m
    JSONParser jsonParser = new JSONParser();
    try {
        JSONObject jsonObject = (JSONObject) jsonParser.parse(s);
        Set<String> keyset = jsonObject.keySet();
        String jsonValue = "";
        for (String jsonkey : keyset) {
            jsonValue = (String) jsonObject.get(jsonkey).toString();
            if (jsonValue == null || jsonValue == "") {
                jsonValue = "";
            }
            String lenValue = String.valueOf(jsonValue.length());
            if (lenValue == null || lenValue == "") {
                lenValue = "0";
            }
            context.write(new Text(jsonkey), new Text("1\t" + lenValue));
        }

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

From source file:com.endgame.binarypig.util.JsonUtil.java

/**
 * Note: copied from elephantbird pig JsonLoader
 *///from  w ww .j  a  v  a 2s  .co  m
public Map<String, Object> walkJson(JSONObject jsonObj) {
    Map<String, Object> v = Maps.newHashMap();
    for (Object key : jsonObj.keySet()) {
        v.put(key.toString(), wrap(jsonObj.get(key)));
    }
    return v;
}

From source file:me.timothy.ddd.entities.EntityInventory.java

@Override
public void loadFrom(JSONObject jsonObject) {
    Set<?> keys = jsonObject.keySet();

    for (Object o : keys) {
        if (o instanceof String) {
            String key = (String) o;
            switch (key.toLowerCase()) {
            case "items":
                JSONArray arr = getArray(jsonObject, key);
                for (Object o2 : arr) {
                    if (o2 instanceof String)
                        items.add((String) o2);
                }//from ww w . j a  v  a  2s . c o m
                break;
            default:
                logger.warn("Unknown key: " + key);
            }
        }
    }
}

From source file:com.bowprog.sql.constructeur.Table.java

public boolean appliqueJSON(JSONObject jSONObject) {
    fkSQL.clear();/*from w  ww.ja v a  2s. co m*/
    Collection<String> str = jSONObject.keySet();
    for (String table : str) {
        try {
            JSONObject tableColonne = (JSONObject) jSONObject.get(table);
            tableName = table;
            String col = createCol(tableColonne);
            String sql = "CREATE TABLE IF NOT EXISTS `" + tableName + "`(" + col + ")";
            statement.execute(sql);
        } catch (SQLException ex) {
            Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }
    for (String sql : fkSQL) {
        try {
            statement.execute(sql);
        } catch (SQLException ex) {
            Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }
    return false;
}

From source file:com.couragelabs.logging.GlobalContextSocketAppender.java

/**
 * @param globalContext Global context to set.
 * @throws ParseException If parsing the global context fails.
 *///from  w ww .ja  v  a2s .co m
public void setGlobalContext(String globalContext) throws ParseException {
    if (globalContext != null) {
        this.globalContext = new HashMap<>();
        JSONParser parser = new JSONParser();
        Object parsed = parser.parse(globalContext);
        if (parsed instanceof String) {
            this.globalContext.put("global", (String) parsed);
        } else if (parsed instanceof JSONArray) {
            Iterator iterator = ((JSONArray) parsed).iterator();
            int i = 0;
            while (iterator.hasNext()) {
                this.globalContext.put(format("global[%d]", i), String.valueOf(iterator.next()));
                i++;
            }
        } else if (parsed instanceof JSONObject) {
            JSONObject parsedObject = (JSONObject) parsed;
            for (Object key : parsedObject.keySet()) {
                this.globalContext.put(String.valueOf(key), String.valueOf(parsedObject.get(key)));
            }
        } else {
            System.err.println("Unable to handle context type: " + parsed.getClass());
        }
    }
}

From source file:com.johncroth.histo.logging.LogHistogramParser.java

LogHistogram parseHistogramJson(JSONObject jo) {
    LogHistogram result = new LogHistogram();
    for (Object key : jo.keySet()) {
        int iKey = Integer.parseInt(String.valueOf(key));
        JSONObject joBucket = (JSONObject) jo.get(key);
        long c = (Long) joBucket.get(COUNT);
        double w = (Double) joBucket.get(WEIGHT);
        result.setBucket(iKey, c, w);/*w w w  .  ja  v  a 2s  .  c o m*/
    }
    return result;
}