Example usage for org.json JSONArray getString

List of usage examples for org.json JSONArray getString

Introduction

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

Prototype

public String getString(int index) throws JSONException 

Source Link

Document

Get the string associated with an index.

Usage

From source file:it.moondroid.chatbot.alice.Sraix.java

public static String sraixPannous(String input, String hint, Chat chatSession) {
    try {//from  w w  w . jav  a  2  s .  c o m
        String rawInput = input;
        if (hint == null)
            hint = MagicStrings.sraix_no_hint;
        input = " " + input + " ";
        input = input.replace(" point ", ".");
        input = input.replace(" rparen ", ")");
        input = input.replace(" lparen ", "(");
        input = input.replace(" slash ", "/");
        input = input.replace(" star ", "*");
        input = input.replace(" dash ", "-");
        // input = chatSession.bot.preProcessor.denormalize(input);
        input = input.trim();
        input = input.replace(" ", "+");
        int offset = CalendarUtils.timeZoneOffset();
        //System.out.println("OFFSET = "+offset);
        String locationString = "";
        if (chatSession.locationKnown) {
            locationString = "&location=" + chatSession.latitude + "," + chatSession.longitude;
        }
        // https://weannie.pannous.com/api?input=when+is+daylight+savings+time+in+the+us&locale=en_US&login=pandorabots&ip=169.254.178.212&botid=0&key=CKNgaaVLvNcLhDupiJ1R8vtPzHzWc8mhIQDFSYWj&exclude=Dialogues,ChatBot&out=json
        // exclude=Dialogues,ChatBot&out=json&clientFeatures=show-images,reminder,say&debug=true
        String url = "https://ask.pannous.com/api?input=" + input + "&locale=en_US&timeZone=" + offset
                + locationString + "&login=" + MagicStrings.pannous_login + "&ip="
                + NetworkUtils.localIPAddress() + "&botid=0&key=" + MagicStrings.pannous_api_key
                + "&exclude=Dialogues,ChatBot&out=json&clientFeatures=show-images,reminder,say&debug=true";
        MagicBooleans.trace("in Sraix.sraixPannous, url: '" + url + "'");
        String page = NetworkUtils.responseContent(url);
        //MagicBooleans.trace("in Sraix.sraixPannous, page: " + page);
        String text = "";
        String imgRef = "";
        String urlRef = "";
        if (page == null || page.length() == 0) {
            text = MagicStrings.sraix_failed;
        } else {
            JSONArray outputJson = new JSONObject(page).getJSONArray("output");
            //MagicBooleans.trace("in Sraix.sraixPannous, outputJson class: " + outputJson.getClass() + ", outputJson: " + outputJson);
            if (outputJson.length() == 0) {
                text = MagicStrings.sraix_failed;
            } else {
                JSONObject firstHandler = outputJson.getJSONObject(0);
                //MagicBooleans.trace("in Sraix.sraixPannous, firstHandler class: " + firstHandler.getClass() + ", firstHandler: " + firstHandler);
                JSONObject actions = firstHandler.getJSONObject("actions");
                //MagicBooleans.trace("in Sraix.sraixPannous, actions class: " + actions.getClass() + ", actions: " + actions);
                if (actions.has("reminder")) {
                    //MagicBooleans.trace("in Sraix.sraixPannous, found reminder action");
                    Object obj = actions.get("reminder");
                    if (obj instanceof JSONObject) {
                        if (MagicBooleans.trace_mode)
                            System.out.println("Found JSON Object");
                        JSONObject sObj = (JSONObject) obj;
                        String date = sObj.getString("date");
                        date = date.substring(0, "2012-10-24T14:32".length());
                        if (MagicBooleans.trace_mode)
                            System.out.println("date=" + date);
                        String duration = sObj.getString("duration");
                        if (MagicBooleans.trace_mode)
                            System.out.println("duration=" + duration);

                        Pattern datePattern = Pattern.compile("(.*)-(.*)-(.*)T(.*):(.*)");
                        Matcher m = datePattern.matcher(date);
                        String year = "", month = "", day = "", hour = "", minute = "";
                        if (m.matches()) {
                            year = m.group(1);
                            month = String.valueOf(Integer.parseInt(m.group(2)) - 1);
                            day = m.group(3);

                            hour = m.group(4);
                            minute = m.group(5);
                            text = "<year>" + year + "</year>" + "<month>" + month + "</month>" + "<day>" + day
                                    + "</day>" + "<hour>" + hour + "</hour>" + "<minute>" + minute + "</minute>"
                                    + "<duration>" + duration + "</duration>";

                        } else
                            text = MagicStrings.schedule_error;
                    }
                } else if (actions.has("say") && !hint.equals(MagicStrings.sraix_pic_hint)
                        && !hint.equals(MagicStrings.sraix_shopping_hint)) {
                    MagicBooleans.trace("in Sraix.sraixPannous, found say action");
                    Object obj = actions.get("say");
                    //MagicBooleans.trace("in Sraix.sraixPannous, obj class: " + obj.getClass());
                    //MagicBooleans.trace("in Sraix.sraixPannous, obj instanceof JSONObject: " + (obj instanceof JSONObject));
                    if (obj instanceof JSONObject) {
                        JSONObject sObj = (JSONObject) obj;
                        text = sObj.getString("text");
                        if (sObj.has("moreText")) {
                            JSONArray arr = sObj.getJSONArray("moreText");
                            for (int i = 0; i < arr.length(); i++) {
                                text += " " + arr.getString(i);
                            }
                        }
                    } else {
                        text = obj.toString();
                    }
                }
                if (actions.has("show") && !text.contains("Wolfram")
                        && actions.getJSONObject("show").has("images")) {
                    MagicBooleans.trace("in Sraix.sraixPannous, found show action");
                    JSONArray arr = actions.getJSONObject("show").getJSONArray("images");
                    int i = (int) (arr.length() * Math.random());
                    //for (int j = 0; j < arr.length(); j++) System.out.println(arr.getString(j));
                    imgRef = arr.getString(i);
                    if (imgRef.startsWith("//"))
                        imgRef = "http:" + imgRef;
                    imgRef = "<a href=\"" + imgRef + "\"><img src=\"" + imgRef + "\"/></a>";
                    //System.out.println("IMAGE REF="+imgRef);

                }
                if (hint.equals(MagicStrings.sraix_shopping_hint) && actions.has("open")
                        && actions.getJSONObject("open").has("url")) {
                    urlRef = "<oob><url>" + actions.getJSONObject("open").getString("url") + "</oob></url>";

                }
            }
            if (hint.equals(MagicStrings.sraix_event_hint) && !text.startsWith("<year>"))
                return MagicStrings.sraix_failed;
            else if (text.equals(MagicStrings.sraix_failed))
                return AIMLProcessor.respond(MagicStrings.sraix_failed, "nothing", "nothing", chatSession);
            else {
                text = text.replace("&#39;", "'");
                text = text.replace("&apos;", "'");
                text = text.replaceAll("\\[(.*)\\]", "");
                String[] sentences;
                sentences = text.split("\\. ");
                //System.out.println("Sraix: text has "+sentences.length+" sentences:");
                String clippedPage = sentences[0];
                for (int i = 1; i < sentences.length; i++) {
                    if (clippedPage.length() < 500)
                        clippedPage = clippedPage + ". " + sentences[i];
                    //System.out.println(i+". "+sentences[i]);
                }

                clippedPage = clippedPage + " " + imgRef + " " + urlRef;
                clippedPage = clippedPage.trim();
                log(rawInput, clippedPage);
                return clippedPage;
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        System.out.println("Sraix '" + input + "' failed");
    }
    return MagicStrings.sraix_failed;
}

From source file:com.intel.xdk.facebook.IntelXDKFacebook.java

/**
     * Executes the request and returns PluginResult.
     */*w ww. j av  a2  s . c o  m*/
     * @param action            The action to execute.
     * @param args              JSONArray of arguments for the plugin.
     * @param callbackContext   The callback context used when calling back into JavaScript.
     * @return                  True when the action was valid, false otherwise.
     */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("enableFrictionlessRequests")) {
        this.enableFrictionlessRequests();
    } else if (action.equals("login")) {
        this.login(args.getString(0));
    } else if (action.equals("logout")) {
        this.logout();
    } else if (action.equals("requestWithGraphAPI")) {
        //this.callbackContext = callbackContext;
        this.requestWithGraphAPI(new String[] { args.getString(0), args.getString(1), args.getString(2) });
    } else if (action.equals("requestWithRestAPI")) {
        //this.requestWithRestAPI(args.toString().replace("[", "").replace("]", "").split(","));
        if (Debug.isDebuggerConnected())
            Log.d("[IntelXCKFacebook]", "requestWithRestAPI: Has been deprecated.");
        String js = "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.request.response',true,true);e.success=false;e.error='Facebook REST APIs have been deprecated.';e.raw='';e.data={};document.dispatchEvent(e);";
        //webView.loadUrl(js);
        injectJS(js);
    } else if (action.equals("showAppRequestDialog")) {
        this.showAppRequestDialog(args.getString(0));
    } else if (action.equals("showNewsFeedDialog")) {
        this.showNewsFeedDialog(args.getString(0));
    } else {
        return false;
    }

    // All actions are async.
    //callbackContext.success();
    return true;
}

