Example usage for org.json.simple JSONObject get

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

Introduction

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

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:luceneindexdemo.LuceneIndexDemo.java

public static void missOperation(String type)
        throws FileNotFoundException, IOException, org.json.simple.parser.ParseException, SQLException {
    //JSONObject jsObject=new JSONObject();
    System.out.println("this brings out all your connection with the person you miss");
    String query = "match (n:People)-[r:KNOWS]-(b:People) where n.name='" + user + "' and r.relType='" + type
            + "' return filter(x in n.interest where x in b.interest) as common,b.name";
    Connection con = DriverManager.getConnection("jdbc:neo4j://localhost:7474/");
    ResultSet rs = con.createStatement().executeQuery(query);
    JSONParser jsParser = new JSONParser();
    FileReader freReader = new FileReader("/home/rishav12/NetBeansProjects/LuceneIndexDemo/location.json");
    JSONObject jsono = (JSONObject) jsParser.parse(freReader);
    JSONArray jslocArray = (JSONArray) jsono.get("CHENNAI");
    int count = 0;
    while (rs.next()) {
        System.out.println(rs.getString("b.name"));
        String searchQuery = "start n=node:restaurant('withinDistance:[" + jslocArray.get(0) + ","
                + jslocArray.get(1) + ",13.5]') where ";
        JSONArray jsArray = (JSONArray) jsParser.parse(rs.getString("common"));
        Iterator<JSONArray> iterJsArray = jsArray.iterator();

        count++;//from  ww w  . j a  v a 2 s . c  om
        int k = 0;
        int flag = 0;
        while (iterJsArray.hasNext()) {
            flag = 1;
            if (k == 0) {
                searchQuery = searchQuery + "n.type='" + iterJsArray.next() + "'";
                k = k + 1;

            } else
                searchQuery = searchQuery + " or n.type='" + iterJsArray.next() + "'";
        }

        if (flag == 1) {
            searchQuery += " return n.name,n.type";
            ResultSet commonInterest = con.createStatement().executeQuery(searchQuery);
            System.out.println("Sir based on your common interests with " + rs.getString("b.name")
                    + " \ni will plan out something nearby you");
            while (commonInterest.next()) {
                System.out
                        .println(commonInterest.getString("n.name") + " " + commonInterest.getString("n.type"));
            }
        } else {
            System.err.println("you do not seem to share any common interest with" + rs.getString("b.name"));
        }

    }
    return;

}

From source file:net.maxgigapop.mrs.driver.openstack.OpenStackModelBuilder.java

