Advertisement
Guest User

Codigo

a guest
May 5th, 2018
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 54.77 KB | None | 0 0
  1. /* Classe Weather.java *********************************************************************/
  2.  
  3. package main.java.com.wfdai.weatherforecastdai.main.weather;
  4.  
  5. import java.util.Date;
  6.  
  7. /**
  8.  * Classe para instanciar os dados metereologicos
  9.  *
  10.  * @author Programador
  11.  */
  12. public class Weather {
  13.  
  14.     int direcaoVento;
  15.     float velocidadeVento;
  16.     double temperatura;
  17.     float pressao;
  18.     Date dataDados;
  19.     int humidade;
  20.     float visibilidade;
  21.     String nascerSol;
  22.     String porSol;
  23.  
  24.     public int getDirecaoVento() {
  25.         return direcaoVento;
  26.     }
  27.  
  28.     public float getVelocidadeVento() {
  29.         return velocidadeVento;
  30.     }
  31.  
  32.     public double getTemperatura() {
  33.         return temperatura;
  34.     }
  35.  
  36.     public float getPressao() {
  37.         return pressao;
  38.     }
  39.  
  40.     public Date getDataDados() {
  41.         return dataDados;
  42.     }
  43.  
  44.     public int getHumidade() {
  45.         return humidade;
  46.     }
  47.  
  48.     public float getVisibilidade() {
  49.         return visibilidade;
  50.     }
  51.  
  52.     public String getNascerSol() {
  53.         return nascerSol;
  54.     }
  55.  
  56.     public String getPorSol() {
  57.         return porSol;
  58.     }
  59. }
  60.  
  61.  
  62. /* Classe WeatherFactory.java *********************************************************************/
  63.  
  64. package main.java.com.wfdai.weatherforecastdai.main.weather;
  65.  
  66. import java.io.IOException;
  67. import javax.xml.bind.JAXBException;
  68. import main.java.com.wfdai.weatherforecastdai.main.GestorErros;
  69.  
  70. /**
  71.  * Fabrica de Objetos Weather
  72.  *
  73.  * @author Programador
  74.  */
  75. public class WeatherFactory {
  76.  
  77.     GestorErros erros = new GestorErros();
  78.  
  79.     public WeatherFactory() {
  80.     }
  81.  
  82.     public static WeatherInterface getWeather(String criteria) {
  83.         if (criteria.equals("yahoo")) {
  84.             return new WeatherYahoo();
  85.         } else if (criteria.equals("OWM")) {
  86.             return new OpenWeatherMaps();
  87.         }
  88.         return null;
  89.     }
  90.  
  91.     /**
  92.      * Recolhe os dados das API's externas e seleciona um com dados validos.
  93.      *
  94.      * @param localizacao String com a localização
  95.      * @param weather Objecto com os dados meteorologicos recolhidos.
  96.      * @throws javax.xml.bind.JAXBException
  97.      * @throws java.io.IOException
  98.      */
  99.     public void setWeather(String localizacao, Weather weather) throws JAXBException, IOException {
  100.  
  101.         try {
  102.             WeatherInterface weatherIn = WeatherFactory.getWeather("OWM");
  103.             weatherIn.setWeather(localizacao, weather);
  104.  
  105.         } catch (NullPointerException e) {
  106.  
  107.             System.out.println("city not found");
  108.  
  109.             try {
  110.                 WeatherInterface weatherIn = WeatherFactory.getWeather("yahoo");
  111.                 weatherIn.setWeather(localizacao, weather);
  112.  
  113.             } catch (IOException ex) {
  114.                 erros.putErro("YW IOException: " + ex.getCause().toString());
  115.  
  116.             } catch (JAXBException ex) {
  117.                 erros.putErro("YW JAXBException: " + ex.getCause().toString());
  118.             }
  119.  
  120.         } catch (IOException ex) {
  121.             erros.putErro("OWM IOException: " + ex.getCause().toString());
  122.         } catch (JAXBException ex) {
  123.             erros.putErro("OWM JAXBException: " + ex.getCause().toString());
  124.         }
  125.     }
  126. }
  127.  
  128. /* Classe WeatherInterface.java *********************************************************************/
  129.  
  130. package main.java.com.wfdai.weatherforecastdai.main.weather;
  131.  
  132. import java.io.IOException;
  133. import javax.xml.bind.JAXBException;
  134.  
  135. /**
  136.  * Interface weather
  137.  *
  138.  * @author Programador
  139.  */
  140. interface WeatherInterface {
  141.  
  142.     /**
  143.      * Recolhe os dados da API externa
  144.      *
  145.      * @param localizacao String com a localização
  146.      * @param weather Objecto com os dados meteorologicos recolhidos.
  147.      * @throws JAXBException
  148.      * @throws IOException
  149.      */
  150.     public void setWeather(String localizacao, Weather weather) throws JAXBException, IOException;
  151. }
  152.  
  153. /* Classe WeatherYahoo.java *********************************************************************/
  154.  
  155. package main.java.com.wfdai.weatherforecastdai.main.weather;
  156.  
  157. import com.github.fedy2.weather.YahooWeatherService;
  158. import com.github.fedy2.weather.data.Channel;
  159. import com.github.fedy2.weather.data.unit.DegreeUnit;
  160. import java.io.IOException;
  161. import java.util.List;
  162. import javax.xml.bind.JAXBException;
  163.  
  164. /**
  165.  * Recolhe os dados da API externa Weather Yahoo
  166.  *
  167.  * @author Programador
  168.  */
  169. public class WeatherYahoo implements WeatherInterface {
  170.  
  171.     /**
  172.      * Recolhe os dados da API externa Weather Yahoo
  173.      *
  174.      * @param localizacao String com a localização
  175.      * @param weather Objecto com os dados meteorologicos recolhidos.
  176.      * @throws JAXBException
  177.      * @throws IOException
  178.      */
  179.     @Override
  180.     public void setWeather(String localizacao, Weather weather) throws JAXBException, IOException {
  181.         YahooWeatherService service = new YahooWeatherService();
  182.         List<Channel> channel;
  183.         channel = service.getForecastForLocation(localizacao, DegreeUnit.CELSIUS).first(1);
  184.         weather.direcaoVento = channel.get(0).wind.getDirection();
  185.         weather.velocidadeVento = channel.get(0).wind.getSpeed();
  186.         weather.temperatura = channel.get(0).item.getCondition().getTemp();
  187.         weather.pressao = (float) (0.029890669 * channel.get(0).atmosphere.getPressure());
  188.         weather.dataDados = channel.get(0).item.getPubDate();
  189.         weather.humidade = channel.get(0).atmosphere.getHumidity();
  190.         weather.visibilidade = channel.get(0).atmosphere.getVisibility();
  191.         if ("AM".equals(channel.get(0).astronomy.getSunrise().getConvention().toString())) {
  192.             weather.nascerSol = String.format("%02d", channel.get(0).astronomy.getSunrise().getHours()) + ":"
  193.                     + String.format("%02d", channel.get(0).astronomy.getSunrise().getMinutes());
  194.         } else {
  195.             weather.nascerSol = String.format("%02d", channel.get(0).astronomy.getSunrise().getHours() + 12)
  196.                     + ":" + String.format("%02d", channel.get(0).astronomy.getSunrise().getMinutes());
  197.         }
  198.         if ("AM".equals(channel.get(0).astronomy.getSunset().getConvention().toString())) {
  199.             weather.porSol = String.format("%02d", channel.get(0).astronomy.getSunset().getHours()) + ":"
  200.                     + String.format("%02d", channel.get(0).astronomy.getSunset().getMinutes());
  201.         } else {
  202.             weather.porSol = String.format("%02d", channel.get(0).astronomy.getSunset().getHours()
  203.                     + 12) + ":" + String.format("%02d", channel.get(0).astronomy.getSunset().getMinutes());
  204.         }
  205.     }
  206. }
  207.  
  208. /* Classe OpenWeatherMaps.java *********************************************************************/
  209.  
  210. package main.java.com.wfdai.weatherforecastdai.main.weather;
  211.  
  212. import java.io.IOException;
  213. import java.text.SimpleDateFormat;
  214. import javax.xml.bind.JAXBException;
  215. import net.aksingh.owmjapis.CurrentWeather;
  216. import net.aksingh.owmjapis.OpenWeatherMap;
  217.  
  218. /**
  219.  * Recolhe os dados da API externa Open Weather Maps
  220.  *
  221.  * @author Programador
  222.  */
  223. public class OpenWeatherMaps implements WeatherInterface {
  224.  
  225.     /**
  226.      * Recolhe os dados da API externa Open Weather Maps
  227.      *
  228.      * @param localizacao String com a localização
  229.      * @param weather Objecto com os dados meteorologicos recolhidos.
  230.      * @throws JAXBException
  231.      * @throws IOException
  232.      */
  233.     @Override
  234.     public void setWeather(String localizacao, Weather weather) throws JAXBException, IOException {
  235.         boolean isMetric = true;
  236.         OpenWeatherMap owm = new OpenWeatherMap("");
  237.         owm.setUnits(OpenWeatherMap.Units.METRIC);
  238.         owm.setApiKey("07187078b07349a4c3098d15c10305af");
  239.         owm.setLang(OpenWeatherMap.Language.PORTUGUESE);
  240.         CurrentWeather cwd = owm.currentWeatherByCityName(localizacao);
  241.         weather.direcaoVento = Math.round(cwd.getWindInstance().getWindDegree());
  242.         weather.velocidadeVento = cwd.getWindInstance().getWindSpeed();
  243.         weather.temperatura = Math.round(cwd.getMainInstance().getTemperature());
  244.         weather.pressao = Math.round(cwd.getMainInstance().getPressure());
  245.         weather.dataDados = cwd.getDateTime();
  246.         weather.humidade = Math.round(cwd.getMainInstance().getHumidity());
  247.         weather.visibilidade = 100 - cwd.getCloudsInstance().getPercentageOfClouds();
  248.         weather.nascerSol = new SimpleDateFormat("HH:mm").format(cwd.getSysInstance().getSunriseTime());
  249.         weather.porSol = new SimpleDateFormat("HH:mm").format(cwd.getSysInstance().getSunsetTime());
  250.     }
  251. }
  252.  
  253. /* Classe Publisher.java *********************************************************************/
  254.  
  255. package main.java.com.wfdai.weatherforecastdai.main;
  256.  
  257. import org.eclipse.paho.client.mqttv3.MqttClient;
  258. import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
  259. import org.eclipse.paho.client.mqttv3.MqttException;
  260. import org.eclipse.paho.client.mqttv3.MqttMessage;
  261. import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
  262.  
  263. /**
  264.  * Envia mensagens para o Broker
  265.  *
  266.  * @author Programador
  267.  */
  268. public class Publisher {
  269.  
  270.     String topic;
  271.     String content;
  272.     MemoryPersistence persistence;
  273.  
  274.     public Publisher() {
  275.     }
  276.  
  277.     /**
  278.      * Recebe uma mensagem e envia-a para o broker
  279.      *
  280.      * @param mensagem String com o conteudo da mensagem.
  281.      * @param topico String com o tópico do Broker.
  282.      */
  283.     public void publish(String topico, String mensagem) {
  284.         this.publish(topico, mensagem, true);
  285.  
  286.     }
  287.  
  288.     /**
  289.      * Recebe uma mensagem e envia-a para o broker
  290.      *
  291.      * @param mensagem String com o conteudo da mensagem.
  292.      * @param topico String com o tópico do Broker.
  293.      * @param retained boolean com opção de reter a mensagem
  294.      */
  295.     public void publish(String topico, String mensagem, boolean retained) {
  296.         int qos = 2;
  297.         String broker = "tcp://127.0.0.1:9001";
  298.         String clientId = "javaServer";
  299.         this.topic = topico;
  300.         this.content = mensagem;
  301.         this.persistence = new MemoryPersistence();
  302.  
  303.         try {
  304.             MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
  305.             MqttConnectOptions connOpts = new MqttConnectOptions();
  306.             connOpts.setCleanSession(true);
  307.             System.out.println("Connecting to broker: " + broker);
  308.             sampleClient.connect(connOpts);
  309.             System.out.println("Connected");
  310.             System.out.println("Publishing message: " + content);
  311.             MqttMessage message = new MqttMessage(content.getBytes());
  312.             message.setQos(qos);
  313.             message.setRetained(retained);
  314.             sampleClient.publish(topic, message);
  315.             System.out.println("Message published");
  316.             sampleClient.disconnect();
  317.             System.out.println("Disconnected");
  318.             //System.exit(0);
  319.         } catch (MqttException me) {
  320.             System.out.println("reason " + me.getReasonCode());
  321.             System.out.println("msg " + me.getMessage());
  322.             System.out.println("loc " + me.getLocalizedMessage());
  323.             System.out.println("cause " + me.getCause());
  324.             System.out.println("excep " + me);
  325.         }
  326.     }
  327. }
  328.  
  329. /* Classe Parser.java *********************************************************************/
  330.  
  331. package main.java.com.wfdai.weatherforecastdai.main;
  332.  
  333. import java.text.SimpleDateFormat;
  334. import main.java.com.wfdai.weatherforecastdai.main.weather.Weather;
  335. import java.util.Date;
  336. import main.java.com.wfdai.weatherforecastdai.main.KPI.RegistoKPI;
  337.  
  338. /**
  339.  * Transforma dados e Objectos em JSON na especificação PPMP
  340.  *
  341.  * @author Programador
  342.  */
  343. public class Parser {
  344.  
  345.     String parsedMessage;
  346.  
  347.     public Parser() {
  348.     }
  349.  
  350.     /**
  351.      * Dá return de uma String com a mensagem em JSON...
  352.      *
  353.      * @return mensagem em JSON
  354.      */
  355.     public String getParsedMessage() {
  356.         return parsedMessage;
  357.     }
  358.     private final SimpleDateFormat rfc3339 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
  359.  
  360.     /**
  361.      * Transforma os Parametros numa mensagem PPMP.
  362.      *
  363.      * @param weather Objecto com os dados meteorologicos recolhidos.
  364.      */
  365.     public void setParser(Weather weather) {
  366.         parsedMessage
  367.                 = "{\n"
  368.                 + "  \"content-spec\": \"urn:spec://eclipse.org/unide/measurement-message#v2\",\n"
  369.                 + "  \"device\": {\n    \"deviceID\": \"servidorjava\"\n  },\n"
  370.                 + "  \"measurements\": [\n"
  371.                 + "    {\n"
  372.                 + "      \"ts\": \"" + rfc3339.format(weather.getDataDados()) + "\",\n"
  373.                 + "      \"series\": {\n"
  374.                 + "        \"$_time\": [ 0 ],\n"
  375.                 + "        \"DirecaoVento\": [ " + weather.getDirecaoVento() + " ],\n"
  376.                 + "        \"VelocidadeVento\": [ " + weather.getVelocidadeVento() + " ],\n"
  377.                 + "        \"Temperatura\": [ " + weather.getTemperatura() + " ],\n"
  378.                 + "        \"Pressao\": [ " + weather.getPressao() + " ],\n"
  379.                 + "        \"Humidade\": [ " + weather.getHumidade() + " ],\n"
  380.                 + "        \"Visibilidade\": [ " + weather.getVisibilidade() + " ],\n"
  381.                 + "        \"NascerSol\": [ \"" + weather.getNascerSol() + "\" ],\n"
  382.                 + "        \"PorSol\": [ \"" + weather.getPorSol() + "\" ]\n"
  383.                 + "      }\n    }\n  ]\n}";
  384.     }
  385.  
  386.     /**
  387.      * Transforma os Parametros numa mensagem PPMP.
  388.      *
  389.      * @param historico Objecto com o conjuto de dados de meteorologicas
  390.      * recolhidos.
  391.      */
  392.     public void setParser(Historico historico) {
  393.         parsedMessage
  394.                 = "{\n"
  395.                 + "  \"content-spec\": \"urn:spec://eclipse.org/unide/measurement-message#v2\",\n"
  396.                 + "  \"device\": {\n    \"deviceID\": \"servidorjava\"\n  },\n"
  397.                 + "  \"measurements\": [\n"
  398.                 + "    {\n"
  399.                 + "      \"ts\": \"" + rfc3339.format(new Date()) + "\",\n"
  400.                 + "      \"series\": {\n"
  401.                 + "        \"$_time\": " + historico.getDataDados().toString() + ",\n"
  402.                 + "        \"DirecaoVento\": " + historico.getDirecaoVento().toString() + " ,\n"
  403.                 + "        \"VelocidadeVento\": " + historico.getVelocidadeVento().toString() + ",\n"
  404.                 + "        \"Temperatura\": " + historico.getTemperatura().toString() + ",\n"
  405.                 + "        \"Pressao\": " + historico.getPressao() + ",\n"
  406.                 + "        \"Humidade\": " + historico.getHumidade().toString() + ",\n"
  407.                 + "        \"Visibilidade\": " + historico.getVisibilidade().toString() + ",\n"
  408.                 + "        \"NascerSol\": " + historico.getNascerSol().toString() + ",\n"
  409.                 + "        \"PorSol\": " + historico.getPorSol().toString() + "\n"
  410.                 + "      }\n    }\n  ]\n}";
  411.     }
  412.  
  413.     /**
  414.      * Transforma os Parametros numa mensagem PPMP.
  415.      *
  416.      * @param ts timestamp do alerta
  417.      * @param code codigo do alerta
  418.      * @param title Titulo do alerta
  419.      * @param description Descrição do alerta
  420.      */
  421.     public void setParser(Date ts, String code, String title, String description) {
  422.         parsedMessage
  423.                 = "{\n"
  424.                 + "  \"content-spec\": \"urn:spec://eclipse.org/unide/measurement-message#v2\",\n"
  425.                 + "  \"device\": {\n    \"deviceID\": \"servidorjava\"\n  },\n"
  426.                 + "  \"messages\": [\n"
  427.                 + "    {\n"
  428.                 + "      \"ts\": \"" + rfc3339.format(ts) + "\",\n"
  429.                 + "      \"code\": \"" + code + "\",\n"
  430.                 + "      \"title\": \"" + title + "\",\n"
  431.                 + "      \"description\": \"" + description + "\"\n"
  432.                 + "      }\n    }\n  ]\n}";
  433.     }
  434.  
  435.     /**
  436.      * Transforma os Parametros numa mensagem PPMP.
  437.      *
  438.      * @param registoKPI Objecto com o conjuto de dados de KPI's recolhidos.
  439.      */
  440.     public void setParser(RegistoKPI registoKPI) {
  441.         parsedMessage
  442.                 = "{\n"
  443.                 + "  \"content-spec\": \"urn:spec://eclipse.org/unide/measurement-message#v2\",\n"
  444.                 + "  \"device\": {\n    \"deviceID\": \"servidorjava\"\n  },\n"
  445.                 + "  \"measurements\": [\n"
  446.                 + "    {\n"
  447.                 + "      \"ts\": \"" + rfc3339.format(new Date()) + "\",\n"
  448.                 + "      \"series\": {\n"
  449.                 + "        \"$_time\": " + registoKPI.getTime().toString() + ",\n"
  450.                 + "        \"Uptime\": " + registoKPI.getUptime().toString() + " ,\n"
  451.                 + "        \"Total Clientes\": " + registoKPI.getTotalClients().toString() + " ,\n"
  452.                 + "        \"Clientes Ativos\": " + registoKPI.getActiveClients().toString() + ",\n"
  453.                 + "        \"Mensagens\": " + registoKPI.getMessages().toString() + ",\n"
  454.                 + "        \"Subscrições\": " + registoKPI.getSubscriptions() + ",\n"
  455.                 + "        \"Carga do sistema nos últimos 5 minutos\": " + registoKPI.getReceivedLoad5().toString() + ",\n"
  456.                 + "        \"Carga do sistema nos últimos 15 minutos\": " + registoKPI.getReceivedLoad15().toString() + ",\n"
  457.                 + "        \"Bytes enviados nos últimos 15 minutos\": " + registoKPI.getBytesSent15().toString() + "\n"
  458.                 + "      }\n    }\n  ]\n }";
  459.     }
  460.  
  461.     /**
  462.      * Transforma os Parametros numa mensagem PPMP.
  463.      *
  464.      * @param erro Objecto com o conjuto de dados de erros recolhidos.
  465.      */
  466.     public void setParser(GestorErros erro) {
  467.         parsedMessage
  468.                 = "{\n"
  469.                 + "  \"content-spec\": \"urn:spec://eclipse.org/unide/measurement-message#v2\",\n"
  470.                 + "  \"device\": {\n    \"deviceID\": \"servidorjava\"\n  },\n"
  471.                 + "  \"measurements\": [\n"
  472.                 + "    {\n"
  473.                 + "      \"ts\": \"" + rfc3339.format(new Date()) + "\",\n"
  474.                 + "      \"series\": {\n"
  475.                 + "        \"$_time\": " + erro.getTime().toString() + ",\n"
  476.                 + "        \"Erros\": " + erro.getErros().toString() + "\n"
  477.                 + "      }\n    }\n  ]\n}";
  478.     }
  479.  
  480. }
  481.  
  482. /* Classe Alerta.java *********************************************************************/
  483.  
  484. package main.java.com.wfdai.weatherforecastdai.main;
  485.  
  486. import main.java.com.wfdai.weatherforecastdai.main.weather.Weather;
  487.  
  488. /**
  489.  * Envia alertas
  490.  *
  491.  * @author Programador
  492.  */
  493. public class Alerta {
  494.  
  495.     Parser parser = new Parser();
  496.     Publisher publisher = new Publisher();
  497.  
  498.     /**
  499.      * Verifica se é necessário enviar alerta e , em caso afirmativo envia uma
  500.      * mensagem para o Broker no topico respetivo
  501.      *
  502.      * @param weather Objecto com os dados meteorologicos recolhidos.
  503.      * @param localidade String com a localidade.
  504.      */
  505.     public void checkAlerta(Weather weather, String localidade) {
  506.         if (weather.getTemperatura() < 2) {
  507.             parser.setParser(weather.getDataDados(), "gelo", "Alerta! Possibilidade de gelo na estrada",
  508.                     "Detectamos que a temperatura ambiente em " + localidade + " é inferior a 2ºC, "
  509.                     + "o que pode significar uma grande probabilidade de gelo na estrada.");
  510.             publisher.publish(localidade + "/alertas/gelo", parser.getParsedMessage(), false);
  511.         }
  512.         if (weather.getTemperatura() > 30) {
  513.             parser.setParser(weather.getDataDados(), "incendio", "Alerta! Possibilidade de Incendio",
  514.                     "Detectamos que a temperatura ambiente em " + localidade + ""
  515.                     + " é superior a 30ºC, o que pode significar um risco de incendio muito elevado.");
  516.             publisher.publish(localidade + "/alertas/incendio", parser.getParsedMessage(), false);
  517.         }
  518.         if (weather.getHumidade() > 95) {
  519.             parser.setParser(weather.getDataDados(), "precipitacao", "Alerta! Possibilidade de Precipitação",
  520.                     "Detectamos que a percentagem de húmidade no ar em " + localidade + " é superior a 95%, o que"
  521.                     + " pode significar Precipitação.");
  522.             publisher.publish(localidade + "/alertas/precipitacao", parser.getParsedMessage(), false);
  523.         }
  524.         if (weather.getVelocidadeVento() > 90) {
  525.             parser.setParser(weather.getDataDados(), "vento", "Alerta! Possibilidade de Ventos Fortes",
  526.                     "Detectamos Ventos fortes em " + localidade + ", com uma velocidade aproximada de " + weather.getVelocidadeVento() + "km/h.");
  527.             publisher.publish(localidade + "/alertas/vento", parser.getParsedMessage(), false);
  528.         }
  529.  
  530.     }
  531.  
  532. }
  533.  
  534. /* Classe KPI.java *********************************************************************/
  535.  
  536. package main.java.com.wfdai.weatherforecastdai.main.KPI;
  537.  
  538. import main.java.com.wfdai.weatherforecastdai.main.GestorErros;
  539. import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
  540. import org.eclipse.paho.client.mqttv3.MqttCallback;
  541. import org.eclipse.paho.client.mqttv3.MqttClient;
  542. import org.eclipse.paho.client.mqttv3.MqttException;
  543. import org.eclipse.paho.client.mqttv3.MqttMessage;
  544.  
  545. /**
  546.  * Recebe KPI's do broker
  547.  *
  548.  * @author Programador
  549.  */
  550. public class KPI implements MqttCallback {
  551.  
  552.     private String uptime, totalClients, activeClients, messages, subscriptions, receivedLoad5, receivedLoad15, bytesSent15;
  553.  
  554.     MqttClient client;
  555.     GestorErros erros = new GestorErros();
  556.  
  557.     public KPI() {
  558.     }
  559.  
  560.     /**
  561.      * Recebe KPI's do Broker
  562.      *
  563.      * @throws java.lang.InterruptedException
  564.      */
  565.     public void getKPI() throws InterruptedException {
  566.         try {
  567.             client = new MqttClient("tcp://127.0.0.1:9001", "javaServer");
  568.             client.connect();
  569.             client.setCallback(this);
  570.             client.subscribe("$SYS/broker/#");
  571.             Thread.sleep(9 * 1000);
  572.             client.disconnect();
  573.  
  574.         } catch (MqttException e) {
  575.             erros.putErro("GetKPI MQTT exception: " + e.getCause().toString());
  576.         }
  577.     }
  578.  
  579.     @Override
  580.     public void connectionLost(Throwable cause) {
  581.         // TODO Auto-generated method stub
  582.  
  583.     }
  584.  
  585.     @Override
  586.     public void messageArrived(String topic, MqttMessage message)
  587.             throws Exception {
  588.  
  589.         this.setKPI(message.toString(), topic);
  590.     }
  591.  
  592.     @Override
  593.     public void deliveryComplete(IMqttDeliveryToken token) {
  594.         // TODO Auto-generated method stub
  595.  
  596.     }
  597.  
  598.     /**
  599.      * Atribui KPI's a atributos do objeto do tipo KPI
  600.      *
  601.      * @param message Mensagem recebida do broker
  602.      * @param topic Topico da mensagem do broker
  603.      */
  604.     public void setKPI(String message, String topic) {
  605.  
  606.         switch (topic) {
  607.             case "$SYS/broker/uptime":
  608.                 this.setUptime(message);
  609.                 break;
  610.             case "$SYS/broker/clients/total":
  611.                 this.setTotalClients(message);
  612.                 break;
  613.             case "$SYS/broker/clients/active":
  614.                 this.setActiveClients(message);
  615.                 break;
  616.             case "$SYS/broker/messages/stored":
  617.                 this.setMessages(message);
  618.                 break;
  619.             case "$SYS/broker/subscriptions/count":
  620.                 this.setSubscriptions(message);
  621.                 break;
  622.             case "$SYS/broker/load/messages/received/5min":
  623.                 this.setReceivedLoad5(message);
  624.                 break;
  625.             case "$SYS/broker/load/messages/received/15min":
  626.                 this.setReceivedLoad15(message);
  627.                 break;
  628.             case "$SYS/broker/load/bytes/sent/15min":
  629.                 this.setBytesSent15(message);
  630.                 break;
  631.             default:
  632.                 break;
  633.         }
  634.     }
  635.  
  636.     public String getUptime() {
  637.         return uptime;
  638.     }
  639.  
  640.     public void setUptime(String uptime) {
  641.         this.uptime = uptime;
  642.     }
  643.  
  644.     public String getTotalClients() {
  645.         return totalClients;
  646.     }
  647.  
  648.     public void setTotalClients(String totalClients) {
  649.         this.totalClients = totalClients;
  650.     }
  651.  
  652.     public String getActiveClients() {
  653.         return activeClients;
  654.     }
  655.  
  656.     public void setActiveClients(String activeClients) {
  657.         this.activeClients = activeClients;
  658.     }
  659.  
  660.     public String getMessages() {
  661.         return messages;
  662.     }
  663.  
  664.     public void setMessages(String messages) {
  665.         this.messages = messages;
  666.     }
  667.  
  668.     public String getSubscriptions() {
  669.         return subscriptions;
  670.     }
  671.  
  672.     public void setSubscriptions(String subscriptions) {
  673.         this.subscriptions = subscriptions;
  674.     }
  675.  
  676.     public String getReceivedLoad5() {
  677.         return receivedLoad5;
  678.     }
  679.  
  680.     public void setReceivedLoad5(String receivedLoad5) {
  681.         this.receivedLoad5 = receivedLoad5;
  682.     }
  683.  
  684.     public String getReceivedLoad15() {
  685.         return receivedLoad15;
  686.     }
  687.  
  688.     public void setReceivedLoad15(String receivedLoad15) {
  689.         this.receivedLoad15 = receivedLoad15;
  690.     }
  691.  
  692.     public String getBytesSent15() {
  693.         return bytesSent15;
  694.     }
  695.  
  696.     public void setBytesSent15(String bytesSent15) {
  697.         this.bytesSent15 = bytesSent15;
  698.     }
  699.  
  700. }
  701.  
  702. /* Classe DataBase.java *********************************************************************/
  703.  
  704. package main.java.com.wfdai.weatherforecastdai.main;
  705.  
  706. /**
  707.  * Instancia as credenciais para a Base de Dados
  708.  *
  709.  * @author Programador
  710.  */
  711. public class DataBase {
  712.  
  713.     private final String user = "wfdai";
  714.     private final String password = "ieY4eemaJeifoh4z";
  715.     private final String serverName = "34.243.203.139";
  716.  
  717.     public String getUser() {
  718.         return user;
  719.     }
  720.  
  721.     public String getPassword() {
  722.         return password;
  723.     }
  724.  
  725.     public String getServerName() {
  726.         return serverName;
  727.     }
  728.  
  729. }
  730.  
  731. /* Classe GestorErros.java *********************************************************************/
  732.  
  733. package main.java.com.wfdai.weatherforecastdai.main;
  734.  
  735. import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
  736. import java.sql.Connection;
  737. import java.sql.ResultSet;
  738. import java.sql.SQLException;
  739. import java.sql.Statement;
  740. import java.time.LocalDate;
  741. import java.time.LocalDateTime;
  742. import java.time.LocalTime;
  743. import java.util.ArrayList;
  744. import java.util.Date;
  745.  
  746. /**
  747.  * Regista erros na Base de Dados e envia o registo para o broker
  748.  *
  749.  * @author Programador
  750.  */
  751. public class GestorErros {
  752.  
  753.     String erro;
  754.     ArrayList<String> erros;
  755.     ArrayList<Date> time;
  756.  
  757.     public GestorErros() {
  758.         this.erros = new ArrayList<>();
  759.         this.time = new ArrayList<>();
  760.     }
  761.  
  762.     public GestorErros(String erro) {
  763.         this.erro = erro;
  764.     }
  765.  
  766.     Parser parser = new Parser();
  767.     Publisher publish = new Publisher();
  768.  
  769.     /**
  770.      * Recebe os erros e regista-os na BD
  771.      *
  772.      * @param erro String com a causa do erro
  773.      */
  774.     public void putErro(String erro) {
  775.         try {
  776.             MysqlDataSource dataSource = new MysqlDataSource();
  777.             DataBase database = new DataBase();
  778.             dataSource.setUser(database.getUser());
  779.             dataSource.setPassword(database.getPassword());
  780.             dataSource.setServerName(database.getServerName());
  781.             try (Connection conn = dataSource.getConnection()) {
  782.                 Statement st = conn.createStatement();
  783.                 if (!erro.isEmpty()) {
  784.                     st.executeUpdate("INSERT INTO mydb.Erros (`erro`)"
  785.                             + "VALUES ('" + erro + "')");
  786.                 }
  787.             }
  788.  
  789.         } catch (SQLException e) {
  790.             System.err.println("Got an exception! ");
  791.             System.err.println(e.getMessage());
  792.         }
  793.     }
  794.  
  795.     /**
  796.      * Recolhe os erros da BD e envia-os para o Broker
  797.      *
  798.      */
  799.     public void getErro() {
  800.         try {
  801.             MysqlDataSource dataSource = new MysqlDataSource();
  802.             DataBase database = new DataBase();
  803.             dataSource.setUser(database.getUser());
  804.             dataSource.setPassword(database.getPassword());
  805.             dataSource.setServerName(database.getServerName());
  806.             try (Connection conn = dataSource.getConnection()) {
  807.                 Statement st = conn.createStatement();
  808.                 ResultSet rs = st.executeQuery("Select * from mydb.Erros ");
  809.  
  810.                 while (rs.next()) {
  811.                     erros.add(rs.getString("erro"));
  812.                     LocalDate datePart = LocalDate.parse(rs.getDate("time").toString());
  813.                     LocalTime timePart = LocalTime.parse(rs.getTime("time").toString());
  814.                     LocalDateTime dt = LocalDateTime.of(datePart, timePart);
  815.                     Date data = java.sql.Timestamp.valueOf(dt);
  816.                     time.add(data);
  817.  
  818.                 }
  819.             }
  820.             parser.setParser(this);
  821.             String mensagem = parser.getParsedMessage();
  822.             publish.publish("/Erros", mensagem);
  823.         } catch (SQLException e) {
  824.             System.err.println("Got an exception! ");
  825.             System.err.println(e.getMessage());
  826.         }
  827.     }
  828.  
  829.     public ArrayList<String> getErros() {
  830.         return erros;
  831.     }
  832.  
  833.     public ArrayList<Date> getTime() {
  834.         return time;
  835.     }
  836.  
  837.     public void setErro(String erro) {
  838.         this.erro = erro;
  839.     }
  840.  
  841. }
  842.  
  843. /* Classe Historico.java *********************************************************************/
  844.  
  845. package main.java.com.wfdai.weatherforecastdai.main;
  846.  
  847. import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
  848. import java.sql.Connection;
  849. import java.sql.ResultSet;
  850. import java.sql.SQLException;
  851. import java.sql.Statement;
  852. import main.java.com.wfdai.weatherforecastdai.main.weather.Weather;
  853. import java.text.DateFormat;
  854. import java.util.Date;
  855. import java.text.SimpleDateFormat;
  856. import java.time.LocalDate;
  857. import java.time.LocalDateTime;
  858. import java.time.LocalTime;
  859. import java.util.ArrayList;
  860.  
  861. /**
  862.  * Guarda e Recolhe Dados relativos a meteorologia na Base de Dados
  863.  *
  864.  * @author Programador
  865.  */
  866. public class Historico {
  867.  
  868.     DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
  869.     ArrayList<Integer> direcaoVento;
  870.     ArrayList<Float> velocidadeVento;
  871.     ArrayList<Integer> temperatura;
  872.     ArrayList<Float> pressao;
  873.     ArrayList<String> dataDados;
  874.     ArrayList<Integer> humidade;
  875.     ArrayList<Float> visibilidade;
  876.     ArrayList<String> nascerSol;
  877.     ArrayList<String> porSol;
  878.  
  879.     public Historico() {
  880.         this.direcaoVento = new ArrayList<>();
  881.         this.velocidadeVento = new ArrayList<>();
  882.         this.temperatura = new ArrayList<>();
  883.         this.pressao = new ArrayList<>();
  884.         this.dataDados = new ArrayList<>();
  885.         this.humidade = new ArrayList<>();
  886.         this.visibilidade = new ArrayList<>();
  887.         this.nascerSol = new ArrayList<>();
  888.         this.porSol = new ArrayList<>();
  889.     }
  890.  
  891.     /**
  892.      * Recebe os dados e coloca-os na base de dados
  893.      *
  894.      * @param weather Objecto com os dados meteorologicos recolhidos.
  895.      * @param localidade String com a localidade.
  896.      */
  897.     public void putHistorico(Weather weather, String localidade) {
  898.  
  899.         try {
  900.             MysqlDataSource dataSource = new MysqlDataSource();
  901.             DataBase database = new DataBase();
  902.             dataSource.setUser(database.getUser());
  903.             dataSource.setPassword(database.getPassword());
  904.             dataSource.setServerName(database.getServerName());
  905.             try (Connection conn = dataSource.getConnection()) {
  906.                 Statement st = conn.createStatement();
  907.                 st.executeUpdate("INSERT INTO mydb.Historico (`localidade`, `direcaoVento`, `velocidadeVento`, `temperatura`, "
  908.                         + "`pressao`, `dataDados`, `humidade`, `visibilidade`, `nascerSol`, `porSol`)"
  909.                         + "VALUES ('" + localidade + "','" + weather.getDirecaoVento() + "','" + weather.getVelocidadeVento() + "','"
  910.                         + weather.getTemperatura() + "','" + weather.getPressao()
  911.                         + "','" + dateFormat.format(weather.getDataDados()) + "','" + weather.getHumidade() + "','" + weather.getVisibilidade()
  912.                         + "','" + weather.getNascerSol() + "','" + weather.getPorSol() + "')");
  913.             }
  914.         } catch (SQLException e) {
  915.             System.err.println("Got an exception! ");
  916.             System.err.println(e.getMessage());
  917.         }
  918.     }
  919.  
  920.     /**
  921.      * Busca o histórico dos dados metereologicos relativamente a localidade
  922.      * pretendida
  923.      *
  924.      * @param localidade String com a localidade.
  925.      */
  926.     public void getHistorico(String localidade) {
  927.         direcaoVento.clear();
  928.         velocidadeVento.clear();
  929.         temperatura.clear();
  930.         pressao.clear();
  931.         dataDados.clear();
  932.         humidade.clear();
  933.         visibilidade.clear();
  934.         nascerSol.clear();
  935.         porSol.clear();
  936.  
  937.         try {
  938.             MysqlDataSource dataSource = new MysqlDataSource();
  939.             DataBase database = new DataBase();
  940.             dataSource.setUser(database.getUser());
  941.             dataSource.setPassword(database.getPassword());
  942.             dataSource.setServerName(database.getServerName());
  943.             try (Connection conn = dataSource.getConnection()) {
  944.                 Statement st = conn.createStatement();
  945.                 ResultSet rs = st.executeQuery(""
  946.                         + "SELECT max(`localidade`) as `localidade`, "
  947.                         + " max(`direcaoVento`) as `direcaoVento`, max(`velocidadeVento`) as `velocidadeVento`, "
  948.                         + " max(`temperatura`) as `temperatura`, max(`pressao`) as `pressao`, max(`dataDados`) as `dataDados`, "
  949.                         + " max(`humidade`) as `humidade`, max(`visibilidade`) as `visibilidade`, max(`nascerSol`) as `nascerSol`, "
  950.                         + " max(`porSol`) as `porSol` "
  951.                         + "FROM mydb.Historico "
  952.                         + "where localidade = '" + localidade + "' group by dataDados ;");
  953.  
  954.                 while (rs.next()) {
  955.                     direcaoVento.add(rs.getInt("direcaoVento"));
  956.                     velocidadeVento.add(rs.getFloat("velocidadeVento"));
  957.                     temperatura.add(rs.getInt("temperatura"));
  958.                     pressao.add(rs.getFloat("pressao"));
  959.  
  960.                     LocalDate datePart = LocalDate.parse(rs.getDate("dataDados").toString());
  961.                     LocalTime timePart = LocalTime.parse(rs.getTime("dataDados").toString());
  962.                     LocalDateTime dt = LocalDateTime.of(datePart, timePart);
  963.                     Date data = java.sql.Timestamp.valueOf(dt);
  964.                     dataDados.add("\"" + data + "\"");
  965.                     humidade.add(rs.getInt("humidade"));
  966.                     visibilidade.add(rs.getFloat("visibilidade"));
  967.                     nascerSol.add("\"" + rs.getString("nascerSol") + "\"");
  968.                     porSol.add("\"" + rs.getString("porSol") + "\"");
  969.                     System.out.println("");
  970.                 }
  971.             }
  972.         } catch (SQLException e) {
  973.             System.err.println("Got an exception! ");
  974.             System.err.println(e.getMessage());
  975.         }
  976.     }
  977.  
  978.     public ArrayList<Integer> getDirecaoVento() {
  979.         return direcaoVento;
  980.     }
  981.  
  982.     public ArrayList<Float> getVelocidadeVento() {
  983.         return velocidadeVento;
  984.     }
  985.  
  986.     public ArrayList<Integer> getTemperatura() {
  987.         return temperatura;
  988.     }
  989.  
  990.     public ArrayList<Float> getPressao() {
  991.         return pressao;
  992.     }
  993.  
  994.     public ArrayList<String> getDataDados() {
  995.         return dataDados;
  996.     }
  997.  
  998.     public ArrayList<Integer> getHumidade() {
  999.         return humidade;
  1000.     }
  1001.  
  1002.     public ArrayList<Float> getVisibilidade() {
  1003.         return visibilidade;
  1004.     }
  1005.  
  1006.     public ArrayList<String> getNascerSol() {
  1007.         return nascerSol;
  1008.     }
  1009.  
  1010.     public ArrayList<String> getPorSol() {
  1011.         return porSol;
  1012.     }
  1013.  
  1014. }
  1015.  
  1016. /* Classe RegistoKPI.java *********************************************************************/
  1017.  
  1018. package main.java.com.wfdai.weatherforecastdai.main.KPI;
  1019.  
  1020. import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
  1021. import java.sql.Connection;
  1022. import java.sql.ResultSet;
  1023. import java.sql.SQLException;
  1024. import java.sql.Statement;
  1025. import java.text.DateFormat;
  1026. import java.util.Date;
  1027. import java.text.SimpleDateFormat;
  1028. import java.time.LocalDate;
  1029. import java.time.LocalDateTime;
  1030. import java.time.LocalTime;
  1031. import java.util.ArrayList;
  1032. import main.java.com.wfdai.weatherforecastdai.main.DataBase;
  1033.  
  1034. /**
  1035.  * Regista e devolve dados relativos a KPI's
  1036.  *
  1037.  * @author Programador
  1038.  */
  1039. public class RegistoKPI {
  1040.  
  1041.     DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
  1042.  
  1043.     protected ArrayList<String> uptime, totalClients, activeClients, messages, subscriptions, receivedLoad5, receivedLoad15, bytesSent15, time;
  1044.  
  1045.     public RegistoKPI() {
  1046.         this.uptime = new ArrayList<>();
  1047.         this.totalClients = new ArrayList<>();
  1048.         this.activeClients = new ArrayList<>();
  1049.         this.messages = new ArrayList<>();
  1050.         this.subscriptions = new ArrayList<>();
  1051.         this.receivedLoad5 = new ArrayList<>();
  1052.         this.receivedLoad15 = new ArrayList<>();
  1053.         this.bytesSent15 = new ArrayList<>();
  1054.         this.time = new ArrayList<>();
  1055.     }
  1056.  
  1057.     /**
  1058.      * Coloca KPI's na base de dados
  1059.      *
  1060.      * @param kpi Objeto KPI
  1061.      */
  1062.     public void putKPI(KPI kpi) {
  1063.         try {
  1064.             MysqlDataSource dataSource = new MysqlDataSource();
  1065.             DataBase database = new DataBase();
  1066.             dataSource.setUser(database.getUser());
  1067.             dataSource.setPassword(database.getPassword());
  1068.             dataSource.setServerName(database.getServerName());
  1069.             try (Connection conn = dataSource.getConnection()) {
  1070.                 Statement st = conn.createStatement();
  1071.                 st.executeUpdate("INSERT INTO mydb.KPI (`uptime`,totalClients, activeClients, messages, subscriptions, receivedLoad5, receivedLoad15, bytesSent15)"
  1072.                         + "VALUES ('" + kpi.getUptime() + "', '" + kpi.getTotalClients() + "', '" + kpi.getActiveClients() + "', '"
  1073.                         + kpi.getMessages() + "', '" + kpi.getSubscriptions() + "', '" + kpi.getReceivedLoad5() + "', '" + kpi.getReceivedLoad15() + "', '"
  1074.                         + kpi.getBytesSent15() + "')");
  1075.             }
  1076.         } catch (SQLException e) {
  1077.             System.err.println("Got an exception! ");
  1078.             System.err.println(e.getMessage());
  1079.         }
  1080.     }
  1081.  
  1082.     /**
  1083.      * Obtem o Registo dos KPI's da base de dados e atribui-os a atributos do objeto do tipo RegistoKPI
  1084.      *
  1085.      */
  1086.     public void getRegistoKPI() {
  1087.         uptime.clear();
  1088.         totalClients.clear();
  1089.         activeClients.clear();
  1090.         messages.clear();
  1091.         subscriptions.clear();
  1092.         receivedLoad5.clear();
  1093.         receivedLoad15.clear();
  1094.         bytesSent15.clear();
  1095.         time.clear();
  1096.  
  1097.         try {
  1098.             MysqlDataSource dataSource = new MysqlDataSource();
  1099.             DataBase database = new DataBase();
  1100.             dataSource.setUser(database.getUser());
  1101.             dataSource.setPassword(database.getPassword());
  1102.             dataSource.setServerName(database.getServerName());
  1103.             try (Connection conn = dataSource.getConnection()) {
  1104.                 Statement st = conn.createStatement();
  1105.                 ResultSet rs = st.executeQuery("Select * from mydb.KPI");
  1106.  
  1107.                 while (rs.next()) {
  1108.                     uptime.add("\"" + rs.getString("uptime") + "\"");
  1109.                     totalClients.add(rs.getString("totalClients"));
  1110.                     activeClients.add(rs.getString("activeClients"));
  1111.                     messages.add(rs.getString("messages"));
  1112.                     subscriptions.add(rs.getString("subscriptions"));
  1113.                     receivedLoad5.add(rs.getString("receivedLoad5"));
  1114.                     receivedLoad15.add(rs.getString("receivedLoad15"));
  1115.                     bytesSent15.add(rs.getString("bytesSent15"));
  1116.  
  1117.                     LocalDate datePart = LocalDate.parse(rs.getDate("time").toString());
  1118.                     LocalTime timePart = LocalTime.parse(rs.getTime("time").toString());
  1119.                     LocalDateTime dt = LocalDateTime.of(datePart, timePart);
  1120.                     Date data = java.sql.Timestamp.valueOf(dt);
  1121.                     time.add("\"" + data.toString() + "\"");
  1122.                     //time.add(rs.getDate("time"));
  1123.                 }
  1124.             }
  1125.         } catch (SQLException e) {
  1126.             System.err.println("Got an exception! ");
  1127.             System.err.println(e.getMessage());
  1128.         }
  1129.     }
  1130.  
  1131.     public ArrayList<String> getUptime() {
  1132.         return uptime;
  1133.     }
  1134.  
  1135.     public ArrayList<String> getTotalClients() {
  1136.         return totalClients;
  1137.     }
  1138.  
  1139.     public ArrayList<String> getActiveClients() {
  1140.         return activeClients;
  1141.     }
  1142.  
  1143.     public ArrayList<String> getMessages() {
  1144.         return messages;
  1145.     }
  1146.  
  1147.     public ArrayList<String> getSubscriptions() {
  1148.         return subscriptions;
  1149.     }
  1150.  
  1151.     public ArrayList<String> getReceivedLoad5() {
  1152.         return receivedLoad5;
  1153.     }
  1154.  
  1155.     public ArrayList<String> getReceivedLoad15() {
  1156.         return receivedLoad15;
  1157.     }
  1158.  
  1159.     public ArrayList<String> getBytesSent15() {
  1160.         return bytesSent15;
  1161.     }
  1162.  
  1163.     public ArrayList<String> getTime() {
  1164.         return time;
  1165.     }
  1166.  
  1167. }
  1168.  
  1169. /* Classe App.java *********************************************************************/
  1170.  
  1171. package main.java.com.wfdai.weatherforecastdai.main;
  1172.  
  1173. import main.java.com.wfdai.weatherforecastdai.main.KPI.KPI;
  1174. import java.io.IOException;
  1175. import javax.xml.bind.JAXBException;
  1176. import main.java.com.wfdai.weatherforecastdai.main.KPI.RegistoKPI;
  1177. import main.java.com.wfdai.weatherforecastdai.main.weather.Weather;
  1178. import main.java.com.wfdai.weatherforecastdai.main.weather.WeatherFactory;
  1179.  
  1180. /**
  1181.  * Classe responsavel por instanciar o ETL
  1182.  *
  1183.  * @author Programador
  1184.  */
  1185. public class App {
  1186.  
  1187.     String[] localidades = {"Vila Velha de Ródão,Castelo Branco,Portugal", "Mação ,Santarém,Portugal", "Sines,Setúbal,Portugal", "Arcos de Valdevez,Viana do Castelo,Portugal", "Caminha,Viana do Castelo,Portugal", "Melgaço,Viana do Castelo,Portugal", "Monção,Viana do Castelo,Portugal", "Paredes de Coura,Viana do Castelo,Portugal", "Ponte da Barca,Viana do Castelo,Portugal", "Ponte de Lima,Viana do Castelo,Portugal", "Valença,Viana do Castelo,Portugal", "Viana do Castelo,Viana do Castelo,Portugal", "Vila Nova de Cerveira,Viana do Castelo,Portugal", "Amares,Braga,Portugal", "Barcelos,Braga,Portugal", "Braga,Braga,Portugal", "Esposende,Braga,Portugal", "Terras de Bouro,Braga,Portugal", "Vila Verde,Braga,Portugal", "Cabeceiras de Basto,Braga,Portugal", "Fafe,Braga,Portugal", "Guimarães,Braga,Portugal", "Mondim de Basto,Vila Real,Portugal", "Póvoa de Lanhoso,Braga,Portugal", "Vieira do Minho,Braga,Portugal", "Vila Nova de Famalicão,Braga,Portugal", "Vizela,Braga,Portugal", "Arouca,Aveiro,Portugal", "Espinho,Aveiro,Portugal", "Gondomar,Porto,Portugal", "Maia,Porto,Portugal", "Matosinhos,Porto,Portugal", "Oliveira de Azeméis,Aveiro,Portugal", "Paredes,Porto,Portugal", "Porto,Porto,Portugal", "Póvoa de Varzim,Porto,Portugal", "Santa Maria da Feira,Aveiro,Portugal", "Santo Tirso,Porto,Portugal", "São João da Madeira,Aveiro,Portugal", "Trofa,Porto,Portugal",
  1188.         "Vale de Cambra,Aveiro,Portugal", "Valongo,Porto,Portugal", "Vila do Conde,Porto,Portugal", "Vila Nova de Gaia,Porto,Portugal", "Amarante,Porto,Portugal", "Baião,Porto,Portugal", "Castelo de Paiva,Aveiro,Portugal", "Celorico de Basto,Braga,Portugal", "Cinfães,Viseu,Portugal", "Felgueiras,Porto,Portugal", "Lousada,Porto,Portugal", "Marco de Canaveses,Porto,Portugal", "Paços de Ferreira,Porto,Portugal", "Penafiel,Porto,Portugal", "Resende,Viseu,Portugal", "Boticas,Vila Real,Portugal", "Chaves,Vila Real,Portugal", "Montalegre,Vila Real,Portugal", "Ribeira de Pena,Vila Real,Portugal", "Valpaços,Vila Real,Portugal", "Vila Pouca de Aguiar,Vila Real,Portugal", "Alijó,Vila Real,Portugal", "Armamar,Viseu,Portugal", "Carrazeda de Ansiães,Bragança,Portugal", "Freixo de Espada à Cinta,Bragança,Portugal", "Lamego,Viseu,Portugal", "Mesão Frio,Vila Real,Portugal", "Moimenta da Beira,Viseu,Portugal", "Murça,Vila Real,Portugal", "Penedono,Viseu,Portugal", "Peso da Régua,Vila Real,Portugal", "Sabrosa,Vila Real,Portugal", "Santa Marta de Penaguião,Vila Real,Portugal", "São João da Pesqueira,Viseu,Portugal", "Sernancelhe,Viseu,Portugal", "Tabuaço,Viseu,Portugal", "Tarouca,Viseu,Portugal", "Torre de Moncorvo,Bragança,Portugal", "Vila Nova de Foz Côa,Guarda,Portugal", "Vila Real,Vila Real,Portugal", "Alfândega da Fé,Bragança,Portugal", "Bragança,Bragança,Portugal", "Macedo de Cavaleiros,Bragança,Portugal", "Miranda do Douro,Bragança,Portugal", "Mirandela,Bragança,Portugal", "Mogadouro,Bragança,Portugal", "Vila Flor,Bragança,Portugal", "Vimioso,Bragança,Portugal", "Vinhais,Bragança,Portugal", "Águeda,Aveiro,Portugal", "Albergaria-a-Velha,Aveiro,Portugal", "Anadia,Aveiro,Portugal", "Aveiro,Aveiro,Portugal", "Estarreja,Aveiro,Portugal", "Ílhavo,Aveiro,Portugal", "Murtosa,Aveiro,Portugal", "Oliveira do Bairro,Aveiro,Portugal", "Ovar,Aveiro,Portugal", "Sever do Vouga,Aveiro,Portugal", "Vagos,Aveiro,Portugal", "Arganil,Coimbra,Portugal", "Cantanhede,Coimbra,Portugal", "Coimbra,Coimbra,Portugal", "Condeixa-a-Nova,Coimbra,Portugal", "Figueira da Foz,Coimbra,Portugal", "Góis,Coimbra,Portugal", "Lousã,Coimbra,Portugal", "Mealhada,Aveiro,Portugal", "Mira,Coimbra,Portugal", "Miranda do Corvo,Coimbra,Portugal", "Montemor-o-Velho,Coimbra,Portugal", "Mortágua,Viseu,Portugal", "Oliveira do Hospital,Coimbra,Portugal", "Pampilhosa da Serra,Coimbra,Portugal", "Penacova,Coimbra,Portugal", "Penela,Coimbra,Portugal",
  1189.         "Soure,Coimbra,Portugal", "Tábua,Coimbra,Portugal", "Vila Nova de Poiares,Coimbra,Portugal", "Batalha,Leiria,Portugal", "Leiria,Leiria,Portugal", "Marinha Grande,Leiria,Portugal", "Pombal,Leiria,Portugal", "Porto de Mós,Leiria,Portugal", "Alvaiázere,Leiria,Portugal", "Ansião,Leiria,Portugal", "Castanheira de Pera,Leiria,Portugal", "Figueiró dos Vinhos,Leiria,Portugal", "Pedrógão Grande,Leiria,Portugal", "Aguiar da Beira,Guarda,Portugal", "Carregal do Sal,Viseu,Portugal", "Castro Daire,Viseu,Portugal", "Mangualde,Viseu,Portugal", "Nelas,Viseu,Portugal", "Oliveira de Frades,Viseu,Portugal", "Penalva do Castelo,Viseu,Portugal", "Santa Comba Dão,Viseu,Portugal", "São Pedro do Sul,Viseu,Portugal", "Sátão,Viseu,Portugal", "Tondela,Viseu,Portugal", "Vila Nova de Paiva,Viseu,Portugal", "Viseu,Viseu,Portugal", "Vouzela,Viseu,Portugal", "Almeida,Guarda,Portugal", "Belmonte,Castelo Branco,Portugal", "Celorico da Beira,Guarda,Portugal", "Covilhã,Castelo Branco,Portugal", "Figueira de Castelo Rodrigo,Guarda,Portugal", "Fornos de Algodres,Guarda,Portugal", "Fundão,Castelo Branco,Portugal", "Gouveia,Guarda,Portugal", "Guarda,Guarda,Portugal", "Manteigas,Guarda,Portugal", "Mêda,Guarda,Portugal", "Pinhel,Guarda,Portugal", "Sabugal,Guarda,Portugal", "Seia,Guarda,Portugal", "Trancoso,Guarda,Portugal", "Castelo Branco,Castelo Branco,Portugal", "Idanha-a-Nova,Castelo Branco,Portugal", "Oleiros,Castelo Branco,Portugal", "Penamacor,Castelo Branco,Portugal", "Proença-a-Nova,Castelo Branco,Portugal", "Alcobaça,Leiria,Portugal", "Alenquer,Lisboa,Portugal", "Arruda dos Vinhos,Lisboa,Portugal", "Bombarral,Leiria,Portugal", "Cadaval,Lisboa,Portugal", "Caldas da Rainha,Leiria,Portugal", "Lourinhã,Lisboa,Portugal", "Nazaré,Leiria,Portugal", "Óbidos,Leiria,Portugal", "Peniche,Leiria,Portugal", "Sobral de Monte Agraço,Lisboa,Portugal", "Torres Vedras,Lisboa,Portugal", "Abrantes,Santarém,Portugal", "Alcanena,Santarém,Portugal", "Constância,Santarém,Portugal", "Entroncamento,Santarém,Portugal", "Ferreira do Zêzere,Santarém,Portugal", "Ourém,Santarém,Portugal", "Sardoal,Santarém,Portugal", "Sertã,Castelo Branco,Portugal", "Tomar,Santarém,Portugal", "Torres Novas,Santarém,Portugal", "Vila de Rei,Castelo Branco,Portugal", "Vila Nova da Barquinha,Santarém,Portugal", "Alcochete,Setúbal,Portugal", "Almada,Setúbal,Portugal", "Amadora,Lisboa,Portugal", "Barreiro,Setúbal,Portugal", "Cascais,Lisboa,Portugal", "Lisboa,Lisboa,Portugal", "Loures,Lisboa,Portugal", "Mafra,Lisboa,Portugal", "Moita,Setúbal,Portugal", "Montijo,Setúbal,Portugal", "Odivelas,Lisboa,Portugal", "Oeiras,Lisboa,Portugal", "Palmela,Setúbal,Portugal", "Seixal,Setúbal,Portugal", "Sesimbra,Setúbal,Portugal", "Setúbal,Setúbal,Portugal", "Sintra,Lisboa,Portugal", "Vila Franca de Xira,Lisboa,Portugal", "Almeirim,Santarém,Portugal", "Alpiarça,Santarém,Portugal", "Azambuja,Lisboa,Portugal", "Benavente,Santarém,Portugal", "Cartaxo,Santarém,Portugal", "Chamusca,Santarém,Portugal", "Coruche,Santarém,Portugal", "Golegã,Santarém,Portugal", "Rio Maior,Santarém,Portugal", "Salvaterra de Magos,Santarém,Portugal", "Santarém,Santarém,Portugal", "Alcácer do Sal,Setúbal,Portugal", "Grândola,Setúbal,Portugal",
  1190.         "Odemira,Beja,Portugal", "Santiago do Cacém,Setúbal,Portugal", "Alter do Chão,Portalegre,Portugal", "Arronches,Portalegre,Portugal", "Avis,Portalegre,Portugal", "Campo Maior,Portalegre,Portugal", "Castelo de Vide,Portalegre,Portugal", "Crato,Portalegre,Portugal", "Elvas,Portalegre,Portugal", "Fronteira,Portalegre,Portugal", "Gavião,Portalegre,Portugal", "Marvão,Portalegre,Portugal", "Monforte,Portalegre,Portugal", "Nisa,Portalegre,Portugal", "Ponte de Sor,Portalegre,Portugal", "Portalegre,Portalegre,Portugal", "Sousel,Portalegre,Portugal", "Alandroal,Évora,Portugal", "Arraiolos,Évora,Portugal", "Borba,Évora,Portugal", "Estremoz,Évora,Portugal", "Évora,Évora,Portugal", "Montemor-o-Novo,Évora,Portugal", "Mora,Évora,Portugal", "Mourão,Évora,Portugal", "Portel,Évora,Portugal", "Redondo,Évora,Portugal", "Reguengos de Monsaraz,Évora,Portugal", "Vendas Novas,Évora,Portugal", "Viana do Alentejo,Évora,Portugal", "Vila Viçosa,Évora,Portugal", "Aljustrel,Beja,Portugal", "Almodôvar,Beja,Portugal", "Alvito,Beja,Portugal", "Barrancos,Beja,Portugal", "Beja,Beja,Portugal", "Castro Verde,Beja,Portugal", "Cuba,Beja,Portugal", "Ferreira do Alentejo,Beja,Portugal", "Mértola,Beja,Portugal", "Moura,Beja,Portugal", "Ourique,Beja,Portugal", "Serpa,Beja,Portugal", "Vidigueira,Beja,Portugal", "Albufeira,Faro,Portugal", "Alcoutim,Faro,Portugal", "Aljezur,Faro,Portugal", "Castro Marim,Faro,Portugal", "Faro,Faro,Portugal", "Lagoa,Faro,Portugal", "Lagos,Faro,Portugal", "Loulé,Faro,Portugal", "Monchique,Faro,Portugal", "Olhão,Faro,Portugal", "Portimão,Faro,Portugal", "São Brás de Alportel,Faro,Portugal", "Silves,Faro,Portugal", "Tavira,Faro,Portugal", "Vila do Bispo,Faro,Portugal", "Vila Real de Santo António,Faro,Portugal", "Angra do Heroísmo,Terceira,Portugal", "Calheta,São Jorge,Portugal", "Corvo,Corvo,Portugal", "Horta,Faial,Portugal", "Lagoa,São Miguel,Portugal", "Lajes das Flores,Flores,Portugal", "Lajes do Pico,Pico,Portugal", "Madalena,Pico,Portugal", "Nordeste,São Miguel,Portugal", "Ponta Delgada,São Miguel,Portugal", "Povoação,São Miguel,Portugal", "Praia da Vitória,Terceira,Portugal", "Ribeira Grande,São Miguel,Portugal", "Santa Cruz da Graciosa,Graciosa,Portugal", "Santa Cruz das Flores,Flores,Portugal", "São Roque do Pico,Pico,Portugal", "Velas,São Jorge,Portugal", "Vila do Porto,Santa Maria,Portugal", "Vila Franca do Campo,São Miguel,Portugal", "Calheta,Madeira,Portugal", "Câmara de Lobos,Madeira,Portugal", "Funchal,Madeira,Portugal", "Machico,Madeira,Portugal", "Ponta do Sol,Madeira,Portugal", "Porto Moniz,Madeira,Portugal", "Porto Santo,Porto Santo,Portugal", "Ribeira Brava,Madeira,Portugal", "Santa Cruz,Madeira,Portugal", "Santana,Madeira,Portugal", "São Vicente,Madeira,Portugal"};
  1191.     Weather weather = new Weather();
  1192.     WeatherFactory weatherFactory = new WeatherFactory();
  1193.     Parser parser = new Parser();
  1194.     Historico historico = new Historico();
  1195.     Publisher publisher = new Publisher();
  1196.     Alerta alerta = new Alerta();
  1197.     KPI kpi = new KPI();
  1198.     RegistoKPI registoKPI = new RegistoKPI();
  1199.  
  1200.     public App() {
  1201.  
  1202.     }
  1203.  
  1204.     /**
  1205.      * Corre todas as localidades, recolhe os dados metereologicos, verifica se
  1206.      * existem alertas, e envia a mensagem para o Broker
  1207.      *
  1208.      * @throws javax.xml.bind.JAXBException
  1209.      * @throws java.io.IOException
  1210.      */
  1211.     public void cicloLocalidades() throws JAXBException, IOException {
  1212.         for (String localidade : localidades) {
  1213.             weatherFactory.setWeather(localidade, weather);
  1214.             alerta.checkAlerta(weather, localidade);
  1215.             parser.setParser(weather);
  1216.             String mensagem = parser.getParsedMessage();
  1217.             publisher.publish(localidade, mensagem);
  1218.         }
  1219.     }
  1220.  
  1221.     /**
  1222.      * Corre todas as localidades, recolhe os dados metereologicos, guarda os
  1223.      * dados na BD, recolhe os dados da BD, e envia o Histórico atualizado para
  1224.      * o Broker
  1225.      *
  1226.      * @throws javax.xml.bind.JAXBException
  1227.      * @throws java.io.IOException
  1228.      */
  1229.     public void cicloHistorico() throws JAXBException, IOException {
  1230.         for (String localidade : localidades) {
  1231.             weatherFactory.setWeather(localidade, weather);
  1232.             historico.putHistorico(weather, localidade);
  1233.             historico.getHistorico(localidade);
  1234.             parser.setParser(historico);
  1235.             String mensagem = parser.getParsedMessage();
  1236.             publisher.publish(localidade + "/historico", mensagem);
  1237.         }
  1238.     }
  1239.  
  1240.     /**
  1241.      * Recebe os KPI´s, regista-os na BD, recolhe os KPI´s da BD, e envia os
  1242.      * KPI's atualizados para o Broker
  1243.      *
  1244.      * @throws java.lang.InterruptedException
  1245.      */
  1246.     public void cicloKpi() throws InterruptedException {
  1247.         kpi.getKPI();
  1248.         registoKPI.putKPI(kpi);
  1249.         registoKPI.getRegistoKPI();
  1250.         parser.setParser(registoKPI);
  1251.         String mensagem = parser.getParsedMessage();
  1252.         publisher.publish("/kpi", mensagem);
  1253.     }
  1254. }
  1255.  
  1256. /* Classe Main.java *********************************************************************/
  1257.  
  1258. package main.java.com.wfdai.weatherforecastdai.main;
  1259.  
  1260. import java.io.IOException;
  1261. import javax.xml.bind.JAXBException;
  1262.  
  1263. /**
  1264.  * Define o processo de execução da App WFDAI
  1265.  *
  1266.  * @author Programador
  1267.  */
  1268. public class Main {
  1269.  
  1270.     public static void main(String[] args) throws JAXBException, IOException, InterruptedException {
  1271.         App app = new App();
  1272.         GestorErros gestorErros = new GestorErros();
  1273.         gestorErros.getErro();
  1274.         app.cicloKpi();
  1275.         GestorErros erros = new GestorErros();
  1276.         for (int i = 9; i < 10; i++) {
  1277.             if (i < 8) {
  1278.  
  1279.                 app.cicloKpi();
  1280.                 app.cicloLocalidades();
  1281.                 System.out.println("sleep");
  1282.                 try {
  1283.                     Thread.sleep(5 * 60 * 1000);
  1284.                 } catch (InterruptedException exc) {
  1285.                     erros.putErro("Thread interrupted: " + exc.getCause().toString());
  1286.                     break;
  1287.                 }
  1288.  
  1289.             } else {
  1290.                 app.cicloHistorico();
  1291.                 i = 0;
  1292.             }
  1293.         }
  1294.     }
  1295. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement