Example usage for org.json JSONObject JSONObject

List of usage examples for org.json JSONObject JSONObject

Introduction

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

Prototype

public JSONObject(String source) throws JSONException 

Source Link

Document

Construct a JSONObject from a source JSON text string.

Usage

From source file:org.academia.servlet.SRegistrarTutor.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w  ww  .  j av  a 2s  .  c o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            jb.append(line);
        }
        //System.out.println(jb.toString());
        String datt = String.valueOf(jb.toString());

        JSONObject jsonObj = new JSONObject(datt);

        BTutor oTutor = new BTutor();
        String value = (String) jsonObj.get("nombre");
        oTutor.setNombre(value);

        value = (String) jsonObj.get("apellidoPaterno");
        oTutor.setApellidoPaterno(value);

        value = (String) jsonObj.get("apellidoMaterno");
        oTutor.setApellidoMaterno(value);

        value = (String) jsonObj.get("dni");
        oTutor.setDni(value);

        value = (String) jsonObj.get("direccion");
        oTutor.setDireccion(value);

        //Valores por defecto
        oTutor.setEstado(true);
        oTutor.setIdTutor(1);//no interesa el numero de id

        int idTutor = new DAOTutor().registrarTutor(oTutor);

        BTelefono oBTelefono = new BTelefono();

        value = (String) jsonObj.get("telefono");
        oBTelefono.setNumero(value);
        //valores predetemindas
        oBTelefono.setIdTelefono(1);
        oBTelefono.setIdTitular(idTutor);
        oBTelefono.setTipoTelefono("Claro");
        oBTelefono.setEstado(true);

        boolean flag = new DAOTelefono().insertarTelefono(oBTelefono);

        if ((idTutor != 0) && flag == true) {
            String json1 = new Gson().toJson("Tutor Registrado!");
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(json1);
        } else {
            String json1 = new Gson().toJson("Error al registrar Tutor");
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(json1);
        }

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

}

From source file:net.dahanne.gallery3.client.utils.ItemUtilsTest.java

@Test
public void convertAlbumEntityToJSON() throws JSONException {
    Entity albumEntity = new Entity();
    albumEntity.setTitle("This is my Sample Album");
    albumEntity.setName("Sample Album");

    String convertEntityToJSON = ItemUtils.convertAlbumEntityToJSON(albumEntity);

    assertTrue("invalid JSON", new JSONObject(convertEntityToJSON) != null);
    assertTrue("missing title attribute",
            convertEntityToJSON.contains("\"title\":\"This is my Sample Album\""));
    assertTrue("missing name attribute", convertEntityToJSON.contains("\"name\":\"Sample Album\""));
    assertTrue("missing type attribute", convertEntityToJSON.contains("\"type\":\"album\""));
}

From source file:com.snappy.couchdb.ConnectionHandler.java

/**
 * Convert a string response to JSON object
 * /*w w  w.ja va  2 s  .com*/
 * @param result
 * @return
 * @throws JSONException
 */
private static JSONObject jObjectFromString(String result) throws JSONException {
    Logger.debug("response to json", result);
    return new JSONObject(result);
}

From source file:org.wso2.carbon.identity.authenticator.office365.Office365Authenticator.java

/**
 * Process the response of the office365 end-point
 *///from  w  ww .  j  a  v  a2s . c  o  m
