Example usage for org.json JSONArray length

List of usage examples for org.json JSONArray length

Introduction

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

Prototype

public int length() 

Source Link

Document

Get the number of elements in the JSONArray, included nulls.

Usage

From source file:GUI.simplePanel.java

public simplePanel() {
    self = this;//from   w  w  w  . j av a  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.j  a va2 s . 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) {
        }
    }

}

From source file:GUI.simplePanel.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    try {/*  ww  w  .  j a  va2  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) {
                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();
    }
}

From source file:nl.hnogames.domoticzapi.Parsers.TemperaturesParser.java

@Override
public void parseResult(String result) {

    try {/* w ww.  ja v a  2  s  .co m*/
        JSONArray jsonArray = new JSONArray(result);
        ArrayList<TemperatureInfo> mTemperatures = new ArrayList<>();

        if (jsonArray.length() > 0) {

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject row = jsonArray.getJSONObject(i);
                mTemperatures.add(new TemperatureInfo(row));
            }
        }

        temperatureReceiver.onReceiveTemperatures(mTemperatures);

    } catch (JSONException e) {
        Log.e(TAG, "TemperatureParser JSON exception");
        e.printStackTrace();
        temperatureReceiver.onError(e);
    }
}

From source file:com.sakisds.icymonitor.activities.AddNotificationActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_add_notification);
    mSettings = getSharedPreferences(MainViewActivity.SHAREDPREFS_FILE, 0);

    // Prepare buttons
    findViewById(R.id.button_add).setOnClickListener(this);
    findViewById(R.id.button_cancel).setOnClickListener(this);
    findViewById(R.id.button_notification_help).setOnClickListener(this);

    // Prepare spinners
    mDeviceSpinner = (Spinner) findViewById(R.id.spinner_device);
    mTypeSpinner = (Spinner) findViewById(R.id.spinner_type);
    mSensorSpinner = (Spinner) findViewById(R.id.spinner_sensor);
    mConditionSpinner = (Spinner) findViewById(R.id.spinner_condition);

    // Edittext//from www.  ja  v  a 2 s  .c  o  m
    mSensorValue = (EditText) findViewById(R.id.editText_value);

    // Checkbox
    mRingOnceCheckbox = (CheckBox) findViewById(R.id.checkbox_notif_ringonce);

    // URL
    mURL = getIntent().getExtras().getString(MainViewActivity.EXTRA_ADDRESS);

    // Client
    mClient.setMaxRetriesAndTimeout(2, 2000);

    // Retrieve sensors
    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    params.put("type", "listdev");
    params.put("id", String.valueOf(mSettings.getLong("device_id", -2)));

    final Activity context = this;
    final ProgressDialog progress = ProgressDialog.show(this, "",
            getResources().getString(R.string.retrieving_devices), false);

    mClient.get(mURL, params, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(JSONObject response) {
            try {
                // System
                JSONArray systemResponse = response.getJSONArray("System");

                int len = systemResponse.length();
                int lenTemp = 0;
                int lenFan = 0;
                int lenVolt = 0;

                for (int i = 0; i < len; i++) {
                    Sensor sensor = new Sensor(systemResponse.getJSONObject(i));

                    if (sensor.getType().equals("Temperature")) {
                        lenTemp++;
                    } else if (sensor.getType().equals("Fan")) {
                        lenFan++;
                    } else if (sensor.getType().equals("Voltage")) {
                        lenVolt++;
                    }
                }

                mSystemTempSensors = new Sensor[lenTemp];
                mSystemFanSensors = new Sensor[lenFan];
                mSystemVoltSensors = new Sensor[lenVolt];

                int iTemp = 0;
                int iFan = 0;
                int iVolt = 0;

                for (int i = 0; i < len; i++) {
                    Sensor sensor = new Sensor(systemResponse.getJSONObject(i));

                    if (sensor.getType().equals("Temperature")) {
                        mSystemTempSensors[iTemp] = sensor;
                        iTemp++;
                    } else if (sensor.getType().equals("Fan")) {
                        mSystemFanSensors[iFan] = sensor;
                        iFan++;
                    } else if (sensor.getType().equals("Voltage")) {
                        mSystemVoltSensors[iVolt] = sensor;
                        iVolt++;
                    }
                }

                // CPU
                JSONArray cpuResponse = response.getJSONArray("CPU");

                len = cpuResponse.length();
                lenTemp = 0;
                int lenLoad = 0;
                int lenClock = 0;
                int lenPower = 0;

                for (int i = 0; i < len; i++) {
                    Sensor sensor = new Sensor(cpuResponse.getJSONObject(i));

                    if (sensor.getType().equals("Temperature")) {
                        lenTemp++;
                    } else if (sensor.getType().equals("Load")) {
                        lenLoad++;
                    } else if (sensor.getType().equals("Clock")) {
                        lenClock++;
                    } else if (sensor.getType().equals("Power")) {
                        lenPower++;
                    }
                }

                mCPUTempSensors = new Sensor[lenTemp];
                mCPULoadSensors = new Sensor[lenLoad];
                mCPUPowerSensors = new Sensor[lenPower];
                mCPUClockSensors = new Sensor[lenClock];

                iTemp = 0;
                int iLoad = 0;
                int iPower = 0;
                int iClock = 0;

                for (int i = 0; i < len; i++) {
                    Sensor sensor = new Sensor(cpuResponse.getJSONObject(i));

                    if (sensor.getType().equals("Temperature")) {
                        mCPUTempSensors[iTemp] = sensor;
                        iTemp++;
                    } else if (sensor.getType().equals("Power")) {
                        mCPUPowerSensors[iPower] = sensor;
                        iPower++;
                    } else if (sensor.getType().equals("Clock")) {
                        mCPUClockSensors[iClock] = sensor;
                        iClock++;
                    } else if (sensor.getType().equals("Load")) {
                        mCPULoadSensors[iLoad] = sensor;
                        iLoad++;
                    }
                }

                // GPU
                JSONArray gpuResponse = response.getJSONArray("GPU");

                len = gpuResponse.length();
                lenTemp = 0;
                lenLoad = 0;
                lenClock = 0;
                lenFan = 0;

                for (int i = 0; i < len; i++) {
                    Sensor sensor = new Sensor(gpuResponse.getJSONObject(i));

                    if (sensor.getType().equals("Temperature")) {
                        lenTemp++;
                    } else if (sensor.getType().equals("Load")) {
                        lenLoad++;
                    } else if (sensor.getType().equals("Clock")) {
                        lenClock++;
                    } else if (sensor.getType().equals("Fan")) {
                        lenFan++;
                    }
                }

                mGPUTempSensors = new Sensor[lenTemp];
                mGPULoadSensors = new Sensor[lenLoad];
                mGPUFanSensors = new Sensor[lenFan];
                mGPUClockSensors = new Sensor[lenClock];

                iTemp = 0;
                iLoad = 0;
                iClock = 0;
                iFan = 0;

                for (int i = 0; i < len; i++) {
                    Sensor sensor = new Sensor(gpuResponse.getJSONObject(i));

                    if (sensor.getType().equals("Temperature")) {
                        mGPUTempSensors[iTemp] = sensor;
                        iTemp++;
                    } else if (sensor.getType().equals("Fan")) {
                        mGPUFanSensors[iFan] = sensor;
                        iFan++;
                    } else if (sensor.getType().equals("Clock")) {
                        mGPUClockSensors[iClock] = sensor;
                        iClock++;
                    } else if (sensor.getType().equals("Load")) {
                        mGPULoadSensors[iLoad] = sensor;
                        iLoad++;
                    }
                }

                // Prepare spinners
                setAdapter(mSensorSpinner, mSystemTempSensors);

                mTypeSpinner.setOnItemSelectedListener(new TypeOnItemSelectedListener());
                mDeviceSpinner.setOnItemSelectedListener(new DeviceOnItemSelectedListener());

                // Close window
                progress.hide();
            } catch (JSONException e) {
                Toast.makeText(context, getString(R.string.error_could_not_reach_host), Toast.LENGTH_LONG)
                        .show();
                progress.hide();
            }
        }

        @Override
        public void onFailure(Throwable error, String content) {
            Toast.makeText(context, getString(R.string.error_could_not_reach_host) + ":" + error.getMessage(),
                    Toast.LENGTH_LONG).show();
            finish();
            progress.hide();
            Log.e("Notif", error.getMessage());
        }
    });
}

