Advertisement
aviksaha

Untitled

Aug 16th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.75 KB | None | 0 0
  1. import java.sql.SQLException;
  2. import java.text.DecimalFormat;
  3. import java.io.BufferedInputStream;
  4. import java.io.BufferedOutputStream;
  5. import java.io.BufferedReader;
  6. import java.io.BufferedWriter;
  7. import java.io.DataInputStream;
  8. import java.io.DataOutputStream;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. import java.io.InputStreamReader;
  12. import java.io.OutputStreamWriter;
  13. import java.io.PrintWriter;
  14. import java.net.HttpURLConnection;
  15. import java.net.MalformedURLException;
  16. import java.net.ServerSocket;
  17. import java.net.Socket;
  18. import java.net.URL;
  19. import java.sql.Connection;
  20. import java.sql.DriverManager;
  21. import java.sql.PreparedStatement;
  22. import java.sql.ResultSet;
  23. import java.text.DateFormat;
  24. import java.text.ParseException;
  25. import java.text.SimpleDateFormat;
  26. import java.util.logging.Level;
  27. import java.util.logging.Logger;
  28. import org.json.simple.JSONArray;
  29. import org.json.simple.JSONObject;
  30. import org.json.simple.parser.JSONParser;
  31.  
  32. /**
  33. * A server program which accepts requests from clients to
  34. * capitalize strings. When clients connect, a new thread is
  35. * started to handle an interactive dialog in which the client
  36. * sends in a string and the server thread sends back the
  37. * capitalized version of the string.
  38. *
  39. * The program is runs in an infinite loop, so shutdown in platform
  40. * dependent. If you ran it from a console window with the "java"
  41. * interpreter, Ctrl+C generally will shut it down.
  42. */
  43. public class JavaApplication12 {
  44. Connection conn = null;
  45. /**
  46. * Application method to run the server runs in an infinite loop
  47. * listening on port 9898. When a connection is requested, it
  48. * spawns a new thread to do the servicing and immediately returns
  49. * to listening. The server keeps a unique client number for each
  50. * client that connects just to show interesting logging
  51. * messages. It is certainly not necessary to do this.
  52. */
  53. public static void main(String[] args) throws Exception {
  54. System.out.println("The capitalization server is running.");
  55. int clientNumber = 0;
  56. ServerSocket listener = new ServerSocket(3000);
  57.  
  58.  
  59.  
  60. Class.forName("oracle.jdbc.OracleDriver");
  61.  
  62. try {
  63. while (true) {
  64. new Capitalizer(listener.accept(), clientNumber++).start();
  65. }
  66. } finally {
  67. listener.close();
  68. }
  69. }
  70.  
  71. /**
  72. * A private thread to handle capitalization requests on a particular
  73. * socket. The client terminates the dialogue by sending a single line
  74. * containing only a period.
  75. */
  76. private static class Capitalizer extends Thread {
  77. private Socket socket;
  78. private int clientNumber;
  79. private BufferedReader in;
  80. private BufferedWriter out;
  81. private PrintWriter pw;
  82. public DataOutputStream dout;
  83. public DataInputStream din;
  84. public Connection conn = null;
  85. //static DataOutputStream dout;
  86. //private DataOutputStream dout;
  87.  
  88.  
  89. public Capitalizer(Socket socket, int clientNumber) throws SQLException {
  90. this.socket = socket;
  91. this.clientNumber = clientNumber;
  92. conn = DriverManager.getConnection("jdbc:oracle:thin:@203.188.246.141:1521:orcl","vehicle","mononsoft");
  93. // TODO code application logic here
  94. System.out.println("Successfully Connected");
  95.  
  96. log("New connection with client# " + clientNumber + " at " + socket);
  97. }
  98.  
  99. /**
  100. * Services this thread's client by first sending the
  101. * client a welcome message then repeatedly reading strings
  102. * and sending back the capitalized version of the string.
  103. */
  104. public void run() {
  105. try {
  106.  
  107. // Decorate the streams so we can send characters
  108. // and not just bytes. Ensure output is flushed
  109. // after every newline.
  110. // in = new BufferedReader(
  111. //new InputStreamReader(socket.getInputStream()));
  112. ////out = new BufferedWriter(
  113. //new OutputStreamWriter(socket.getOutputStream()));
  114.  
  115. //dout = new DataOutputStream(socket.getOutputStream());
  116.  
  117. //pw = new PrintWriter(socket.getOutputStream());
  118.  
  119. din = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
  120. dout = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
  121.  
  122. // Send a welcome message to the client.
  123. //out.println("Hello, you are client #" + clientNumber + ".");
  124. //out.println("Enter a line with only a period to quit\n");
  125.  
  126. // Get messages from the client, line by line; return them
  127. // capitalized
  128. //out.write("**,imei:864180035993786,100");
  129.  
  130.  
  131. //String clientData= in.readUTF();
  132.  
  133.  
  134.  
  135. while (true) {
  136.  
  137. byte[] byteData = null;
  138. String location=null;
  139. try {
  140. byteData = receiveData(din);
  141. } catch (Exception ex) {
  142. Logger.getLogger(JavaApplication12.class.getName()).log(Level.SEVERE, null, ex);
  143. }
  144. String clientRequestMessage = new String(byteData).trim();
  145. String clientData = doProcess(clientRequestMessage);
  146. if(clientData==null){
  147. String [] check = clientRequestMessage.split(":");
  148.  
  149. log("final Message : "+clientRequestMessage);
  150. String [] arr = clientRequestMessage.split(",");
  151. //int i=0;
  152. if( !"imei".equals(check[0])||"L".equals(arr[4])){
  153.  
  154. System.out.println("Unauthorized value supplied by device");
  155. break;
  156. }
  157. //for(String a : arr)
  158. //System.out.println(a);
  159. String [] arr1 = arr[0].split(":");
  160. //To display Latitute and Longtitude
  161. System.out.println("Latitude : "+degree_to_decimal(arr[7],arr[8]));
  162. System.out.println("Longitude : "+degree_to_decimal(arr[9],arr[10]));
  163. try {
  164. location = getAddressByGpsCoordinates(String.valueOf(degree_to_decimal(arr[9],arr[10])),String.valueOf(degree_to_decimal(arr[7],arr[8])));
  165. //end to display Latitude and Longditude
  166. } catch (MalformedURLException ex) {
  167. Logger.getLogger(JavaApplication12.class.getName()).log(Level.SEVERE, null, ex);
  168. } catch (org.json.simple.parser.ParseException ex) {
  169. Logger.getLogger(JavaApplication12.class.getName()).log(Level.SEVERE, null, ex);
  170. }
  171.  
  172. // concat date
  173. char[] datearr = arr[2].toCharArray();
  174. String date= datearr[5] + "/" + datearr[2] + datearr[3] + "/20"+datearr[0]+datearr[1];
  175. String datew= datearr[4] + date;
  176. //concat date end
  177. // for(int i=0;i<datearr.length;i++){
  178. // System.out.println(arr[2]+" "+datearr[i]+" "+datew);
  179. // }
  180. // find maximum value to insert into Column "ID"
  181.  
  182. String Query1="select MAX(ID) as insert_id from GPS_INFO_HISTORY";
  183. PreparedStatement ps1 = conn.prepareStatement(Query1);
  184. ResultSet rs=ps1.executeQuery();
  185. int total=0;
  186. while (rs.next()) {
  187. total=rs.getInt("insert_id"); // store maximum value into total
  188. }
  189.  
  190. // insert all value insert into GPS_INFO_HISTORY table
  191. String Query = "Insert into GPS_INFO_HISTORY(ID, SN_IMEI_ID, TRACKER_ID,R_DATETIME, L_DATETIME,LATITUDE,LONGITUDE,SPEED, ALTITUDE, AZIMUTH, HDOP, GPS_VALID, TRACKER_STATE, VOLTAGE1, VOLTAGE2, ALARM_ID, BASE_ID, SATELLITE_NUMBER, GSM_SIGNAL, JOURNEY, RUN_TIME, VOLTAGE3, VOLTAGE4, VOLTAGE5, VOLTAGE6, VOLTAGE7, VOLTAGE8, RFID, GEOFENCE_ALARM_ID, LOCATION, PROTOCOL_VER, PROTOCOL_DATA) values(?, ?, ?,?,?, ?, ?,?,?,?,?,?,?,?,?,?, ?,?,?, ?, ?,?,?,?,?,?,?,?,?,?,?,?)";
  192. PreparedStatement ps = conn.prepareStatement(Query);
  193. //------ (ID, SN_IMEI_ID, TRACKER_ID,R_DATETIME, L_DATETIME,LATITUDE,LONGITUDE,SPEED, ALTITUDE, AZIMUTH, HDOP, TRACKER_STATE, GPS_VALID, ALARM_ID)
  194.  
  195. // set date format datew variable
  196. DateFormat formatter;
  197. java.util.Date dob;
  198. formatter = new SimpleDateFormat("dd/MM/yy");
  199. dob = formatter.parse(datew);
  200. //datew formation complete
  201.  
  202. //Date date1=new SimpleDateFormat("dd/MM/yyyy").parse("02/15/2012");
  203. ps.setInt(1, total+1); //ID
  204. ps.setString(2, arr1[1]); //SN_IMEI_ID
  205. ps.setString(3, arr1[1]); //TRACKER_ID
  206. ps.setDate(4, new java.sql.Date(dob.getTime())); //R_DATETIME
  207. ps.setDate(5, new java.sql.Date(dob.getTime())); //L_DATETIME
  208. ps.setString(6, String.valueOf(degree_to_decimal(arr[7],arr[8]))); //LATITUDE
  209. ps.setString(7, String.valueOf(degree_to_decimal(arr[9],arr[10]))); //LONGITUDE
  210. if(arr[11]==null||"".equals(arr[11])){
  211. ps.setFloat(8, 0);
  212. }else{
  213. ps.setFloat(8, Float.valueOf(arr[11]));
  214. } //SPEED
  215. ps.setInt(9, 0); //ALTITUDE
  216. ps.setInt(10, 0); //AZIMUTH
  217. ps.setFloat(11, 0); //HDOP
  218. ps.setString(12, "1"); //GPS_VALID
  219. ps.setString(13, "1"); //TRACKER_STATE
  220. ps.setFloat(14, 0); //VOLTAGE1
  221. ps.setFloat(15, 0); //VOLTAGE2
  222. ps.setInt(16, 123); //ps.setInt(16, Integer.parseInt(arr[1])); //ALARM_ID
  223. ps.setString(17, null); //BASE_ID
  224. ps.setInt(18, 0); //SATELLITE_NUMBER
  225. ps.setInt(19, 0); //GSM_SIGNAL
  226. ps.setInt(20, 0); //JOURNEY
  227. ps.setInt(21, 0); //RUN_TIME
  228. ps.setFloat(22, 0); //VOLTAGE3
  229. ps.setFloat(23, 0); //VOLTAGE4
  230. ps.setFloat(24, 0); //VOLTAGE5
  231. ps.setFloat(25, 0); //VOLTAGE6
  232. ps.setFloat(26, 0); //VOLTAGE7
  233. ps.setFloat(27, 0); //VOLTAGE8
  234. ps.setString(28, null); //RFID
  235. ps.setInt(29, 0); //GEOFENCE_ALARM_ID
  236. ps.setString(30, location); //LOCATION
  237. ps.setInt(31, 1); //PROTOCOL_VER
  238. ps.setString(32, null); //PROTOCOL_DATA
  239. int c = ps.executeUpdate();
  240. if(c==1){
  241. System.out.println("successfully inserted");
  242. }
  243.  
  244.  
  245. break;
  246. }
  247. else{
  248. sendData(dout, clientData.getBytes());
  249. }
  250.  
  251. }
  252.  
  253. } catch (ParseException ex) {
  254. Logger.getLogger(JavaApplication12.class.getName()).log(Level.SEVERE, null, ex);
  255. } catch (SQLException ex) {
  256. Logger.getLogger(JavaApplication12.class.getName()).log(Level.SEVERE, null, ex);
  257. } catch (IOException e) {
  258. log("Error handling client# " + clientNumber + ": " + e);
  259. } finally {
  260. try {
  261. //din.flush();
  262. dout.flush();
  263. din.close();
  264. try {
  265. conn.close();
  266. } catch (SQLException ex) {
  267. Logger.getLogger(JavaApplication12.class.getName()).log(Level.SEVERE, null, ex);
  268. }
  269. //out.flush();
  270. //out.close();
  271. //pw.flush();
  272. //pw.close();
  273. socket.close();
  274. } catch (IOException ex) {
  275. Logger.getLogger(JavaApplication12.class.getName()).log(Level.SEVERE, null, ex);
  276. }
  277. log("Connection with client# " + clientNumber + " closed");
  278. }
  279. }
  280.  
  281. /**
  282. * Logs a simple message. In this case we just write the
  283. * message to the server applications standard output.
  284. */
  285. private void log(String message) {
  286. System.out.println(message);
  287. }
  288. public static String doProcess(String message)
  289. {
  290. System.out.println("Processing the Client Request...");
  291. // if (message.equals("CLIENT_REQUEST:SEND_SYSTEM_TIME"))
  292. // {
  293. // Date date = new Date(System.currentTimeMillis());
  294. // return date.toString();
  295. // }
  296. // else
  297. // {
  298. // return "SERVER-ERROR:INVALID_REQUEST";
  299. // }
  300. if(message.length()==26){
  301. return "LOAD";
  302. }
  303. else if(message.length()==16){
  304. return "ON";
  305. }
  306. else{
  307. return null;
  308. }
  309. }
  310.  
  311. /**
  312. * Method receives the Client Request
  313. */
  314. public static byte[] receiveData(DataInputStream din) throws Exception
  315. {
  316. try
  317. {
  318. byte[] inputData = new byte[1024];
  319. din.read(inputData);
  320. return inputData;
  321. }
  322. catch (Exception exception)
  323. {
  324. throw exception;
  325. }
  326. }
  327. public static String getAddressByGpsCoordinates(String lng, String lat)
  328. throws MalformedURLException, IOException, org.json.simple.parser.ParseException {
  329.  
  330. URL url = new URL("https://maps.googleapis.com/maps/api/geocode/json?latlng="
  331. + lat + "," + lng + "&key=AIzaSyCXx3ubAosxwUQH4i4gMo6j89RaUbdISz0");
  332. //'https://maps.googleapis.com/maps/api/geocode/json?latlng=23.73929,90.375586&key=AIzaSyCXx3ubAosxwUQH4i4gMo6j89RaUbdISz0'
  333. HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  334. String formattedAddress = "";
  335.  
  336. try {
  337. InputStream in = url.openStream();
  338.  
  339. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  340. String result, line = reader.readLine();
  341. result = line;
  342. System.out.println("hiii"+result);
  343. while ((line = reader.readLine()) != null) {
  344. result += line;
  345. }
  346.  
  347. JSONParser parser = new JSONParser();
  348. JSONObject rsp = (JSONObject) parser.parse(result);
  349.  
  350. if (rsp.containsKey("results")) {
  351. JSONArray matches = (JSONArray) rsp.get("results");
  352. JSONObject data = (JSONObject) matches.get(0); //TODO: check if idx=0 exists
  353. formattedAddress = (String) data.get("formatted_address");
  354. System.out.println("hi");
  355. }
  356. else{
  357. System.out.println("none");
  358. }
  359.  
  360. return "";
  361. } finally {
  362. urlConnection.disconnect();
  363. return formattedAddress;
  364. }
  365. }
  366.  
  367. /**
  368. * Method used to Send Response to Client
  369. */
  370. public static synchronized void sendData(DataOutputStream dout, byte[] byteData)
  371. {
  372. if (byteData == null)
  373. {
  374. return;
  375. }
  376. try
  377. {
  378. dout.write(byteData);
  379. dout.flush();
  380. }
  381. catch (Exception exception)
  382. {
  383. }
  384. }
  385. public float degree_to_decimal(String coordinates_in_degrees, String direction){
  386. DecimalFormat df = new DecimalFormat("#0.######");
  387. int degrees = (int)(Float.valueOf(coordinates_in_degrees) / 100);
  388. double minutes = Double.valueOf(coordinates_in_degrees) - Double.valueOf(degrees * 100);
  389. double seconds = minutes / 60.0;
  390. double coordinates_in_decimal = degrees + seconds;
  391.  
  392. if ((direction .equals("S")) || (direction.equals("W"))) {
  393. coordinates_in_decimal = coordinates_in_decimal * (-1);
  394. }
  395. String ret = df.format(coordinates_in_decimal);
  396. return Float.valueOf(ret);
  397. //return (float) minutes;
  398. }
  399. }
  400. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement