Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

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

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

From source file:com.github.secondsun.catfactsdemo.networking.CatFactFetcherService.java

protected void onHandleIntent(Intent intent) {

    if (intent.getBooleanExtra(LOAD, false)) {

        CharSequence contentText;

        if (data.size() > 0) {
            contentText = "Data Loaded";
        } else {//from www .ja v a2s . co  m
            contentText = "Awaiting Data Load";
        }
        Intent notificationIntent = new Intent(this, CatFacts.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        Notification notification = new Notification.Builder(this).setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("CatFact Fetcher").setContentText(contentText).setContentIntent(pendingIntent)
                .build();
        startForeground(ONGOING_NOTIFICATION_ID, notification);
    } else if (intent.getBooleanExtra(UNLOAD, false)) {
        stopForeground(true);
    } else {
        if (intent.getBooleanExtra(RESET, false)) {
            data.clear();
            Intent notificationIntent = new Intent(this, CatFacts.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
            Notification notification = new Notification.Builder(this).setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("CatFact Fetcher").setContentText("Awaiting Data Load")
                    .setContentIntent(pendingIntent).build();
            startForeground(ONGOING_NOTIFICATION_ID, notification);
        }
        if (data.size() == 0) {
            try {
                Thread.sleep(Constants.DELAY);

                OkHttpClient client = new OkHttpClient();

                Request request = new Request.Builder().url(Constants.CAT_FACTS_URL).build();

                Response response = client.newCall(request).execute();

                JSONObject responseJson = new JSONObject(response.body().string());
                JSONArray facts = responseJson.getJSONArray("facts");

                ArrayList<String> toReturn = new ArrayList<>(facts.length());

                for (int i = 0; i < facts.length(); i++) {
                    toReturn.add(facts.getString(i));
                }

                data = toReturn;

            } catch (InterruptedException | IOException | JSONException e) {
                ArrayList<String> toReturn = new ArrayList<>();
                toReturn.add("Error:" + e.getMessage());
                data = toReturn;

            }
        }

        Intent notificationIntent = new Intent(this, CatFacts.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        Notification notification = new Notification.Builder(this).setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("CatFact Fetcher").setContentText("Data Available")
                .setContentIntent(pendingIntent).build();
        startForeground(ONGOING_NOTIFICATION_ID, notification);

        sendData();
    }

}

From source file:uk.bcu.services.ItunesSearchService.java

/** This is making api calls */
public void run() {
    //String api_key = "096174e14f0efd0be330fce5f1f84de2";

    String url = //"https://itunes.apple.com/search?term="+query1+"&entity=album";
            "http://itunes.apple.com/search?term=" + query1 + "&media=movie";
    //"http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=" +
    //   api_key+ "&q="+query;

    boolean error = false;
    HttpClient httpclient = null;/*from ww w.j  a va 2 s .  c  o m*/
    try {
        httpclient = new DefaultHttpClient();
        HttpResponse data = httpclient.execute(new HttpGet(url));
        HttpEntity entity = data.getEntity();
        String result = EntityUtils.toString(entity, "UTF8");

        JSONObject json = new JSONObject(result);
        if (json.getInt("resultCount") > 0) {
            resultss = json.getJSONArray("results");
        } else {
            error = true;
        }
    } catch (Exception e) {
        resultss = null;
        error = true;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    super.serviceComplete(error);
}

From source file:edu.msu.walajahi.sunshine.app.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.//from w  w  w  . j  av  a 2  s . co m
 */
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        }
        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + " Inserted");

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
}

From source file:com.extremeboredom.wordattack.utils.JSONUtils.java

/**
 * get String array from jsonObject//from w ww  .j a v a2  s .  c om
 *
 * @param jsonObject
 * @param key
 * @param defaultValue
 * @return <ul>
 * <li>if jsonObject is null, return defaultValue</li>
 * <li>if key is null or empty, return defaultValue</li>
 * <li>if {@link JSONObject#getJSONArray(String)} exception, return defaultValue</li>
 * <li>if {@link JSONArray#getString(int)} exception, return defaultValue</li>
 * <li>return string array</li>
 * </ul>
 */
public static String[] getStringArray(JSONObject jsonObject, String key, String[] defaultValue) {
    if (jsonObject == null || StringUtils.isEmpty(key)) {
        return defaultValue;
    }

    try {
        JSONArray statusArray = jsonObject.getJSONArray(key);
        if (statusArray != null) {
            String[] value = new String[statusArray.length()];
            for (int i = 0; i < statusArray.length(); i++) {
                value[i] = statusArray.getString(i);
            }
            return value;
        }
    } catch (JSONException e) {
        if (isPrintException) {
            e.printStackTrace();
        }
        return defaultValue;
    }
    return defaultValue;
}

From source file:com.extremeboredom.wordattack.utils.JSONUtils.java

/**
 * get String list from jsonObject/*from www  .ja va 2  s. co m*/
 *
 * @param jsonObject
 * @param key
 * @param defaultValue
 * @return <ul>
 * <li>if jsonObject is null, return defaultValue</li>
 * <li>if key is null or empty, return defaultValue</li>
 * <li>if {@link JSONObject#getJSONArray(String)} exception, return defaultValue</li>
 * <li>if {@link JSONArray#getString(int)} exception, return defaultValue</li>
 * <li>return string array</li>
 * </ul>
 */
public static List<String> getStringList(JSONObject jsonObject, String key, List<String> defaultValue) {
    if (jsonObject == null || StringUtils.isEmpty(key)) {
        return defaultValue;
    }

    try {
        JSONArray statusArray = jsonObject.getJSONArray(key);
        if (statusArray != null) {
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < statusArray.length(); i++) {
                list.add(statusArray.getString(i));
            }
            return list;
        }
    } catch (JSONException e) {
        if (isPrintException) {
            e.printStackTrace();
        }
        return defaultValue;
    }
    return defaultValue;
}

From source file:com.extremeboredom.wordattack.utils.JSONUtils.java

/**
 * get JSONArray from jsonObject/*from  w w w .  java  2s. c  o m*/
 *
 * @param jsonObject
 * @param key
 * @param defaultValue
 * @return <ul>
 * <li>if jsonObject is null, return defaultValue</li>
 * <li>if key is null or empty, return defaultValue</li>
 * <li>if {@link JSONObject#getJSONArray(String)} exception, return defaultValue</li>
 * <li>return {@link JSONObject#getJSONArray(String)}</li>
 * </ul>
 */
public static JSONArray getJSONArray(JSONObject jsonObject, String key, JSONArray defaultValue) {
    if (jsonObject == null || StringUtils.isEmpty(key)) {
        return defaultValue;
    }

    try {
        return jsonObject.getJSONArray(key);
    } catch (JSONException e) {
        if (isPrintException) {
            e.printStackTrace();
        }
        return defaultValue;
    }
}

From source file:com.example.android.popularmoviesist2.data.FetchTrailerMovieTask.java

private String[] getMoviesDataFromJson(String moviesJsonStr) throws JSONException {

    final String JSON_LIST = "results";
    final String JSON_ID = "id";
    final String JSON_KEY = "key";
    final String JSON_NAME = "name";
    final String JSON_SITE = "site";

    urlYoutbe.clear();/*w w w . j  av a  2 s  . co  m*/

    try {
        JSONObject moviesJson = new JSONObject(moviesJsonStr);
        JSONArray moviesArray = moviesJson.getJSONArray(JSON_LIST);

        final String[] result = new String[moviesArray.length()];

        for (int i = 0; i < moviesArray.length(); i++) {

            JSONObject movie = moviesArray.getJSONObject(i);
            String id = movie.getString(JSON_ID);
            String key = movie.getString(JSON_KEY);
            String name = movie.getString(JSON_NAME);
            String site = movie.getString(JSON_SITE);

            result[i] = key;
        }
        return result;
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
        return null;
    }

}

From source file:gov.sfmta.sfpark.MainScreenActivity.java

public void readData() throws JSONException {
    MYLOG("readData() start");

    if (SFparkActivity.responseString == null || SFparkActivity.responseString == "") {
        return;//  www  .  ja  va  2  s  . c o m
    }

    String message = null;
    JSONObject rootObject = null;
    JSONArray jsonAVL = null;

    rootObject = new JSONObject(SFparkActivity.responseString);
    message = rootObject.getString("MESSAGE");
    jsonAVL = rootObject.getJSONArray("AVL");
    timeStampXML = rootObject.getString("AVAILABILITY_UPDATED_TIMESTAMP");

    MYLOG(message);

    int i = 0;
    int len = jsonAVL.length();

    if (annotations == null) {
        annotations = new ArrayList<MyAnnotation>();
    } else {
        annotations.clear();
    }

    for (i = 0; i < len; ++i) {
        JSONObject interestArea = jsonAVL.getJSONObject(i);
        MyAnnotation annotation = new MyAnnotation();
        annotation.allGarageData = interestArea;
        annotation.initFromData();

        // new: UBER-HACK! SFMTA wants me to hide the Calif/Steiner lot.
        if ("California and Steiner Lot".equals(annotation.title))
            continue;

        annotations.add(annotation);
    }

    MYLOG("readData() finish ");
}

From source file:com.cdd.bao.importer.KeywordMapping.java

public JSONObject createAssay(JSONObject keydata, Schema schema, Map<Schema.Assignment, SchemaTree> treeCache)
        throws JSONException, IOException {
    String uniqueID = null;/*from   w  w w.  j av  a  2 s.c  o m*/
    List<String> linesTitle = new ArrayList<>(), linesBlock = new ArrayList<>();
    List<String> linesSkipped = new ArrayList<>(), linesProcessed = new ArrayList<>();
    Set<String> gotAnnot = new HashSet<>(), gotLiteral = new HashSet<>();
    JSONArray jsonAnnot = new JSONArray();
    final String SEP = "::";

    // assertions: these always supply a term
    for (Assertion asrt : assertions) {
        JSONObject obj = new JSONObject();
        obj.put("propURI", ModelSchema.expandPrefix(asrt.propURI));
        obj.put("groupNest", new JSONArray(expandPrefixes(asrt.groupNest)));
        obj.put("valueURI", ModelSchema.expandPrefix(asrt.valueURI));
        jsonAnnot.put(obj);

        String hash = asrt.propURI + SEP + asrt.valueURI + SEP
                + (asrt.groupNest == null ? "" : String.join(SEP, asrt.groupNest));
        gotAnnot.add(hash);
    }

    // go through the columns one at a time
    for (String key : keydata.keySet()) {
        String data = keydata.getString(key);

        Identifier id = findIdentifier(key);
        if (id != null) {
            if (uniqueID == null)
                uniqueID = id.prefix + data;
            continue;
        }

        TextBlock tblk = findTextBlock(key);
        if (tblk != null) {
            if (Util.isBlank(tblk.title))
                linesTitle.add(data);
            else
                linesBlock.add(tblk.title + ": " + data);
        }

        Value val = findValue(key, data);
        if (val != null) {
            if (Util.isBlank(val.valueURI)) {
                linesSkipped.add(key + ": " + data);
            } else {
                String hash = val.propURI + SEP + val.valueURI + SEP
                        + (val.groupNest == null ? "" : String.join(SEP, val.groupNest));
                if (gotAnnot.contains(hash))
                    continue;

                JSONObject obj = new JSONObject();
                obj.put("propURI", ModelSchema.expandPrefix(val.propURI));
                obj.put("groupNest", new JSONArray(expandPrefixes(val.groupNest)));
                obj.put("valueURI", ModelSchema.expandPrefix(val.valueURI));
                jsonAnnot.put(obj);
                gotAnnot.add(hash);
                linesProcessed.add(key + ": " + data);
            }
            continue;
        }

        Literal lit = findLiteral(key, data);
        if (lit != null) {
            String hash = lit.propURI + SEP + (lit.groupNest == null ? "" : String.join(SEP, lit.groupNest))
                    + SEP + data;
            if (gotLiteral.contains(hash))
                continue;

            JSONObject obj = new JSONObject();
            obj.put("propURI", ModelSchema.expandPrefix(lit.propURI));
            obj.put("groupNest", new JSONArray(expandPrefixes(lit.groupNest)));
            obj.put("valueLabel", data);
            jsonAnnot.put(obj);
            gotLiteral.add(hash);
            linesProcessed.add(key + ": " + data);

            continue;
        }

        Reference ref = findReference(key, data);
        if (ref != null) {
            Pattern ptn = Pattern.compile(ref.valueRegex);
            Matcher m = ptn.matcher(data);
            if (!m.matches() || m.groupCount() < 1)
                throw new IOException(
                        "Pattern /" + ref.valueRegex + "/ did not match '" + data + "' to produce a group.");

            JSONObject obj = new JSONObject();
            obj.put("propURI", ModelSchema.expandPrefix(ref.propURI));
            obj.put("groupNest", new JSONArray(expandPrefixes(ref.groupNest)));
            obj.put("valueLabel", ref.prefix + m.group(1));
            jsonAnnot.put(obj);
            linesProcessed.add(key + ": " + data);

            continue;
        }

        // probably shouldn't get this far, but just in case
        linesSkipped.add(key + ": " + data);
    }

    // annotation collapsing: sometimes there's a branch sequence that should exclude parent nodes
    for (int n = 0; n < jsonAnnot.length(); n++) {
        JSONObject obj = jsonAnnot.getJSONObject(n);
        String propURI = obj.getString("propURI"), valueURI = obj.optString("valueURI");
        if (valueURI == null)
            continue;
        String[] groupNest = obj.getJSONArray("groupNest").toStringArray();
        Schema.Assignment[] assnList = schema.findAssignmentByProperty(ModelSchema.expandPrefix(propURI),
                groupNest);
        if (assnList.length == 0)
            continue;
        SchemaTree tree = treeCache.get(assnList[0]);
        if (tree == null)
            continue;

        Set<String> exclusion = new HashSet<>();
        for (SchemaTree.Node node = tree.getNode(valueURI); node != null; node = node.parent)
            exclusion.add(node.uri);
        if (exclusion.size() == 0)
            continue;

        for (int i = jsonAnnot.length() - 1; i >= 0; i--)
            if (i != n) {
                obj = jsonAnnot.getJSONObject(i);
                if (!obj.has("valueURI"))
                    continue;
                if (!propURI.equals(obj.getString("propURI")))
                    continue;
                if (!Objects.deepEquals(groupNest, obj.getJSONArray("groupNest").toStringArray()))
                    continue;
                if (!exclusion.contains(obj.getString("valueURI")))
                    continue;
                jsonAnnot.remove(i);
            }
    }

    /*String text = "";
    if (linesBlock.size() > 0) text += String.join("\n", linesBlock) + "\n\n";
    if (linesSkipped.size() > 0) text += "SKIPPED:\n" + String.join("\n", linesSkipped) + "\n\n";
    text += "PROCESSED:\n" + String.join("\n", linesProcessed);*/

    List<String> sections = new ArrayList<>();
    if (linesTitle.size() > 0)
        sections.add(String.join(" / ", linesTitle));
    if (linesBlock.size() > 0)
        sections.add(String.join("\n", linesBlock));
    sections.add("#### IMPORTED ####");
    if (linesSkipped.size() > 0)
        sections.add("SKIPPED:\n" + String.join("\n", linesSkipped));
    if (linesProcessed.size() > 0)
        sections.add("PROCESSED:\n" + String.join("\n", linesProcessed));
    String text = String.join("\n\n", sections);

    JSONObject assay = new JSONObject();
    assay.put("uniqueID", uniqueID);
    assay.put("text", text);
    assay.put("schemaURI", schema.getSchemaPrefix());
    assay.put("annotations", jsonAnnot);
    return assay;
}

From source file:GUI.simplePanel.java

public simplePanel() {
    self = this;/*from   www . j ava 2s.  c om*/
    final Microphone mic = new Microphone(FLACFileWriter.FLAC);//Instantiate microphone and have 

    final GSpeechDuplex dup = new GSpeechDuplex("AIzaSyBc-PCGLbT2M_ZBLUPEl9w2OY7jXl90Hbc");//Instantiate the API
    dup.addResponseListener(new GSpeechResponseListener() {// Adds the listener
        public void onResponse(GoogleResponse gr) {
            System.out.println("got response");
            jTextArea1.setText(gr.getResponse() + "\n" + jTextArea1.getText());

            getjLabel1().setText("Awaiting Command");
            if (gr.getResponse().contains("temperature")) {
                try {
                    String reply = util.httpRequest.sendPost("127.0.0.1", 8383, "", "/getServices");
                    JSONObject obj;

                    obj = new JSONObject(reply);
                    JSONArray services = obj.getJSONArray("services");
                    boolean found = false;
                    for (int i = 0; i < services.length(); i++) {
                        if (found) {
                            return;
                        }
                        Object pref = services.getJSONObject(i).get("url");
                        String url = (String) pref;
                        if (url.contains("temp")) {
                            // http://127.0.0.1:8181/sensor/1/temp
                            String serviceHost = (url.split(":")[1].substring(2));
                            int Port = Integer.parseInt((url.split(":")[2]).split("/")[0]);
                            String servicePath = (url.split(":")[2].substring(url.split(":")[2].indexOf("/")));
                            String serviceReply = util.httpRequest.sendPost(serviceHost, Port, "", servicePath);

                            JSONObject temperature;

                            obj = new JSONObject(serviceReply);
                            String temp = obj.getJSONObject("sensor").getString("Temperature");
                            JOptionPane.showMessageDialog(self,
                                    "Temperature is " + temp.substring(0, temp.indexOf(".") + 2) + " Celsius");
                            found = true;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (gr.getResponse().contains("light") || gr.getResponse().startsWith("li")) {
                try {
                    String reply = util.httpRequest.sendPost("127.0.0.1", 8383, "", "/getServices");
                    JSONObject obj;

                    obj = new JSONObject(reply);
                    JSONArray services = obj.getJSONArray("services");
                    boolean found = false;
                    for (int i = 0; i < services.length(); i++) {
                        if (found) {
                            return;
                        }
                        Object pref = services.getJSONObject(i).get("url");
                        String url = (String) pref;
                        if (url.contains("light")) {
                            // http://127.0.0.1:8181/sensor/1/temp
                            String serviceHost = (url.split(":")[1].substring(2));
                            int Port = Integer.parseInt((url.split(":")[2]).split("/")[0]);
                            String servicePath = (url.split(":")[2].substring(url.split(":")[2].indexOf("/")));
                            String serviceReply = util.httpRequest.sendPost(serviceHost, Port, "", servicePath);

                            JSONObject temperature;

                            obj = new JSONObject(serviceReply);
                            String temp = obj.getJSONObject("sensor").getString("Light");
                            JOptionPane.showMessageDialog(self, "Light levels are at " + temp + " of 1023 ");
                            found = true;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else if ((gr.getResponse().contains("turn on") || gr.getResponse().contains("turn off"))
                    && gr.getResponse().contains("number")) {
                int numberIndex = gr.getResponse().indexOf("number ") + "number ".length();
                String number = gr.getResponse().substring(numberIndex).split(" ")[0];
                if (number.equals("for") || number.equals("four")) {
                    number = "4";
                }
                if (number.equals("to") || number.equals("two") || number.equals("cho")) {
                    number = "2";
                }
                if (number.equals("one")) {
                    number = "1";
                }
                if (number.equals("three")) {
                    number = "3";
                }

                try {
                    String reply = util.httpRequest.sendPost("127.0.0.1", 8383, "", "/getServices");
                    JSONObject obj;

                    obj = new JSONObject(reply);
                    JSONArray services = obj.getJSONArray("services");
                    boolean found = false;
                    for (int i = 0; i < services.length(); i++) {
                        if (found) {
                            return;
                        }
                        Object pref = services.getJSONObject(i).get("url");
                        String url = (String) pref;
                        if (url.contains("sensor/" + number)) {
                            // http://127.0.0.1:8181/sensor/1/temp
                            String serviceHost = (url.split(":")[1].substring(2));
                            int Port = Integer.parseInt((url.split(":")[2]).split("/")[0]);
                            String servicePath = (url.split(":")[2].substring(url.split(":")[2].indexOf("/")));
                            String serviceReply = util.httpRequest.sendPost(serviceHost, Port, "", servicePath);

                            JSONObject temperature;

                            obj = new JSONObject(serviceReply);
                            String temp = obj.getJSONObject("sensor").getString("Switch");
                            if (!(temp.equals("0") || temp.equals("1"))) {
                                JOptionPane.showMessageDialog(self,
                                        "Sensor does not provide a switch service man");
                            } else if (gr.getResponse().contains("turn on") && temp.equals("1")) {
                                JOptionPane.showMessageDialog(self,
                                        "Switch is already on at sensor " + number + "!");
                            } else if (gr.getResponse().contains("turn off") && temp.equals("0")) {
                                JOptionPane.showMessageDialog(self,
                                        "Switch is already off at sensor " + number + "!");
                            } else if (gr.getResponse().contains("turn on") && temp.equals("0")) {
                                String serviceReply2 = util.httpRequest.sendPost(serviceHost, Port, "",
                                        "/sensor/" + number + "/switch");
                                JOptionPane.showMessageDialog(self, "Request for switch sent");
                            } else if (gr.getResponse().contains("turn off") && temp.equals("1")) {
                                String serviceReply2 = util.httpRequest.sendPost(serviceHost, Port, "",
                                        "/sensor/" + number + "/switch");
                                JOptionPane.showMessageDialog(self, "Request for switch sent");
                            }

                            found = true;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else if (gr.getResponse().contains("change") && gr.getResponse().contains("number")) {

                int numberIndex = gr.getResponse().indexOf("number ") + "number ".length();
                String number = gr.getResponse().substring(numberIndex).split(" ")[0];
                if (number.equals("for") || number.equals("four")) {
                    number = "4";
                }
                if (number.equals("to") || number.equals("two") || number.equals("cho")) {
                    number = "2";
                }
                if (number.equals("one")) {
                    number = "1";
                }
                if (number.equals("three")) {
                    number = "3";
                }

                try {
                    String reply = util.httpRequest.sendPost("127.0.0.1", 8383, "", "/getServices");
                    JSONObject obj;

                    obj = new JSONObject(reply);
                    JSONArray services = obj.getJSONArray("services");
                    boolean found = false;
                    for (int i = 0; i < services.length(); i++) {
                        if (found) {
                            return;
                        }
                        Object pref = services.getJSONObject(i).get("url");
                        String url = (String) pref;
                        if (url.contains("sensor/" + number)) {
                            // http://127.0.0.1:8181/sensor/1/temp
                            String serviceHost = (url.split(":")[1].substring(2));
                            int Port = Integer.parseInt((url.split(":")[2]).split("/")[0]);
                            String servicePath = (url.split(":")[2].substring(url.split(":")[2].indexOf("/")));
                            String serviceReply = util.httpRequest.sendPost(serviceHost, Port, "", servicePath);

                            JSONObject temperature;

                            obj = new JSONObject(serviceReply);
                            String temp = obj.getJSONObject("sensor").getString("Switch");
                            if (!(temp.equals("0") || temp.equals("1"))) {
                                JOptionPane.showMessageDialog(self,
                                        "Sensor does not provide a switch service man");
                            } else {
                                String serviceReply2 = util.httpRequest.sendPost(serviceHost, Port, "",
                                        "/sensor/" + number + "/switch");
                                JOptionPane.showMessageDialog(self, "Request for switch sent");
                            }

                            found = true;
                        }
                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(self, e.getLocalizedMessage());
                }
            } else if (gr.getResponse().contains("get all")) {

                try {
                    String reply = util.httpRequest.sendPost("127.0.0.1", 8383, "", "/getServices");
                    JSONObject obj;

                    obj = new JSONObject(reply);
                    JSONArray services = obj.getJSONArray("services");
                    boolean found = false;
                    String servicesString = "";
                    for (int i = 0; i < services.length(); i++) {
                        Object pref = services.getJSONObject(i).get("url");
                        String url = (String) pref;
                        servicesString += url + "\n";

                    }
                    JOptionPane.showMessageDialog(self, servicesString);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                try {
                    ChatterBotFactory factory = new ChatterBotFactory();
                    ChatterBot bot1 = factory.create(CLEVERBOT);
                    ChatterBotSession bot1session = bot1.createSession();
                    String s = gr.getResponse();
                    String response = bot1session.think(s);
                    JOptionPane.showMessageDialog(self, response);
                } catch (Exception e) {
                }
            }
            System.out.println("Google thinks you said: " + gr.getResponse());
            System.out.println("with "
                    + ((gr.getConfidence() != null) ? (Double.parseDouble(gr.getConfidence()) * 100) : null)
                    + "% confidence.");
            System.out.println("Google also thinks that you might have said:" + gr.getOtherPossibleResponses());
        }
    });
    initComponents();
    jTextField1.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                String input = jTextField1.getText();
                jTextField1.setText("");
                textParser(input);
            }
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void keyReleased(KeyEvent e) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });
    jButton1.addMouseListener(new MouseListener() {

        @Override
        public void mouseClicked(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void mousePressed(MouseEvent e) {
            // it record FLAC file.
            File file = new File("CRAudioTest.flac");//The File to record the buffer to. 
            //You can also create your own buffer using the getTargetDataLine() method.
            System.out.println("Start Talking Honey");
            try {
                mic.captureAudioToFile(file);//Begins recording
            } catch (Exception ex) {
                ex.printStackTrace();//Prints an error if something goes wrong.
            }
            //System.out.println("You can stop now");
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            try {
                mic.close();//Stops recording
                //Sends 10 second voice recording to Google
                byte[] data = Files.readAllBytes(mic.getAudioFile().toPath());//Saves data into memory.
                dup.recognize(data, (int) mic.getAudioFormat().getSampleRate(), self);
                //mic.getAudioFile().delete();//Deletes Buffer file
                //REPEAT
            } catch (Exception ex) {
                ex.printStackTrace();//Prints an error if something goes wrong.
            }
            System.out.println("You can stop now");

        }

        @Override
        public void mouseEntered(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void mouseExited(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });

    setVisible(true);

}