Example usage for java.time LocalDateTime now

List of usage examples for java.time LocalDateTime now

Introduction

In this page you can find the example usage for java.time LocalDateTime now.

Prototype

public static LocalDateTime now() 

Source Link

Document

Obtains the current date-time from the system clock in the default time-zone.

Usage

From source file:com.peso.Workout.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w w w  .ja v  a 2  s . c o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean bError = false;
    String mensajeError = "";

    String nombre = "";
    String peso = "";
    String workout = "";
    LocalDateTime ultimaLlamada = null;
    LocalDateTime ahora = null;
    LocalDateTime lesionado = null;

    //Errores
    if (request.getSession().getAttribute("nombre") == null) {
        mensajeError = "no hay nombre resgistrado";
        bError = true;
    } else {
        workout = request.getParameter("workout");

        if (workout == null) {
            mensajeError = "falta el parametro workout";
            bError = true;
        } else if (!StringUtils.isNumeric(workout)) {
            mensajeError = "workout debe de ser numrico";
            bError = true;
        }
    }
    if (!bError) {
        //Registrar el usuario
        nombre = (String) request.getSession().getAttribute("nombre");
        peso = (String) request.getSession().getAttribute("peso");
        ahora = LocalDateTime.now();
        ultimaLlamada = (LocalDateTime) request.getSession().getAttribute("ultimaLlamada");
        if (ultimaLlamada == null) {
            ultimaLlamada = LocalDateTime.now();
        }
        //engordar cada 10 segundos, tiempo entre llamadas.
        Duration segundos = Duration.between(ultimaLlamada, ahora);
        int iPeso = NumberUtils.toInt(peso);
        iPeso += (segundos.getSeconds() / 10);

        //mirar si lesion
        lesionado = (LocalDateTime) request.getSession().getAttribute("lesionado");
        Duration segundosLesion = null;

        // si hay lesion esperar tiempo
        if (lesionado != null) {
            segundosLesion = Duration.between(lesionado, ahora);
            if (segundosLesion.getSeconds() >= 30) {
                // se le quita la lesion
                request.getSession().setAttribute("lesionado", null);
            }
            request.setAttribute("lesionado", (30 - segundosLesion.getSeconds()) + "");
        } else//si han pasado menos de 5 seg se lesiona
        {
            if (segundos.getSeconds() <= 5) {
                request.getSession().setAttribute("lesionado", ahora);
            } else {
                //si no la hay adelgaza el tiempo requerido.
                int kilosAdelgazar = (NumberUtils.toInt(workout) / 30);
                kilosAdelgazar *= (int) (0.2 * iPeso);
                iPeso -= kilosAdelgazar;
            }
        }
        peso = iPeso + "";
        request.getSession().setAttribute("peso", peso);
        request.getSession().setAttribute("ultimaLlamada", ahora);

        request.setAttribute("nombre", nombre);
        request.setAttribute("peso", peso);
        request.getRequestDispatcher("/workout.jsp").forward(request, response);
    } else {
        request.setAttribute(Constantes.ATRIBUTO_ERROR, mensajeError);
        request.getRequestDispatcher(Constantes.PAGINA_ERROR).forward(request, response);
    }
}

From source file:com.fns.grivet.service.SchemaService.java

@Transactional
public com.fns.grivet.model.Class linkSchema(JSONObject payload) {
    String type = payload.getString(ID);
    Assert.notNull(type, "JSON Schema must declare an id!");
    com.fns.grivet.model.Class c = classRepository.findByName(type);
    Assert.notNull(c, String.format("Type [%s] must be registered before linking a JSON Schema!", type));
    c.setValidatable(true);/*w ww . j a va 2 s  . c o m*/
    c.setJsonSchema(payload.toString());
    c.setUpdatedTime(LocalDateTime.now());
    classRepository.save(c);
    return c;
}

From source file:org.ow2.proactive.workflow_catalog.rest.entity.Bucket.java

public Bucket(String name, String owner) {
    this(name, LocalDateTime.now(), owner);
}

From source file:com.romeikat.datamessie.core.base.service.download.ContentDownloader.java

