Example usage for org.json JSONArray JSONArray

List of usage examples for org.json JSONArray JSONArray

Introduction

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

Prototype

public JSONArray(Object array) throws JSONException 

Source Link

Document

Construct a JSONArray from an array

Usage

From source file:edu.asu.msse.sgowdru.moviemediaplayerrpc.AsyncCollectionConnect.java

@Override
protected JSONObject doInBackground(MethodInformation... aRequest) {
    try {//from   www .ja v  a 2 s  . co m
        JSONArray ja = new JSONArray(aRequest[0].params);
        String requestData = "{ \"jsonrpc\":\"2.0\", \"method\":\"" + aRequest[0].method + "\", \"params\":"
                + ja.toString() + ",\"id\":3}";
        JsonRPCRequestViaHttp conn = new JsonRPCRequestViaHttp((new URL(aRequest[0].urlString)));

        // If the method name is getTitles, retun json array of movie names
        if (aRequest[0].method.equals("getTitles")) {
            String resultStr = conn.call(requestData);
            System.out.println(resultStr);
            aRequest[0].resultAsJson = resultStr;
            json = new JSONObject(resultStr);
        }
        // If the method name is "get" return the movie details for the particular parameter that is passed to it
        else if (aRequest[0].method.equals("get")) {
            String resultStr = conn.call(requestData);
            System.out.println(resultStr);
            aRequest[0].resultAsJson = resultStr;
            json = new JSONObject(resultStr);
        }
    } catch (Exception ex) {
        android.util.Log.d(this.getClass().getSimpleName(), "exception in remote call " + ex.getMessage());
    }
    // Return JSON object in both the cases
    return json;
}

From source file:de.jaetzold.philips.hue.HueBridgeComm.java

List<JSONObject> request(RM method, String fullPath, String json) throws IOException {
    final URL url = new URL(baseUrl, fullPath);
    log.fine("Request to " + method + " " + url + (json != null && json.length() > 0 ? ": " + json : ""));
    final URLConnection connection = url.openConnection();
    if (connection instanceof HttpURLConnection) {
        HttpURLConnection httpConnection = (HttpURLConnection) connection;
        httpConnection.setRequestMethod(method.name());
        if (json != null && json.length() > 0) {
            if (method == RM.GET || method == RM.DELETE) {
                throw new HueCommException("Will not send json content for request method " + method);
            }//from  w ww  . j av  a 2s  .  c om
            httpConnection.setDoOutput(true);
            httpConnection.getOutputStream().write(json.getBytes(REQUEST_CHARSET));
        }
    } else {
        throw new IllegalStateException("The current baseUrl \"" + baseUrl + "\" is not http?");
    }

    final BufferedReader reader = new BufferedReader(
            new InputStreamReader(connection.getInputStream(), REQUEST_CHARSET));
    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        builder.append(line).append('\n');
    }
    log.fine("Response from " + method + " " + url + ": " + builder);
    final String jsonString = builder.toString();
    List<JSONObject> result = new ArrayList<>();
    if (jsonString.trim().startsWith("{")) {
        result.add(new JSONObject(jsonString));
    } else {
        final JSONArray array = new JSONArray(jsonString);
        for (int i = 0; i < array.length(); i++) {
            result.add(array.getJSONObject(i));
        }
    }
    return result;
}

From source file:com.escapeir.server.Connect.java

@Override
protected Boolean doInBackground(Boolean... params) {
    HttpPost httppost = null;/*ww w. ja  v a2  s . co m*/
    // setOrGet = true is set user
    // setOrGet = false is Get user
    setOrGet = params[0];
    String urlExecute = "", urlSet = "http://escapeir.uphero.com/setUser.php",
            urlGet = "http://escapeir.uphero.com/getUser.php";
    String result = "";
    InputStream is = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        if (setOrGet) {
            httppost = new HttpPost(urlSet);

            final ArrayList<NameValuePair> insertUser = new ArrayList<NameValuePair>();
            insertUser.add(new BasicNameValuePair("user", EscapeIRApplication.USER_NAME));
            insertUser.add(new BasicNameValuePair("time", EscapeIRApplication.USER_TIME));
            httppost.setEntity(new UrlEncodedFormEntity(insertUser));

        } else {
            httppost = new HttpPost(urlGet);

        }
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.i("Connect", "Connect");
    } catch (Exception e) {
        Log.e(EscapeIRApplication.TAG, "Error in http connection " + e.toString());
    }
    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();

        result = sb.toString();

        Log.i(EscapeIRApplication.TAG, "resultado");
        Log.i(EscapeIRApplication.TAG, result);
    } catch (Exception e) {
        Log.e(EscapeIRApplication.TAG, "Error converting result " + e.toString());
    }
    // parse json data
    if (setOrGet) {
        // return if is set user
        return true;
    } else {
        try {
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                EscapeIRApplication.usersServer
                        .add(new User(json_data.getString("user"), json_data.getString("time")));
                Log.i(EscapeIRApplication.TAG,
                        "time: " + json_data.getString("time") + ", name: " + json_data.getString("user"));
            }
        } catch (JSONException e) {
            Log.e(EscapeIRApplication.TAG, "Error parsing data " + e.toString());
        }
    }
    return true;
}

