Example usage for org.json JSONArray get

List of usage examples for org.json JSONArray get

Introduction

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

Prototype

public Object get(int index) throws JSONException 

Source Link

Document

Get the object value associated with an index.

Usage

From source file:org.everit.osgi.webconsole.configuration.ConfigServlet.java

private Map<String, List<String>> extractRawAttributesFromJSON(final JSONObject json) {
    Map<String, List<String>> rawAttributes = new HashMap<>();
    for (Object rawKey : json.keySet()) {
        String key = (String) rawKey;
        JSONArray valueArr = (JSONArray) json.get(key);
        int stringCount = valueArr.length();
        List<String> values = new ArrayList<String>(stringCount);
        for (int i = 0; i < stringCount; ++i) {
            Object value = valueArr.get(i);
            if (value.equals(JSONObject.NULL)) {
                values.add(null);// ww w .ja  va 2  s  .  c  om
            } else {
                values.add(value.toString());
            }
        }
        rawAttributes.put(key, values);
    }
    return rawAttributes;
}

From source file:org.achtern.AchternEngine.core.resource.loader.json.JsonLoader.java

/**
 * Converts a {@link org.json.JSONArray} into an array of
 * {@link java.lang.Object}s//  w  w  w  .  j ava2 s  .c  o  m
 * @param array JSONArray
 * @return Object array
 */
public static Object[] toObjectArray(JSONArray array) {
    Object[] objects = new Object[array.length()];
    for (int i = 0; i < objects.length; i++) {
        objects[i] = array.get(i);

    }

    return objects;
}

From source file:com.atinternet.tracker.Builder.java

/**
 * Prepare the hit queryString//ww w  .j  ava 2s  .  com
 *
 * @return LinkedHashMap
 */
private LinkedHashMap<String, Object[]> prepareQuery() {
    LinkedHashMap<String, Object[]> formattedParameters = new LinkedHashMap<String, Object[]>();

    ArrayList<Param> completeBuffer = new ArrayList<Param>() {
        {
            addAll(persistentParams);
            addAll(volatileParams);
        }
    };

    ArrayList<Param> params = organizeParameters(completeBuffer);

    for (Param p : params) {
        String value = p.getValue().execute();
        String key = p.getKey();

        HashMap<String, String> plugins = PluginParam.get(tracker);
        if (plugins.containsKey(key)) {
            String pluginClass = plugins.get(key);
            Plugin plugin = null;
            try {
                plugin = (Plugin) Class.forName(pluginClass).newInstance();
                plugin.execute(tracker);
                value = plugin.getResponse();
                p.setType(Param.Type.JSON);
                key = Hit.HitParam.JSON.stringValue();
            } catch (Exception e) {
                e.printStackTrace();
                value = null;
            }
        } else if (key.equals(Hit.HitParam.UserId.stringValue())) {
            if (TechnicalContext.doNotTrackEnabled(Tracker.getAppContext())) {
                value = OPT_OUT;
            } else if (((Boolean) configuration.get(TrackerConfigurationKeys.HASH_USER_ID))) {
                value = Tool.SHA_256(value);
            }
        }

        if (p.getType() == Param.Type.Closure && Tool.parseJSON(value) != null) {
            p.setType(Param.Type.JSON);
        }

        if (value != null) {
            // Referrer processing
            if (key.equals(Hit.HitParam.Referrer.stringValue())) {

                value = value.replace("&", "$").replaceAll("[<>]", "");
            }

            if (p.getOptions() != null && p.getOptions().isEncode()) {
                value = Tool.percentEncode(value);
                p.getOptions().setSeparator(Tool.percentEncode(p.getOptions().getSeparator()));
            }
            int duplicateParamIndex = -1;
            String duplicateParamKey = null;

            Set<String> keys = formattedParameters.keySet();

            String[] keySet = keys.toArray(new String[keys.size()]);
            int length = keySet.length;
            for (int i = 0; i < length; i++) {
                if (keySet[i].equals(key)) {
                    duplicateParamIndex = i;
                    duplicateParamKey = key;
                    break;
                }
            }

            if (duplicateParamIndex != -1) {
                List<Object[]> values = new ArrayList<Object[]>(formattedParameters.values());
                Param duplicateParam = (Param) values.get(duplicateParamIndex)[0];
                String str = ((String) formattedParameters.get(duplicateParamKey)[1]).split("=")[0] + "=";
                String val = ((String) formattedParameters.get(duplicateParamKey)[1]).split("=")[1];

                if (p.getType() == Param.Type.JSON) {
                    Object json = Tool.parseJSON(Tool.percentDecode(val));
                    Object newJson = Tool.parseJSON(Tool.percentDecode(value));

                    if (json != null && json instanceof JSONObject) {
                        Map dictionary = Tool.toMap((JSONObject) json);

                        if (newJson instanceof JSONObject) {
                            Map newDictionary = Tool.toMap((JSONObject) newJson);
                            dictionary.putAll(newDictionary);

                            JSONObject jsonData = new JSONObject(dictionary);
                            formattedParameters.put(key, new Object[] { duplicateParam,
                                    makeSubQuery(key, Tool.percentEncode(jsonData.toString())) });
                        } else {
                            Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                                    "Couldn't append value to a dictionary");
                        }
                    } else if (json != null && json instanceof JSONArray) {
                        try {
                            ArrayList<Object> array = new ArrayList<Object>();
                            JSONArray jArray = (JSONArray) json;
                            for (int i = 0; i < jArray.length(); i++) {
                                array.add(jArray.get(i).toString());
                            }
                            if (newJson instanceof JSONArray) {
                                jArray = (JSONArray) newJson;
                                for (int i = 0; i < jArray.length(); i++) {
                                    array.add(jArray.get(i).toString());
                                }
                                JSONObject jsonData = new JSONObject(array.toString());
                                formattedParameters.put(key, new Object[] { duplicateParam,
                                        makeSubQuery(key, Tool.percentEncode(jsonData.toString())) });
                            } else {
                                Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                                        "Couldn't append value to an array");
                            }
                        } catch (JSONException e) {
                            Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                                    "Couldn't append value to an array");
                        }
                    } else {
                        Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                                "Couldn't append value to a JSON Object");
                    }
                } else if (duplicateParam.getType() == Param.Type.JSON) {
                    Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                            "Couldn't append value to a JSON Object");
                } else {
                    formattedParameters.put(key,
                            new Object[] { duplicateParam, str + val + p.getOptions().getSeparator() + value });
                }
            } else {
                formattedParameters.put(key, new Object[] { p, makeSubQuery(key, value) });
            }
        }
    }
    return formattedParameters;
}