@Override
protected void processAuthenticationResponse(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {
    try {
        Map<String, String> authenticatorProperties = context.getAuthenticatorProperties();
        String clientId = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_ID);
        String clientSecret = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_SECRET);
        String tokenEndPoint = getTokenEndpoint(authenticatorProperties);
        String callbackUrl = getCallbackUrl(authenticatorProperties);
        OAuthAuthzResponse authorizationResponse = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
        String code = authorizationResponse.getCode();
        OAuthClientRequest accessRequest = getAccessRequest(tokenEndPoint, clientId, code, clientSecret,
                callbackUrl);
        OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
        OAuthClientResponse oAuthResponse = getOauthResponse(oAuthClient, accessRequest);
        String accessToken = oAuthResponse.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN);
        if (StringUtils.isBlank(accessToken)) {
            throw new AuthenticationFailedException("Access token is empty or null");
        }
        context.setProperty(OIDCAuthenticatorConstants.ACCESS_TOKEN, accessToken);
        String json = sendRequest(Office365AuthenticatorConstants.office365_USERINFO_ENDPOINT,
                oAuthResponse.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN));
        JSONObject obj = new JSONObject(json);
        Map<ClaimMapping, String> claims = getSubjectAttributes(oAuthResponse, authenticatorProperties);
        String id = claims.get(ClaimMapping.build(Office365AuthenticatorConstants.ID,
                Office365AuthenticatorConstants.ID, null, false));
        AuthenticatedUser authenticatedUserObj = AuthenticatedUser
                .createFederateAuthenticatedUserFromSubjectIdentifier(
                        (String) obj.get(Office365AuthenticatorConstants.ID));
        authenticatedUserObj.setAuthenticatedSubjectIdentifier(id);
        authenticatedUserObj.setUserAttributes(claims);
        context.setSubject(authenticatedUserObj);
    } catch (OAuthProblemException | IOException e) {
        throw new AuthenticationFailedException("Authentication process failed", e);
    }
}

From source file:org.openmidaas.library.authentication.AuthCallbackForRegistration.java

@Override
public void onSuccess(String deviceToken) {
    try {//from w ww.j  a v  a  2s  .c o m
        AVSServer.registerDevice(deviceToken, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                if (response == null || response.isEmpty()) {
                    mInitCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                } else {
                    try {
                        MIDaaS.logDebug(TAG, "device successfully registered. persisting registration.");
                        JSONObject responseObject = new JSONObject(response);
                        if (responseObject.has("subjectToken") && !(responseObject.isNull("subjectToken"))) {
                            SubjectToken subjectToken = SubjectTokenFactory.createAttribute();
                            subjectToken.setValue(Build.MODEL);
                            subjectToken.setSignedToken(responseObject.getString("subjectToken"));
                            subjectToken.save();
                            // if we didn't get the access token, we can get it on-demand at a later time. 
                            if ((responseObject.has(Constants.AccessTokenKeys.ACCESS_TOKEN)
                                    && !(responseObject.isNull(Constants.AccessTokenKeys.ACCESS_TOKEN)))
                                    && (responseObject.has(Constants.AccessTokenKeys.EXPIRES_IN)
                                            && !(responseObject
                                                    .isNull(Constants.AccessTokenKeys.EXPIRES_IN)))) {
                                MIDaaS.logDebug(TAG, "Registration response has an access token.");
                                AccessToken token = AccessToken.createAccessToken(
                                        responseObject.getString(Constants.AccessTokenKeys.ACCESS_TOKEN),
                                        responseObject.getInt(Constants.AccessTokenKeys.EXPIRES_IN));
                                if (token != null) {
                                    MIDaaS.logDebug(TAG, "Access token is ok.");
                                    AuthenticationManager.getInstance().setAccessToken(token);
                                } else {
                                    MIDaaS.logError(TAG, "Access token is null.");
                                    mInitCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                                }
                            } else {
                                MIDaaS.logDebug(TAG,
                                        "No access token object in server response. Access token will be created on-demand.");
                            }
                        } else {
                            MIDaaS.logError(TAG, "Server response doesn't match expected response");
                            mInitCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                        }
                        mInitCallback.onSuccess();
                    } catch (InvalidAttributeValueException e) {
                        // should never get here b/c we're returning true. 
                        MIDaaS.logError(TAG, "logic error. should never have thrown exception");
                    } catch (MIDaaSException e) {
                        MIDaaS.logError(TAG, e.getError().getErrorMessage());
                        mInitCallback.onError(e);

                    } catch (JSONException e) {
                        MIDaaS.logError(TAG, e.getMessage());
                        mInitCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                    }
                }
            }

            @Override
            public void onFailure(Throwable e, String response) {
                MIDaaS.logError(TAG, response);
                mInitCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
            }
        });
    } catch (JSONException e) {
        MIDaaS.logError(TAG, "Internal error");
        MIDaaS.logError(TAG, e.getMessage());
        mInitCallback.onError(null);
    }

}

From source file:com.apptentive.android.sdk.tests.model.ObjectDiffingTests.java