From source file:com.neuron.trafikanten.dataProviders.trafikanten.TrafikantenRealtime.java

@Override
public void run() {
    try {/*from w w  w  . j a  va 2s.  c o  m*/
        final String urlString = Trafikanten.getApiUrl() + "/reisrest/realtime/GetAllDepartures/" + stationId;
        Log.i(TAG, "Loading realtime data : " + urlString);

        final StreamWithTime streamWithTime = HelperFunctions.executeHttpRequest(context,
                new HttpGet(urlString), true);
        ThreadHandleTimeData(streamWithTime.timeDifference);

        /*
         * Parse json
         */
        //long perfSTART = System.currentTimeMillis();
        //Log.i(TAG,"PERF : Getting realtime data");
        final JSONArray jsonArray = new JSONArray(HelperFunctions.InputStreamToString(streamWithTime.stream));
        final int arraySize = jsonArray.length();
        for (int i = 0; i < arraySize; i++) {
            final JSONObject json = jsonArray.getJSONObject(i);
            RealtimeData realtimeData = new RealtimeData();
            try {
                realtimeData.expectedDeparture = HelperFunctions
                        .jsonToDate(json.getString("ExpectedDepartureTime"));
            } catch (org.json.JSONException e) {
                realtimeData.expectedDeparture = HelperFunctions
                        .jsonToDate(json.getString("ExpectedArrivalTime"));
            }

            try {
                realtimeData.lineId = json.getInt("LineRef");
            } catch (org.json.JSONException e) {
                realtimeData.lineId = -1;
            }

            try {
                realtimeData.vehicleMode = json.getInt("VehicleMode");
            } catch (org.json.JSONException e) {
                realtimeData.vehicleMode = 0; // default = bus
            }

            try {
                realtimeData.destination = json.getString("DestinationName");
            } catch (org.json.JSONException e) {
                realtimeData.destination = "Ukjent";
            }

            try {
                realtimeData.departurePlatform = json.getString("DeparturePlatformName");
                if (realtimeData.departurePlatform.equals("null")) {
                    realtimeData.departurePlatform = "";
                }

            } catch (org.json.JSONException e) {
                realtimeData.departurePlatform = "";
            }

            try {
                realtimeData.realtime = json.getBoolean("Monitored");
            } catch (org.json.JSONException e) {
                realtimeData.realtime = false;
            }
            try {
                realtimeData.lineName = json.getString("PublishedLineName");
            } catch (org.json.JSONException e) {
                realtimeData.lineName = "";
            }

            try {
                if (json.has("InCongestion")) {
                    realtimeData.inCongestion = json.getBoolean("InCongestion");
                }
            } catch (org.json.JSONException e) {
                // can happen when incongestion is empty string.
            }

            try {
                if (json.has("VehicleFeatureRef")) {
                    realtimeData.lowFloor = json.getString("VehicleFeatureRef").equals("lowFloor");
                }
            } catch (org.json.JSONException e) {
                // lowfloor = false by default
            }

            try {
                if (json.has("TrainBlockPart") && !json.isNull("TrainBlockPart")) {
                    JSONObject trainBlockPart = json.getJSONObject("TrainBlockPart");
                    if (trainBlockPart.has("NumberOfBlockParts")) {
                        realtimeData.numberOfBlockParts = trainBlockPart.getInt("NumberOfBlockParts");
                    }
                }
            } catch (org.json.JSONException e) {
                // trainblockpart is initialized by default
            }

            ThreadHandlePostData(realtimeData);
        }

        //Log.i(TAG,"PERF : Parsing web request took " + ((System.currentTimeMillis() - perfSTART)) + "ms");

    } catch (Exception e) {
        if (e.getClass() == InterruptedException.class) {
            ThreadHandlePostExecute(null);
            return;
        }
        ThreadHandlePostExecute(e);
        return;
    }
    ThreadHandlePostExecute(null);
}

From source file:org.akvo.caddisfly.sensor.colorimetry.strip.ui.ResultActivity.java

