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:org.nuxeo.connect.data.PackageDescriptor.java

@JSONImportMethod(name = "provides")
protected void setProvidesAsJSON(JSONArray array) throws JSONException {
    PackageDependency[] deps = new PackageDependency[array.length()];
    for (int i = 0; i < array.length(); i++) {
        deps[i] = new PackageDependency(array.getString(i));
    }/* ww w. j av a  2s .c om*/
    setProvides(deps);
}

From source file:org.nuxeo.connect.data.PackageDescriptor.java

@JSONImportMethod(name = "targetPlatforms")
public void setTargetPlatformsAsJSON(JSONArray array) throws JSONException {
    String[] targets = new String[array.length()];
    for (int i = 0; i < array.length(); i++) {
        targets[i] = array.getString(i);
    }/* w ww  . j av a2 s.com*/
    MutableObject packageDependencies = new MutableObject();
    targetPlatforms = fixTargetPlatforms(name, targets, packageDependencies);
    setDependencies((PackageDependency[]) packageDependencies.getValue());
}

From source file:com.facebook.config.AbstractExpandedConfJSONProvider.java

private JSONObject getExpandedJSONConfig() throws JSONException {
    Set<String> traversedFiles = new HashSet<>();
    Queue<String> toTraverse = new LinkedList<>();

    // Seed the graph traversal with the root node
    traversedFiles.add(root);//w w  w  . java2  s  . c om
    toTraverse.add(root);

    // Policy: parent configs will override children (included) configs
    JSONObject expanded = new JSONObject();
    while (!toTraverse.isEmpty()) {
        String current = toTraverse.remove();
        JSONObject json = load(current);
        JSONObject conf = json.getJSONObject(CONF_KEY);
        Iterator<String> iter = conf.keys();
        while (iter.hasNext()) {
            String key = iter.next();
            // Current config will get to insert keys before its include files
            if (!expanded.has(key)) {
                expanded.put(key, conf.get(key));
            }
        }
        // Check if the file itself has any included files
        if (json.has(INCLUDES_KEY)) {
            JSONArray includes = json.getJSONArray(INCLUDES_KEY);
            for (int idx = 0; idx < includes.length(); idx++) {
                String include = resolve(current, includes.getString(idx));
                if (traversedFiles.contains(include)) {
                    LOG.warn("Config file was included twice: " + include);
                } else {
                    toTraverse.add(include);
                    traversedFiles.add(include);
                }
            }
        }
    }

    return expanded;
}

From source file:com.atolcd.alfresco.ProxyAuditFilter.java