public static OntModel createOntology(String hostName, String tenantName, String tenantPasswd)
        throws IOException {

    String host = "charon.dragon.maxgigapop.net";
    String tenant = "admin";
    String tenantId;// w ww  .  j  a va  2 s . co  m
    String token;

    Logger logger = Logger.getLogger(OpenStackModelBuilder.class.getName());

    OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_MICRO_RULE_INF);

    model.setNsPrefix("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
    model.setNsPrefix("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
    model.setNsPrefix("xsd", "http://www.w3.org/2001/XMLSchema#");
    model.setNsPrefix("owl", "http://www.w3.org/2002/07/owl#");
    model.setNsPrefix("nml", "http://schemas.ogf.org/nml/2013/03/base#");
    model.setNsPrefix("mrs", "http://schemas.ogf.org/mrs/2013/12/topology#");

    Property hasNode = model.createProperty("http://schemas.ogf.org/nml/2013/03/base#hasNode");
    Property hasService = model.createProperty("http://schemas.ogf.org/nml/2013/03/base#hasService");
    Property providesVM = model.createProperty("http://schemas.ogf.org/mrs/2013/12/topology#providesVM");
    Property type = model.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
    Property memory_mb = model.createProperty("http://schemas.ogf.org/mrs/2013/12/topology#memory_mb");
    Property num_core = model.createProperty("http://schemas.ogf.org/mrs/2013/12/topology#num_core");
    Property disk_gb = model.createProperty("http://schemas.ogf.org/mrs/2013/12/topology#disk_gb");

    Resource HypervisorService = model
            .createResource("http://schemas.ogf.org/mrs/2013/12/topology#HypervisorService");
    Resource Node = model.createResource("http://schemas.ogf.org/nml/2013/03/base#Node");
    Resource Topology = model.createResource("http://schemas.ogf.org/mrs/2013/12/topology#Topology");
    Resource VirtualSwitchService = model
            .createResource("http://schemas.ogf.org/mrs/2013/12/topology#VirtualSwitchService");
    Resource NamedIndividual = model.createResource("http://www.w3.org/2002/07/owl#NamedIndividual");
    Resource Nova = model.createResource("urn:ogf:network:dragon.maxgigapop.net:openstack-nova");
    Resource Neutron = model.createResource("urn:ogf:network:dragon.maxgigapop.net:openstack-neutron");
    Resource OpenstackTopology = model.createResource("urn:ogf:network:dragon.maxgigapop.net:topology");

    model.add(model.createStatement(OpenstackTopology, type, Topology));
    model.add(model.createStatement(OpenstackTopology, type, NamedIndividual));

    model.add(model.createStatement(Nova, type, HypervisorService));
    model.add(model.createStatement(Nova, type, NamedIndividual));

    model.add(model.createStatement(Neutron, type, VirtualSwitchService));
    model.add(model.createStatement(Neutron, type, NamedIndividual));

    token = OpenStackRESTClient.getToken(host, tenant, "admin", "admin");
    tenantId = OpenStackRESTClient.getTenantId(host, tenant, token);
    JSONArray novaDescription = OpenStackRESTClient.pullNovaConfig(host, tenantId, token);

    for (Object o : novaDescription) {

        JSONArray node = (JSONArray) ((JSONObject) o).get("host");

        if (node != null) {

            JSONObject resource = (JSONObject) ((JSONObject) node.get(0)).get("resource");
            String nodeName = (String) resource.get("host");
            Long numCpu = (Long) resource.get("cpu");
            Long memMb = (Long) resource.get("memory_mb");
            Long diskGb = (Long) resource.get("disk_gb");

            Resource computeNode = model.createResource("urn:ogf:network:dragon.maxgigapop.net:" + nodeName);
            Literal cpu = model.createTypedLiteral(numCpu);
            Literal mem = model.createTypedLiteral(memMb);
            Literal disk = model.createTypedLiteral(diskGb);

            model.add(model.createStatement(OpenstackTopology, hasNode, computeNode));
            model.add(model.createStatement(computeNode, type, Node));
            model.add(model.createStatement(computeNode, type, NamedIndividual));
            model.add(model.createStatement(computeNode, hasService, Nova));

            model.add(model.createStatement(computeNode, memory_mb, mem));
            model.add(model.createStatement(computeNode, disk_gb, disk));
            model.add(model.createStatement(computeNode, num_core, cpu));
        }

        JSONObject networkHost = (JSONObject) ((JSONObject) o).get("network_host");
        if (networkHost != null) {

            Resource networkNode = model.createResource(
                    "urn:ogf:network:dragon.maxgigapop.net:" + (String) networkHost.get("host_name"));

            model.add(model.createStatement(OpenstackTopology, hasNode, networkNode));
            model.add(model.createStatement(networkNode, type, Node));
            model.add(model.createStatement(networkNode, type, NamedIndividual));
            model.add(model.createStatement(networkNode, hasService, Neutron));
        }
    }

    tenantId = OpenStackRESTClient.getTenantId(host, "demo", token);
    token = OpenStackRESTClient.getToken(host, "demo", "demo", "demo");
    JSONArray vms = OpenStackRESTClient.pullNovaVM(host, tenantId, token);

    for (Object o : vms) {

        String vmName = (String) ((JSONObject) o).get("name");
        Resource vm = model.createResource("urn:ogf:network:dragon.maxgigapop.net:" + vmName);

        model.add(model.createStatement(vm, type, Node));
        model.add(model.createStatement(vm, type, NamedIndividual));

        model.add(model.createStatement(Nova, providesVM, vm));

    }

    /* 
    JSONArray ports = (JSONArray) OpenStackRESTClient.pullNeutron(host, tenantId, token).get("ports");        
    for(Object o : ports) {
            
            
    } */

    logger.log(Level.INFO, "Ontology model for OpenStack driver rewritten");

    return model;
}

From source file:com.nubits.nubot.trading.wrappers.TradeUtilsCCEDK.java

public static String getCCDKEvalidNonce(String htmlString) {
    //used by ccedkqueryservice

    JSONParser parser = new JSONParser();
    try {//ww w. j  a  v a 2  s. co m
        //{"errors":{"nonce":"incorrect range `nonce`=`1234567891`, must be from `1411036100` till `1411036141`"}
        JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));
        JSONObject errors = (JSONObject) httpAnswerJson.get("errors");
        String nonceError = (String) errors.get("nonce");

        //String startStr = " must be from";
        //int indexStart = nonceError.lastIndexOf(startStr) + startStr.length() + 2;
        //String from = nonceError.substring(indexStart, indexStart + 10);

        String startStr2 = " till";
        int indexStart2 = nonceError.lastIndexOf(startStr2) + startStr2.length() + 2;
        String to = nonceError.substring(indexStart2, indexStart2 + 10);

        //if (to.equals(from)) {
        //    LOG.info("Detected ! " + to + " = " + from);
        //    return "retry";
        //}

        return to;
    } catch (ParseException ex) {
        LOG.error(htmlString + " " + ex.toString());
        return "1234567891";
    }
}