@Override
public void showResults() {
    resultImageUrl = UUID.randomUUID().toString() + ".png";
    Intent intent = getIntent();//from   ww w.j  ava2s .  co  m
    String uuid = intent.getStringExtra(Constant.UUID);

    Mat strip;
    StripTest stripTest = new StripTest();

    // get information on the strip test from JSON
    StripTest.Brand brand = stripTest.getBrand(uuid);

    // for display purposes sort the patches by position on the strip
    List<StripTest.Brand.Patch> patches = brand.getPatchesSortedByPosition();

    // get the JSON describing the images of the patches that were stored before
    JSONArray imagePatchArray = null;
    try {
        String json = FileUtil.readFromInternalStorage(this, Constant.IMAGE_PATCH);
        if (json != null) {
            imagePatchArray = new JSONArray(json);
        }

    } catch (JSONException e) {
        Timber.e(e);
    }

    // cycle over the patches and interpret them
    if (imagePatchArray != null) {
        // if this strip is of type 'GROUP', take the first image and use that for all the patches
        AtomicInteger workCounter;
        if (brand.getGroupingType() == StripTest.GroupType.GROUP) {
            workCounter = new AtomicInteger(1);
            // handle grouping case
            boolean isInvalidStrip = FileUtil.fileExists(this, Constant.STRIP + "0" + Constant.ERROR);
            strip = ResultUtil.getMatFromFile(this, patches.get(0).getId());
            if (strip != null) {
                // create empty mat to serve as a template
                resultImage = new Mat(0, strip.cols(), CvType.CV_8UC3,
                        new Scalar(MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE));
                new BitmapTask(isInvalidStrip, strip, true, brand, patches, 0, workCounter).execute(strip);
            }
        } else {
            workCounter = new AtomicInteger(patches.size());
            // if this strip is of type 'INDIVIDUAL' handle patch by patch
            for (int i = 0; i < patches.size(); i++) { // handle patch
                // read strip from file
                strip = ResultUtil.getMatFromFile(this, patches.get(i).getId());

                if (strip != null) {
                    if (i == 0) {
                        // create empty mat to serve as a template
                        resultImage = new Mat(0, strip.cols(), CvType.CV_8UC3,
                                new Scalar(MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE, MAX_RGB_INT_VALUE));
                    }
                    new BitmapTask(false, strip, false, brand, patches, i, workCounter).execute(strip);
                }
            }
        }
    } else {
        TextView textView = new TextView(this);
        textView.setText(R.string.noData);
        LinearLayout layout = (LinearLayout) findViewById(R.id.layout_results);

        layout.addView(textView);
    }

    findViewById(R.id.progressBar).setVisibility(View.GONE);
    findViewById(R.id.testProgress).setVisibility(View.GONE);
}

From source file:com.df.app.carsWaiting.CarsWaitingListActivity.java

/**
 * /* w w w.  ja va 2  s  . co  m*/
 * @param result
 */
private void fillInData(String result) {
    try {
        JSONArray jsonArray = new JSONArray(result);

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            CarsWaitingItem item = new CarsWaitingItem();
            item.setPlateNumber(jsonObject.getString("plateNumber"));
            item.setExteriorColor(jsonObject.getString("exteriorColor"));
            item.setCarType(jsonObject.getString("licenseModel"));
            item.setDate(jsonObject.getString("createDate"));
            item.setCarId(jsonObject.getInt("carId"));
            item.setJsonObject(jsonObject);

            data.add(item);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    adapter.notifyDataSetChanged();

    startNumber = data.size() + 1;

    if (data.size() == 0) {
        footerView.setVisibility(View.GONE);
    } else {
        footerView.setVisibility(View.VISIBLE);
    }

    //        for(int i = 0; i < data.size(); i++)
    //            swipeListView.closeAnimate(i);

    //        // 0, ??(?
    //        if(data.size() == 0) {
    //            DeleteFiles.deleteFiles(AppCommon.photoDirectory);
    //            DeleteFiles.deleteFiles(AppCommon.savedDirectory);
    //        }
}

From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java

/**
 * Make remote request to get all loyalty cards stored in Cozy
 *///from   ww w  .  j  a  v  a2 s  . c o  m
public String getRemoteExpenses() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new ExpenseSyncEvent(SYNC_MESSAGE, "Your Cozy has no expenses stored."));
                Expense.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        EventBus.getDefault().post(new ExpenseSyncEvent(SYNC_MESSAGE,
                                "Reading expenses on Cozy " + i + "/" + jsonArray.length() + "..."));
                        JSONObject expenseJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        Expense expense = Expense.getByRemoteId(expenseJson.get("_id").toString());
                        if (expense == null) {
                            expense = new Expense(expenseJson);
                        } else {
                            expense.setRemoteId(expenseJson.getString("_id"));
                            expense.setAmount(expenseJson.getDouble("amount"));
                            expense.setCategory(expenseJson.getString("category"));
                            expense.setDate(expenseJson.getString("date"));

                            if (expenseJson.has("deviceId")) {
                                expense.setDeviceId(expenseJson.getString("deviceId"));
                            } else {
                                expense.setDeviceId(Device.registeredDevice().getLogin());
                            }
                        }
                        expense.save();

                        if (expenseJson.has("receipts")) {
                            JSONArray receiptsArray = expenseJson.getJSONArray("receipts");

                            for (int j = 0; j < receiptsArray.length(); j++) {
                                JSONObject recJsonObject = receiptsArray.getJSONObject(i);
                                Receipt receipt = new Receipt();
                                receipt.setBase64(recJsonObject.getString("base64"));
                                receipt.setExpense(expense);
                                receipt.setName("");
                                receipt.save();
                            }
                        }
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:com.muzima.service.PreferenceService.java