From source file:to.networld.fbtosemweb.FacebookToSIOC.java

/**
 * TODO: If a link was posted, add also the link to the SIOC block.
 * @throws IOException// ww w  .j  ava 2s  .com
 * @throws JSONException
 */
public void createSIOC() throws IOException, JSONException {
    Element rootNode = this.rdfDocument.addElement(new QName("RDF", RDF_NS));
    rootNode.add(SIOC_NS);
    rootNode.add(DCT_NS);

    JSONArray wallEntries = this.object.getJSONArray("data");
    for (int count = 0; count < wallEntries.length(); count++) {
        JSONObject wallEntry = (JSONObject) wallEntries.get(count);
        Element siocPost = rootNode.addElement(new QName("Post", SIOC_NS)).addAttribute(
                new QName("about", RDF_NS), "http://graph.facebook.com/" + wallEntry.getString("id"));
        siocPost.addElement(new QName("content", SIOC_NS)).setText(wallEntry.getString("message"));
        String creatorID = wallEntry.getJSONObject("from").getString("id");
        siocPost.addElement(new QName("hasCreator", SIOC_NS)).addAttribute(new QName("resource", RDF_NS),
                "http://graph.facebook.com/" + creatorID);
        try {
            siocPost.addElement(new QName("created", SIOC_NS)).setText(wallEntry.getString("created_time"));
        } catch (JSONException e) {
        }
        try {
            siocPost.addElement(new QName("modified", SIOC_NS)).setText(wallEntry.getString("updated_time"));
        } catch (JSONException e) {
        }

        try {
            JSONArray comments = wallEntry.getJSONObject("comments").getJSONArray("data");
            for (int count1 = 0; count1 < comments.length(); count1++) {
                JSONObject comment = comments.getJSONObject(count1);
                Element replyNode = siocPost.addElement(new QName("has_reply", SIOC_NS));
                Element replyPost = replyNode.addElement(new QName("Post", SIOC_NS));
                replyPost.addAttribute(new QName("about", RDF_NS),
                        "http://graph.facebook.com/" + comment.getString("id"));
                replyPost.addElement(new QName("content", SIOC_NS)).setText(comment.getString("message"));
                String replierID = comment.getJSONObject("from").getString("id");
                replyPost.addElement(new QName("hasCreator", SIOC_NS))
                        .addAttribute(new QName("resource", RDF_NS), "http://graph.facebook.com/" + replierID);
                try {
                    replyPost.addElement(new QName("created", SIOC_NS))
                            .setText(comment.getString("created_time"));
                } catch (JSONException e) {
                }
                try {
                    replyPost.addElement(new QName("modified", SIOC_NS))
                            .setText(comment.getString("updated_time"));
                } catch (JSONException e) {
                }
            }
        } catch (JSONException e) {
            // TODO: Log here something, at least during development.
        }
    }
}

