Java tutorial
import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import static java.lang.Math.atan2; import static java.lang.Math.sin; import static java.lang.Math.cos; import static java.lang.Math.pow; import static java.lang.Math.sqrt; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.WindowConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author LU$er */ public class Main_Window extends JFrame implements ActionListener { private final String API_KEY = "AIzaSyAd5ABfTtt0UT_K5GKs2e-yPhXgQP2vAqU"; private HttpURLConnection Connection = null, Test_Connection = null; private URL ServerAddress = null, Url_Trial = null; private DataOutputStream wr = null; private ArrayList<Point> POI_List = new ArrayList<Point>(); private ArrayList<Number_Name> Temp_List = new ArrayList<Number_Name>(); //Keeps index and name in order to display in ascending order private ArrayList<Double> Distances_List = new ArrayList<Double>(); //Keeps distances of every POI from user long and lat private ArrayList<Double> Distances_List_2 = new ArrayList<Double>(); private final String TEST_URL = "http://www.google.com"; private final String PHOTO_URL = "https://maps.googleapis.com/maps/api/place/photo?"; // J Components private static JButton Retrieve_POIs_Button = null; private static JLabel Welcome_Label = null, Latitude_Label = null, Longitude_Label = null, Radius_Label = null, Category_Label = null, POIS_Label = null; private static JTextField Latitude_TextField = null, Longitude_TextField = null, Radius_TextField = null; private static JComboBox Categories = null; private static final String[] Categories_Names = { "lodging", "food", "cafe", "night_club", "car_rental", "museum", "church", "hospital", "pharmacy", "police", "post_office" }; private static JRadioButton Open_Status = null; private Container pane = null; private JPanel P = null; private static JList list = null; private String strData = null, Temp_Name = null, Encode_String = null, Temp_Address = null; private BufferedReader Buffered_Reader = null; private JSONObject JsonObject = null; private JSONParser jsonParser = null; private double Temp_Rating, Temp_X, Temp_Y; private static JLabel Distance_L = new JLabel(), Address_L = new JLabel(), Rating_L = new JLabel(), IMAGE_LABEL = new JLabel(); //Public Constructor- Default public Main_Window() { super("Google Places Application"); //First call Constructor of JFrame this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //We do not want our application to terminate when a JFrame is closed this.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { int Answer = JOptionPane.showConfirmDialog(null, "Exit Application ? ", "Exit ? ", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (Answer == JOptionPane.YES_OPTION) { if (POI_List.isEmpty()) { POI_List.clear(); } if (Distances_List.isEmpty()) { Distances_List.clear(); } if (Temp_List.isEmpty()) { Temp_List.clear(); } if (Distances_List_2.isEmpty()) { Distances_List_2.clear(); } System.exit(1); } else { setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); } } }); //The listener object created from that class is then registered with a Window using the window's addWindowListener method. // this.setSize(1100, 700); // Size of Window this.setLocationRelativeTo(null); // Display Window in center of Screen this.setVisible(true); this.getContentPane().setBackground(Color.LIGHT_GRAY); // //Initialization of J Components POIS_Label = new JLabel("Points of Interest:"); POIS_Label.setForeground(Color.black); POIS_Label.setFont(new Font("Courier New", Font.BOLD, 25)); POIS_Label.setBounds(600, 30, 350, 150); Retrieve_POIs_Button = new JButton("Retrieve POIs"); Retrieve_POIs_Button.setForeground(Color.black); Retrieve_POIs_Button.setFont(new Font("Courier New", Font.BOLD, 35)); Retrieve_POIs_Button.setBounds(25, 450, 350, 150); Open_Status = new JRadioButton(" Open Now?"); Open_Status.setForeground(Color.black); Open_Status.setBackground(Color.LIGHT_GRAY); Open_Status.setBounds(20, 380, 100, 30); Welcome_Label = new JLabel("Welcome to Google Places"); Welcome_Label.setForeground(Color.BLUE); Welcome_Label.setFont(new Font("Courier New", Font.BOLD, 35)); Welcome_Label.setBounds(240, 20, 600, 60); Latitude_Label = new JLabel("Latitude:"); Latitude_Label.setForeground(Color.BLACK); Latitude_Label.setFont(new Font("Courier New", Font.PLAIN, 25)); Latitude_Label.setBounds(15, 80, 200, 100); Longitude_Label = new JLabel("Longitude:"); Longitude_Label.setForeground(Color.BLACK); Longitude_Label.setFont(new Font("Courier New", Font.PLAIN, 25)); Longitude_Label.setBounds(15, 130, 250, 100); Radius_Label = new JLabel("Radius:"); Radius_Label.setForeground(Color.BLACK); Radius_Label.setFont(new Font("Courier New", Font.PLAIN, 25)); Radius_Label.setBounds(15, 180, 250, 100); Category_Label = new JLabel("Category:"); Category_Label.setForeground(Color.BLACK); Category_Label.setFont(new Font("Courier New", Font.PLAIN, 25)); Category_Label.setBounds(15, 250, 250, 100); Latitude_TextField = new JTextField(7); Latitude_TextField.setForeground(Color.BLACK); Latitude_TextField.setBounds(165, 116, 180, 30); Longitude_TextField = new JTextField(7); Longitude_TextField.setForeground(Color.BLACK); Longitude_TextField.setBounds(170, 168, 180, 30); Radius_TextField = new JTextField(7); Radius_TextField.setForeground(Color.BLACK); Radius_TextField.setBounds(125, 215, 180, 30); Categories = new JComboBox(Categories_Names); Categories.setForeground(Color.BLACK); Categories.setBackground(Color.white); Categories.setBounds(15, 320, 180, 30); POI_List = new ArrayList(); pane = getContentPane(); //Manager pane.setLayout(null); // Deactivate Manager Layout //JPANEL P = new JPanel(); P.setBackground(Color.GRAY); P.setBounds(600, 120, 450, 180); P.setBackground(Color.GRAY); pane.add(P); pane.add(POIS_Label); pane.add(Retrieve_POIs_Button); pane.add(Welcome_Label); pane.add(Longitude_Label); pane.add(Latitude_Label); pane.add(Radius_Label); pane.add(Category_Label); pane.add(Latitude_TextField); pane.add(Longitude_TextField); pane.add(Radius_TextField); pane.add(Categories); pane.add(Open_Status); Retrieve_POIs_Button.addActionListener(this); setContentPane(pane); } //End of Constructor BLock //Assisting Methods public boolean Blank_Fileds_Checker() //true if everything is Ok { if (!Latitude_TextField.getText().equals("")) { if (!Longitude_TextField.getText().equals("")) { if (!Radius_TextField.getText().equals("")) { return true; } JOptionPane.showMessageDialog(null, "Please insert all Fields"); return false; } JOptionPane.showMessageDialog(null, "Please insert all Fields"); return false; } JOptionPane.showMessageDialog(null, "Please insert all Fields"); return false; } public boolean Validility_Fields_Checker() { try { Double.parseDouble(Latitude_TextField.getText()); Double.parseDouble(Longitude_TextField.getText()); Double.parseDouble(Radius_TextField.getText()); return true; } catch (Exception IOE) { JOptionPane.showMessageDialog(null, "Only numbers are allowed"); Latitude_TextField.setText(""); Longitude_TextField.setText(""); Radius_TextField.setText(""); return false; } } public boolean Open_Status_Checker() { if (Open_Status.isSelected()) { return true; } return false; } public boolean Connectivity_Checker() { try { try { Url_Trial = new URL(TEST_URL); Test_Connection = (HttpURLConnection) Url_Trial.openConnection(); Test_Connection.connect(); if (Test_Connection.getResponseCode() == 200) { return true; } JOptionPane.showMessageDialog(null, "Connection Error"); return false; } catch (Exception exception) { JOptionPane.showMessageDialog(null, "Connection Error"); return false; } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Connection Error"); return false; } } public void Send_Receive_Data_Google_Service(boolean State) { try { ServerAddress = new URL("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + Double.parseDouble(Latitude_TextField.getText()) + "," + Double.parseDouble(Longitude_TextField.getText()) + "&radius=" + Double.parseDouble(Radius_TextField.getText()) + "&opennow=" + Boolean.toString(State) + "&types=" + Categories.getSelectedItem().toString() + "&key=" + API_KEY); //DELTE String str = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + Double.parseDouble(Latitude_TextField.getText()) + "," + Double.parseDouble(Longitude_TextField.getText()) + "&radius=" + Double.parseDouble(Radius_TextField.getText()) + "&opennow=" + Boolean.toString(State) + "&types=" + Categories.getSelectedItem().toString() + "&key=" + API_KEY; System.out.println(" To url einai -> " + str); //set up out communications stuff Connection = null; //Set up the initial connection Connection = (HttpURLConnection) ServerAddress.openConnection(); Connection.setRequestMethod("GET"); Connection.setDoOutput(true); //Set the DoOutput flag to true if you intend to use the URL connection for output Connection.setDoInput(true); Connection.setRequestProperty("Content-type", "text/xml"); //Sets the general request property Connection.setAllowUserInteraction(false); Encode_String = URLEncoder.encode("test", "UTF-8"); Connection.setRequestProperty("Content-length", "" + Encode_String.length()); Connection.setReadTimeout(10000); // A non-zero value specifies the timeout when reading from Input stream when a connection is established to a resource. //If the timeout expires before there is data available for read, a java.net.SocketTimeoutException is raised. } catch (IOException IOE) { JOptionPane.showMessageDialog(null, "Error -> " + IOE.getLocalizedMessage(), "Exception - IOException", JOptionPane.ERROR_MESSAGE, null); } try { wr = new DataOutputStream(Connection.getOutputStream()); //open output stream to write } catch (IOException IOE) { JOptionPane.showMessageDialog(null, "Error -> " + IOE.getLocalizedMessage(), "Exception - IOException", JOptionPane.ERROR_MESSAGE, null); } try { wr.writeBytes("q=" + strData); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(), "Exception - IOException", JOptionPane.ERROR_MESSAGE, null); } try { wr.flush(); //Force all data to write in channel } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(), "Exception - IOException", JOptionPane.ERROR_MESSAGE, null); } try { //read the result from the server Buffered_Reader = new BufferedReader(new InputStreamReader(Connection.getInputStream())); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(), "Exception - IOException", JOptionPane.ERROR_MESSAGE, null); } jsonParser = new JSONParser(); //JSON Parser try { JsonObject = (JSONObject) jsonParser.parse(Buffered_Reader); //Parse whole BuffererReader IN Object JSONArray Results_Array_Json = (JSONArray) JsonObject.get("results"); //take whole array - from json format //results - is as string unique that contains all the essential information such as arrays, and strings. So to extract all info we extract results into JSONarray //And this comes up due to json format for (int i = 0; i < Results_Array_Json.size(); i++) // Loop over each each part of array that contains info we must extract { JSONObject o = (JSONObject) Results_Array_Json.get(i); try { //We assume that for every POI exists for sure an address !!! thats why the code is not insida a try-catch Temp_Name = (String) o.get("name"); Temp_Address = (String) o.get("vicinity"); JSONObject Str_1 = (JSONObject) o.get("geometry"); //Geometry is object so extract geometry JSONArray Photo_1 = (JSONArray) o.get("photos"); JSONObject Photo_2 = (JSONObject) Photo_1.get(0); String Photo_Ref = (String) Photo_2.get("photo_reference"); JSONObject Str_2 = (JSONObject) Str_1.get("location"); Temp_X = (double) Str_2.get("lat"); Temp_Y = (double) Str_2.get("lng"); //In case some POI has no Rating try { //Inside try-catch block because may some POI has no rating Temp_Rating = (double) o.get("rating"); Point POI_Object = new Point(Temp_Name, Temp_Address, Photo_Ref, Temp_Rating, Temp_X, Temp_Y); POI_List.add(POI_Object); //Add POI in List to keep it } catch (Exception Er) { //JOptionPane.showMessageDialog ( null, "No rating for this POI " ) ; Point POI_Object_2 = new Point(Temp_Name, Temp_Address, Photo_Ref, 0.0, Temp_X, Temp_Y); POI_List.add(POI_Object_2); //Add POI in List to keep it } } catch (Exception E) { //JOptionPane.showMessageDialog ( this, "Error -> " + E.getLocalizedMessage ( ) + ", " + E.getMessage ( ) ) ; } o.clear(); } } catch (ParseException PE) { JOptionPane.showMessageDialog(this, "Error -> " + PE.getLocalizedMessage(), "Parse, inside while JSON ERROR", JOptionPane.ERROR_MESSAGE, null); } catch (IOException IOE) { JOptionPane.showMessageDialog(this, "Error -> " + IOE.getLocalizedMessage(), "IOExcpiton", JOptionPane.ERROR_MESSAGE, null); } if (POI_List.isEmpty()) { JOptionPane.showMessageDialog(this, "No Results"); } else { //Calculate Distance every POI from Longitude and latitude of User for (int k = 0; k < POI_List.size(); k++) { double D1 = Double.parseDouble(Latitude_TextField.getText()) - POI_List.get(k).Get_Distance_X(); double D2 = Double.parseDouble(Longitude_TextField.getText()) - POI_List.get(k).Get_Distance_Y(); double a = pow(sin(D1 / 2), 2) + cos(POI_List.get(k).Get_Distance_X()) * cos(Double.parseDouble(Latitude_TextField.getText())) * pow(sin(D2 / 2), 2); double c = 2 * atan2(sqrt(a), sqrt(1 - a)); double d = 70000 * c; // (where R is the radius of the Earth) in meters //add to list Distances_List.add(d); } //COPY array because Distances_List will be corrupted for (int g = 0; g < Distances_List.size(); g++) { Distances_List_2.add(Distances_List.get(g)); } for (int l = 0; l < Distances_List.size(); l++) { int Dou = Distances_List.indexOf(Collections.min(Distances_List)); //Take the min , but the result is the position that the min is been placed Number_Name N = new Number_Name(POI_List.get(Dou).Get_Name()); //Create an object with the name of POI in the min position in the POI_List Temp_List.add(N); Distances_List.set(Dou, 9999.99); //Make the number in the min position so large so be able to find the next min } String[] T = new String[Temp_List.size()]; //String array to holds all names of POIS that are going to be dispayled in ascending order //DISPLAY POI IN JLIST - Create String Array with Names in ascending order to create JList for (int h = 0; h < Temp_List.size(); h++) { T[h] = Temp_List.get(h).Get_Name(); } //System.out.println ( " Size T -> " + T.length ) ; //Make JList and put String names list = new JList(T); list.setForeground(Color.BLACK); list.setBackground(Color.GRAY); list.setBounds(550, 140, 400, 400); //list.setSelectionMode ( ListSelectionModel.SINGLE_SELECTION ) ; JScrollPane p = new JScrollPane(list); P.add(p); setContentPane(pane); //OK list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { String selected = list.getSelectedValue().toString(); System.out.println("Selected string" + selected); for (int n = 0; n < POI_List.size(); n++) { if (selected.equals(POI_List.get(n).Get_Name())) { try { //read the result from the server BufferedImage img = null; URL u = new URL( "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=" + POI_List.get(n).Get_Photo_Ref() + "&key=" + API_KEY); Image image = ImageIO.read(u); IMAGE_LABEL.setText(""); IMAGE_LABEL.setIcon(new ImageIcon(image)); IMAGE_LABEL.setBounds(550, 310, 500, 200); //SOSOSOSOSOS pane.add(IMAGE_LABEL); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Error -> " + ex.getLocalizedMessage(), "Exception - IOException", JOptionPane.ERROR_MESSAGE, null); } Distance_L.setBounds(550, 460, 350, 150); Distance_L.setText(""); Distance_L.setText( "Distance from the current location: " + Distances_List_2.get(n) + "m"); pane.add(Distance_L); Address_L.setBounds(550, 500, 350, 150); Address_L.setText(""); Address_L.setText("Address: " + POI_List.get(n).Get_Address()); pane.add(Address_L); Rating_L.setBounds(550, 540, 350, 150); Rating_L.setText(""); Rating_L.setText("Rating: " + POI_List.get(n).Get_Rating()); pane.add(Rating_L); } } } }); } //Else not empty } //End of Method @Override public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); if (Retrieve_POIs_Button == source) { //Do Checks if (Connectivity_Checker()) { if (Blank_Fileds_Checker()) { if (Validility_Fields_Checker()) { if (Open_Status_Checker()) { Send_Receive_Data_Google_Service(true); } else { Send_Receive_Data_Google_Service(false); } } } } } } } //End of Main_Window Class