Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

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

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

From source file:org.brickred.socialauth.provider.FourSquareImpl.java

/**
 * Gets the list of contacts of the user.
 * //  ww  w .j  a  va2  s . co  m
 * @return List of contact objects representing Contacts. Only name and
 *         profile URL will be available
 */

@Override
public List<Contact> getContactList() throws Exception {
    LOG.info("Fetching contacts from " + CONTACTS_URL);

    Response serviceResponse;
    try {
        serviceResponse = authenticationStrategy.executeFeed(CONTACTS_URL);
    } catch (Exception e) {
        throw new SocialAuthException("Error while getting contacts from " + CONTACTS_URL, e);
    }
    if (serviceResponse.getStatus() != 200) {
        throw new SocialAuthException("Error while getting contacts from " + CONTACTS_URL + "Status : "
                + serviceResponse.getStatus());
    }
    String respStr;
    try {
        respStr = serviceResponse.getResponseBodyAsString(Constants.ENCODING);
    } catch (Exception exc) {
        throw new SocialAuthException("Failed to read response from  " + CONTACTS_URL, exc);
    }
    LOG.debug("User Contacts list in JSON " + respStr);
    JSONObject resp = new JSONObject(respStr);
    List<Contact> plist = new ArrayList<Contact>();
    JSONArray items = new JSONArray();
    if (resp.has("response")) {
        JSONObject robj = resp.getJSONObject("response");
        if (robj.has("friends")) {
            JSONObject fobj = robj.getJSONObject("friends");
            if (fobj.has("items")) {
                items = fobj.getJSONArray("items");
            }
        } else {
            throw new SocialAuthException("Failed to parse the user profile json : " + respStr);
        }
    } else {
        throw new SocialAuthException("Failed to parse the user profile json : " + respStr);
    }
    LOG.debug("Contacts Found : " + items.length());
    for (int i = 0; i < items.length(); i++) {
        JSONObject obj = items.getJSONObject(i);
        Contact c = new Contact();
        if (obj.has("firstName")) {
            c.setFirstName(obj.getString("firstName"));
        }
        if (obj.has("lastName")) {
            c.setLastName(obj.getString("lastName"));
        }
        if (obj.has("id")) {
            c.setProfileUrl(VIEW_PROFILE_URL + obj.getString("id"));
            c.setId(obj.getString("id"));
        }
        plist.add(c);
    }

    return plist;
}

From source file:com.ecml.MidiOptions.java

/** Initialize the options from a json string
 * /*  ww  w . jav a  2  s. c o m*/
 * @param jsonString
 */
public static MidiOptions fromJson(String jsonString) {
    if (jsonString == null) {
        return null;
    }
    MidiOptions options = new MidiOptions();
    try {
        JSONObject json = new JSONObject(jsonString);
        JSONArray jsonTracks = json.getJSONArray("tracks");
        options.tracks = new boolean[jsonTracks.length()];
        for (int i = 0; i < options.tracks.length; i++) {
            options.tracks[i] = jsonTracks.getBoolean(i);
        }

        JSONArray jsonMute = json.getJSONArray("mute");
        options.mute = new boolean[jsonMute.length()];
        for (int i = 0; i < options.mute.length; i++) {
            options.mute[i] = jsonMute.getBoolean(i);
        }

        JSONArray jsonInstruments = json.getJSONArray("instruments");
        options.instruments = new int[jsonInstruments.length()];
        for (int i = 0; i < options.instruments.length; i++) {
            options.instruments[i] = jsonInstruments.getInt(i);
        }

        if (json.has("time")) {
            JSONObject jsonTime = json.getJSONObject("time");
            int numer = jsonTime.getInt("numerator");
            int denom = jsonTime.getInt("denominator");
            int quarter = jsonTime.getInt("quarter");
            int tempo = jsonTime.getInt("tempo");
            options.time = new TimeSignature(numer, denom, quarter, tempo);
        }

        options.useDefaultInstruments = json.getBoolean("useDefaultInstruments");
        options.scrollVert = json.getBoolean("scrollVert");
        options.showPiano = json.getBoolean("showPiano");
        options.showNoteColors = json.getBoolean("showNoteColors");
        options.showLyrics = json.getBoolean("showLyrics");
        options.delay = json.getInt("delay");
        options.twoStaffs = json.getBoolean("twoStaffs");
        options.showNoteLetters = json.getInt("showNoteLetters");
        options.transpose = json.getInt("transpose");
        options.key = json.getInt("key");
        options.combineInterval = json.getInt("combineInterval");
        options.shade1Color = json.getInt("shade1Color");
        options.shade2Color = json.getInt("shade2Color");
        options.showMeasures = json.getBoolean("showMeasures");
        options.playMeasuresInLoop = json.getBoolean("playMeasuresInLoop");
        options.playMeasuresInLoopStart = json.getInt("playMeasuresInLoopStart");
        options.playMeasuresInLoopEnd = json.getInt("playMeasuresInLoopEnd");
    } catch (Exception e) {
        return null;
    }
    return options;
}