@Override
public void doFilter(ServletRequest sReq, ServletResponse sRes, FilterChain chain)
        throws IOException, ServletException {
    // Get the HTTP request/response/session
    HttpServletRequest request = (HttpServletRequest) sReq;
    // HttpServletResponse response = (HttpServletResponse) sRes;
    RequestWrapper requestWrapper = new RequestWrapper(request);
    // Initialize a new request context
    RequestContext context = ThreadLocalRequestContext.getRequestContext();

    String referer = request.getHeader("referer");

    if (context == null) {
        try {//from   w ww. j av  a2s .com
            // Perform a "silent" init - i.e. no user creation or remote
            // connections
            context = RequestContextUtil.initRequestContext(getApplicationContext(), request, true);
            try {
                RequestContextUtil.populateRequestContext(context, request);
            } catch (ResourceLoaderException e) {
                // e.printStackTrace();
            } catch (UserFactoryException e) {
                // e.printStackTrace();
            }
        } catch (RequestContextException ex) {
            throw new ServletException(ex);
        }
    }
    User user = context.getUser();
    String requestURI = request.getRequestURI();
    String method = request.getMethod().toUpperCase();

    if (user != null) {
        try {
            JSONObject auditSample = new JSONObject();
            auditSample.put(AUDIT_ID, "0");
            auditSample.put(AUDIT_USER_ID, user.getId());
            auditSample.put(AUDIT_SITE, "");
            auditSample.put(AUDIT_APP_NAME, "");
            auditSample.put(AUDIT_ACTION_NAME, "");
            auditSample.put(AUDIT_OBJECT, "");
            auditSample.put(AUDIT_TIME, Long.toString(System.currentTimeMillis()));

            // For documents only (only in sites!)
            if (requestURI.endsWith("/doclib/activity") && request.getMethod().equals(POST)) {
                String type = request.getContentType().split(";")[0];
                if (type.equals("application/json")) {
                    // Get JSON Object
                    JSONObject activityFeed = new JSONObject(requestWrapper.getStringContent());

                    String activityType = activityFeed.getString("type");
                    if (activityType != null) {
                        if ("file-added".equals(activityType)
                                || ("file-updated".equals(activityType)
                                        && (referer != null && !referer.contains("document-details"))) // Done in JavaScript on "document-details" page
                                || "file-deleted".equals(activityType)) {
                            if (activityFeed.has("nodeRef")) {
                                auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);
                                auditSample.put(AUDIT_SITE, activityFeed.getString("site"));
                                auditSample.put(AUDIT_ACTION_NAME, activityType);
                                auditSample.put(AUDIT_OBJECT, activityFeed.getString("nodeRef"));
                                auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);

                                remoteCall(request, auditSample);
                            }
                        } else if ("files-added".equals(activityType) || "files-deleted".equals(activityType)) {
                            // multiple file uploads/deletions (5 or more)
                            Integer fileCount = activityFeed.getInt("fileCount");
                            if (fileCount != null && fileCount > 0) {
                                auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);
                                auditSample.put(AUDIT_SITE, activityFeed.getString("site"));
                                auditSample.put(AUDIT_ACTION_NAME, "file-" + activityType.split("-")[1]);
                                auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);
                                // auditSample.put(AUDIT_OBJECT, "");

                                for (int i = 0; i < fileCount; i++) {
                                    remoteCall(request, auditSample);
                                }
                            }
                        }
                    }
                }
            } else if (requestURI.startsWith(URI_NODE_UPDATE) && requestURI.endsWith(FORMPROCESSOR)) {
                JSONObject updatedData = new JSONObject(requestWrapper.getStringContent());
                // Online edit used the same form (plus the cm_content
                // metadata)
                if (!updatedData.has("prop_cm_content")) {
                    auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);
                    auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, 1));

                    auditSample.put(AUDIT_ACTION_NAME, "update");
                    auditSample.put(AUDIT_SITE, TEMP_SITE);
                    remoteCall(request, auditSample);
                }
            } else if (requestURI.endsWith("/activity/create")) {
                String jsonPost = requestWrapper.getStringContent();
                if (jsonPost != null && !jsonPost.isEmpty()) {
                    JSONObject json = new JSONObject(jsonPost);
                    String mod = AuditHelper.extractModFromActivity(json);
                    if (mod != null) {
                        auditSample.put(AUDIT_APP_NAME, mod);
                        auditSample.put(AUDIT_SITE, json.getString("site"));
                        auditSample.put(AUDIT_ACTION_NAME, AuditHelper.extractActionFromActivity(json));
                        auditSample.put(AUDIT_OBJECT, json.getString("nodeRef"));
                        remoteCall(request, auditSample);
                    }
                }
            } else if (requestURI.equals(URI_UPLOAD)) {
                // XXX: issue with big files
                // Nothing to do - Insert request is done in JavaScript
            } else if (requestURI.endsWith("/comments") || requestURI.endsWith("/replies")) {
                // Comments & replies
                String[] urlTokens = request.getHeader("referer").toString().split("/");
                HashMap<String, String> auditData = this.getUrlData(urlTokens);

                auditSample.put(AUDIT_SITE, auditData.get(KEY_SITE));
                auditSample.put(AUDIT_APP_NAME, auditData.get(KEY_MODULE));
                auditSample.put(AUDIT_ACTION_NAME, "comments");
                auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, 1));

                // Remote call for DB
                remoteCall(request, auditSample);
            } else if (requestURI.startsWith(URI_WIKI)) {
                String[] urlTokens = requestURI.split("/");
                String wikiPageId = urlTokens[urlTokens.length - 1];
                String siteId = urlTokens[urlTokens.length - 2];
                if (method.equals(Method.PUT.toString().toString())) {
                    JSONObject params = new JSONObject(requestWrapper.getStringContent());
                    auditSample.put(AUDIT_SITE, siteId);
                    auditSample.put(AUDIT_APP_NAME, MOD_WIKI);
                    if (params.has("currentVersion")) {
                        auditSample.put(AUDIT_ACTION_NAME, "update-post");
                    } else {
                        auditSample.put(AUDIT_ACTION_NAME, "create-post");
                    }

                    String auditObject = getNodeRefRemoteCall(request, user.getId(), siteId, MOD_WIKI,
                            wikiPageId);
                    auditSample.put(AUDIT_OBJECT, auditObject);

                    // Remote call
                    remoteCall(request, auditSample);
                } else if (method.equals(DELETE)) {
                    auditSample.put(AUDIT_SITE, siteId);
                    auditSample.put(AUDIT_APP_NAME, MOD_WIKI);
                    auditSample.put(AUDIT_ACTION_NAME, "delete-post");
                    auditSample.put(AUDIT_OBJECT, wikiPageId);
                    // Remote call
                    remoteCall(request, auditSample);
                }
            } else if (requestURI.startsWith(URI_BLOG)) {
                auditSample.put(AUDIT_APP_NAME, MOD_BLOG);
                if (method.equals(POST)) {
                    JSONObject params = new JSONObject(requestWrapper.getStringContent());
                    auditSample.put(AUDIT_SITE, params.get("site"));
                    auditSample.put(AUDIT_ACTION_NAME, "blog-create");
                    auditSample.put(AUDIT_OBJECT, params.get("title"));

                    remoteCall(request, auditSample);
                } else if (method.equals(PUT)) {
                    JSONObject params = new JSONObject(requestWrapper.getStringContent());
                    auditSample.put(AUDIT_SITE, params.get("site"));
                    auditSample.put(AUDIT_ACTION_NAME, "blog-update");
                    auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, 0));

                    remoteCall(request, auditSample);
                } else if (method.equals(DELETE)) {
                    String[] urlTokens = requestURI.split("/");
                    auditSample.put(AUDIT_OBJECT, urlTokens[urlTokens.length - 1]);
                    auditSample.put(AUDIT_SITE, urlTokens[urlTokens.length - 3]);
                    auditSample.put(AUDIT_ACTION_NAME, "blog-delete");

                    remoteCall(request, auditSample);
                }
            } else if (requestURI.startsWith(URI_DISCUSSIONS)) {
                auditSample.put(AUDIT_APP_NAME, "discussions");
                if (method.equals(POST)) {
                    JSONObject params = new JSONObject(requestWrapper.getStringContent());
                    auditSample.put(AUDIT_SITE, params.get("site"));
                    auditSample.put(AUDIT_ACTION_NAME, "discussions-create");
                    auditSample.put(AUDIT_OBJECT, params.get("title"));

                    remoteCall(request, auditSample);
                } else if (method.equals(PUT)) {
                    JSONObject params = new JSONObject(requestWrapper.getStringContent());
                    String siteId = (String) params.get("site");
                    auditSample.put(AUDIT_SITE, siteId);
                    auditSample.put(AUDIT_ACTION_NAME, "discussions-update");

                    String[] urlTokens = requestURI.split("/");
                    String discussionId = urlTokens[urlTokens.length - 1];
                    String auditObject = getNodeRefRemoteCall(request, user.getId(), siteId, "discussions",
                            discussionId);
                    auditSample.put(AUDIT_OBJECT, auditObject);

                    remoteCall(request, auditSample);
                } else if (method.equals(DELETE)) {
                    String[] urlTokens = requestURI.split("/");
                    auditSample.put(AUDIT_ACTION_NAME, "discussions-deleted");
                    auditSample.put(AUDIT_OBJECT, urlTokens[urlTokens.length - 1]);
                    auditSample.put(AUDIT_SITE, urlTokens[urlTokens.length - 3]);

                    remoteCall(request, auditSample);
                }
            } else if (requestURI.startsWith(URI_LINKS) && !method.equals(GET)) {
                String[] urlTokens = requestURI.split("/");
                JSONObject params = new JSONObject(requestWrapper.getStringContent());
                auditSample.put(AUDIT_APP_NAME, MOD_LINKS);

                if (method.equals(POST)) {
                    if (requestURI.startsWith(URI_LINKS + "delete/")) {
                        auditSample.put(AUDIT_SITE, urlTokens[urlTokens.length - 2]);
                        auditSample.put(AUDIT_OBJECT, params.getJSONArray("items").get(0));
                        auditSample.put(AUDIT_ACTION_NAME, "links-delete");
                    } else {
                        auditSample.put(AUDIT_OBJECT, params.get("title"));
                        auditSample.put(AUDIT_SITE, urlTokens[urlTokens.length - 3]);
                        auditSample.put(AUDIT_ACTION_NAME, "links-create");
                    }
                    remoteCall(request, auditSample);
                } else if (method.equals(PUT)) {
                    String siteId = urlTokens[urlTokens.length - 3];
                    auditSample.put(AUDIT_SITE, siteId);
                    auditSample.put(AUDIT_ACTION_NAME, "links-update");

                    String auditObject = getNodeRefRemoteCall(request, user.getId(), siteId, MOD_LINKS,
                            urlTokens[urlTokens.length - 1]);
                    auditSample.put(AUDIT_OBJECT, auditObject);

                    remoteCall(request, auditSample);
                }
            } else if (requestURI.startsWith(URI_DOWNLOAD)) {
                String a = request.getParameter("a");
                if (a != null && !a.isEmpty()) {
                    auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);
                    auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, 1));

                    auditSample.put(AUDIT_ACTION_NAME, "true".equalsIgnoreCase(a) ? "download" : "stream");
                    auditSample.put(AUDIT_SITE, TEMP_SITE);
                    remoteCall(request, auditSample);
                }
            } else if (requestURI.startsWith(URI_ACTION)) {
                // XXX: done in JavaScript
            } else if (requestURI.endsWith("memberships") && method.equals(GET)) {

                String type = request.getParameter("authorityType");
                String nf = request.getParameter("nf");
                String[] urlTokens = requestURI.split("/");

                auditSample.put(AUDIT_SITE, urlTokens[urlTokens.length - 2]);
                auditSample.put(AUDIT_APP_NAME, MOD_MEMBERS);
                auditSample.put(AUDIT_ACTION_NAME, type.toLowerCase());
                auditSample.put(AUDIT_OBJECT, nf);
                remoteCall(request, auditSample);
            } else if (requestURI.endsWith(URI_CALENDAR)) {
                JSONObject params = new JSONObject(requestWrapper.getStringContent());
                auditSample.put(AUDIT_APP_NAME, MOD_CALENDAR);
                auditSample.put(AUDIT_ACTION_NAME, "create");
                auditSample.put(AUDIT_SITE, params.get("site"));
                auditSample.put(AUDIT_OBJECT, params.get("what"));

                remoteCall(request, auditSample);
            } else if ((requestURI.startsWith(URI_DATALIST) || requestURI.startsWith(URI_DATALIST_DELETE))
                    && method.equals(POST)) {
                boolean isDeleteRequest = request.getParameter("alf_method") != null;
                auditSample.put(AUDIT_APP_NAME, MOD_DATA);
                auditSample.put(AUDIT_SITE, TEMP_SITE);
                if (isDeleteRequest) {
                    auditSample.put(AUDIT_ACTION_NAME, "datalist-delete");
                    JSONObject params = new JSONObject(requestWrapper.getStringContent());
                    JSONArray items = params.getJSONArray("nodeRefs");
                    for (int i = 0; i < items.length(); i++) {
                        auditSample.put(AUDIT_OBJECT, items.getString(i));

                        remoteCall(request, auditSample);
                    }
                } else {
                    auditSample.put(AUDIT_ACTION_NAME, "datalist-post");
                    auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, 0));

                    remoteCall(request, auditSample);
                }
            } else if (requestURI.startsWith(URI_SOCIAL_PUBLISHING) && method.equals(POST)) {
                auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);
                auditSample.put(AUDIT_SITE, TEMP_SITE);

                auditSample.put(AUDIT_ACTION_NAME, "publish");
                JSONObject params = new JSONObject(requestWrapper.getStringContent());
                JSONArray items = params.getJSONArray("publishNodes");
                for (int i = 0; i < items.length(); i++) {
                    auditSample.put(AUDIT_OBJECT, items.getString(i));
                    remoteCall(request, auditSample);
                }
            } else if (requestURI.indexOf("/ratings") != -1) {
                auditSample.put(AUDIT_APP_NAME, MOD_DOCUMENT);
                auditSample.put(AUDIT_SITE, TEMP_SITE);
                int offset = 1;
                if (POST.equals(method)) {
                    auditSample.put(AUDIT_ACTION_NAME, "rate");
                } else if (DELETE.equals(method)) {
                    auditSample.put(AUDIT_ACTION_NAME, "unrate");
                    offset = 2;
                }
                auditSample.put(AUDIT_OBJECT, getNodeRefFromUrl(requestURI, offset));
                remoteCall(request, auditSample);
            }

        } catch (JSONException e) {
            logger.error("JSON Error during a remote call ...");
            if (logger.isDebugEnabled()) {
                logger.debug(e.getMessage(), e);
            }
        }
    }
    chain.doFilter(requestWrapper, sRes);
}