From source file:com.ct.speech.HintReceiver.java

/**
 * Fire an intent to start the speech recognition activity.
 * /*from   w  w w . j  a va  2s .  co  m*/
 * @param args
 *            Argument array with the following string args: [req
 *            code][number of matches][prompt string] Google speech
 *            recognizer
 */

private void startSpeechRecognitionActivity(JSONArray args) {
    // int reqCode = 42; // Hitchhiker? // global now
    int maxMatches = 2;
    String prompt = "";
    String language = "";
    try {
        if (args.length() > 0) {
            // Request code - passed back to the caller on a successful
            // operation
            String temp = args.getString(0);
            reqCode = Integer.parseInt(temp);
        }
        if (args.length() > 1) {
            // Maximum number of matches, 0 means the recognizer decides
            String temp = args.getString(1);
            maxMatches = Integer.parseInt(temp);
        }
        if (args.length() > 2) {
            // Optional text prompt
            prompt = args.getString(2);
        }
        if (args.length() > 3) {
            // Optional language specified
            language = args.getString(3);
        }
    } catch (Exception e) {
        Log.e(TAG, String.format("startSpeechRecognitionActivity exception: %s", e.toString()));
    }
    final Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra("calling_package", "com.ct.BasicAppFrame");
    // If specific language
    if (!language.equals("")) {
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
    }
    if (maxMatches > 0)
        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxMatches);
    if (!(prompt.length() == 0))
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
    // ctx.startActivityForResult(this, intent, reqCode); //removed to try
    // using recognizer directly
    try {
        this.ctx.runOnUiThread(new Runnable() {
            public void run() {
                final SpeechRecognizer recognizer = SpeechRecognizer.createSpeechRecognizer((Context) ctx);
                RecognitionListener listener = new RecognitionListener() {
                    @Override
                    public void onResults(Bundle results) {
                        //closeRecordedFile();
                        sendBackResults(results);
                        ArrayList<String> voiceResults = results
                                .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                        if (voiceResults == null) {
                            Log.e(TAG, "No voice results");
                        } else {
                            // Log.d(TAG, "Printing matches: ");
                            for (@SuppressWarnings("unused")
                            String match : voiceResults) {
                                // Log.d(TAG, match);
                            }
                        }
                        recognizer.destroy();
                    }

                    @Override
                    public void onReadyForSpeech(Bundle params) {
                        // Log.d(TAG, "Ready for speech");
                    }

                    @Override
                    public void onError(int error) {
                        Log.d(TAG, "Error listening for speech: " + error);
                        if (error == SpeechRecognizer.ERROR_NO_MATCH) {
                            sendBackResults(NO_MATCH);
                        } else if (error == SpeechRecognizer.ERROR_SPEECH_TIMEOUT) {
                            sendBackResults(NO_INPUT);
                        } else {
                            speechFailure("unknown error");
                        }
                        recognizer.destroy();
                    }

                    @Override
                    public void onBeginningOfSpeech() {
                        // Log.d(TAG, "Speech starting");
                        setStartOfSpeech();
                    }

                    @Override
                    //doesn't fire in Android after Ice Cream Sandwich
                    public void onBufferReceived(byte[] buffer) {
                    }

                    @Override
                    public void onEndOfSpeech() {
                        setEndOfSpeech();
                    }

                    @Override
                    public void onEvent(int eventType, Bundle params) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onPartialResults(Bundle partialResults) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onRmsChanged(float rmsdB) {
                        // TODO Auto-generated method stub

                    }
                };
                recognizer.setRecognitionListener(listener);
                Log.d(TAG, "starting speech recognition activity");
                recognizer.startListening(intent);
            }
        });
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.sqisland.android.gcm_client.Gcm.java

@Override
public boolean execute(String action, final JSONArray args, final CallbackContext command_para)
        throws JSONException {
    if ("start".equals(action)) {
        command = command_para;/*from   w  ww  .  j  a  va 2 s  .  com*/
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                try {
                    start(args.getString(1), args.getString(0));
                } catch (JSONException e) {
                    command.success();
                }
            }
        });
    }
    return true;
}