From source file:org.loklak.api.geo.GeocodeServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Query post = RemoteAccess.evaluate(request);

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;/*from w ww  .ja  v a2 s  .  co  m*/
    }

    // parameters
    String callback = post.get("callback", "");
    boolean jsonp = callback != null && callback.length() > 0;
    boolean minified = post.get("minified", false);
    String data = post.get("data", "");
    String places = post.get("places", "");
    if (places.length() == 0 && data.length() == 0) {
        response.sendError(503,
                "you must submit a data attribut with a json containing the property 'places' with a list of place names");
        return;
    }

    String[] place = new String[0];
    if (places.length() > 0) {
        place = places.split(",");
    } else {
        // parse the json data
        try {
            JSONObject json = new JSONObject(data);
            if (json.has("places") && json.get("places") instanceof JSONArray) {
                JSONArray p = json.getJSONArray("places");
                place = new String[p.length()];
                int i = 0;
                for (Object o : p)
                    place[i++] = (String) o;
            } else {
                response.sendError(400, "submitted data is not well-formed: expected a list of strings");
                return;
            }
        } catch (IOException e) {
            Log.getLog().warn(e);
        }
    }

    // find locations for places
    JSONObject locations = new JSONObject(true);
    for (String p : place) {
        GeoMark loc = DAO.geoNames.analyse(p, null, 5, Long.toString(System.currentTimeMillis()));
        if (loc != null) {
            locations.put(p, loc.toJSON(minified));
        } else {
            locations.put(p, new JSONObject());
        }
    }

    post.setResponse(response, "application/javascript");

    // generate json
    JSONObject m = new JSONObject(true);
    m.put("locations", locations);

    // write json
    response.setCharacterEncoding("UTF-8");
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print(m.toString(minified ? 0 : 2));
    if (jsonp)
        sos.println(");");
    sos.println();
    post.finalize();
}