From source file:ch.icclab.cyclops.dashboard.users.Admin.java

@Put
public Representation updateAdmins(Representation entity) {
    String sessionId = "";
    JSONArray admins;
    JSONObject updateObject = new JSONObject();

    try {/*from w w w.  j av a2 s .c om*/
        JsonRepresentation represent = new JsonRepresentation(entity);
        JSONObject requestJson = represent.getJsonObject();
        JSONArray uniqueMembers = new JSONArray();
        admins = requestJson.getJSONArray("admins");
        sessionId = requestJson.getString("sessionId");

        String adminGroupName = LoadConfiguration.configuration.get("OPENAM_ADMIN_GROUP_NAME");
        String adminEntryPattern = LoadConfiguration.configuration.get("OPENAM_ADMIN_USER_PATTERN");

        updateObject.put("name", adminGroupName);
        updateObject.put("realm", "/");
        updateObject.put("cn", new JSONArray(new String[] { adminGroupName }));
        updateObject.put("description", "");

        for (int i = 0; i < admins.length(); i++) {
            String adminName = admins.getString(i);
            String uniqueMember = adminEntryPattern.replace("{{USERNAME}}", adminName);
            uniqueMembers.put(uniqueMember);
        }

        updateObject.put("uniquemember", uniqueMembers);

    } catch (JSONException e) {
        //TODO: error handling
    } catch (IOException e) {
        //TODO: error handling
    }

    String url = LoadConfiguration.configuration.get("OPENAM_LIST_ADMINS_URL");
    ClientResource clientResource = new ClientResource(url);

    Series<Header> headers = (Series<Header>) clientResource.getRequestAttributes()
            .get("org.restlet.http.headers");

    if (headers == null) {
        headers = new Series<Header>(Header.class);
        clientResource.getRequestAttributes().put("org.restlet.http.headers", headers);
    }

    headers.set("iPlanetDirectoryPro", sessionId);
    return clientResource.put(updateObject);
}