From source file:com.nginious.http.serialize.JsonSerializerTestCase.java

public void testJsonSerializer() throws Exception {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
    SerializableBean bean = new SerializableBean();
    bean.setBooleanValue(true);/*from   w w  w .jav  a 2 s .  c o  m*/
    bean.setDoubleValue(0.451);
    bean.setFloatValue(1.34f);
    bean.setIntValue(3400100);
    bean.setLongValue(3400100200L);
    bean.setShortValue((short) 32767);
    bean.setStringValue("String");
    bean.setDateValue(format.parse("2011-08-24T08:50:23+0200"));
    Date calDate = format.parse("2011-08-24T08:52:23+0200");
    Calendar cal = Calendar.getInstance();
    cal.setTime(calDate);
    bean.setCalendarValue(cal);
    bean.setObjectValue(TimeZone.getDefault());

    InBean inBean = new InBean();
    inBean.setFirst(true);
    inBean.setSecond(0.567d);
    inBean.setThird(0.342f);
    inBean.setFourth(100);
    inBean.setFifth(3400200100L);
    inBean.setSixth((short) 32767);
    inBean.setSeventh("String");
    inBean.setEight(format.parse("2011-08-25T08:50:23+0200"));
    cal = Calendar.getInstance();
    calDate = format.parse("2011-08-25T08:52:23+0200");
    cal.setTime(calDate);
    inBean.setNinth(cal);
    bean.setBeanValue(inBean);

    List<InBean> beanList = new ArrayList<InBean>();
    beanList.add(inBean);
    beanList.add(inBean);
    bean.setBeanListValue(beanList);

    List<String> stringList = new ArrayList<String>();
    stringList.add("One");
    stringList.add("Two");
    stringList.add("Three");
    bean.setStringListValue(stringList);

    ApplicationClassLoader classLoader = new ApplicationClassLoader(
            Thread.currentThread().getContextClassLoader());
    SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader);
    Serializer<SerializableBean> serializer = serializerFactory.createSerializer(SerializableBean.class,
            "application/json");
    assertEquals("application/json", serializer.getMimeType());

    StringWriter strWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(strWriter);

    serializer.serialize(writer, bean);
    writer.flush();
    JSONObject json = new JSONObject(strWriter.toString());
    assertNotNull(json);
    assertTrue(json.has("serializableBean"));
    json = json.getJSONObject("serializableBean");

    assertEquals(true, json.getBoolean("booleanValue"));
    assertEquals(0.451, json.getDouble("doubleValue"));
    assertEquals(1.34f, (float) json.getDouble("floatValue"));
    assertEquals(3400100, json.getInt("intValue"));
    assertEquals(3400100200L, json.getLong("longValue"));
    assertEquals(32767, (short) json.getInt("shortValue"));
    assertEquals("String", json.getString("stringValue"));
    assertEquals("2011-08-24T08:50:23+02:00", json.getString("dateValue"));
    assertEquals("2011-08-24T08:52:23+02:00", json.getString("calendarValue"));
    assertEquals(TimeZone.getDefault().toString(), json.getString("objectValue"));

    assertTrue(json.has("beanValue"));
    JSONObject inBeanJson = json.getJSONObject("beanValue");
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));

    assertTrue(json.has("stringListValue"));
    JSONArray stringListJson = json.getJSONArray("stringListValue");
    assertEquals("One", stringListJson.get(0));
    assertEquals("Two", stringListJson.get(1));
    assertEquals("Three", stringListJson.get(2));

    assertTrue(json.has("beanListValue"));
    JSONArray beanListJson = json.getJSONArray("beanListValue");

    inBeanJson = beanListJson.getJSONObject(0);
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));

    inBeanJson = beanListJson.getJSONObject(1);
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));
}