From source file:com.spoiledmilk.cykelsuperstier.break_rote.BreakRouteActivity.java

private void parseStationsFromJson() {
    metroStations = new ArrayList<OverlayData>();
    sTrainStations = new ArrayList<OverlayData>();
    localTrainStations = new ArrayList<OverlayData>();
    try {//from  ww  w . ja  v  a  2 s .  co m
        String stationsStr = Util.stringFromJsonAssets(this, "stations/stations.json");
        JSONArray stationsJson = (new JSONObject(stationsStr)).getJSONArray("stations");
        for (int i = 0; i < stationsJson.length(); i++) {
            JSONObject stationJson = (JSONObject) stationsJson.get(i);
            if (!stationJson.has("coords"))
                continue;
            String[] coords = stationJson.getString("coords").split("\\s+");
            String type = stationJson.getString("type");
            if (type.equals("service")) {
                continue;
            } else if (type.equals("metro")) {
                metroStations.add(new OverlayData(stationJson.getString("name"), stationJson.getString("line"),
                        Double.parseDouble(coords[1]), Double.parseDouble(coords[0]),
                        R.drawable.metro_logo_pin));
            } else if (type.equals("s-train")) {
                sTrainStations.add(new OverlayData(stationJson.getString("name"), stationJson.getString("line"),
                        Double.parseDouble(coords[1]), Double.parseDouble(coords[0]),
                        R.drawable.list_subway_icon));
            } else if (type.equals("local-train")) {
                localTrainStations.add(new OverlayData(stationJson.getString("name"),
                        stationJson.getString("line"), Double.parseDouble(coords[1]),
                        Double.parseDouble(coords[0]), R.drawable.list_subway_icon));
            }
        }
    } catch (Exception e) {
        LOG.e(e.getLocalizedMessage());
    }
}

From source file:com.cssweb.android.view.KlineViewSingle.java

/**
 * ??/*  ww  w .  j a  v  a  2  s . co  m*/
 * @throws JSONException 
 */