From source file:com.ksutopia.bbtalks.plugins.P201SpeechToText.java

/**
  * Fire an intent to start the speech recognition activity.
  */*from www  . j  a  v a2  s.  c o m*/
  * @param args Argument array with the following string args: [req code][number of matches][prompt string]
  */
private void startSpeechRecognitionActivity(JSONArray args) {
    int maxMatches = 0;
    String prompt = "";
    String language = Locale.getDefault().toString();

    try {
        if (args.length() > 0) {
            // Maximum number of matches, 0 means the recognizer decides
            String temp = args.getString(0);
            maxMatches = Integer.parseInt(temp);
        }
        if (args.length() > 1) {
            // Optional text prompt
            prompt = args.getString(1);
        }
        if (args.length() > 2) {
            // Optional language specified
            language = args.getString(2);
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, String.format("startSpeechRecognitionActivity exception: %s", e.toString()));
    }

    // Create the intent and set parameters
    speech = SpeechRecognizer.createSpeechRecognizer(context);
    recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.getPackageName());
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "en");
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);

    if (maxMatches > 0)
        recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxMatches);
    if (!prompt.equals(""))
        recognizerIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
    speech.setRecognitionListener(listener);
    speech.startListening(recognizerIntent);
}

From source file:com.ofalvai.bpinfo.api.bkkinfo.BkkInfoClient.java