From source file:com.nginious.http.serialize.JsonSerializerTestCase.java

public void testNamedJsonSerializer() throws Exception {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
    NamedBean bean = new NamedBean();
    bean.setBooleanValue(true);//ww  w .  j a  v a2 s .  com
    bean.setDoubleValue(0.451);
    bean.setFloatValue(1.34f);
    bean.setIntValue(3400100);
    bean.setLongValue(3400100200L);
    bean.setShortValue((short) 32767);
    bean.setStringValue("String");
    bean.setDateValue(format.parse("2011-08-24T08:50:23+0200"));
    Date calDate = format.parse("2011-08-24T08:52:23+0200");
    Calendar cal = Calendar.getInstance();
    cal.setTime(calDate);
    bean.setCalendarValue(cal);
    bean.setObjectValue(TimeZone.getDefault());

    InBean inBean = new InBean();
    inBean.setFirst(true);
    inBean.setSecond(0.567d);
    inBean.setThird(0.342f);
    inBean.setFourth(100);
    inBean.setFifth(3400200100L);
    inBean.setSixth((short) 32767);
    inBean.setSeventh("String");
    inBean.setEight(format.parse("2011-08-25T08:50:23+0200"));
    cal = Calendar.getInstance();
    calDate = format.parse("2011-08-25T08:52:23+0200");
    cal.setTime(calDate);
    inBean.setNinth(cal);
    bean.setBeanValue(inBean);

    List<InBean> beanList = new ArrayList<InBean>();
    beanList.add(inBean);
    beanList.add(inBean);
    bean.setBeanListValue(beanList);

    List<String> stringList = new ArrayList<String>();
    stringList.add("One");
    stringList.add("Two");
    stringList.add("Three");
    bean.setStringListValue(stringList);

    ApplicationClassLoader classLoader = new ApplicationClassLoader(
            Thread.currentThread().getContextClassLoader());
    SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader);
    Serializer<NamedBean> serializer = serializerFactory.createSerializer(NamedBean.class, "application/json");
    assertEquals("application/json", serializer.getMimeType());

    StringWriter strWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(strWriter);

    serializer.serialize(writer, bean);
    writer.flush();
    JSONObject json = new JSONObject(strWriter.toString());
    assertNotNull(json);
    assertTrue(json.has("testNamedBean"));
    json = json.getJSONObject("testNamedBean");

    assertEquals(true, json.getBoolean("testBooleanValue"));
    assertEquals(0.451, json.getDouble("testDoubleValue"));
    assertEquals(1.34f, (float) json.getDouble("testFloatValue"));
    assertEquals(3400100, json.getInt("testIntValue"));
    assertEquals(3400100200L, json.getLong("testLongValue"));
    assertEquals(32767, (short) json.getInt("testShortValue"));
    assertEquals("String", json.getString("testStringValue"));
    assertEquals("2011-08-24T08:50:23+02:00", json.getString("testDateValue"));
    assertEquals("2011-08-24T08:52:23+02:00", json.getString("testCalendarValue"));
    assertEquals(TimeZone.getDefault().toString(), json.getString("testObjectValue"));

    assertTrue(json.has("testBeanValue"));
    JSONObject inBeanJson = json.getJSONObject("testBeanValue");
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));

    assertTrue(json.has("testStringListValue"));
    JSONArray stringListJson = json.getJSONArray("testStringListValue");
    assertEquals("One", stringListJson.get(0));
    assertEquals("Two", stringListJson.get(1));
    assertEquals("Three", stringListJson.get(2));

    assertTrue(json.has("testBeanListValue"));
    JSONArray beanListJson = json.getJSONArray("testBeanListValue");

    inBeanJson = beanListJson.getJSONObject(0);
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));

    inBeanJson = beanListJson.getJSONObject(1);
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));
}

From source file:com.hueemulator.lighting.utils.TestUtils.java

@SuppressWarnings("unchecked")
private static Object convertJsonElement(Object elem) throws JSONException {
    if (elem instanceof JSONObject) {
        JSONObject obj = (JSONObject) elem;
        Iterator<String> keys = obj.keys();
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        while (keys.hasNext()) {
            String key = keys.next();
            jsonMap.put(key, convertJsonElement(obj.get(key)));
        }/* www.  jav  a 2s.c om*/
        return jsonMap;
    } else if (elem instanceof JSONArray) {
        JSONArray arr = (JSONArray) elem;
        Set<Object> jsonSet = new HashSet<Object>();
        for (int i = 0; i < arr.length(); i++) {
            jsonSet.add(convertJsonElement(arr.get(i)));
        }
        return jsonSet;
    } else {
        return elem;
    }
}

