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:com.dynamobi.network.DynamoNetworkUdr.java

/**
 * Composes a jar file .jar name from attributes in obj:
 * publisher-package-version.jar//from   w  w  w .  j  av a2  s.co  m
 */
private static String jarName(JSONObject obj) {
    return obj.get("publisher") + "-" + obj.get("package") + "-" + obj.get("version") + ".jar";
}

From source file:freebase.api.FreebaseAPIMusic.java

public static List<Recording> getRecording(String fromDate, String toDate) {
    try {/*from  w  w  w .  j  av  a 2 s  . co  m*/
        properties.load(new FileInputStream("freebase.properties"));
        HttpTransport httpTransport = new NetHttpTransport();
        HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
        JSONParser parser = new JSONParser();
        //            String query = "[{\"id\":null,\"name\":null,\"type\":\"/astronomy/planet\"}]";
        String query = readQueryFromFile("queries/q2.json");
        query = manipulateQuery(query, fromDate, toDate);
        //JSONArray queryJObj = (JSONArray) JSONValue.parse(query);
        //query = queryJObj.toJSONString();
        //query = "[{\"id\":null,\"name\":null,\"type\":\"/film/film\"}]";
        //query = "[{\"mid\":null,\"name\":null,\"language\":\"English Language\",\"country\":\"United States of America\",\"type\":\"/film/film\",\"initial_release_date>=\":\"2000-01-01\",\"initial_release_date<=\":\"2020-01-01\",\"initial_release_date\":null,\"directed_by\":[{\"mid\":null,\"name\":null}],\"starring\":[{\"mid\":null,\"actor\":[{\"mid\":null,\"name\":null}],\"character\":[{\"mid\":null,\"name\":null}]}],\"limit\":1}]";
        GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/mqlread");
        url.put("query", query);
        url.put("key", properties.get("API_KEY"));
        // url.put("cursor", current_cursor);
        System.out.println("URL:" + url);
        HttpRequest request = requestFactory.buildGetRequest(url);
        HttpResponse httpResponse = request.execute();
        JSONObject response = (JSONObject) parser.parse(httpResponse.parseAsString());
        JSONArray results = (JSONArray) response.get("result");
        //            if (response.get("cursor") instanceof Boolean) {
        //                System.out.println("End of The Result, cursor=" + response.get("cursor"));
        //            } else {
        //                current_cursor = (String) response.get("cursor");
        //            }
        //            System.out.println(results.toString());
        Utils.writeDataIntoFile(results.toString() + "\n", JSON_DUMP_FILE);
        List<Recording> recordings = encodeJSON(results);
        return recordings;
        //            for (Object result : results) {
        //                System.out.println(JsonPath.read(result, "$.name").toString());
        //            }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

@SuppressWarnings("unchecked")
public static JSONObject authAccessToken(String email, String password) {

    String clientToken = null;//from  w  ww. j a v a  2 s . c  o m

    JSONObject fileObj = readAccessToken();

    if (fileObj != null) {
        clientToken = (String) fileObj.get("clientToken");
    }

    if (clientToken == null) {
        byte[] arr = new byte[32];
        Crypt.getBytes(arr);
        clientToken = UUID.nameUUIDFromBytes(arr).toString();
    }

    JSONObject obj = new JSONObject();

    JSONObject agent = new JSONObject();
    agent.put("name", "Minecraft");
    agent.put("version", 1);

    obj.put("agent", agent);

    obj.put("username", email);
    obj.put("password", password);
    obj.put("clientToken", clientToken);

    JSONObject reply = sendRequest(obj, "authenticate");

    if (reply == null) {
        return null;
    }

    JSONObject stripped = stripLoginDetails(reply, true);
    if (stripped == null) {
        return null;
    }

    writeAccessToken(stripped);

    AuthManager.loginDetails = stripped;

    return reply;
}

From source file:it.infn.ct.InstantiateVM.java

public static String instantiateVM(JSONObject egiInput) {
    OCCI_ENDPOINT_HOST = (String) egiInput.get("endpoint");
    RES_TPL = (String) egiInput.get("resourceTpl");
    OS_TPL = (String) egiInput.get("osTpl");
    PUBLIC_KEY_PATH = (String) egiInput.get("publicKey");
    CONTEXT_PATH = (String) egiInput.get("contextualisation");
    AUTH = (String) egiInput.get("auth");
    TRUSTED_CERT_REPOSITORY_PATH = (String) egiInput.get("trustedCertificatesPath");
    PROXY_PATH = (String) egiInput.get("proxyPath");

    MIXIN = Arrays.asList(RES_TPL, OS_TPL);

    CONTEXT = Arrays.asList("public_key=" + PUBLIC_KEY_PATH, "user_data=" + CONTEXT_PATH);

    Boolean result = false;//from   w  w w  .  j av a  2 s.com
    String networkInterfaceLocation = "";
    String networkInterfaceLocation_stripped = "";
    Resource vm_resource = null;
    URI uri_location = null;

    if (verbose) {
        System.out.println();
        if (ACTION != null && !ACTION.isEmpty())
            System.out.println("[ACTION] = " + ACTION);
        else
            System.out.println("[ACTION] = Get dump model");
        System.out.println("AUTH = " + AUTH);
        if (OCCI_ENDPOINT_HOST != null && !OCCI_ENDPOINT_HOST.isEmpty())
            System.out.println("OCCI_ENDPOINT_HOST = " + OCCI_ENDPOINT_HOST);
        if (RESOURCE != null && !RESOURCE.isEmpty())
            System.out.println("RESOURCE = " + RESOURCE);
        if (MIXIN != null && !MIXIN.isEmpty())
            System.out.println("MIXIN = " + MIXIN);
        if (TRUSTED_CERT_REPOSITORY_PATH != null && !TRUSTED_CERT_REPOSITORY_PATH.isEmpty())
            System.out.println("TRUSTED_CERT_REPOSITORY_PATH = " + TRUSTED_CERT_REPOSITORY_PATH);
        if (PROXY_PATH != null && !PROXY_PATH.isEmpty())
            System.out.println("PROXY_PATH = " + PROXY_PATH);
        if (CONTEXT != null && !CONTEXT.isEmpty())
            System.out.println("CONTEXT = " + CONTEXT);
        if (OCCI_PUBLICKEY_NAME != null && !OCCI_PUBLICKEY_NAME.isEmpty())
            System.out.println("OCCI_PUBLICKEY_NAME = " + OCCI_PUBLICKEY_NAME);
        if (ATTRIBUTES != null && !ATTRIBUTES.isEmpty())
            System.out.println("ATTRIBUTES = " + ATTRIBUTES);
        if (verbose)
            System.out.println("Verbose = True ");
        else
            System.out.println("Verbose = False ");
    }

    Properties properties = new Properties();

    if (ACTION != null && !ACTION.isEmpty())
        properties.setProperty("ACTION", ACTION);

    if (OCCI_ENDPOINT_HOST != null && !OCCI_ENDPOINT_HOST.isEmpty())
        properties.setProperty("OCCI_ENDPOINT_HOST", OCCI_ENDPOINT_HOST);

    if (RESOURCE != null && !RESOURCE.isEmpty())
        for (int i = 0; i < RESOURCE.size(); i++) {
            if ((!RESOURCE.get(i).equals("compute")) && (!RESOURCE.get(i).equals("storage"))
                    && (!RESOURCE.get(i).equals("network")) && (!RESOURCE.get(i).equals("os_tpl"))
                    && (!RESOURCE.get(i).equals("resource_tpl")))
                properties.setProperty("OCCI_VM_RESOURCE_ID", RESOURCE.get(i));
            else {
                properties.setProperty("RESOURCE", RESOURCE.get(i));
                properties.setProperty("OCCI_VM_RESOURCE_ID", "empty");
            }
        }

    if (MIXIN != null && !MIXIN.isEmpty())
        for (int i = 0; i < MIXIN.size(); i++) {
            if (MIXIN.get(i).contains("template") || MIXIN.get(i).contains("os_tpl"))
                properties.setProperty("OCCI_OS_TPL", MIXIN.get(i));

            if (MIXIN.get(i).contains("resource_tpl"))
                properties.setProperty("OCCI_RESOURCE_TPL", MIXIN.get(i));
        }

    if (ATTRIBUTES != null && !ATTRIBUTES.isEmpty())
        for (int i = 0; i < ATTRIBUTES.size(); i++) {
            if (ATTRIBUTES.get(i).contains("occi.core.title")) {
                String _OCCI_CORE_TITLE = ATTRIBUTES.get(i).substring(ATTRIBUTES.get(i).lastIndexOf("=") + 1);

                properties.setProperty("OCCI_CORE_TITLE", _OCCI_CORE_TITLE);
            }

            if (ATTRIBUTES.get(i).contains("occi.storage.size")) {
                String _OCCI_STORAGE_SIZE = ATTRIBUTES.get(i).substring(ATTRIBUTES.get(i).lastIndexOf("=") + 1);

                properties.setProperty("OCCI_STORAGE_SIZE", _OCCI_STORAGE_SIZE);
            }
        }

    properties.setProperty("TRUSTED_CERT_REPOSITORY_PATH", TRUSTED_CERT_REPOSITORY_PATH);
    properties.setProperty("PROXY_PATH", PROXY_PATH);

    if (CONTEXT != null && !CONTEXT.isEmpty()) {
        for (int i = 0; i < CONTEXT.size(); i++) {
            if (CONTEXT.get(i).contains("public_key"))
                properties.setProperty("PUBLIC_KEY_FILE", CONTEXT.get(i));

            if (CONTEXT.get(i).contains("user_data"))
                properties.setProperty("USER_DATA", CONTEXT.get(i));
        }
    }

    if (OCCI_PUBLICKEY_NAME != null && !OCCI_PUBLICKEY_NAME.isEmpty())
        properties.setProperty("OCCI_PUBLICKEY_NAME", OCCI_PUBLICKEY_NAME);
    properties.setProperty("OCCI_AUTH", AUTH);

    try {
        HTTPAuthentication authentication = new VOMSAuthentication(PROXY_PATH);

        authentication.setCAPath(TRUSTED_CERT_REPOSITORY_PATH);

        Client client = new HTTPClient(URI.create(OCCI_ENDPOINT_HOST), authentication, MediaType.TEXT_PLAIN,
                false);

        //Connect client
        client.connect();

        Model model = client.getModel();
        EntityBuilder eb = new EntityBuilder(model);

        instantiatedVmId = doCreate(properties, eb, model, client, egiInput);
        System.out.println("VM ID: " + instantiatedVmId);
        return instantiatedVmId;
    } catch (CommunicationException ex) {
        throw new RuntimeException(ex);
    }

}

From source file:com.worldline.easycukes.commons.helpers.JSONHelper.java

/**
 * Returns a particular property from a JSONObject
 *
 * @param jsonObject JSONObject you want to parse
 * @param simpleProp property you're searching for
 * @return An Object matching the required property
 *///from   w w w . j av a  2  s.  co m
private static Object getProperty(@NonNull JSONObject jsonObject, @NonNull String simpleProp) {
    final int idx1 = simpleProp.indexOf("[");
    if (idx1 > 0) {
        final JSONArray jsonArray = (JSONArray) jsonObject.get(simpleProp.substring(0, idx1));
        return getProperty(jsonArray, simpleProp.substring(idx1));
    } else
        return jsonObject.get(simpleProp);
}

From source file:com.punyal.medusaserver.californiumServer.core.MedusaValidation.java

public static Client check(String medusaServerAddress, String myTicket, String ticket) {
    CoapClient coapClient = new CoapClient();
    Logger.getLogger("org.eclipse.californium.core.network.CoAPEndpoint").setLevel(Level.OFF);
    Logger.getLogger("org.eclipse.californium.core.network.EndpointManager").setLevel(Level.OFF);
    Logger.getLogger("org.eclipse.californium.core.network.stack.ReliabilityLayer").setLevel(Level.OFF);

    CoapResponse response;//w  ww  . j av a2  s  . c o m

    coapClient.setURI(medusaServerAddress + "/" + MEDUSA_SERVER_VALIDATION_SERVICE_NAME);
    JSONObject json = new JSONObject();
    json.put(JSON_MY_TICKET, myTicket);
    json.put(JSON_TICKET, ticket);
    response = coapClient.put(json.toString(), 0);

    if (response != null) {
        //System.out.println(response.getResponseText());

        try {
            json.clear();
            json = (JSONObject) JSONValue.parse(response.getResponseText());
            long expireTime = (Long) json.get(JSON_TIME_TO_EXPIRE) + (new Date()).getTime();
            String userName = json.get(JSON_USER_NAME).toString();
            String[] temp = json.get(JSON_ADDRESS).toString().split("/");
            String address;
            if (temp[1] != null)
                address = temp[1];
            else
                address = "0.0.0.0";
            Client client = new Client(InetAddress.getByName(address), userName, null,
                    UnitConversion.hexStringToByteArray(ticket), expireTime);
            return client;
        } catch (Exception e) {
        }

    } else {
        // TODO: take 
    }
    return null;
}

From source file:iracing.webapi.SpectatorSessionParser.java

static List<SpectatorSession> parse(String json) {
    JSONParser parser = new JSONParser();
    List<SpectatorSession> output = null;
    try {/*from  w w  w  .j a  v a 2  s . co m*/
        JSONArray rootArray = (JSONArray) parser.parse(json);
        output = new ArrayList<SpectatorSession>();
        for (int i = 0; i < rootArray.size(); i++) {
            JSONObject r = (JSONObject) rootArray.get(i);
            SpectatorSession o = new SpectatorSession();
            o.setSubSessionStatus(getString(r, "subses_status"));
            o.setSessionStatus(getString(r, "ses_status"));

            JSONObject b = (JSONObject) r.get("broadcast");
            SpectatorSession.BroadcastInfo bi = new SpectatorSession.BroadcastInfo();
            bi.setCanBroadcast((Boolean) b.get("canBroadcast"));
            bi.setSubSessionId(getLong(b, "subSessionId"));
            bi.setBroadcaster((Boolean) b.get("isBroadcaster"));
            bi.setMaximumUsers(getInt(b, "maxUsers"));
            bi.setAvailableSpectatorSlots(getInt(b, "availSpectatorSlots"));
            bi.setNumberOfDrivers(getInt(b, "numDrivers"));
            bi.setNumberOfDriverSlots(getInt(b, "numDriverSlots"));
            bi.setNumberOfSpectators(getInt(b, "numSpectators"));
            bi.setNumberOfBroadcasters(getInt(b, "numBroadcasters"));
            bi.setNumberOfSpectatorSlots(getInt(b, "numSpectatorSlots"));
            bi.setAvailableReservedBroadcasterSlots(getInt(b, "availReservedBCasterSlots"));
            bi.setCanWatch((Boolean) b.get("canWatch"));
            o.setBroadcastInfo(bi);

            o.setSubSessionId(getLong(r, "subsessionid"));
            o.setSessionId(getLong(r, "sessionid"));
            o.setSeriesId(getInt(r, "seriesid"));
            o.setTrackId(getInt(r, "trackid"));

            JSONObject h = (JSONObject) r.get("hosted");
            if (h != null) {
                SpectatorSession.HostedInfo hi = new SpectatorSession.HostedInfo();
                hi.setHeatFilterAmount(getInt(h, "heatFilterAmount"));
                hi.setPracticeLength(getInt(h, "practiceLength"));
                JSONArray a = (JSONArray) h.get("admins");
                List<SpectatorSession.DriverInfo> driverList = new ArrayList<SpectatorSession.DriverInfo>();
                for (int j = 0; j < a.size(); j++) {
                    JSONObject ar = (JSONObject) a.get(j);
                    if (ar != null) {
                        SpectatorSession.DriverInfo di = new SpectatorSession.DriverInfo();
                        di.setCustomerId(getLong(ar, "custId"));
                        di.setName(getString(ar, "displayName", true));
                        driverList.add(di);
                    }
                }
                hi.setAdministrators(driverList);
                hi.setOrderId(getLong(h, "orderId"));
                hi.setMaximumIrating(getInt(h, "maxIR"));
                hi.setMinimumLicenseLevel(getInt(h, "minLicLevel"));
                hi.setRootPrivateSessionId(getLong(h, "rootPrivateSessionId"));
                hi.setDescription(getString(h, "desc", true));
                hi.setFastTows(getInt(h, "fastTows"));
                hi.setQualifyingLength(getInt(h, "qualLength"));
                hi.setRaceLength(getInt(h, "raceLength"));
                hi.setRestrictResults((getInt(h, "restrictResults")) == 1);
                hi.setHardcoreLevelId(getInt(h, "hardcoreLevel"));
                hi.setId(getLong(h, "id"));
                hi.setMaximumLicenseLevel(getInt(h, "maxLicLevel"));
                hi.setQualifyingLaps(getInt(h, "qualLaps"));
                hi.setHostName(getString(h, "host", true));
                // TODO: handle allowed clubs/leagues/teams
                hi.setRaceLaps(getInt(h, "raceLaps"));
                hi.setNumberOfServers(getInt(h, "numServers"));
                hi.setCustomerId(getLong(h, "custid"));
                // TODO: handle league info
                hi.setHeatGridType(getInt(h, "heatGridType"));
                hi.setExpires(new Date(getLong(h, "expires")));
                hi.setHeatAddedDrivers(getInt(h, "heatAddedDrivers"));
                hi.setNumberOfServersFinished(getInt(h, "numServersFinished"));
                hi.setMultiClass((getInt(h, "multiClass")) == 1);
                hi.setRestrictViewing((getInt(h, "restrictViewing")) == 1);
                hi.setSessionName(getString(h, "sessionName", true));
                List<Integer> carList = new ArrayList<Integer>();
                JSONArray ca = (JSONArray) h.get("carIds");
                for (int j = 0; j < ca.size(); j++) {
                    carList.add(((Long) ca.get(j)).intValue());
                }
                hi.setCars(carList);
                hi.setReason(getString(h, "reason", true));
                hi.setTrackId(getInt(h, "trackId"));
                hi.setLaunchAt(new Date(getLong(h, "launchAt")));
                hi.setMaximumDrivers(getInt(h, "maxDrivers"));
                hi.setSessionId(getLong(h, "sessionId"));
                hi.setHeatGridsId(getInt(h, "heatGridsId"));
                hi.setParentPrivateSessionId(getLong(h, "parentPrivateSessionId"));
                hi.setNightMode((getInt(h, "nightMode")) == 1);
                hi.setHeatSessionType(getInt(h, "heatSessionType"));
                hi.setHeatFilterType(getInt(h, "heatFilterType"));
                hi.setHeatFinal((getInt(h, "heatFinal")) == 1);
                hi.setCreated(new Date(getLong(h, "created")));
                hi.setCautions((getInt(h, "cautions")) == 1);
                hi.setFixedSetup((getInt(h, "fixedSetup")) == 1);
                hi.setRestartType(getInt(h, "restartType"));
                hi.setTimeLimit(getInt(h, "timeLimit"));
                hi.setPasswordProtected((Boolean) h.get("pwdProtected"));
                hi.setFarmId(getInt(h, "farmId"));
                hi.setStatus(getInt(h, "status"));
                hi.setLoneQualifying((getInt(h, "loneQualify")) == 1);
                hi.setRollingStart((getInt(h, "rollingStarts")) == 1);
                hi.setNumberOfServersStarted(getInt(h, "numServersStarted"));
                JSONArray ff = (JSONArray) h.get("maxPercentFuelFills");
                List<Integer> fuelList = new ArrayList<Integer>();
                for (int j = 0; j < ff.size(); j++) {
                    fuelList.add(((Long) ff.get(j)).intValue());
                }
                // TODO: finish handling % fuel fills
                hi.setMinimumIrating(getInt(h, "minIR"));
                o.setHostedInfo(hi);
            }
            o.setStartTime(new Date(getLong(r, "start_time")));
            o.setEventTypeId(getInt(r, "evttype"));
            o.setPrivateSessionId(getLong(r, "privatesessionid"));
            o.setSeasonId(getInt(r, "seasonid"));
            output.add(o);
        }
    } catch (ParseException ex) {
        Logger.getLogger(SpectatorSessionParser.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:com.walmartlabs.mupd8.application.Config.java

private static HashMap<String, JSONObject> extractWorkerJSONs(JSONObject configuration) {
    HashMap<String, JSONObject> performers = new HashMap<String, JSONObject>();

    JSONObject applications = (JSONObject) getScopedValue(configuration,
            new String[] { "mupd8", "application" });
    if (applications == null) {
        // Lost cause: No applications found.
        System.err.println("No mupd8:application found; Config.workerJSONs not set.");
        return performers;
    }/* ww  w. j a v a 2s  . co  m*/
    Set<?> applicationNames = applications.keySet();
    if (applicationNames.size() != 1) {
        System.err.println("Exactly one application definition expected, but got "
                + Integer.toString(applicationNames.size()) + " instead; Config.workerJSONs not set.");
        return performers;
    }
    String applicationName = applicationNames.toArray(new String[] {})[0];
    JSONObject performerSection = (JSONObject) getScopedValue(applications,
            new String[] { applicationName, "performers" });

    for (Object k : performerSection.keySet()) {
        String key = (String) k;
        performers.put(key, (JSONObject) performerSection.get(key));
    }

    return performers;
}

From source file:com.krypc.hl.pr.controller.PatientRecordController.java

public static ResponseWrapper convertQueryResponse(ResponseWrapper wrapper) throws ParseException {
    if (wrapper.resultObject instanceof ChainCodeResponse) {
        ChainCodeResponse res = (ChainCodeResponse) wrapper.resultObject;
        if (res.getStatus() == Status.SUCCESS) {
            String plain_json = res.getMessage().toStringUtf8();
            JSONParser parser = new JSONParser();
            JSONObject job = (JSONObject) parser.parse(plain_json);
            wrapper.resultObject = job.get("resultObject");
            wrapper.errorCode = (long) job.get("errorCode");
            wrapper.errorDetails = (String) job.get("errorDetails");
            wrapper.errorMessage = (String) job.get("errorMessage");
            return wrapper;
        }//  www  .  java2s . c om
    }
    return null;
}

From source file:eu.dety.burp.joseph.utilities.Converter.java

/**
 * Get RSA PublicKey list by JWK JSON input
 * //from w ww .  j a v  a 2  s  .c  om
 * @param input
 *            JSON Web Key {@link JSONObject}
 * @return List of {@link PublicKey}
 */
public static List<PublicKey> getRsaPublicKeysByJwk(final Object input) {
    List<PublicKey> keys = new ArrayList<>();

    if (!(input instanceof JSONObject))
        return keys;

    JSONObject inputJsonObject = (JSONObject) input;

    // Multiple keys existent
    if (inputJsonObject.containsKey("keys")) {
        loggerInstance.log(Converter.class, "Key array found...", Logger.LogLevel.DEBUG);

        for (final Object value : (JSONArray) inputJsonObject.get("keys")) {
            JSONObject keyJson = (JSONObject) value;

            PublicKey key = getRsaPublicKeyByJwk(keyJson);

            if (key != null)
                keys.add(key);
        }
    } else {
        PublicKey key = getRsaPublicKeyByJwk(inputJsonObject);

        if (key != null)
            keys.add(key);
    }

    return keys;
}