private void makeTodayData() throws JSONException {
    int l = quoteData.getJSONArray("K").length();
    if (quoteData.isNull("joTMP")) {//temp??
        newStockhandler();
        return;
    }
    if (!quoteData.getBoolean("tradeFlag")) {
        //??????
        //???0??
        return;
    }
    JSONObject tempvalue = quoteData.getJSONObject("joTMP");
    double zrsp = quoteData.getDouble("zrsp");
    period = quoteData.getString("period");
    if (period.equals("week") || period.equals("month") || period.equals("year")) {
        if (tempvalue.getString(period) != null) {
            if (tempvalue.isNull("ma") || quoteData.isNull("MA") || quoteData.isNull("K")) {
                makeTmpData();
                return;
            }
            int tp = quoteData.getInt("tp");
            if (tp == 1) {
                String date = tempvalue.getJSONObject(period).getString("date");
                if (DateTool.isSameWeekMonthYear(date, period)) {
                    quoteData.getJSONArray("K").getJSONArray(l - 1).put(1,
                            tempvalue.getJSONObject(period).getDouble("open"));
                    quoteData.getJSONArray("K").getJSONArray(l - 1).put(2,
                            tempvalue.getJSONObject(period).getDouble("high"));
                    quoteData.getJSONArray("K").getJSONArray(l - 1).put(3,
                            tempvalue.getJSONObject(period).getDouble("low"));
                    quoteData.getJSONArray("K").getJSONArray(l - 1).put(4, zrsp);
                    quoteData.getJSONArray("K").getJSONArray(l - 1).put(5,
                            tempvalue.getJSONObject(period).getDouble("cjsl"));
                    quoteData.getJSONArray("K").getJSONArray(l - 1).put(6,
                            tempvalue.getJSONObject(period).getDouble("cjje"));
                    //quoteData.getJSONArray("K").getJSONArray(l-1).put(0, ) ;
                    zrsp = tempvalue.getJSONObject(period).getDouble("close");
                }
            } else {
                int spayday = quoteData.getInt("spday");
                double cjsl = quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(5);
                double cjje = quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(6);
                if (spayday == 0) {//0??temp?????
                    quoteData.getJSONArray("K").getJSONArray(l - 1).put(2,
                            Math.max(quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(2),
                                    tempvalue.getJSONObject(period).getDouble("high")));
                    quoteData.getJSONArray("K").getJSONArray(l - 1).put(3,
                            Math.min(quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(3),
                                    tempvalue.getJSONObject(period).getDouble("low")));
                    quoteData.getJSONArray("K").getJSONArray(l - 1).put(5,
                            cjsl + tempvalue.getJSONObject(period).getDouble("cjsl"));
                    quoteData.getJSONArray("K").getJSONArray(l - 1).put(6,
                            cjje + tempvalue.getJSONObject(period).getDouble("cjje"));
                } else {
                    quoteData.getJSONArray("K").getJSONArray(l - 1).put(2,
                            Math.max(quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(2),
                                    tempvalue.getJSONObject(period).getDouble("high")));
                    quoteData.getJSONArray("K").getJSONArray(l - 1).put(3,
                            Math.min(quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(3),
                                    tempvalue.getJSONObject(period).getDouble("low")));
                    quoteData.getJSONArray("K").getJSONArray(l - 1).put(5,
                            tempvalue.getJSONObject(period).getDouble("cjsl"));
                    quoteData.getJSONArray("K").getJSONArray(l - 1).put(6,
                            tempvalue.getJSONObject(period).getDouble("cjje"));
                }
                double jrkp = tempvalue.getJSONObject(period).getDouble("open");
                if (jrkp != 0) {
                    quoteData.getJSONArray("K").getJSONArray(l - 1).put(1, jrkp);
                }
                zrsp = tempvalue.getJSONObject(period).getDouble("close");
            }
        }
    }

    String qt = quoteData.getJSONArray("K").getJSONArray(l - 1).getString(0);
    double high = quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(2);
    double low = quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(3);
    double zjcj = quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(4);
    double cjsl = quoteData.getJSONArray("K").getJSONArray(l - 1).getDouble(5);

    double summa4 = tempvalue.getJSONObject("ma").getDouble("sumMa4");
    double summa9 = tempvalue.getJSONObject("ma").getDouble("sumMa9");
    double summa19 = tempvalue.getJSONObject("ma").getDouble("sumMa19");
    double summa59 = tempvalue.getJSONObject("ma").getDouble("sumMa59");
    double sumvolma4 = tempvalue.getJSONObject("ma").getDouble("sumMavol4");
    double sumvolma9 = tempvalue.getJSONObject("ma").getDouble("sumMavol9");

    if (mainIndicatorType.toUpperCase().equals("MA") || mainIndicatorType.toUpperCase().equals("BOLL")) {
        quoteData.getJSONArray("MA").put(new JSONArray());
        quoteData.getJSONArray("MA").getJSONArray(l - 1).put(0, qt);
        double ma5 = 0;
        if (l > 4)
            ma5 = (summa4 + zjcj) / 5;
        quoteData.getJSONArray("MA").getJSONArray(l - 1).put(1, ma5);
        double ma10 = 0;
        if (l > 9)
            ma10 = (summa9 + zjcj) / 10;
        quoteData.getJSONArray("MA").getJSONArray(l - 1).put(2, ma10);
        double ma20 = 0;
        if (l > 19)
            ma20 = (summa19 + zjcj) / 20;
        quoteData.getJSONArray("MA").getJSONArray(l - 1).put(3, ma20);
        double ma60 = 0;
        if (l > 59)
            ma60 = (summa59 + zjcj) / 60;
        quoteData.getJSONArray("MA").getJSONArray(l - 1).put(4, ma60);
    }
    double mavol5 = (sumvolma4 + cjsl) / 5;
    quoteData.getJSONArray("MA").getJSONArray(l - 1).put(5, mavol5);

    double mavol10 = (sumvolma9 + cjsl) / 10;
    quoteData.getJSONArray("MA").getJSONArray(l - 1).put(6, mavol10);

    if (mainIndicatorType.equals("BOLL")) {
        quoteData.getJSONArray("BOLL").put(new JSONArray());
        double mid = 0;
        double upper = 0;
        double lower = 0;
        if (l > 25) {
            double sumClose = tempvalue.getJSONObject("boll").getDouble("sumClose");
            double sumPowClose = tempvalue.getJSONObject("boll").getDouble("sumPowClose");
            double maPow = 0;
            double temp;
            if (l > 25) {
                mid = (sumClose + zjcj) / 26;
                maPow = (sumPowClose + zjcj * zjcj) / 26;
                temp = (maPow - mid * mid);
                if (temp < 0)
                    temp = 0;
                upper = mid + 2 * Math.sqrt((temp * 26) / (26 - 1));
                lower = mid - 2 * Math.sqrt((temp * 26) / (26 - 1));
            }
        }

        quoteData.getJSONArray("BOLL").getJSONArray(l - 1).put(0, qt);
        quoteData.getJSONArray("BOLL").getJSONArray(l - 1).put(1, mid);
        quoteData.getJSONArray("BOLL").getJSONArray(l - 1).put(2, upper);
        quoteData.getJSONArray("BOLL").getJSONArray(l - 1).put(3, lower);
    }

    if (indicatorType.equals("MACD")) {
        quoteData.getJSONArray("MACD").put(new JSONArray());
        double prevemashort = 0;
        double prevemalong = 0;
        double prevdea = 0;
        double dif = 0;
        double dea = 0;
        double macd = 0;
        double emashort = 0;
        double emalong = 0;

        prevemashort = tempvalue.getJSONObject("macd").getDouble("emaShort");
        prevemalong = tempvalue.getJSONObject("macd").getDouble("emaLong");
        prevdea = tempvalue.getJSONObject("macd").getDouble("dea");

        if (l > 1) {
            emashort = (2 * zjcj + (12 - 1) * prevemashort) / (12 + 1);
            emalong = (2 * zjcj + (26 - 1) * prevemalong) / (26 + 1);
            dif = emashort - emalong;
            dea = (2 * dif + (9 - 1) * prevdea) / (9 + 1);
            macd = (dif - dea) * 2;
        }

        quoteData.getJSONArray("MACD").getJSONArray(l - 1).put(0, qt);
        quoteData.getJSONArray("MACD").getJSONArray(l - 1).put(1, dif);
        quoteData.getJSONArray("MACD").getJSONArray(l - 1).put(2, dea);
        quoteData.getJSONArray("MACD").getJSONArray(l - 1).put(3, macd);
    }
    if (indicatorType.equals("BIAS")) {
        quoteData.getJSONArray("BIAS").put(new JSONArray());
        double sum5 = tempvalue.getJSONObject("bias").getDouble("sum5");
        double sum11 = tempvalue.getJSONObject("bias").getDouble("sum11");
        double sum23 = tempvalue.getJSONObject("bias").getDouble("sum23");

        double bias1 = l >= 6 ? (zjcj - (sum5 + zjcj) / 6) / ((sum5 + zjcj) / 6) * 100 : 0;
        double bias2 = l >= 12 ? (zjcj - (sum11 + zjcj) / 12) / ((sum11 + zjcj) / 12) * 100 : 0;
        double bias3 = l >= 24 ? (zjcj - (sum23 + zjcj) / 24) / ((sum23 + zjcj) / 24) * 100 : 0;
        quoteData.getJSONArray("BIAS").getJSONArray(l - 1).put(0, qt);
        quoteData.getJSONArray("BIAS").getJSONArray(l - 1).put(1, bias1);
        quoteData.getJSONArray("BIAS").getJSONArray(l - 1).put(2, bias2);
        quoteData.getJSONArray("BIAS").getJSONArray(l - 1).put(3, bias3);
    }
    if (indicatorType.equals("RSI")) {
        quoteData.getJSONArray("RSI").put(new JSONArray());

        double rsi1 = 0;
        double rsi2 = 0;
        double rsi3 = 0;

        if (l > 1 && tempvalue.has("rsi")) {
            double smaMax1 = tempvalue.getJSONObject("rsi").getDouble("smaMax1");
            double smaMax2 = tempvalue.getJSONObject("rsi").getDouble("smaMax2");
            double smaMax3 = tempvalue.getJSONObject("rsi").getDouble("smaMax3");
            double smaAbs1 = tempvalue.getJSONObject("rsi").getDouble("smaAbs1");
            double smaAbs2 = tempvalue.getJSONObject("rsi").getDouble("smaAbs2");
            double smaAbs3 = tempvalue.getJSONObject("rsi").getDouble("smaAbs3");

            double rsiMax1 = (Math.max(zjcj - zrsp, 0.0) * 1 + smaMax1 * (6 - 1)) / 6;
            double rsiAbs1 = (Math.abs(zjcj - zrsp) * 1 + smaAbs1 * (6 - 1)) / 6;
            if (rsiAbs1 == 0)
                rsi1 = 0;
            else
                rsi1 = rsiMax1 / rsiAbs1 * 100;

            double rsiMax2 = (Math.max(zjcj - zrsp, 0.0) * 1 + smaMax2 * (12 - 1)) / 12;
            double rsiAbs2 = (Math.abs(zjcj - zrsp) * 1 + smaAbs2 * (12 - 1)) / 12;
            if (rsiAbs2 == 0)
                rsi2 = 0;
            else
                rsi2 = rsiMax2 / rsiAbs2 * 100;

            double rsiMax3 = (Math.max(zjcj - zrsp, 0.0) * 1 + smaMax3 * (24 - 1)) / 24;
            double rsiAbs3 = (Math.abs(zjcj - zrsp) * 1 + smaAbs3 * (24 - 1)) / 24;
            if (rsiAbs3 == 0)
                rsi3 = 0;
            else
                rsi3 = rsiMax3 / rsiAbs3 * 100;
        }
        quoteData.getJSONArray("RSI").getJSONArray(l - 1).put(0, qt);
        quoteData.getJSONArray("RSI").getJSONArray(l - 1).put(1, rsi1);
        quoteData.getJSONArray("RSI").getJSONArray(l - 1).put(2, rsi2);
        quoteData.getJSONArray("RSI").getJSONArray(l - 1).put(3, rsi3);
    }
    if (indicatorType.equals("KDJ")) {
        quoteData.getJSONArray("KDJ").put(new JSONArray());
        double newk = 0;
        double newd = 0;
        double newj = 0;

        if (l > 1 && tempvalue.has("kdj")) {
            double K = quoteData.getJSONArray("KDJ").getJSONArray(l - 2).getDouble(1);
            double D = quoteData.getJSONArray("KDJ").getJSONArray(l - 2).getDouble(2);
            double HHV = tempvalue.getJSONObject("kdj").getDouble("hhv");
            double LLV = tempvalue.getJSONObject("kdj").getDouble("llv");
            double nowllv = 0.0;

            if (LLV < low) // l?
                nowllv = LLV;
            else
                nowllv = low;

            double nowhhv = 0.0;
            if (HHV > high)
                nowhhv = HHV;
            else
                nowhhv = high;
            double rsv;
            if (Math.abs(nowhhv - nowllv) < 0.0001) {
                rsv = 0;
            } else {
                rsv = (zjcj - nowllv) / (nowhhv - nowllv) * 100;
            }
            newk = (rsv * 1 + K * (3 - 1)) / 3;
            newd = (newk * 1 + D * (3 - 1)) / 3;
            newj = 3 * newk - 2 * newd;
        }
        quoteData.getJSONArray("KDJ").getJSONArray(l - 1).put(0, qt);
        quoteData.getJSONArray("KDJ").getJSONArray(l - 1).put(1, newk);
        quoteData.getJSONArray("KDJ").getJSONArray(l - 1).put(2, newd);
        quoteData.getJSONArray("KDJ").getJSONArray(l - 1).put(3, newj);
    }
    if (indicatorType.equals("CCI")) {
        quoteData.getJSONArray("CCI").put(new JSONArray());
        double CCI = 0;
        if (l > 13 && tempvalue.has("cci")) {
            JSONArray typlist = tempvalue.getJSONObject("cci").getJSONArray("typ");
            double sumTyp = 0;
            double TYP = (zjcj + high + low) / 3;
            double rit = 0;
            for (int i = 0; i < typlist.length(); i++) {
                rit = typlist.getDouble(i);
                if (i == 13)
                    break;
                sumTyp += rit;
            }
            sumTyp += TYP;
            double ma = sumTyp / 14;

            sumTyp = 0;
            for (int i = 0; i < typlist.length(); i++) {
                rit = typlist.getDouble(i);
                if (i == 13)
                    break;
                sumTyp += Math.abs(rit - ma);
            }
            sumTyp += Math.abs(TYP - ma);
            double avedev = sumTyp / 14;

            if (avedev == 0)
                CCI = 0;
            else
                CCI = (TYP - ma) / (0.015 * avedev);
        }
        quoteData.getJSONArray("CCI").getJSONArray(l - 1).put(0, qt);
        quoteData.getJSONArray("CCI").getJSONArray(l - 1).put(1, CCI);
    }
    if (indicatorType.equals("OBV")) {
        quoteData.getJSONArray("OBV").put(new JSONArray());
        double obv = 0, maobv = 0;
        if (tempvalue.has("obv")) {
            if (zjcj > zrsp) {
                obv = tempvalue.getJSONObject("obv").getDouble("obv") + cjsl;
            }
            if (zjcj == zrsp) {
                obv = 0;
            }
            if (zjcj < zrsp) {
                obv = tempvalue.getJSONObject("obv").getDouble("obv") - cjsl;
            }
            if (l >= 29) {
                maobv = (tempvalue.getJSONObject("obv").getDouble("sumObv29") + obv) / 30;
            } else {
                maobv = 0;
            }
        }
        quoteData.getJSONArray("OBV").getJSONArray(l - 1).put(0, qt);
        quoteData.getJSONArray("OBV").getJSONArray(l - 1).put(1, obv);
        quoteData.getJSONArray("OBV").getJSONArray(l - 1).put(2, maobv);
    }
    if (indicatorType.equals("PSY")) {
        quoteData.getJSONArray("PSY").put(new JSONArray());
        double countPsy = 0, psy = 0, psyma = 0;
        if (zjcj > zrsp) {
            countPsy = 1;
        } else {
            countPsy = 0;
        }
        if (l >= 11 && tempvalue.has("psy")) {
            countPsy += tempvalue.getJSONObject("psy").getDouble("psyCount11");
            psy = countPsy / 12 * 100;
            psyma = (tempvalue.getJSONObject("psy").getDouble("sumPsy") + psy) / 6;
        } else {
            psy = 0;
        }
        quoteData.getJSONArray("PSY").getJSONArray(l - 1).put(0, qt);
        quoteData.getJSONArray("PSY").getJSONArray(l - 1).put(1, psy);
        quoteData.getJSONArray("PSY").getJSONArray(l - 1).put(2, psyma);
    }
    if (indicatorType.equals("ROC")) {
        quoteData.getJSONArray("ROC").put(new JSONArray());
        double roc = 0, rocma = 0;
        if (l > 12 && tempvalue.has("roc")) {
            double refClose12 = tempvalue.getJSONObject("roc").getDouble("refClose12");
            if (refClose12 == 0) {
                roc = 0;
            } else {
                roc = 100 * (zjcj - refClose12) / refClose12;
            }
            rocma = (tempvalue.getJSONObject("roc").getDouble("sumRoc") + roc) / 6;
        } else {
            roc = 0;
        }
        quoteData.getJSONArray("ROC").getJSONArray(l - 1).put(0, qt);
        quoteData.getJSONArray("ROC").getJSONArray(l - 1).put(1, roc);
        quoteData.getJSONArray("ROC").getJSONArray(l - 1).put(2, rocma);
    }
    if (indicatorType.equals("WR")) {
        quoteData.getJSONArray("WR").put(new JSONArray());
        double wr = 0, wr2 = 0;
        if (l > 9 && tempvalue.has("wr")) {
            double llv = tempvalue.getJSONObject("wr").getDouble("llv");
            double hhv = tempvalue.getJSONObject("wr").getDouble("hhv");
            hhv = Math.max(hhv, high);
            llv = Math.min(llv, low);
            if (hhv == llv) {
                wr = 0;
            } else {
                wr = 100 * (hhv - zjcj) / (hhv - llv);
            }
        } else {
            wr = 0;
        }
        if (l > 5 && tempvalue.has("wr")) {
            double llv2 = tempvalue.getJSONObject("wr").getDouble("llv2");
            double hhv2 = tempvalue.getJSONObject("wr").getDouble("hhv2");

            hhv2 = Math.max(hhv2, high);
            llv2 = Math.min(llv2, low);
            if (hhv2 == llv2) {
                wr2 = 0;
            } else {
                wr2 = 100 * (hhv2 - zjcj) / (hhv2 - llv2);
            }
        } else {
            wr2 = 0;
        }
        quoteData.getJSONArray("WR").getJSONArray(l - 1).put(0, qt);
        quoteData.getJSONArray("WR").getJSONArray(l - 1).put(1, wr);
        quoteData.getJSONArray("WR").getJSONArray(l - 1).put(2, wr2);
    }
    if (indicatorType.equals("VR")) {
        quoteData.getJSONArray("VR").put(new JSONArray());
        double vr = 0, vrma = 0;
        if (l >= 24 && tempvalue.has("vr")) {
            double sum1 = tempvalue.getJSONObject("vr").getDouble("sum1");
            double sum2 = tempvalue.getJSONObject("vr").getDouble("sum2");
            if (zjcj > zrsp) {
                sum1 += cjsl;
            } else {
                sum2 += cjsl;
            }
            if (sum2 == 0) {
                vr = 0;
            } else {
                vr = 100 * sum1 / sum2;
            }
        } else {
            vr = 0;
        }
        if (l >= 6)
            vrma = (tempvalue.getJSONObject("vr").getDouble("sumVr") + vr) / 6;
        quoteData.getJSONArray("VR").getJSONArray(l - 1).put(0, qt);
        quoteData.getJSONArray("VR").getJSONArray(l - 1).put(1, vr);
        quoteData.getJSONArray("VR").getJSONArray(l - 1).put(2, vrma);
    }
}

