Example usage for org.json JSONArray JSONArray

List of usage examples for org.json JSONArray JSONArray

Introduction

In this page you can find the example usage for org.json JSONArray JSONArray.

Prototype

public JSONArray(Object array) throws JSONException 

Source Link

Document

Construct a JSONArray from an array

Usage

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesUtility.java

protected static JSONArray makeResponseJSONArray(String data) {

    JSONArray array = null;/*www . j  a va 2 s . c o m*/
    try {
        array = new JSONArray(data);
    } catch (JSONException e) {
        array = new JSONArray();
        array.put(makeResponseJSONObject(data));
    }

    return array;
}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

@Override
public Iterable<VirtualMachineProduct> listProducts(VirtualMachineProductFilterOptions options,
        Architecture architecture) throws InternalException, CloudException {
    ProviderContext ctx = getProvider().getContext();
    if (ctx == null) {
        throw new CloudException("No context was set for this request");
    }//from  w ww . ja va  2s .c  om
    // FIXME: until core fixes the annotation for architecture let's assume it's nullable
    String cacheName = "productsALL";
    if (architecture != null) {
        cacheName = "products" + architecture.name();
    }
    Cache<VirtualMachineProduct> cache = Cache.getInstance(getProvider(), cacheName,
            VirtualMachineProduct.class, CacheLevel.REGION, new TimePeriod<Day>(1, TimePeriod.DAY));
    Iterable<VirtualMachineProduct> products = cache.get(ctx);

    if (products == null) {
        List<VirtualMachineProduct> list = new ArrayList<VirtualMachineProduct>();

        try {
            InputStream input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts.json");

            if (input != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder json = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    json.append(line);
                    json.append("\n");
                }
                JSONArray arr = new JSONArray(json.toString());
                JSONObject toCache = null;

                for (int i = 0; i < arr.length(); i++) {
                    JSONObject productSet = arr.getJSONObject(i);
                    String cloud, providerName;

                    if (productSet.has("cloud")) {
                        cloud = productSet.getString("cloud");
                    } else {
                        continue;
                    }
                    if (productSet.has("provider")) {
                        providerName = productSet.getString("provider");
                    } else {
                        continue;
                    }
                    if (!productSet.has("products")) {
                        continue;
                    }
                    if (toCache == null || (providerName.equals("AWS") && cloud.equals("AWS"))) {
                        toCache = productSet;
                    }
                    if (providerName.equalsIgnoreCase(getProvider().getProviderName())
                            && cloud.equalsIgnoreCase(getProvider().getCloudName())) {
                        toCache = productSet;
                        break;
                    }
                }
                if (toCache == null) {
                    logger.warn("No products were defined");
                    return Collections.emptyList();
                }
                JSONArray plist = toCache.getJSONArray("products");

                for (int i = 0; i < plist.length(); i++) {
                    JSONObject product = plist.getJSONObject(i);
                    boolean supported = false;

                    if (architecture != null) {
                        if (product.has("architectures")) {
                            JSONArray architectures = product.getJSONArray("architectures");

                            for (int j = 0; j < architectures.length(); j++) {
                                String a = architectures.getString(j);

                                if (architecture.name().equals(a)) {
                                    supported = true;
                                    break;
                                }
                            }
                        }
                        if (!supported) {
                            continue;
                        }
                    }
                    if (product.has("excludesRegions")) {
                        JSONArray regions = product.getJSONArray("excludesRegions");

                        for (int j = 0; j < regions.length(); j++) {
                            String r = regions.getString(j);

                            if (r.equals(ctx.getRegionId())) {
                                supported = false;
                                break;
                            }
                        }
                    }
                    if (!supported) {
                        continue;
                    }
                    VirtualMachineProduct prd = toProduct(product);

                    if (prd != null) {
                        if (options != null) {
                            if (options.matches(prd)) {
                                list.add(prd);
                            }
                        } else {
                            list.add(prd);
                        }
                    }

                }

            } else {
                logger.warn("No standard products resource exists for /org/dasein/cloud/aws/vmproducts.json");
            }
            input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts-custom.json");
            if (input != null) {
                ArrayList<VirtualMachineProduct> customList = new ArrayList<VirtualMachineProduct>();
                TreeSet<String> discard = new TreeSet<String>();
                boolean discardAll = false;

                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder json = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    json.append(line);
                    json.append("\n");
                }
                JSONArray arr = new JSONArray(json.toString());
                JSONObject toCache = null;

                for (int i = 0; i < arr.length(); i++) {
                    JSONObject listing = arr.getJSONObject(i);
                    String cloud, providerName, endpoint = null;

                    if (listing.has("cloud")) {
                        cloud = listing.getString("cloud");
                    } else {
                        continue;
                    }
                    if (listing.has("provider")) {
                        providerName = listing.getString("provider");
                    } else {
                        continue;
                    }
                    if (listing.has("endpoint")) {
                        endpoint = listing.getString("endpoint");
                    }
                    if (!cloud.equals(getProvider().getCloudName())
                            || !providerName.equals(getProvider().getProviderName())) {
                        continue;
                    }
                    if (endpoint != null && endpoint.equals(ctx.getCloud().getEndpoint())) {
                        toCache = listing;
                        break;
                    }
                    if (endpoint == null && toCache == null) {
                        toCache = listing;
                    }
                }
                if (toCache != null) {
                    if (toCache.has("discardDefaults")) {
                        discardAll = toCache.getBoolean("discardDefaults");
                    }
                    if (toCache.has("discard")) {
                        JSONArray dlist = toCache.getJSONArray("discard");

                        for (int i = 0; i < dlist.length(); i++) {
                            discard.add(dlist.getString(i));
                        }
                    }
                    if (toCache.has("products")) {
                        JSONArray plist = toCache.getJSONArray("products");

                        for (int i = 0; i < plist.length(); i++) {
                            JSONObject product = plist.getJSONObject(i);
                            boolean supported = false;
                            if (architecture != null) {

                                if (product.has("architectures")) {
                                    JSONArray architectures = product.getJSONArray("architectures");

                                    for (int j = 0; j < architectures.length(); j++) {
                                        String a = architectures.getString(j);

                                        if (architecture.name().equals(a)) {
                                            supported = true;
                                            break;
                                        }
                                    }
                                }
                                if (!supported) {
                                    continue;
                                }
                            }
                            if (product.has("excludesRegions")) {
                                JSONArray regions = product.getJSONArray("excludesRegions");

                                for (int j = 0; j < regions.length(); j++) {
                                    String r = regions.getString(j);

                                    if (r.equals(ctx.getRegionId())) {
                                        supported = false;
                                        break;
                                    }
                                }
                            }
                            if (!supported) {
                                continue;
                            }
                            VirtualMachineProduct prd = toProduct(product);

                            if (prd != null) {
                                customList.add(prd);
                            }
                        }
                    }
                    if (!discardAll) {
                        for (VirtualMachineProduct product : list) {
                            if (!discard.contains(product.getProviderProductId())) {
                                customList.add(product);
                            }
                        }
                    }
                    list = customList;
                }
            }
            products = list;
            cache.put(ctx, products);

        } catch (IOException e) {
            throw new InternalException(e);
        } catch (JSONException e) {
            throw new InternalException(e);
        }
    }
    return products;
}

