PageRenderTime 1532ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/SDTP_Socket_Mongo/src/tpsocket/servidores/ThreadAtenderClima.java

https://gitlab.com/HeanGee/SD_Socket
Java | 148 lines | 104 code | 16 blank | 28 comment | 4 complexity | ecc1726e366aac5f01f76f4a274f72a5 MD5 | raw file
  1. package tpsocket.servidores;
  2. import tpsocket.clientes.Clima;
  3. import tpsocket.constantes.Defaults;
  4. import tpsocket.logs.LogFileManager;
  5. import tpsocket.basededatos.ConexionBD;
  6. import com.google.gson.Gson;
  7. import java.io.DataInputStream;
  8. import java.io.DataOutputStream;
  9. import java.io.IOException;
  10. import java.net.Socket;
  11. import java.util.logging.Level;
  12. import java.util.logging.Logger;
  13. import javax.swing.JOptionPane;
  14. /**
  15. *
  16. * @author Estercita
  17. */
  18. public class ThreadAtenderClima extends Thread
  19. {
  20. private final Socket clientSocket;
  21. private DataOutputStream canalSalida;
  22. private DataInputStream canalEntrada;
  23. public ThreadAtenderClima(Socket clientSocket)
  24. {
  25. super("ThreadAtenderClima");
  26. this.clientSocket = clientSocket;
  27. }
  28. @Override
  29. public void run()
  30. {
  31. try
  32. {
  33. /** Crear canales de entrada y salida. */
  34. this.canalEntrada = new DataInputStream(this.clientSocket.getInputStream());
  35. this.canalSalida = new DataOutputStream(this.clientSocket.getOutputStream());
  36. int longitudString;
  37. StringBuilder log = new StringBuilder();
  38. do
  39. {
  40. log.append("Esperando recibir longitud del mensaje en bytes...");
  41. this.escribirLog(log.toString());
  42. log = log.delete(0, log.length());
  43. /** Negociacion - Obtener la longitud del mensaje en bytes. */
  44. longitudString = this.canalEntrada.readInt();
  45. if(longitudString>0)
  46. {
  47. log.append("Longitud recibida; ").append(longitudString);
  48. this.escribirLog(log.toString());
  49. log = log.delete(0, log.length());
  50. /** Replay de recepciĆ³n de longitud. */
  51. this.canalSalida.writeUTF("ok");
  52. /** Dimensionar un byte[] con el tamanho recibido. */
  53. byte[] bytesReceived = new byte[longitudString];
  54. /** Cargar bytesReceived, byte a byte, con los bytes que envia el cliente. */
  55. log.append("Recibiendo mensaje en bytes...");
  56. this.escribirLog(log.toString());
  57. log = log.delete(0, log.length());
  58. for(int i=0; i<longitudString; i++)
  59. bytesReceived[i] = (byte)this.canalEntrada.readByte();
  60. /** Convierte en String el mensaje recibido en bytes. */
  61. String contentReceived_inString;
  62. contentReceived_inString = new String(bytesReceived);
  63. /** Log. */
  64. log.append("Mensaje en bytes recibido. Mensaje convertido a String.");
  65. this.escribirLog(log.toString());
  66. log = log.delete(0, log.length());
  67. /** GUARDAR EN BASE DE DATOS contentReceived_inString. */
  68. // ConexionBD conec = new ConexionBD("localhost" , 27017,"test"); //Crea un Cliente del MongoDB
  69. // conec.crear(); //crea la conexion a la BD
  70. // System.out.println("***Insertando a la Base de Datos...");
  71. // conec.insertar("Clima",contentReceived_inString); //Inserta a la Base de Datos
  72. // System.out.println("***JSON string insertado***");
  73. /** Replay de recepciĆ³n y procesado de mensaje. */
  74. this.canalSalida.writeUTF("ok");
  75. /* -------------------------------------------------------- */
  76. /** TEST - NO REQUISITO DEL PDF. */
  77. /** Crea un objeto JSON. */
  78. Gson obJSON = new Gson();
  79. /** Des-gson-nea al String, obteniendo un objeto de tipo Satelite. */
  80. /** Instancia ese objeto Satelite. */
  81. log.append("Construyendo objeto a partir del mensaje...");
  82. this.escribirLog(log.toString());
  83. log = log.delete(0, log.length());
  84. Clima objClima = obJSON.fromJson(contentReceived_inString, Clima.class);
  85. /** */
  86. log.append("Objeto construido correctamente: ").append(objClima.getClass());
  87. this.escribirLog(log.toString());
  88. log = log.delete(0, log.length());
  89. /** Registrar log. */
  90. log.append("Mensaje de un cliente Clima del puerto: ")
  91. .append(clientSocket.getPort())
  92. .append(" procesado correctamenete.");
  93. this.escribirLog(log.toString());
  94. log = log.delete(0, log.length());
  95. /* -------------------------------------------------------- */
  96. }
  97. }
  98. while(longitudString>0); /** mientras el cliente le envie una longitud valida. */
  99. /** Cierre de canales y socket. */
  100. if(!this.clientSocket.isClosed() || this.clientSocket.isConnected())
  101. {
  102. log.append("Cliente cerro conexion."
  103. + " Cerrando flujos en el servidor Clima.");
  104. this.escribirLog(log.toString());
  105. this.canalEntrada.close();
  106. this.canalSalida.close();
  107. this.clientSocket.close();
  108. }
  109. }
  110. catch (IOException ex)
  111. {
  112. //JOptionPane.showMessageDialog(null, "IOException desde run() de "+this.getName(), "Exception", JOptionPane.ERROR_MESSAGE);
  113. System.out.println();
  114. Logger.getLogger(ThreadAtenderClima.class.getName()).log(Level.SEVERE, null, ex);
  115. this.escribirLog("I/O Exception desde run() de "+this.getName()+".");
  116. } catch (Throwable ex) {
  117. Logger.getLogger(ThreadAtenderClima.class.getName()).log(Level.SEVERE, null, ex);
  118. }
  119. }
  120. public void escribirLog(String msg)
  121. {
  122. try {
  123. System.out.println("\t[Cli-"+this.clientSocket.getPort()+"]:"+msg);
  124. LogFileManager log = new LogFileManager(Defaults.SERVER_OF_CLIMA_LOGFILEPATH, true);
  125. log.writeTo("\t[Cli-"+this.clientSocket.getPort()+"]:"+msg);
  126. log.closeWriter();
  127. } catch (IOException ex) {
  128. JOptionPane.showMessageDialog(null, "IOException desde escribirLog() de "+this.getName(), "Exception", JOptionPane.ERROR_MESSAGE);
  129. Logger.getLogger(ThreadAtenderClima.class.getName()).log(Level.SEVERE, null, ex);
  130. }
  131. }
  132. }