From source file:br.com.indigo.android.facebook.SocialFacebook.java

private void handleFeedResponse(JSONObject jsonResponse, FeedListener listener) {
    FbSimplePost post;/*  w  w w  . j  ava2 s. com*/
    ArrayList<FbSimplePost> posts = new ArrayList<FbSimplePost>();

    try {
        JSONArray objs = jsonResponse.getJSONArray("data");

        for (int i = 0; i < objs.length(); i++) {
            JSONObject obj = objs.getJSONObject(i);

            post = new FbSimplePost();
            post.setId(obj.getString("id"));

            JSONObject fromJson = obj.optJSONObject("from");
            if (fromJson != null) {
                FbSimpleUser from = new FbSimpleUser();
                from.setId(fromJson.getString("id"));
                from.setName(fromJson.getString("name"));

                post.setFrom(from);
            }

            post.setMessage(obj.optString("message"));
            post.setPicture(obj.optString("picture"));
            post.setLink(obj.optString("link"));
            post.setName(obj.optString("name"));
            post.setCaption(obj.optString("caption"));
            post.setDescription(obj.optString("description"));
            post.setSource(obj.optString("source"));
            post.setType(obj.optString("type"));

            post.setCreatedTime(new Date(obj.getLong("created_time")));
            post.setUpdatedTime(new Date(obj.getLong("updated_time")));

            JSONObject comments = obj.optJSONObject("comments");
            if (comments != null) {
                post.setNumberOfComments(comments.getInt("count"));
            }

            JSONObject likes = obj.optJSONObject("likes");
            if (likes != null) {
                post.setNumberOfLikes(likes.getInt("count"));
            }

            posts.add(post);
        }

        String nextPage = null;
        JSONObject paging = jsonResponse.optJSONObject("paging");
        if (paging != null) {
            nextPage = paging.optString("next");
        }

        listener.onComplete(posts, nextPage);

    } catch (JSONException e) {
        Util.logd(TAG, "Could not parse Json response", e);
        listener.onFail(e);
    }
}