From source file:org.openmrs.mobile.listeners.visit.VisitTypeListener.java

@Override
public void onResponse(JSONObject response) {
    mLogger.d(response.toString());//from   www  .  j a v  a 2  s.co m

    try {
        JSONArray visitTypesObj = response.getJSONArray("results");
        String visitTypeUUID = ((JSONObject) visitTypesObj.get(0)).getString("uuid");
        OpenMRS.getInstance().setVisitTypeUUID(visitTypeUUID);
    } catch (JSONException e) {
        mLogger.d(e.toString());
    }
}

From source file:fr.pasteque.pos.sales.restaurant.JTicketsBagRestaurantMap.java

/** Creates new form JTicketsBagRestaurant */
public JTicketsBagRestaurantMap(AppView app, TicketsEditor panelticket) {

    super(app, panelticket);

    dlReceipts = new DataLogicReceipts();
    dlSales = new DataLogicSales();

    m_restaurantmap = new JTicketsBagRestaurant(app, this);
    m_PlaceCurrent = null;/*from  w  w w .  j  a  v  a  2s  . c om*/
    m_PlaceClipboard = null;
    customer = null;
    this.floors = new ArrayList<Floor>();
    this.places = new HashMap<String, List<Place>>();
    try {
        ServerLoader loader = new ServerLoader();
        ServerLoader.Response r = loader.read("PlacesAPI", "getAll");
        if (r.getStatus().equals(ServerLoader.Response.STATUS_OK)) {
            JSONArray a = r.getArrayContent();
            for (int i = 0; i < a.length(); i++) {
                JSONObject oFloor = a.getJSONObject(i);
                Floor f = new Floor(oFloor);
                this.floors.add(f);
                this.places.put(f.getID(), new ArrayList<Place>());
                JSONArray aPlaces = oFloor.getJSONArray("places");
                for (int j = 0; j < aPlaces.length(); j++) {
                    Place p = new Place(aPlaces.getJSONObject(j));
                    this.places.get(f.getID()).add(p);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    initComponents();

    // add the Floors containers
    if (this.floors.size() > 1) {
        // A tab container for 2 or more floors
        JTabbedPane jTabFloors = new JTabbedPane();
        jTabFloors.applyComponentOrientation(getComponentOrientation());
        jTabFloors.setBorder(new javax.swing.border.EmptyBorder(new Insets(5, 5, 5, 5)));
        jTabFloors.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        jTabFloors.setFocusable(false);
        jTabFloors.setRequestFocusEnabled(false);
        m_jPanelMap.add(jTabFloors, BorderLayout.CENTER);

        for (Floor f : this.floors) {
            f.getContainer().applyComponentOrientation(getComponentOrientation());
            JScrollPane jScrCont = new JScrollPane();
            jScrCont.applyComponentOrientation(getComponentOrientation());
            JPanel jPanCont = new JPanel();
            jPanCont.applyComponentOrientation(getComponentOrientation());

            jTabFloors.addTab(f.getName(), f.getIcon(), jScrCont);
            jScrCont.setViewportView(jPanCont);
            jPanCont.add(f.getContainer());
        }
    } else if (this.floors.size() == 1) {
        // Just a frame for 1 floor
        Floor f = this.floors.get(0);
        f.getContainer().applyComponentOrientation(getComponentOrientation());

        JPanel jPlaces = new JPanel();
        jPlaces.applyComponentOrientation(getComponentOrientation());
        jPlaces.setLayout(new BorderLayout());
        jPlaces.setBorder(new javax.swing.border.CompoundBorder(
                new javax.swing.border.EmptyBorder(new Insets(5, 5, 5, 5)),
                new javax.swing.border.TitledBorder(f.getName())));

        JScrollPane jScrCont = new JScrollPane();
        jScrCont.applyComponentOrientation(getComponentOrientation());
        JPanel jPanCont = new JPanel();
        jPanCont.applyComponentOrientation(getComponentOrientation());

        // jPlaces.setLayout(new FlowLayout());           
        m_jPanelMap.add(jPlaces, BorderLayout.CENTER);
        jPlaces.add(jScrCont, BorderLayout.CENTER);
        jScrCont.setViewportView(jPanCont);
        jPanCont.add(f.getContainer());
    }

    // Add all the Table buttons.
    for (Floor f : this.floors) {
        List<Place> places = this.places.get(f.getID());
        for (Place pl : places) {
            f.getContainer().add(pl.getButton());
            pl.setButtonBounds();
            pl.getButton().addActionListener(new MyActionListener(pl));
        }
    }

    // Add the reservations panel
    m_jreservations = new JTicketsBagRestaurantRes(app, this);
    add(m_jreservations, "res");
}

From source file:com.wglxy.example.dashL.SearchActivity.java

ArrayList<User> parseJSON(String results) throws JSONException, NullPointerException {
    ArrayList<User> list = new ArrayList<User>();
    JSONObject jsonResult = new JSONObject(results);
    int status = jsonResult.getInt("status");
    int numResults = jsonResult.getInt("numResults");

    if (status != 200 && numResults <= 0)
        return list;
    else {/*from   w  w  w. j  av a  2  s  . c  o m*/
        JSONArray arr = jsonResult.getJSONArray("results");
        Log.e(LOG_TAG, "results: " + arr.length());

        for (int i = 0; i < arr.length(); i++) {
            JSONObject jsonObject = arr.getJSONObject(i);
            User user = new User();
            int id = jsonObject.getInt("id");
            String email = jsonObject.getString("email");
            String first_name = jsonObject.getString("first_name");
            String last_name = jsonObject.getString("last_name");
            String business_name = jsonObject.getString("business_name");
            String services = jsonObject.getString("services");
            String address = jsonObject.getString("address");
            int stars = jsonObject.getInt("stars");
            String image = Constants.API_BASE_IMAGE_URL + jsonObject.getString("image");
            Log.e(LOG_TAG, "image: " + image);

            user.setId(id);
            user.setEmail(email);
            user.setFirst_name(first_name);
            user.setLast_name(last_name);
            user.setBusiness_name(business_name);
            user.setAddress(address);
            user.setServices(services);
            user.setStars(stars);
            user.setImage(image);

            list.add(user);
        }
        return list;
    }
}

From source file:game.Clue.JerseyClient.java

public JSONObject getGameState() {

    JSONObject Object = null;
    try {/*w w  w . j a va2  s .co m*/
        URL url = new URL(
                "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/player1");
        URLConnection connection = url.openConnection();
        connection.setDoInput(true);
        //setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        Object = new JSONObject(in.readLine());
        //;
        // JsonParser parser=new JsonParser(in.readLine());

        //  while (in.readLine() != null) {
        //}
        // System.out.print(in.readLine());
        System.out.println(Object.getJSONArray("players").getJSONObject(0).getString("character"));
        System.out.println("\nREST Service Invoked Successfully..GET Request Sent");

        //sendPUT();
        //send JSON to Parser
        //Parser=new JsonParser(in.readLine());
        //System.out.println("Parser called");
        // sendPUT();
        //close connection
        // in.close();
    } catch (Exception e) {
        System.out.println("\nError while calling REST Service");
        System.out.println(e);
    }

    return Object;

}

From source file:at.alladin.rmbt.android.util.CheckSettingsTask.java

/**
* 
*/// w  ww.  j a  v  a2 s.c  o  m
@Override
protected void onPostExecute(final JSONArray resultList) {
    try {
        if (serverConn.hasError())
            hasError = true;
        else if (resultList != null && resultList.length() > 0) {

            JSONObject resultListItem;

            try {
                resultListItem = resultList.getJSONObject(0);

                /* UUID */

                final String uuid = resultListItem.optString("uuid", "");
                if (uuid != null && uuid.length() != 0)
                    ConfigHelper.setUUID(activity.getApplicationContext(), uuid);

                /* urls */

                final ConcurrentMap<String, String> volatileSettings = ConfigHelper.getVolatileSettings();

                final JSONObject urls = resultListItem.optJSONObject("urls");
                if (urls != null) {
                    final Iterator<String> keys = urls.keys();

                    while (keys.hasNext()) {
                        final String key = keys.next();
                        final String value = urls.optString(key, null);
                        if (value != null) {
                            volatileSettings.put("url_" + key, value);
                            if ("statistics".equals(key)) {
                                ConfigHelper.setCachedStatisticsUrl(value, activity);
                            } else if ("control_ipv4_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv4(value, activity);
                            } else if ("control_ipv6_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv6(value, activity);
                            } else if ("url_ipv4_check".equals(key)) {
                                ConfigHelper.setCachedIpv4CheckUrl(value, activity);
                            } else if ("url_ipv6_check".equals(key)) {
                                ConfigHelper.setCachedIpv6CheckUrl(value, activity);
                            }
                        }
                    }
                }

                /* qos names */
                final JSONArray qosNames = resultListItem.optJSONArray("qostesttype_desc");
                if (qosNames != null) {
                    final Map<String, String> qosNamesMap = new HashMap<String, String>();
                    for (int i = 0; i < qosNames.length(); i++) {
                        JSONObject json = qosNames.getJSONObject(i);
                        qosNamesMap.put(json.optString("test_type"), json.optString("name"));
                    }
                    ConfigHelper.setCachedQoSNames(qosNamesMap, activity);
                }

                /* map server */

                final JSONObject mapServer = resultListItem.optJSONObject("map_server");
                if (mapServer != null) {
                    final String host = mapServer.optString("host");
                    final int port = mapServer.optInt("port");
                    final boolean ssl = mapServer.optBoolean("ssl");
                    if (host != null && port > 0)
                        ConfigHelper.setMapServer(host, port, ssl);
                }

                /* control server version */
                final JSONObject versions = resultListItem.optJSONObject("versions");
                if (versions != null) {
                    if (versions.has("control_server_version")) {
                        ConfigHelper.setControlServerVersion(activity,
                                versions.optString("control_server_version"));
                    }
                }

                // ///////////////////////////////////////////////////////
                // HISTORY / FILTER

                final JSONObject historyObject = resultListItem.getJSONObject("history");

                final JSONArray deviceArray = historyObject.getJSONArray("devices");
                final JSONArray networkArray = historyObject.getJSONArray("networks");

                final String historyDevices[] = new String[deviceArray.length()];

                for (int i = 0; i < deviceArray.length(); i++)
                    historyDevices[i] = deviceArray.getString(i);

                final String historyNetworks[] = new String[networkArray.length()];

                for (int i = 0; i < networkArray.length(); i++)
                    historyNetworks[i] = networkArray.getString(i);

                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                activity.setSettings(historyDevices, historyNetworks);

                activity.setHistoryDirty(true);

            } catch (final JSONException e) {
                e.printStackTrace();
            }

        } else
            Log.i(DEBUG_TAG, "LEERE LISTE");
    } finally {
        if (endTaskListener != null)
            endTaskListener.taskEnded(resultList);
    }
}

From source file:com.tune.reporting.base.endpoints.EndpointBase.java

/**
 * Fetch all fields from model and related models of this endpoint.
 *
 * @return Map All endpoint fields./*from  ww  w.ja va  2  s.co  m*/
 *
 * @throws TuneServiceException If service fails to handle post request.
 * @throws TuneSdkException If error within SDK.
 */
protected final Map<String, Map<String, String>> getEndpointFields()
        throws TuneServiceException, TuneSdkException {
    Map<String, String> mapQueryString = new HashMap<String, String>();
    mapQueryString.put("controllers", this.controller);
    mapQueryString.put("details", "modelName,fields");

    TuneServiceClient client = new TuneServiceClient("apidoc", "get_controllers", this.getAuthKey(),
            this.getAuthType(), mapQueryString);

    client.call();

    TuneServiceResponse response = client.getResponse();
    int httpCode = response.getHttpCode();
    JSONArray data = (JSONArray) response.getData();

    if (httpCode != HTTP_STATUS_OK) {
        String requestUrl = response.getRequestUrl();
        throw new TuneServiceException(
                String.format("Connection failure '%s': Request: '%s'", httpCode, requestUrl));
    }

    if ((null == data) || (data.length() == 0)) {
        String requestUrl = response.getRequestUrl();
        throw new TuneServiceException(String.format("Failed to get fields for endpoint: '%s', Request: '%s'",
                this.controller, requestUrl));
    }

    try {
        JSONObject endpointMetaData = data.getJSONObject(0);

        this.endpointModelName = endpointMetaData.getString("modelName");
        JSONArray endpointFields = endpointMetaData.getJSONArray("fields");

        Map<String, Map<String, String>> fieldsFound = new HashMap<String, Map<String, String>>();
        Map<String, Set<String>> relatedFields = new HashMap<String, Set<String>>();

        for (int i = 0; i < endpointFields.length(); i++) {
            JSONObject endpointField = endpointFields.getJSONObject(i);
            Boolean fieldRelated = endpointField.getBoolean("related");
            String fieldType = endpointField.getString("type");
            String fieldName = endpointField.getString("name");
            Boolean fieldDefault = endpointField.has("fieldDefault") ? endpointField.getBoolean("fieldDefault")
                    : false;

            if (fieldRelated) {
                if (fieldType.equals("property")) {
                    String relatedProperty = fieldName;
                    if (!relatedFields.containsKey(relatedProperty)) {
                        relatedFields.put(relatedProperty, new HashSet<String>());
                    }
                    continue;
                }

                String[] fieldRelatedNameParts = fieldName.split("\\.");
                String relatedProperty = fieldRelatedNameParts[0];
                String relatedFieldName = fieldRelatedNameParts[1];

                if (!relatedFields.containsKey(relatedProperty)) {
                    relatedFields.put(relatedProperty, new HashSet<String>());
                }

                Set<String> relatedFieldFields = relatedFields.get(relatedProperty);
                relatedFieldFields.add(relatedFieldName);
                relatedFields.put(relatedProperty, relatedFieldFields);
                continue;
            }

            Map<String, String> fieldFoundInfo = new HashMap<String, String>();
            fieldFoundInfo.put("default", Boolean.toString(fieldDefault));
            fieldFoundInfo.put("related", "false");
            fieldsFound.put(fieldName, fieldFoundInfo);
        }

        Map<String, Map<String, String>> fieldsFoundMerged = new HashMap<String, Map<String, String>>();
        Iterator<Map.Entry<String, Map<String, String>>> it = fieldsFound.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry<String, Map<String, String>> pairs = it.next();

            String fieldFoundName = pairs.getKey();
            Map<String, String> fieldFoundInfo = pairs.getValue();

            fieldsFoundMerged.put(fieldFoundName, fieldFoundInfo);

            if ((fieldFoundName != "_id") && fieldFoundName.endsWith("_id")) {
                String relatedProperty = fieldFoundName.substring(0, fieldFoundName.length() - 3);
                if (relatedFields.containsKey(relatedProperty)
                        && !relatedFields.get(relatedProperty).isEmpty()) {
                    for (String relatedFieldName : relatedFields.get(relatedProperty)) {
                        if ("id" == relatedFieldName) {
                            continue;
                        }
                        String relatedPropertyFieldName = String.format("%s.%s", relatedProperty,
                                relatedFieldName);
                        Map<String, String> relatedPropertyFieldInfo = new HashMap<String, String>();
                        relatedPropertyFieldInfo.put("default", fieldFoundInfo.get("default"));
                        relatedPropertyFieldInfo.put("related", "true");
                        fieldsFoundMerged.put(relatedPropertyFieldName, relatedPropertyFieldInfo);
                    }
                } else {
                    Map<String, String> relatedPropertyFieldInfo = new HashMap<String, String>();
                    relatedPropertyFieldInfo.put("default", fieldFoundInfo.get("default"));
                    relatedPropertyFieldInfo.put("related", "true");
                    String relatedPropertyFieldName = String.format("%s.%s", relatedProperty, "name");
                    fieldsFoundMerged.put(relatedPropertyFieldName, relatedPropertyFieldInfo);
                }
            }
        }

        this.endpointFields = fieldsFoundMerged;

    } catch (JSONException ex) {
        throw new TuneSdkException(ex.getMessage(), ex);
    } catch (Exception ex) {
        throw new TuneSdkException(ex.getMessage(), ex);
    }

    return this.endpointFields;
}

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

protected static String findTsuid(String urlString, HashMap<String, String> tags, String metric,
        long startTime) {

    long endTime = startTime + 1;
    JSONObject results = null;
    results = TimeSeriesRetriever.retrieveTimeSeries(urlString, startTime, endTime, metric, tags, true);
    String ret = null;//from  w w  w . j a v  a2  s  .com
    try {
        JSONArray tsuidsArray = results.getJSONArray("tsuids");
        ret = tsuidsArray.getString(0);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return ret;
}

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 w  w. j  a va 2  s  .co m
    // 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;
}