/**
 * Parses alert details found in the alert detail API response
 * This structure is different than the alert list API response
 *///from w w w.ja  v a  2s. co  m
private Alert parseAlertDetail(JSONObject response) throws JSONException {
    String id = response.getString("id");

    long start = 0;
    if (!response.isNull("kezdEpoch")) {
        start = response.getLong("kezdEpoch");
    }

    long end = 0;
    if (!response.isNull("vegeEpoch")) {
        end = response.getLong("vegeEpoch");
    }

    long timestamp = 0;
    if (!response.isNull("modEpoch")) {
        timestamp = response.getLong("modEpoch");
    }

    String url = getUrl(id);

    String header;
    // The API returns a header of 3 parts separated by "|" characters. We need the last part.
    String rawHeader = response.getString("targy");
    String[] rawHeaderParts = rawHeader.split("\\|");
    header = Utils.capitalizeString(rawHeaderParts[2].trim());

    String description;
    StringBuilder descriptionBuilder = new StringBuilder();
    descriptionBuilder.append(response.getString("feed"));

    JSONArray routesArray = Utils.jsonObjectToArray(response.getJSONObject("jaratok"));
    for (int i = 0; i < routesArray.length(); i++) {
        JSONObject routeNode = routesArray.getJSONObject(i);
        JSONObject optionsNode = routeNode.getJSONObject("opciok");

        if (!optionsNode.isNull("szabad_szoveg")) {
            JSONArray routeTextArray = optionsNode.getJSONArray("szabad_szoveg");
            for (int j = 0; j < routeTextArray.length(); j++) {
                descriptionBuilder.append("<br />");
                descriptionBuilder.append(routeTextArray.getString(j));
            }
        }
    }
    description = descriptionBuilder.toString();

    List<Route> affectedRoutes;
    JSONObject routeDetailsNode = response.getJSONObject("jarat_adatok");
    Iterator<String> affectedRouteIds = response.getJSONObject("jaratok").keys();
    // Some routes in routeDetailsNode are not affected by the alert, but alternative
    // recommended routes. The real affected routes' IDs are in "jaratok"
    affectedRoutes = parseDetailedAffectedRoutes(routeDetailsNode, affectedRouteIds);

    return new Alert(id, start, end, timestamp, url, header, description, affectedRoutes, false);
}