From source file:br.com.indigo.android.facebook.SocialFacebook.java

private void handleUsersResponse(JSONObject jsonResponse, UsersListener listener) {

    FbSimpleUser user = null;//w w  w  .  j  a  va  2  s .com
    ArrayList<FbSimpleUser> friends = new ArrayList<FbSimpleUser>();

    try {
        JSONArray objs = jsonResponse.getJSONArray("data");

        for (int i = 0; i < objs.length(); i++) {
            JSONObject obj = objs.getJSONObject(i);

            user = new FbSimpleUser();
            user.setId(obj.getString("id"));
            user.setName(obj.getString("name"));

            String rsvpStatus = obj.optString("rsvp_status");

            if (rsvpStatus != null) {
                if (rsvpStatus.equals("not_replied")) {
                    user.setRSVPStatus(RSVP_STATUS.NOT_REPLIED);
                } else if (rsvpStatus.equals("attending")) {
                    user.setRSVPStatus(RSVP_STATUS.ATTENDING);
                } else if (rsvpStatus.equals("declined")) {
                    user.setRSVPStatus(RSVP_STATUS.DECLINED);
                } else if (rsvpStatus.equals("unsure")) {
                    user.setRSVPStatus(RSVP_STATUS.MAYBE);
                }
            }

            friends.add(user);
        }

        String nextPage = null;
        JSONObject paging = jsonResponse.optJSONObject("paging");
        if (paging != null) {
            nextPage = paging.optString("next");
        }

        listener.onComplete(friends, nextPage);

    } catch (JSONException e) {
        Util.logd(TAG, "Could not parse Json response", e);
        listener.onFail(e);
    }
}