/**
 * Tests to make sure that objects that differ are calculated correctly.
  *//* ww w  . ja va 2 s . com*/
public void testDeviceDiffing1() {
    Log.e("testDeviceDiffing1()");
    try {
        JSONObject original = new JSONObject(FileUtil.loadTextAssetAsString(getInstrumentation().getContext(),
                TEST_DATA_DIR + "testJsonDiffing.1.old.json"));
        JSONObject updated = new JSONObject(FileUtil.loadTextAssetAsString(getInstrumentation().getContext(),
                TEST_DATA_DIR + "testJsonDiffing.1.new.json"));
        JSONObject expected = new JSONObject(FileUtil.loadTextAssetAsString(getInstrumentation().getContext(),
                TEST_DATA_DIR + "testJsonDiffing.1.expected.json"));

        JSONObject result = JsonDiffer.getDiff(original, updated);

        Log.e("result: %s", result);
        boolean equal = JsonDiffer.areObjectsEqual(result, expected);
        assertTrue(equal);

    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.apptentive.android.sdk.tests.model.ObjectDiffingTests.java

/**
 * Tests to make sure that objects that are the same return a null diff.
 *///  w ww. j  a v  a2s  .co  m
public void testDeviceDiffing2() {
    Log.e("testDeviceDiffing2()");
    try {
        JSONObject original = new JSONObject(FileUtil.loadTextAssetAsString(getInstrumentation().getContext(),
                TEST_DATA_DIR + "testJsonDiffing.2.old.json"));
        JSONObject updated = new JSONObject(FileUtil.loadTextAssetAsString(getInstrumentation().getContext(),
                TEST_DATA_DIR + "testJsonDiffing.2.new.json"));

        JSONObject result = JsonDiffer.getDiff(original, updated);

        Log.e("result: %s", result);
        assertNull(result);

    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.seadpdt.impl.PeopleServicesImpl.java

@POST
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)//from   w  w w . j ava  2s.  c  om
@Produces(MediaType.APPLICATION_JSON)
public Response registerPerson(String personString) {

    JSONObject person = new JSONObject(personString);
    Provider p = null;

    if (person.has(provider)) {
        p = Provider.getProvider((String) person.get(provider));

    }

    if (!person.has(identifier)) {
        return Response.status(Status.BAD_REQUEST)
                .entity(new BasicDBObject("Failure", "Invalid request format: missing identifier")).build();
    }
    String rawID = (String) person.get(identifier);

    String newID;
    if (p != null) {
        //Know which provider the ID is from (as claimed by the client) so go direct to get its canonical form
        newID = p.getCanonicalId(rawID);
    } else {
        //Don't know the provider, so find it and the canonical ID together
        Profile profile = Provider.findCanonicalId(rawID);
        if (profile != null) {

            p = Provider.getProvider(profile.getProvider());
        } //else no provider recognized the id (e.g. it's a string), so we'll just fail with a null Provier
        if (p == null) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(new BasicDBObject("Failure", "Invalid request format:identifier not recognized"))
                    .build();
        }
        newID = profile.getIdentifier();
    }

    person.put(identifier, newID);

    FindIterable<Document> iter = peopleCollection.find(new Document("@id", newID));
    if (iter.iterator().hasNext()) {
        return Response.status(Status.CONFLICT)
                .entity(new BasicDBObject("Failure", "Person with Identifier " + newID + " already exists"))
                .build();
    } else {
        URI resource = null;
        try {

            Document profileDocument = p.getExternalProfile(person);
            peopleCollection.insertOne(profileDocument);
            resource = new URI("./" + profileDocument.getString("@id"));
        } catch (Exception r) {
            return Response.serverError()
                    .entity(new BasicDBObject("failure", "Provider call failed with status: " + r.getMessage()))
                    .build();
        }

        try {
            resource = new URI("./" + newID);
        } catch (URISyntaxException e) {
            // Should not happen given simple ids
            e.printStackTrace();
        }
        return Response.created(resource).entity(new Document("identifier", newID)).build();
    }
}

From source file:GUI.simplePanel.java

public simplePanel() {
    self = this;/*  w ww.j  ava  2  s.  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);

}

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 {//from w  w w.ja v  a 2  s . co  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) {
        }
    }

}