From source file:com.ofalvai.bpinfo.api.bkkinfo.BkkInfoClient.java

/**
 * Parses affected routes found in the alert list API response
 * This structure is different than the alert detail API response
 */// w  w  w .  ja va 2  s .co  m
@NonNull
private List<Route> parseAffectedRoutes(JSONArray routesArray) throws JSONException {
    // The API lists multiple affected routes grouped by their vehicle type (bus, tram, etc.)
    List<Route> routes = new ArrayList<>();
    for (int i = 0; i < routesArray.length(); i++) {
        JSONObject routeNode = routesArray.getJSONObject(i);
        String typeString = routeNode.getString("type");
        RouteType type = parseRouteType(typeString);

        JSONArray concreteRoutes = routeNode.getJSONArray("jaratok");
        for (int j = 0; j < concreteRoutes.length(); j++) {
            String shortName = concreteRoutes.getString(j).trim();
            int[] colors = parseRouteColors(type, shortName);

            // There's no ID returned by the API, using shortName instead
            Route route = new Route(shortName, shortName, null, null, type, colors[0], colors[1]);
            routes.add(route);
        }
    }
    return routes;
}

From source file:com.phonegap.plugins.ftpclient.FtpClient.java

/**
  * Executes the request and returns PluginResult.
  *//from  w w w. ja  v  a 2  s  .c  om
  * @param action        The action to execute.
  * @param args          JSONArry of arguments for the plugin.
  * @param callbackId    The callback id used when calling back into JavaScript.
  * @return              A PluginResult object with a status and message.
  */
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    PluginResult.Status status = PluginResult.Status.OK;
    JSONArray result = new JSONArray();

    try {
        String filename = args.getString(0);
        URL url = new URL(args.getString(1));

        if (action.equals("get")) {
            get(filename, url);
        } else if (action.equals("put")) {
            put(filename, url);
        }
        callbackContext.sendPluginResult(new PluginResult(status, result));
    } catch (JSONException e) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
    } catch (MalformedURLException e) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.MALFORMED_URL_EXCEPTION));
    } catch (IOException e) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION));
    }
    return true;
}

From source file:sh.calaba.driver.client.model.impl.DeviceImpl.java

@Override
public File takeScreenshot(String path) {
    File file = null;/*from w  ww  . jav  a2s  .co m*/
    JSONObject result = executeCalabashCommand(CalabashCommands.TAKE_SCREENSHOT);
    if (result == null || !result.has("bonusInformation")) {
        throw new CalabashException("An error occured while taking a screenshot.");
    }
    try {
        JSONArray bonusInformation = result.getJSONArray("bonusInformation");
        String base64String = bonusInformation.getString(0);

        byte[] img64 = Base64.decodeBase64(base64String);
        file = new File(path);
        FileOutputStream os = new FileOutputStream(file);
        os.write(img64);
        os.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return file;
}