From source file:ai.ilikeplaces.logic.sits9.SubscriberNotifications.java

@Timeout
synchronized public void timeout(final Timer timer)
        throws IOException, SAXException, TransformerException, JSONException, SQLException {

    final HBaseCrudService<GeohashSubscriber> _geohashSubscriberHBaseCrudService = new HBaseCrudService<GeohashSubscriber>();
    final HBaseCrudService<GeohashSubscriber>.Scanner _scanner = _geohashSubscriberHBaseCrudService
            .scan(new GeohashSubscriber(), 1).returnValueBadly();

    while (_scanner.getNewValue() != null) {
        final String _newValue = _scanner.getNewValue();
        Loggers.debug("Scanned value:" + _newValue);
        final RowResponse _rowResponse = new Gson().fromJson(_newValue, RowResponse.class);
        Loggers.debug("Scanned as GSON:" + _rowResponse.toString());

        for (final Row _row : _rowResponse.Row) {

            final BASE64Decoder _base64DecoderRowKey = new BASE64Decoder();
            final byte[] _bytes = _base64DecoderRowKey.decodeBuffer(_row.key);
            final String rowKey = new String(_bytes);
            Loggers.debug("Decoded row key:" + rowKey);

            for (final Cell _cell : _row.Cell) {
                final BASE64Decoder _base64DecoderValue = new BASE64Decoder();
                final byte[] _valueBytes = _base64DecoderValue.decodeBuffer(_cell.$);
                final String _cellAsString = new String(_valueBytes);
                Loggers.debug("Cell as string:" + _cellAsString);
                final GeohashSubscriber _geohashSubscriber = new GeohashSubscriber();

                final DatumReader<GeohashSubscriber> _geohashSubscriberSpecificDatumReader = new SpecificDatumReader<GeohashSubscriber>(
                        _geohashSubscriber.getSchema());
                final BinaryDecoder _binaryDecoder = DecoderFactory.get().binaryDecoder(_valueBytes, null);
                final GeohashSubscriber _read = _geohashSubscriberSpecificDatumReader.read(_geohashSubscriber,
                        _binaryDecoder);
                Loggers.debug("Decoded value avro:" + _read.toString());

                final Date now = new Date();
                final Calendar _week = Calendar.getInstance();
                _week.setTimeInMillis(now.getTime() + (7 * 24 * 60 * 60 * 1000));
                final SimpleDateFormat _simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                _simpleDateFormat.format(_week.getTime());

                final StringBuffer eventList = new StringBuffer("");

                {//Eventful

                    try {

                        final SimpleDateFormat eventfulDate = new SimpleDateFormat("yyyyMMdd00");
                        _simpleDateFormat.format(_week.getTime());

                        final JSONObject jsonObject = Modules.getModules().getEventulFactory()
                                .getInstance("http://api.eventful.com/json/events/search/")
                                .get("", new HashMap<String, String>() {
                                    {//Don't worry, this is a static initializer of this map :)
                                        put("location", "" + _read.getLatitude() + "," + _read.getLongitude());
                                        put("within", "" + 100);
                                        put("date", eventfulDate.format(Calendar.getInstance().getTime()) + "-"
                                                + eventfulDate.format(_week.getTime()));
                                    }/* ww  w  .  j ava 2  s  .c o m*/
                                }

                        );

                        Loggers.debug("Eventful Reply:" + jsonObject.toString());

                        final JSONArray events = jsonObject.getJSONObject("events").getJSONArray("event");

                        final Document eventTemplateDocument = HTMLDocParser
                                .getDocument(RBGet.getGlobalConfigKey("PAGEFILES") + SUBSCRIBER_EMAIL_EVENT);
                        final String eventTemplate = HTMLDocParser
                                .convertNodeToHtml(HTMLDocParser.$("content", eventTemplateDocument));

                        for (int i = 0; i < events.length(); i++) {
                            final JSONObject eventJSONObject = new JSONObject(events.get(i).toString());
                            Double.parseDouble(eventJSONObject.getString(LATITUDE));
                            Double.parseDouble(eventJSONObject.getString(LONGITUDE));
                            final String eventName = eventJSONObject.getString("title");
                            final String eventUrl = eventJSONObject.getString("url");
                            final String eventDate = eventJSONObject.getString("start_time");
                            final String eventVenue = eventJSONObject.getString("venue_name");
                            Loggers.debug("Event name:" + eventName);
                            eventList
                                    .append(eventTemplate
                                            .replace("_name_link_",
                                                    !(("" + eventUrl).isEmpty()) ? eventUrl
                                                            : ("https://www.google.com/search?q=" + eventName
                                                                    .replaceAll(" ", "+").replaceAll("-", "+")))
                                            .replace("_place_link_",
                                                    "https://maps.googleapis.com/maps/api/staticmap?sensor=false&size=600x600&markers=color:blue%7Clabel:S%7C"
                                                            + _read.getLatitude().toString() + ","
                                                            + _read.getLongitude().toString())
                                            .replace("_name_", eventName).replace("_place_", eventVenue)
                                            .replace("_date_", eventDate));
                        }
                    } catch (final Throwable t) {
                        Loggers.error("Error appending Eventful data to Geohash Subscriber", t);
                    }
                }

                {//Foursquare

                    try {

                        _simpleDateFormat.format(_week.getTime());

                        final JSONObject jsonObject = Modules.getModules().getEventulFactory()
                                .getInstance("https://api.foursquare.com/v2/venues/explore")
                                .get("", new HashMap<String, String>() {
                                    {//Don't worry, this is a static initializer of this map :)
                                        put("ll", "" + _read.getLatitude() + "," + _read.getLongitude());
                                        put("radius", "" + 50000);//meters
                                        put("intent", "browse");
                                        put("section", "topPicks");
                                        put("client_secret",
                                                "PODRX5YWBSLAKAYRQ5CLPEPS3WHCXWFIJ3LXF3AKH4U1BDNI");
                                        put("client_id", "25JZAK3TQPLIPUUXPIJWXQ5NSKSPTP4SYZLUZSCTZF3UJ4YX");
                                    }
                                }

                        );

                        Loggers.debug("Foursquare Reply:" + jsonObject.toString());

                        final JSONArray referralArray = jsonObject.getJSONObject("response")
                                .getJSONArray("groups").getJSONObject(0).getJSONArray("items");

                        final Document eventTemplateDocument = HTMLDocParser
                                .getDocument(RBGet.getGlobalConfigKey("PAGEFILES") + SUBSCRIBER_EMAIL_PLACE);
                        final String eventTemplate = HTMLDocParser
                                .convertNodeToHtml(HTMLDocParser.$("content", eventTemplateDocument));

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

                            final JSONObject referral = referralArray.getJSONObject(i);
                            referral.getJSONObject("venue").getJSONObject("location").getDouble("lng");
                            referral.getJSONObject("venue").getJSONObject("location").getDouble("lat");
                            final String eventName = referral.getJSONObject("venue").getString("name");
                            final String eventUrl = referral.getJSONObject("venue").optString("url");
                            final String eventVenue = referral.getJSONObject("venue").getJSONObject("location")
                                    .getString("address");
                            Loggers.debug("Event name:" + eventName);
                            eventList
                                    .append(eventTemplate
                                            .replace("_name_link_",
                                                    !(("" + eventUrl).isEmpty()) ? eventUrl
                                                            : ("https://www.google.com/search?q=" + eventName
                                                                    .replaceAll(" ", "+").replaceAll("-", "+")))
                                            .replace("_place_link_",
                                                    "https://maps.googleapis.com/maps/api/staticmap?sensor=false&size=600x600&markers=color:blue%7Clabel:S%7C"
                                                            + _read.getLatitude().toString() + ","
                                                            + _read.getLongitude().toString())
                                            .replace("_name_", eventName).replace("_place_", eventVenue)
                                            .replace("_date_", eventName));
                        }
                    } catch (final Throwable t) {
                        Loggers.error("Error appending Foursquare data to Geohash Subscriber", t);
                    }
                }

                final String template = HTMLDocParser
                        .getDocumentAsString(RBGet.getGlobalConfigKey("PAGEFILES") + EMAIL_FRAME);
                final Document email = HTMLDocParser
                        .getDocument(RBGet.getGlobalConfigKey("PAGEFILES") + SUBSCRIBER_EMAIL);
                final String _content = HTMLDocParser.convertNodeToHtml(HTMLDocParser.$("content", email));
                final Parameter _unsubscribeLink = new Parameter("http://www.ilikeplaces.com/unsubscribe/")
                        .append(Unsubscribe.TYPE, Unsubscribe.Type.GeohashSubscribe.name(), true)
                        .append(Unsubscribe.VALUE, rowKey);
                final String finalEmail = template.replace("_FrameContent_",
                        _content.replace(" ___||_", eventList.toString()).replace("_unsubscribe_link_",
                                _unsubscribeLink.get()));
                Loggers.debug("Final email:" + finalEmail);
                sendMailLocal.sendAsHTML(_read.getEmailId().toString(), "Thank God it's Friday!", finalEmail);
            }

        }

        _geohashSubscriberHBaseCrudService.scan(new GeohashSubscriber(), _scanner);
    }

    Loggers.debug("Completed scanner");

}