public DownloadResult downloadContent(String url) {
    LOG.debug("Downloading content from {}", url);
    // In case of a new redirection for that source, use redirected URL
    URLConnection urlConnection = null;
    String originalUrl = null;/*from   www. jav a  2  s .  c o m*/
    org.jsoup.nodes.Document jsoupDocument = null;
    Integer statusCode = null;
    final LocalDateTime downloaded = LocalDateTime.now();
    try {
        urlConnection = getConnection(url);
        // Server-side redirection
        final String responseUrl = getResponseUrl(urlConnection);
        if (responseUrl != null) {
            final String redirectedUrl = getRedirectedUrl(url, responseUrl);
            if (isValidRedirection(url, redirectedUrl)) {
                originalUrl = url;
                url = redirectedUrl;
                closeUrlConnection(urlConnection);
                urlConnection = getConnection(url);
                LOG.debug("Redirection (server): {} -> {}", originalUrl, url);
            }
        }
        // Download content for further redirects
        final InputStream urlInputStream = asInputStream(urlConnection, true, false);
        final Charset charset = getCharset(urlConnection);
        jsoupDocument = Jsoup.parse(urlInputStream, charset.name(), url);
        final Elements metaTagsHtmlHeadLink;
        Elements metaTagsHtmlHeadMeta = null;
        // Meta redirection (<link rel="canonical" .../>)
        if (originalUrl == null) {
            metaTagsHtmlHeadLink = jsoupDocument.select("html head link");
            for (final Element metaTag : metaTagsHtmlHeadLink) {
                final Attributes metaTagAttributes = metaTag.attributes();
                if (metaTagAttributes.hasKey("rel")
                        && metaTagAttributes.get("rel").equalsIgnoreCase("canonical")
                        && metaTagAttributes.hasKey("href")) {
                    final String redirectedUrl = metaTagAttributes.get("href").trim();
                    if (isValidRedirection(url, redirectedUrl)) {
                        originalUrl = url;
                        url = redirectedUrl;
                        jsoupDocument = null;
                        LOG.debug("Redirection (<link rel=\"canonical\" .../>): {} -> {}", originalUrl, url);
                        break;
                    }
                }
            }
        }
        // Meta redirection (<meta http-equiv="refresh" .../>)
        if (originalUrl == null) {
            metaTagsHtmlHeadMeta = jsoupDocument.select("html head meta");
            for (final Element metaTag : metaTagsHtmlHeadMeta) {
                final Attributes metaTagAttributes = metaTag.attributes();
                if (metaTagAttributes.hasKey("http-equiv")
                        && metaTagAttributes.get("http-equiv").equalsIgnoreCase("refresh")
                        && metaTagAttributes.hasKey("content")) {
                    final String[] parts = metaTagAttributes.get("content").replace(" ", "").split("=", 2);
                    if (parts.length > 1) {
                        final String redirectedUrl = parts[1];
                        if (isValidRedirection(url, redirectedUrl)) {
                            originalUrl = url;
                            url = redirectedUrl;
                            jsoupDocument = null;
                            LOG.debug("Redirection (<meta http-equiv=\"refresh\" .../>): {} -> {}", originalUrl,
                                    url);
                            break;
                        }
                    }
                }
            }
        }
        // Meta redirection (<meta property="og:url" .../>)
        if (originalUrl == null) {
            for (final Element metaTag : metaTagsHtmlHeadMeta) {
                final Attributes metaTagAttributes = metaTag.attributes();
                if (metaTagAttributes.hasKey("property")
                        && metaTagAttributes.get("property").equalsIgnoreCase("og:url")
                        && metaTagAttributes.hasKey("content")) {
                    final String redirectedUrl = metaTagAttributes.get("content").trim();
                    if (isValidRedirection(url, redirectedUrl)) {
                        originalUrl = url;
                        url = redirectedUrl;
                        jsoupDocument = null;
                        LOG.debug("Redirection (<meta property=\"og:url\" .../>): {} -> {}", originalUrl, url);
                        break;
                    }
                }
            }
        }
    } catch (final Exception e) {
        if (e instanceof HttpStatusException) {
            statusCode = ((HttpStatusException) e).getStatusCode();
        }
        LOG.warn("Could not determine redirected URL for " + url, e);
    } finally {
        closeUrlConnection(urlConnection);
    }
    // Download content (if not yet done)
    String content = null;
    try {
        if (jsoupDocument == null) {
            LOG.debug("Downloading content from {}", url);
            urlConnection = getConnection(url);
            final InputStream urlInputStream = asInputStream(urlConnection, true, false);
            final Charset charset = getCharset(urlConnection);
            jsoupDocument = Jsoup.parse(urlInputStream, charset.name(), url);
        }
    } catch (final Exception e) {
        if (e instanceof HttpStatusException) {
            statusCode = ((HttpStatusException) e).getStatusCode();
        }
        // If the redirected URL does not exist, use the original URL instead
        if (originalUrl == null) {
            LOG.warn("Could not download content from " + url, e);
        }
        // If the redirected URL does not exist and a original URL is available, use the
        // original URL instead
        else {
            try {
                LOG.debug(
                        "Could not download content from redirected URL {}, downloading content from original URL {} instead",
                        url, originalUrl);
                urlConnection = getConnection(originalUrl);
                final InputStream urlInputStream = asInputStream(urlConnection, true, false);
                final Charset charset = getCharset(urlConnection);
                jsoupDocument = Jsoup.parse(urlInputStream, charset.name(), url);
                url = originalUrl;
                originalUrl = null;
                statusCode = null;
            } catch (final Exception e2) {
                LOG.warn("Could not download content from original URL " + url, e);
            }
        }
    } finally {
        closeUrlConnection(urlConnection);
    }
    if (jsoupDocument != null) {
        content = jsoupDocument.html();
    }
    // Strip non-valid characters as specified by the XML 1.0 standard
    final String validContent = xmlUtil.stripNonValidXMLCharacters(content);
    // Unescape HTML characters
    final String unescapedContent = StringEscapeUtils.unescapeHtml4(validContent);
    // Done
    final DownloadResult downloadResult = new DownloadResult(originalUrl, url, unescapedContent, downloaded,
            statusCode);
    return downloadResult;
}