From source file:iracing.webapi.HostedSessionResultSummaryParser.java

static long parse(String json, ItemHandler handler) {
    JSONParser parser = new JSONParser();
    //        System.err.println(json);
    long output = 0;
    if (!"{}".equals(json)) {
        try {/*from  w  w  w .java2  s  .  co  m*/
            JSONObject root = (JSONObject) parser.parse(json);
            output = getLong(root, "rowcount");
            JSONArray rootArray = (JSONArray) root.get("rows");
            for (int i = 0; i < rootArray.size(); i++) {
                JSONObject r = (JSONObject) rootArray.get(i);
                HostedSessionResultSummary summary = new HostedSessionResultSummary();
                summary.setWasPrivate((getInt(r, "private")) == 1);
                summary.setDriverSearchedBestLapTime(getLong(r, "bestlaptime"));
                summary.setDriverSearchedStartingPosition(getInt(r, "startingposition"));
                summary.setDriverSearchedClassStartingPosition(getInt(r, "classstartingposition"));
                summary.setDriverSearchedFinishingPosition(getInt(r, "finishingposition"));
                summary.setDriverSearchedClassFinishingPosition(getInt(r, "classfinishingposition"));
                summary.setDriverSearchedCarClassId(getInt(r, "carclassid"));
                summary.setDriverSearchedIncidents(getInt(r, "incidents"));
                summary.setPracticeLength(getInt(r, "practicelength"));
                summary.setQualifyingLaps(getInt(r, "qualifylaps"));
                summary.setQualifyingLength(getInt(r, "qualifylength"));
                summary.setRaceLaps(getInt(r, "racelaps"));
                summary.setRaceLength(getInt(r, "racelength"));
                summary.setStartTime(new Date(getLong(r, "start_time")));
                summary.setMinimumLicenseLevel(getInt(r, "minliclevel"));
                summary.setMaximumLicenseLevel(getInt(r, "maxliclevel"));
                summary.setMinimumIrating(getInt(r, "minir"));
                summary.setMaximumIrating(getInt(r, "maxir"));
                summary.setPrivateSessionId(getLong(r, "privatesessionid"));
                IracingCustomer host = new IracingCustomer();
                host.setId(getLong(r, "host_custid"));
                host.setName(getString(r, "host_displayname", true));
                summary.setHost(host);
                summary.setHostLicenseLevel(getInt(r, "host_licenselevel"));
                summary.setSessionName(getString(r, "sessionname", true));
                summary.setTrackId(getInt(r, "trackid"));
                summary.setTrackName(getString(r, "track_name", true));
                IracingCustomer winner = new IracingCustomer();
                winner.setId(getLong(r, "winner_custid"));
                winner.setName(getString(r, "winner_displayname", true));
                summary.setWinner(winner);
                summary.setWinnerLicenseLevel(getInt(r, "winner_licenselevel"));
                summary.setSessionId(getLong(r, "sessionid"));
                summary.setSubSessionId(getLong(r, "subsessionid"));
                summary.setSubSessionFinishedAt(new Date(getLong(r, "subsessionfinishedat")));
                summary.setRaceFinishedAt(new Date(getLong(r, "racefinishedat")));
                summary.setLoneQualifying((getInt(r, "lonequalify")) == 1);
                summary.setHardcoreLevelId(getInt(r, "hardcorelevel"));
                summary.setNightMode((getInt(r, "nightmode")) == 1);
                summary.setRestarts(getInt(r, "restarts"));
                summary.setFullCourseCautions((getInt(r, "fullcoursecautions")) == 1);
                summary.setRollingStarts((getInt(r, "rollingstarts")) == 1);
                summary.setMultiClass((getInt(r, "multiclass")) == 1);
                summary.setFixedSetup((getInt(r, "fixed_setup")) == 1);
                summary.setNumberOfFastTows(getInt(r, "numfasttows"));
                String s = getString(r, "carids", true);
                String[] sa = s.split(",");
                List<Integer> carIds = new ArrayList<Integer>();
                for (String carId : sa) {
                    carIds.add(Integer.parseInt(carId));
                }
                summary.setCars(carIds);
                s = getString(r, "max_pct_fuel_fills", true);
                if (!"".equals(s)) {
                    sa = s.split(",");
                    List<Integer> maxFuelFills = new ArrayList<Integer>();
                    for (String mff : sa) {
                        maxFuelFills.add(Integer.parseInt(mff));
                    }
                    summary.setMaximumPercentageFuelFills(maxFuelFills);
                }
                summary.setMaximumDrivers(getInt(r, "maxdrivers"));
                summary.setCreated(new Date(getLong(r, "created")));
                summary.setSessionFastestLap(getLong(r, "sessionfastlap"));
                summary.setCategoryId(getInt(r, "catid"));
                handler.onHostedSessionResultSummaryParsed(summary);
            }
        } catch (ParseException ex) {
            Logger.getLogger(HostedSessionResultSummaryParser.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return output;
}

From source file:com.mycompany.craftdemo.utility.java

public static HashSet<String> getHolidays() {
    HashSet<String> holidays = new HashSet<>();
    JSONObject holidaysData = getAPIData("http://holidayapi.com/v1/holidays?country=US&year=2016");
    JSONObject dates = (JSONObject) holidaysData.get("holidays");

    for (Iterator iterator = dates.keySet().iterator(); iterator.hasNext();) {
        String key = (String) iterator.next();
        holidays.add(key);//from w ww . ja va  2  s  .  c  o  m
    }
    //returning holidays as a set
    return holidays;
}

From source file:it.polimi.geinterface.filter.PropertiesFilter.java

/**
 * Method that parse a JSON {@link String} representing a filter into the corresponding {@link PropertiesFilter}
 * @param jsonPropFilter - the JSON {@link String} representing the filter
 * @return the corresponding {@link PropertiesFilter}
 *///from ww  w  . ja  v  a2 s .c om
public static PropertiesFilter parseFromString(String jsonPropFilter) throws Exception {
    JSONParser p = new JSONParser();

    try {
        JSONObject obj = (JSONObject) p.parse(jsonPropFilter);
        PropertiesFilter ret = new PropertiesFilter();
        for (Object key : obj.keySet())
            ret.put(key, obj.get(key));
        return ret;
    } catch (ParseException e) {
        e.printStackTrace();
        throw new Exception("Error parsing filter " + jsonPropFilter);
    }
}

From source file:org.apache.metron.elasticsearch.integration.ElasticsearchSearchIntegrationTest.java

/**
 * Add test fields to a template with defined types in case they are not defined in the sensor template shipped with Metron.
 * This is useful for testing certain cases, for example faceting on fields of various types.
 * Template follows this pattern://  www  . java  2  s  .c  om
 * { "mappings" : { "xxx_doc" : { "properties" : { ... }}}}
 * @param template - this method has side effects - template is modified with field mappings.
 * @param docType
 */
private static void addTestFieldMappings(JSONObject template, String docType) {
    Map mappings = (Map) template.get("mappings");
    Map docTypeJSON = (Map) mappings.get(docType);
    Map properties = (Map) docTypeJSON.get("properties");
    Map<String, String> longType = new HashMap<>();
    longType.put("type", "long");
    properties.put("long_field", longType);
    Map<String, String> floatType = new HashMap<>();
    floatType.put("type", "float");
    properties.put("latitude", floatType);
    Map<String, String> doubleType = new HashMap<>();
    doubleType.put("type", "double");
    properties.put("score", doubleType);
}

From source file:configuration.Key.java

/**
 * Returns the keys provided in the JSON array.
 * //from   ww  w . j  a va 2  s  .co  m
 * @param array
 *            the JSON array to parse for keys.
 * @return the keys provided in the JSON array.
 */
public static Key[] parseKeys(JSONArray array) {
    List<Key> keys = new LinkedList<Key>();

    if (array == null) {
        throw new NullPointerException("array may not be null!");
    }

    for (int i = 0; i < array.size(); i++) {
        JSONObject object = (JSONObject) array.get(i);
        String key = (String) object.get(KEY_KEY);
        Long version = (Long) object.get(KEY_VERSION);
        int versionInt = version.intValue();
        String algorithm = (String) object.get(KEY_ALGORITHM);
        /*
         * getEncoded() returns the raw bytes of the key (s.
         * http://docs.oracle
         * .com/javase/7/docs/api/javax/crypto/SecretKey.html)
         */
        try {
            byte[] rawKey = Coder.decodeBASE64(key);
            SecretKey secretKey = new SecretKeySpec(rawKey, getSecretKeyAlgorithm(algorithm));
            keys.add(new Key(secretKey, versionInt, algorithm));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return keys.toArray(new Key[0]);
}

From source file:com.storageroomapp.client.Collections.java

/**
 * Parses a String of json text and returns a Collections object.
 * It will correctly parse the Collections object if it is toplevel,
 * or also if nested in an 'array' key-value pair.
 * //from  w  ww  . j  ava2s .  c  o  m
 * @param parent the Application object associated with the json
 * @param json the String with the json text
 * @return an Collections object, or null if the parsing failed
 */
static public Collections parseJson(Application parent, String json) {
    JSONObject root = (JSONObject) JSONValue.parse(json);
    if (root == null) {
        return null;
    }

    // unwrap the collections object if it is a value on key 'array'
    JSONObject rootArray = (JSONObject) root.get("array");
    if (rootArray != null) {
        root = rootArray;
    }
    return parseJsonObject(parent, root);
}

From source file:at.ait.dme.yuma.suite.apps.core.server.annotation.JSONAnnotationHandler.java

public static ArrayList<SemanticTag> parseSemanticTags(JSONArray jsonArray) {
    ArrayList<SemanticTag> tags = new ArrayList<SemanticTag>();

    for (Object obj : jsonArray) {
        JSONObject jsonObj = (JSONObject) obj;
        SemanticTag t = new SemanticTag();

        t.setURI((String) jsonObj.get(KEY_TAG_URI));
        t.setPrimaryLabel((String) jsonObj.get(KEY_TAG_LABEL));
        t.setPrimaryDescription((String) jsonObj.get(KEY_TAG_DESCRIPTION));
        t.setPrimaryLanguage((String) jsonObj.get(KEY_TAG_LANG));
        t.setType((String) jsonObj.get(KEY_TAG_TYPE));

        tags.add(t);/*from   ww w . j av a 2  s  . com*/
    }

    return tags;
}