From source file:GUI.simplePanel.java

public simplePanel() {
    self = this;//from  w  w w  .j a va  2  s.  co  m
    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);

}

From source file:GUI.simplePanel.java

public void textParser(String input) {
    boolean served = false;
    jTextArea1.setText(input + "\n" + jTextArea1.getText());

    getjLabel1().setText("Awaiting Command");
    if (input.contains("temperature")) {
        try {// w w w .  ja v a 2s.  c o  m
            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) {
                    served = true;
                    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");
                    if (temp.length() > 4) {
                        JOptionPane.showMessageDialog(self,
                                "Temperature is " + temp.substring(0, temp.indexOf(".") + 2) + " Celsius");
                    } else {
                        JOptionPane.showMessageDialog(self, "Temperature is " + temp + " Celsius");
                    }

                    found = true;
                }
            }
            JOptionPane.showMessageDialog(self, "I can't know! There are no sensors for that!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (input.contains("light") || input.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) {
                    served = true;
                    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;
                }
            }
            JOptionPane.showMessageDialog(self, "I can't know! There are no sensors for that!");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    if ((input.contains("turn on") || input.contains("turn off")) && input.contains("number")) {
        int numberIndex = input.indexOf("number ") + "number ".length();
        String number = input.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) {
                    served = true;
                    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 (input.contains("turn on") && temp.equals("1")) {
                        JOptionPane.showMessageDialog(self, "Switch is already on at sensor " + number + "!");
                    } else if (input.contains("turn off") && temp.equals("0")) {
                        JOptionPane.showMessageDialog(self, "Switch is already off at sensor " + number + "!");
                    } else if (input.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 (input.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();
        }

    }
    if (input.contains("change") && input.contains("number")) {

        int numberIndex = input.indexOf("number ") + "number ".length();
        String number = input.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) {
                    served = true;
                    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());
        }
    }
    if (input.contains("get all")) {

        try {
            String reply = util.httpRequest.sendPost("127.0.0.1", 8383, "", "/getServices");
            JSONObject obj;
            served = true;
            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();
        }

    }
    if (input.contains("humidity") || input.startsWith("humidity")) {
        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) {
                    served = true;
                    return;
                }
                Object pref = services.getJSONObject(i).get("url");
                String url = (String) pref;
                if (url.contains("humi")) {
                    // 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("Humidity");
                    JOptionPane.showMessageDialog(self, "Humidity levels are at " + temp + " of 1023 ");
                    found = true;
                }
            }
            JOptionPane.showMessageDialog(self, "I can't know! There are no sensors for that!");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    if (input.contains("pressure") || input.startsWith("pressure")) {
        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) {
                    served = true;
                    return;
                }
                Object pref = services.getJSONObject(i).get("url");
                String url = (String) pref;
                if (url.contains("pres")) {
                    // 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("Pressure");
                    JOptionPane.showMessageDialog(self, "Pressure levels are at " + temp + " of 1023 ");
                    found = true;
                }
            }
            JOptionPane.showMessageDialog(self, "I can't know! There are no sensors for that!");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    if (!served) {
        try {
            ChatterBotFactory factory = new ChatterBotFactory();
            ChatterBot bot1 = factory.create(CLEVERBOT);
            ChatterBotSession bot1session = bot1.createSession();
            String s = input;
            String response = bot1session.think(s);
            JOptionPane.showMessageDialog(self, response, "Jarvis says", JOptionPane.INFORMATION_MESSAGE);
        } catch (Exception e) {
        }
    }

}