From source file:io.toffees.mvc.model.BloodSample.java

public void setSampleTimeDate(LocalDateTime sampleDateTime) {
    this.sampleDateTime = LocalDateTime.now();
}

From source file:io.manasobi.utils.DateUtils.java

/**
 *  , ? ? , pattern ? ? ?? .<br><br>
 *
 * DateUtils.getNow("yyyy MM dd? hh mm ss") = "2012 04 12? 20 41 50"<br>
 * DateUtils.getNow("yyyy-MM-dd HH:mm:ss") = "2012-04-12 20:41:50"
 *
 * @param pattern  ? ?  ?/*from   w  w w  .  j a  va 2 s.com*/
 * @return patter ?  ?   
 */
public static String getNow(String pattern) {
    LocalDateTime dateTime = LocalDateTime.now();
    java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern(pattern);
    return dateTime.format(formatter);
}

From source file:beans.BL.java

public BL() {
    try {//from  w  w w  .  ja v a  2s .com
        emf = Persistence.createEntityManagerFactory("GPSPU");
        em = emf.createEntityManager();
    } catch (PersistenceException ex) {
        System.out.println("PersistenceEx +-+-+-+-+-+-+-+-+-+");
        LOGGER.log(Level.WARNING, "Fehler ", ex);
        System.out.println(ex.toString());
        reconnecting = true;
    }

    data_manager = new DataManager();

    track = new Track(LocalDateTime.now(), 1234);
    tracks.add(track);

    saveThread = new saveThread();
    saveThread.start();
}

From source file:com.swcguild.capstoneproject.dao.BlogDaoDbImplTest.java

/**
 * Test of getSearchPosts method, of class BlogDaoDbImpl.
 *///from w ww. j a va2  s .co  m
@Test
public void testGetSearchPosts() {
    System.out.println("getSearchPosts");
    String tag = "super";
    Post post1 = new Post("Supergirl", "Clark Kent", "hot new cousin saves city", "super, girl",
            LocalDateTime.now().toString(), "2015-12-20");
    Post post2 = new Post("Super", "Kent", "cousin saves city", "super", LocalDateTime.now().toString(),
            "2015-12-20");
    Post post3 = new Post("girl", "Clar", "new cousin saves city", "girl", LocalDateTime.now().toString(),
            "2015-12-20");
    post1.setStatus(1);
    post2.setStatus(1);
    post3.setStatus(1);
    dao.addPost(post1);
    dao.addPost(post2);
    dao.addPost(post3);
    List<Post> expResult = new ArrayList();
    expResult.add(post1);
    expResult.add(post2);
    List<Post> result = dao.getAllPosts();
    List<Post> result2 = dao.getSearchPosts("girl");
    assertEquals(expResult.size(), result2.size());

}

From source file:tech.beshu.ror.utils.integration.ElasticsearchTweetsInitializer.java

private void createMessage(RestClient client, String endpoint, String id, String user, String message) {
    try {//from   ww w. j  av  a2  s .c  o m
        HttpPut httpPut = new HttpPut(client.from(endpoint + id));
        httpPut.setHeader("Content-Type", "application/json");
        httpPut.setEntity(new StringEntity("{\n" + "\"user\" : \"" + user + "\",\n" + "\"post_date\" : \""
                + LocalDateTime.now().format(DateTimeFormatter.BASIC_ISO_DATE) + "\",\n" + "\"message\" : \""
                + message + "\"\n" + "}"));
        EntityUtils.consume(client.execute(httpPut).getEntity());
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Creating message failed", e);
    }
}

From source file:fi.helsinki.opintoni.integration.coursepage.CoursePageRestClientTest.java

@Test
public void thatEmptyNotificationListIsReturnedWithEmptyIds() {
    List<CoursePageNotification> notifications = coursePageRestClient
            .getCoursePageNotifications(Sets.newHashSet(), LocalDateTime.now(), Locale.ENGLISH);
    assertThat(notifications.isEmpty()).isTrue();
}