Exemplo n.º 1
0
 /**
  * Attempts to load a KML {@link de.micromata.opengis.kml.v_2_2_0.Style} from a file provided via
  * a file system path.
  *
  * @param url - the path to the file.
  */
 public void setStyleUrl(String url) {
   if (StringUtils.isNotBlank(url)) {
     try {
       styleDoc = null;
       styleUrl = url;
       styleDoc = Kml.unmarshal(new URL(styleUrl).openStream());
     } catch (MalformedURLException e) {
       LOGGER.warn(
           "StyleUrl is not a valid URL. Unable to serve up custom KML de.micromata.opengis.kml.v_2_2_0.Style.",
           e);
     } catch (IOException e) {
       LOGGER.warn(
           "Unable to open de.micromata.opengis.kml.v_2_2_0.Style Document from StyleUrl.", e);
     }
   }
 }
  @POST
  @Path("newticket")
  @Produces(MediaType.APPLICATION_JSON)
  @TransactionAttribute(TransactionAttributeType.NEVER)
  public Response newticket(
      @FormParam("noiselogger") String noiselogger, @Context HttpServletRequest req)
      throws AddressException, MessagingException {
    Date date = new Date();

    TicketDTO newTicket = new TicketDTO();

    JsonResponse json = new JsonResponse();
    json.setData(newTicket); // just return the date we received

    Principal principal = req.getUserPrincipal();
    // only login if not already logged in...
    if (principal == null) {
      json.setStatus("FAILED");
      json.setErrorMsg("Authentication failed");
      return Response.ok().entity(json).build();
    }

    // Retrive info for the noise logger selected
    String path = "/Users/pelldav/University/Tesi/SmartWaterProject/web/file/Noise_loggers.kml";
    Kml kml = Kml.unmarshal(new File(path));
    Document document = (Document) kml.getFeature(); // Get the document features
    Iterator<Feature> iterator =
        document.getFeature().iterator(); // Create an iterator for the placemark
    Feature feature = null;
    while (iterator.hasNext()) {
      feature = iterator.next();
      if (feature.getName().compareTo(noiselogger) == 0) {
        break;
      }
    }
    req.getServletContext().log("ECCOLOOOOOO: " + feature.getDescription());
    String[] description = feature.getDescription().split("<br>");
    String battery = description[1].split("<b>")[1].split("%")[0];
    String status = description[2].split("<b>")[1].split("</b>")[0];

    // set the Company name
    User user = userBean.find(principal.getName());
    newTicket.setCompany(user.getCompany());

    // set the id
    newTicket.setId("" + date.getTime());

    // set the noise logger id
    newTicket.setNoiselogger(noiselogger);

    // retrive state and info from kml
    if (status.compareTo("OK") != 0) { // Error on network sensor
      newTicket.setInfo("Richiesta verifica rete noise loggers");
    } else { // Low battery
      newTicket.setInfo("Richiesta sostituzione batteria - Livello: " + battery + "%");
    }

    // set stato - initial state is always "attivo"
    newTicket.setStato("attivo");

    req.getServletContext().log("ticket creato" + newTicket);

    json.setData(newTicket); // just return the date we received

    Ticket ticket = new Ticket(newTicket);

    // this could cause a runtime exception, i.e. in case the user already exists
    // such exceptions will be caught by our ExceptionMapper, i.e.
    // javax.transaction.RollbackException
    ticketBean.save(
        ticket); // this would use the clients transaction which is committed after save() has
                 // finished

    // Send email to user
    String host = "smtp.gmail.com";
    String from = "*****@*****.**";
    String pass = "******";
    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");

    String[] to = {user.getEmail()};

    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));

    InternetAddress[] toAddress = new InternetAddress[to.length];

    for (int i = 0; i < to.length; i++) { // To get the array of addresses
      toAddress[i] = new InternetAddress(to[i]);
    }
    System.out.println(Message.RecipientType.TO);

    for (int i = 0; i < toAddress.length; i++) {
      message.addRecipient(Message.RecipientType.TO, toAddress[i]);
    }
    message.setSubject("Smart Leak Detection - Richiesta Manutenzione");
    message.setContent(
        "<h1>Smart Leak Detection</h1> <br> <div> Registrazione di manutenzione inviata <br>"
            + newTicket.toString()
            + "</div>",
        "text/html");
    Transport transport = session.getTransport("smtp");
    transport.connect(host, from, pass);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
    req.getServletContext().log("Email sent to: '" + user.getEmail());

    json.setStatus("SUCCESS");

    req.getServletContext()
        .log(
            "successfully added new ticket: '"
                + newTicket.getCompany()
                + "':'"
                + newTicket.getId()
                + "'");

    return Response.ok().entity(json).build();
  }