From source file:com.footprint.cordova.plugin.localnotification.Restore.java

@Override
public void onReceive(Context context, Intent intent) {
    // The application context needs to be set as first
    LocalNotification.setContext(context);

    // Obtain alarm details form Shared Preferences
    SharedPreferences alarms = LocalNotification.getSharedPreferences();
    Set<String> alarmIds = alarms.getAll().keySet();

    /*//from   w ww. jav a 2  s .  c  om
     * For each alarm, parse its alarm options and register is again with
     * the Alarm Manager
     */
    for (String alarmId : alarmIds) {
        try {
            JSONArray args = new JSONArray(alarms.getString(alarmId, ""));
            Options options = new Options(context).parse(args.getJSONObject(0));

            /*
             * If the trigger date was in the past, the notification will be displayed immediately.
             */
            LocalNotification.add(options, false);

        } catch (JSONException e) {
        }
    }
}

From source file:net.di2e.ddf.argo.probe.responselistener.ProbeResponseEndpoint.java

@POST
@Consumes("application/json")
public void getJSONServices(String jsonResponse) {
    LOGGER.debug("Got a probe response in JSON format:\n{}", jsonResponse);
    JSONArray services = new JSONArray(jsonResponse);
    Set<String> createdSources = new HashSet<String>();
    for (int i = 0; i < services.length(); i++) {
        JSONObject jsonService = services.getJSONObject(i);
        // determine factory pid
        String sourceId = jsonService.getString(ArgoConstants.ID_KEY);
        if (!sourceIdExists(sourceId, createdSources)) {
            String serviceContractId = jsonService.getString(ArgoConstants.SERVICE_CONTRACTID_KEY);
            String serviceType = getServiceType(serviceContractId);
            if (serviceType != null) {
                String pid = serviceResolver.getFactoryPid(serviceType);
                LOGGER.debug(/*from   www . j a  va  2s. c  o  m*/
                        "Got a factory pid of '{}' for service '{}' with service contract id '{}' so attempting to create new source '{}'",
                        pid, serviceType, serviceContractId, sourceId);
                createSource(pid, sourceId, jsonService.getString(ArgoConstants.URL_KEY));
                createdSources.add(sourceId);
            } else {
                LOGGER.debug("Could not find a Service Type for the Service Contract ID '{}'",
                        serviceContractId);
            }
        } else {
            LOGGER.debug(
                    "A Source with id '{}' already exists, so not creating a new one from probe, but checking if any values should be overridden",
                    sourceId);
            // TODO override properties
        }
    }
}

From source file:org.droidparts.test.testcase.serialize.AbstractJSONTestCase.java

protected final JSONArray getJSONArray(int resId) throws Exception {
    return new JSONArray(getJSONString(resId));
}

From source file:cc.redpen.server.api.RedPenConfigurationResourceTest.java

@Test
public void availableDocumentParsersAreReturned() throws Exception {
    JSONObject response = (JSONObject) resource.getRedPens("").getEntity();
    assertEquals(new JSONArray(DocumentParser.PARSER_MAP.keySet()).toString(),
            response.get("documentParsers").toString());
}

From source file:ecjtu.net.demon.utils.ACache.java

/**
 * ?JSONArray?/*from w w w .j av a2s. c  om*/
 * 
 * @param key
 * @return JSONArray?
 */
public JSONArray getAsJSONArray(String key) {
    String JSONString = getAsString(key);
    try {
        JSONArray obj = new JSONArray(JSONString);
        return obj;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:nl.hnogames.domoticz.Domoticz.EventsParser.java

@Override
public void parseResult(String result) {
    try {/*from  w w  w .j  ava 2s . co m*/
        JSONArray jsonArray = new JSONArray(result);
        ArrayList<EventInfo> mVars = new ArrayList<>();

        if (jsonArray.length() > 0) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject row = jsonArray.getJSONObject(i);
                mVars.add(new EventInfo(row));
            }
        }

        if (mVars == null || mVars.size() <= 0)
            onError(new NullPointerException("No Events devined in Domoticz."));
        else
            varsReceiver.onReceiveEvents(mVars);

    } catch (JSONException e) {
        Log.e(TAG, "EventsParser JSON exception");
        e.printStackTrace();
        varsReceiver.onError(e);
    }
}

From source file:com.tinyhydra.botd.GoogleOperations.java

public static List<JavaShop> GetShops(Handler handler, Location currentLocation, String placesApiKey) {
    // Use google places to get all the shops within '500' (I believe meters is the default measurement they use)
    // make a list of JavaShops and pass it to the ListView adapter
    List<JavaShop> shopList = new ArrayList<JavaShop>();
    try {//from ww  w.  j ava2  s .  com
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        int accuracy = Math.round(currentLocation.getAccuracy());
        if (accuracy < 500)
            accuracy = 500;
        request.setURI(URI.create("https://maps.googleapis.com/maps/api/place/search/json?location="
                + currentLocation.getLatitude() + "," + currentLocation.getLongitude() + "&radius=" + accuracy
                + "&types=" + URLEncoder.encode("cafe|restaurant|food", "UTF-8")
                + "&keyword=coffee&sensor=true&key=" + placesApiKey));
        HttpResponse response = client.execute(request);
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }

        JSONObject predictions = new JSONObject(sb.toString());
        // Google passes back a status string. if we screw up, it won't say "OK". Alert the user.
        String jstatus = predictions.getString("status");
        if (jstatus.equals("ZERO_RESULTS")) {
            Utils.PostToastMessageToHandler(handler, "No shops found in your area.", Toast.LENGTH_SHORT);
            return shopList;
        } else if (!jstatus.equals("OK")) {
            Utils.PostToastMessageToHandler(handler, "Error retrieving local shops.", Toast.LENGTH_SHORT);
            return shopList;
        }

        // This section may fail if there's no results, but we'll just display an empty list.
        //TODO: alert the user and cancel the dialog if this fails
        JSONArray ja = new JSONArray(predictions.getString("results"));

        for (int i = 0; i < ja.length(); i++) {
            JSONObject jo = (JSONObject) ja.get(i);
            shopList.add(new JavaShop(jo.getString("name"), jo.getString("id"), "", jo.getString("reference"),
                    jo.getString("vicinity")));
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return shopList;
}

From source file:ch.icclab.cyclops.persistence.client.InfluxDBClient.java

public TSDBData getData(String query) {
    JSONArray resultArray;/*from   ww  w .j  a v a 2 s.  com*/
    JSONObject resultObj;
    TSDBData dataObj = null;
    Representation output;
    ObjectMapper mapper = new ObjectMapper();

    Client client = new Client(Protocol.HTTP);
    ClientResource cr = new ClientResource(url);

    cr.addQueryParameter("q", query);
    cr.addQueryParameter("u", username);
    cr.addQueryParameter("p", password);
    cr.get(MediaType.APPLICATION_JSON);
    output = cr.getResponseEntity();

    try {
        resultArray = new JSONArray(output.getText());
        if (!resultArray.isNull(0)) {
            resultObj = new JSONObject();
            resultObj = (JSONObject) resultArray.get(0);
            dataObj = mapper.readValue(resultObj.toString(), TSDBData.class);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return dataObj;
}