From source file:com.keylesspalace.tusky.util.NotificationMaker.java

public static void make(final Context context, final int notifyId, Notification body) {
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    final SharedPreferences notificationPreferences = context.getSharedPreferences("Notifications",
            Context.MODE_PRIVATE);

    if (!filterNotification(preferences, body)) {
        return;/*from   w w w  . ja  va2s . c  o m*/
    }

    String rawCurrentNotifications = notificationPreferences.getString("current", "[]");
    JSONArray currentNotifications;

    try {
        currentNotifications = new JSONArray(rawCurrentNotifications);
    } catch (JSONException e) {
        currentNotifications = new JSONArray();
    }

    boolean alreadyContains = false;

    for (int i = 0; i < currentNotifications.length(); i++) {
        try {
            if (currentNotifications.getString(i).equals(body.account.getDisplayName())) {
                alreadyContains = true;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    if (!alreadyContains) {
        currentNotifications.put(body.account.getDisplayName());
    }

    notificationPreferences.edit().putString("current", currentNotifications.toString()).commit();

    Intent resultIntent = new Intent(context, MainActivity.class);
    resultIntent.putExtra("tab_position", 1);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent deleteIntent = new Intent(context, NotificationClearBroadcastReceiver.class);
    PendingIntent deletePendingIntent = PendingIntent.getBroadcast(context, 0, deleteIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_notify).setContentIntent(resultPendingIntent)
            .setDeleteIntent(deletePendingIntent).setDefaults(0); // So it doesn't ring twice, notify only in Target callback

    if (currentNotifications.length() == 1) {
        builder.setContentTitle(titleForType(context, body))
                .setContentText(truncateWithEllipses(bodyForType(body), 40));

        Target mTarget = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                builder.setLargeIcon(bitmap);

                setupPreferences(preferences, builder);

                ((NotificationManager) (context.getSystemService(Context.NOTIFICATION_SERVICE)))
                        .notify(notifyId, builder.build());
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }
        };

        Picasso.with(context).load(body.account.avatar).placeholder(R.drawable.avatar_default)
                .transform(new RoundedTransformation(7, 0)).into(mTarget);
    } else {
        setupPreferences(preferences, builder);
        try {
            builder.setContentTitle(String.format(context.getString(R.string.notification_title_summary),
                    currentNotifications.length()))
                    .setContentText(truncateWithEllipses(joinNames(context, currentNotifications), 40));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setVisibility(android.app.Notification.VISIBILITY_PRIVATE);
        builder.setCategory(android.app.Notification.CATEGORY_SOCIAL);
    }

    ((NotificationManager) (context.getSystemService(Context.NOTIFICATION_SERVICE))).notify(notifyId,
            builder.build());
}

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

/**
* 
*//*from ww  w  . jav  a2 s .  c  om*/
@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.polyvi.xface.view.XWebChromeClient.java

@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
        JsPromptResult result) {/*ww  w . j a va2 s.co  m*/
    boolean reqOk = false;
    if (url.startsWith("file://") || Config.isUrlWhiteListed(url)) {
        reqOk = true;
    }
    if (reqOk && defaultValue != null && defaultValue.equals("xFace_close_application:")) {
        XAppWebView appView = ((XAppWebView) view);
        int viewId = appView.getViewId();
        XEvent evt = XEvent.createEvent(XEventType.CLOSE_APP, viewId);
        ((XFaceMainActivity) mInterface.getActivity()).getEventCenter().sendEventSync(evt);
        result.confirm("");
        return true;
    } else if (reqOk && defaultValue != null && defaultValue.equals("xFace_app_send_message:")) {
        try {
            JSONArray args = new JSONArray(message);
            Pair<XAppWebView, String> appMessage = new Pair<XAppWebView, String>((XAppWebView) view,
                    args.getString(0));
            XEvent evt = XEvent.createEvent(XEventType.XAPP_MESSAGE, appMessage);
            ((XFaceMainActivity) mInterface.getActivity()).getEventCenter().sendEventSync(evt);
        } catch (JSONException e) {
            XLog.e(CLASS_NAME, "");
            XLog.e(CLASS_NAME, e.getMessage());
        }
        result.confirm("");
        return true;
    }
    return super.onJsPrompt(view, url, message, defaultValue, result);
}

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;//  w ww.j ava2s .c o  m
    results = TimeSeriesRetriever.retrieveTimeSeries(urlString, startTime, endTime, metric, tags, true);
    String ret = null;
    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");
    }/*ww  w .  j a v a2 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;
}

From source file:org.uiautomation.ios.grid.IOSCapabilitiesMonitor.java

private List<DesiredCapabilities> getNodeCapabilities() {
    try {//from   w  w w.ja  v  a2 s  . co  m
        List<DesiredCapabilities> capabilities = new ArrayList<DesiredCapabilities>();

        JSONObject status = getNodeStatusJson();
        if (status == null) {
            return null;
        }

        String ios = status.getJSONObject("value").getJSONObject("ios").optString("simulatorVersion");
        JSONArray supportedApps = status.getJSONObject("value").getJSONArray("supportedApps");

        for (int i = 0; i < supportedApps.length(); i++) {
            Map<String, Object> capability = new HashMap<String, Object>();
            capability.put("maxInstances", "1");
            if (ios.isEmpty()) {
                capability.put("ios", "5.1");
                capability.put("browserName", "IOS Device");
                capability.put(IOSCapabilities.DEVICE, DeviceType.iphone);
            } else {
                capability.put("ios", ios);
                capability.put("browserName", "IOS Simulator");
            }
            JSONObject app = supportedApps.getJSONObject(i);
            for (String key : JSONObject.getNames(app)) {
                if ("locales".equals(key)) {
                    JSONArray loc = app.getJSONArray(key);
                    List<String> locales = new ArrayList<String>();
                    for (int j = 0; j < loc.length(); j++) {
                        locales.add(loc.getString(j));
                    }
                    capability.put("locales", locales);
                } else {
                    Object o = app.get(key);
                    capability.put(key, o);
                }
            }
            capabilities.add(new DesiredCapabilities(capability));
        }
        return capabilities;
    } catch (Exception e) {
        return null;
    }
}