protected List<String> deserialize(String json) {
    if (StringUtils.isEmpty(json))
        return new ArrayList<String>();

    List<String> cohortsList = new ArrayList<String>();
    try {//from  ww w  . ja  va2s .  c  om
        JSONArray jsonArray = new JSONArray(json);
        for (int i = 0; i < jsonArray.length(); i++) {
            cohortsList.add(jsonArray.get(i).toString());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return cohortsList;
}

From source file:com.gistlabs.mechanize.document.json.JsonDocument.java

@Override
protected void loadPage() throws Exception {
    try {//from   w w w .  j a v a  2 s  .com
        JSONTokener jsonTokener = new JSONTokener(new InputStreamReader(getInputStream()));
        char nextClean = jsonTokener.nextClean();
        jsonTokener.back();

        switch (nextClean) {
        case '{':
            this.json = new ObjectNodeImpl(new JSONObject(jsonTokener));
            break;
        case '[':
            this.json = new ArrayNodeImpl(new JSONArray(jsonTokener));
            break;
        default:
            throw new IllegalStateException(
                    String.format("Error processing token=%s from request=%s", nextClean, this.getRequest()));
        }
    } catch (Exception e) {
        throw MechanizeExceptionFactory.newException(e);
    }
}

From source file:com.inductiveautomation.reporting.examples.datasource.common.RestJsonDataSource.java

/**
 * This method is where data can be added to the data map.  We utilitize the
 * {@link ReportExecutionContext} to get the data map, and simple inject our data as an additional
 * entry.//from  w  w w .  j a v a2  s . c o m
 * @param reportExecutionContext provides
 * @param _configObject is the configuration object we defined in Common scope.  It's information originates from
 *                      the Designer's {@link DataSourceConfig} panel.
 */
@Override
public void gatherData(ReportExecutionContext reportExecutionContext, Serializable _configObject)
        throws Exception {
    log = reportExecutionContext.getLog();

    /* Collect information from the config object and add to the data map with the proper ID. */
    Map<String, Object> data = reportExecutionContext.getExecutionData().getData();

    RestJsonDataObject configObject = (RestJsonDataObject) _configObject;

    // verify the user entered a valid datakey
    if (configObject != null && RMKey.isKey(configObject.getKey())) {
        String key = configObject.getKey();
        String url;

        // get the url
        if (!TypeUtilities.isNullOrEmpty(configObject.getUrl())) {
            url = configObject.getUrl();
        } else {
            log.warnf("Url field of REST JSON Datasource %s requires a URL to attempt data collection.", key);
            return;
        }

        log.tracef("Attempting to collect data from '%s' for %s Datakey.", configObject.getUrl(),
                configObject.getKey());

        try {
            //collect the data as a String
            String jsonString = collectData(url);
            if (!TypeUtilities.isNullOrEmpty(jsonString)) {
                try {
                    log.tracef("Attempting to build JSON Object from data string.");
                    // map our simple string to a reporting-engine friendly map
                    JSONObject jsonObject = new JSONObject(jsonString);
                    Map<String, Object> mappedJSON = JsonUtils.toMap(jsonObject);
                    if (mappedJSON != null) {
                        data.put(configObject.getKey(), mappedJSON);
                    }
                } catch (JSONException jse) {
                    // may have an array of json objects, so we try to build a data set out of them
                    log.tracef("Failed to create single JSON object from data, attempting JSONArray from data.",
                            jse);
                    try {
                        JSONArray jsonArray = new JSONArray(jsonString);
                        Dataset dataset = createDatasetFromJSONArray(jsonArray);
                        if (dataset != null) {
                            data.put(configObject.getKey(), dataset);
                        }
                        log.tracef("Dataset created from Json Array and added to map.");
                    } catch (Exception e) {
                        log.warnf("Could not parse JSONArray from \'%s\'.", configObject.getUrl(), e);
                    }
                }
            } else {
                log.warnf("No Json data could be found at \'%s\'", configObject.getUrl());
            }
        } catch (Exception e) {
            log.warnf("Could not create usable data from \'%s\'", configObject.getUrl(), e);
        }
    }
}