Example usage for java.time LocalDateTime toString

List of usage examples for java.time LocalDateTime toString

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Outputs this date-time as a String , such as 2007-12-03T10:15:30 .

Usage

From source file:Main.java

public static void main(String[] args) {
    LocalDateTime a = LocalDateTime.now();

    System.out.println(a.toString());
}

From source file:dhbw.clippinggorilla.external.twitter.TwitterUtils.java

private static Article fillArticle(Status status) {
    Article article = new Article();
    article.setTitle(status.getUser().getName());
    article.setDescription(status.getText());
    article.setBody(status.getText());//  ww w .  j  a  v  a 2s.c om
    article.setSource(SourceUtils.TWITTER);
    for (MediaEntity mediaEntity : status.getMediaEntities()) {
        if (!mediaEntity.getType().equals("video")) {
            article.setUrlToImage(mediaEntity.getMediaURL());
            break;
        }
    }
    if (article.getUrlToImage().isEmpty()) {
        article.setUrlToImage(status.getUser().getBiggerProfileImageURL());
    }
    article.setUrl("https://twitter.com/" + status.getUser().getScreenName() + "/status/" + status.getId());
    article.setId(status.getId() + "");
    article.setAuthor("@" + status.getUser().getScreenName());
    Date date = status.getCreatedAt();
    Instant instant = Instant.ofEpochMilli(date.getTime());
    LocalDateTime createdAt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
    article.setPublishedAt(createdAt.toString());
    return article;
}

From source file:ca.qhrtech.utilities.LocalDateTimeSerializer.java

@Override
public void serialize(LocalDateTime t, JsonGenerator jg, SerializerProvider sp)
        throws IOException, JsonProcessingException {
    jg.writeString(t.toString());
}

From source file:com.esri.geoevent.test.tools.RunTcpInTcpOutTest.java

public void send(String server, Integer port, Long numEvents, Integer rate) {
    Random rnd = new Random();
    BufferedReader br = null;/* www.  ja va 2 s  .  c om*/
    LocalDateTime st = null;

    try {
        Socket sckt = new Socket(server, port);
        OutputStream os = sckt.getOutputStream();
        //PrintWriter sckt_out = new PrintWriter(os, true);

        Integer cnt = 0;

        st = LocalDateTime.now();

        Double ns_delay = 1000000000.0 / (double) rate;

        long ns = ns_delay.longValue();
        if (ns < 0) {
            ns = 0;
        }

        while (cnt < numEvents) {
            cnt += 1;
            LocalDateTime ct = LocalDateTime.now();
            String dtg = ct.toString();
            Double lat = 180 * rnd.nextDouble() - 90.0;
            Double lon = 360 * rnd.nextDouble() - 180.0;
            String line = "RandomPoint," + cnt.toString() + "," + dtg + ",\"" + lon.toString() + ","
                    + lat.toString() + "\"," + cnt.toString() + "\n";

            final long stime = System.nanoTime();

            long etime = 0;
            do {
                etime = System.nanoTime();
            } while (stime + ns >= etime);

            if (cnt % 1000 == 0) {
                //System.out.println(cnt);
            }

            //sckt_out.write(line);
            os.write(line.getBytes());
            os.flush();

        }

        if (st != null) {
            LocalDateTime et = LocalDateTime.now();

            Duration delta = Duration.between(st, et);

            Double elapsed_seconds = (double) delta.getSeconds() + delta.getNano() / 1000000000.0;

            send_rate = (double) numEvents / elapsed_seconds;
        }

        //sckt_out.close();
        sckt.close();
        os = null;
        //sckt_out = null;

    } catch (Exception e) {
        System.err.println(e.getMessage());
        send_rate = -1.0;
    } finally {
        try {
            br.close();
        } catch (Exception e) {
            //
        }

        this.send_rate = send_rate;

    }

}

From source file:at.ac.tuwien.qse.sepm.gui.controller.impl.PhotoInspectorImpl.java

private void updateExifTable(Collection<Photo> photos) {

    // Fetch EXIF data for all photos.
    Collection<Exif> exifs = new ArrayList<>(photos.size());
    for (Photo photo : photos) {
        try {/* ww w .  j  av  a2 s  .  co m*/
            exifs.add(exifService.getExif(photo));
        } catch (ServiceException ex) {
            LOGGER.warn("failed loading EXIF data for photo {}", photo);
            LOGGER.error("", ex);
        }
    }

    exifList.getChildren().clear();
    addExifCell("Fotograf", photos, p -> {
        Photographer photographer = p.getData().getPhotographer();
        if (photographer == null)
            return null;
        return photographer.getName();
    });
    addExifCell("Datum", photos, p -> {
        LocalDateTime date = p.getData().getDatetime();
        if (date == null)
            return null;
        return date.toString().replace("T", " ");
    });
    addExifCell("Kamerahersteller", exifs, Exif::getMake);
    addExifCell("Kameramodell", exifs, Exif::getModel);
    addExifCell("Belichtungszeit", exifs, e -> e.getExposure() + " Sekunden");
    addExifCell("Blende", exifs, Exif::getAperture);
    addExifCell("Brennweite", exifs, Exif::getFocalLength);
    addExifCell("ISO", exifs, Exif::getIso);
    addExifCell("Blitz", exifs, e -> e.isFlash() ? "ausgelst" : "ohne");
    addExifCell("Hhe", exifs, Exif::getAltitude);
}

From source file:com.poc.restfulpoc.service.CustomerServiceTest.java

License:asdf

@Test
void testUpdateCustomer() throws EntityNotFoundException {
    LocalDateTime dateOfBirth = LocalDateTime.now();
    this.customer.setDateOfBirth(dateOfBirth);
    Customer res = this.customerService.updateCustomer(this.customer, RandomUtils.nextLong());
    assertThat(res).isNotNull();/*from   ww  w  .  ja v a  2 s .  c  om*/
    assertThat(res.getFirstName()).isNotNull().isEqualTo("firstName");
    assertThat(res.getDateOfBirth()).isNotNull().isEqualTo(dateOfBirth.toString());
}

From source file:controller.AddNewEC.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  www  .  j  a v a2  s .  co 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 {
    response.setContentType("text/html;charset=UTF-8");
    ExtenuatingCircumstance ec = new ExtenuatingCircumstance();
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            int year = 0;
            String fname = StringUtils.EMPTY;
            String title = StringUtils.EMPTY;
            String desciption = StringUtils.EMPTY;
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            ArrayList<FileItem> files = new ArrayList<>();
            for (FileItem item : multiparts) {
                if (item.isFormField()) {
                    if (item.getFieldName().equals("year")) {
                        year = Integer.parseInt(item.getString());
                    }
                    if (item.getFieldName().equals("title")) {
                        title = item.getString();
                    }
                    if (item.getFieldName().equals("description")) {
                        desciption = item.getString();
                    }

                } else {
                    if (StringUtils.isNotEmpty(item.getName())) {
                        files.add(item);
                    }
                }
            }

            HttpSession session = request.getSession(false);
            Account studentAccount = (Account) session.getAttribute("account");
            LocalDateTime now = WsadUtils.GetCurrentDatetime();

            // insert EC
            ec.setAcademicYear(year);
            ec.setTitle(title);
            ec.setDescription(desciption);
            ec.setProcess_status("submitted");
            ec.setSubmitted_date(now.toString());
            ec.setAccount(studentAccount.getId());

            ExtenuatingCircumstance insertedEC = new ExtenuatingCircumstanceDAO().insertEC(ec);

            //insert assigned coordinator
            Account coordinator = new AccountDAO().getCoordinator(studentAccount.getFaculty());
            insertAssignedCoordinator(coordinator, insertedEC);

            //insert evidence
            insertedEvidence(files, now, insertedEC, studentAccount);

            String mailContent = WsadUtils.buildMailContentForNewEC(insertedEC);
            SendMail.sendMail(coordinator.getEmail(), "New EC", mailContent);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    request.setAttribute("resultMsg", "inserted");
    request.getRequestDispatcher("AddNewECResult.jsp").forward(request, response);
}

From source file:dhbw.clippinggorilla.external.solr.SOLR.java

public static LinkedHashSet<Article> getArticlesFromSolr(Set<String> includedTagsSet,
        Set<String> excludedTagsSet, Map<Source, Boolean> sourcesMap, LocalDateTime date) {
    SolrQuery query = new SolrQuery();

    String include = "";
    String exclude;// w w w  .  ja va  2  s . co m
    String sources = "source:\"";

    List<String> includedTags = new ArrayList<>(includedTagsSet);
    if (includedTags.size() > 0) {
        include = "(" + replaceWhitespaces(includedTags.get(0), true) + ")";
        for (int i = 1; i < includedTags.size(); i++) {
            include += " OR " + "(" + replaceWhitespaces(includedTags.get(i), true) + ")";
        }
    }

    List<String> excludedTags = new ArrayList<>(excludedTagsSet);
    if (excludedTags.size() > 0) {
        exclude = "-(" + replaceWhitespaces(excludedTags.get(0), false) + ")";
        for (int i = 1; i < excludedTags.size(); i++) {
            exclude += " AND " + "-(" + replaceWhitespaces(excludedTags.get(i), false) + ")";
        }
        query.addFilterQuery(exclude);
    }

    for (Map.Entry<Source, Boolean> entry : sourcesMap.entrySet()) {
        if (entry.getValue()) {
            sources = sources.concat(entry.getKey().getId() + "\" OR \"");
        }
    }
    sources = sources.substring(0, sources.length() - 5);

    query.setQuery(include);
    query.set("qf", "title^3 description^2 body");
    query.addFilterQuery("publishedAt:[" + date.toString() + " TO NOW]");
    query.addFilterQuery(sources);

    if (client == null) {
        setServer();
    }

    try {
        QueryResponse queryResponse = client.query(query);
        List<Article> response = queryResponse.getBeans(Article.class);
        return new LinkedHashSet<>(response);
    } catch (SolrServerException | IOException e) {
        Log.error("Solr: Can't Query", e);
        return new LinkedHashSet<>();
    }
}

From source file:com.poc.restfulpoc.controller.CustomerControllerTest.java

@Test
void testUpdateCustomer() throws Exception {
    given(this.customerService.getCustomer(ArgumentMatchers.anyLong())).willReturn(this.customer);
    LocalDateTime dateOfBirth = LocalDateTime.now();
    this.customer.setDateOfBirth(dateOfBirth);
    given(this.customerService.updateCustomer(ArgumentMatchers.any(Customer.class), ArgumentMatchers.anyLong()))
            .willReturn(this.customer);

    this.mockMvc//from   w  w  w  . j  a v  a 2  s  .c  o  m
            .perform(MockMvcRequestBuilders.put("/rest/customers/{customerId}", RandomUtils.nextLong())
                    .content(this.objectMapper.writeValueAsString(this.customer))
                    .contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(status().isOk()).andExpect(jsonPath("firstName").value("firstName"))
            .andExpect(jsonPath("lastName").value("lastName"))
            .andExpect(jsonPath("dateOfBirth").value(dateOfBirth.toString()));
}

From source file:net.resheim.eclipse.timekeeper.ui.Activator.java

/**
 * Must be called by the UI-thread/*from   w  w  w  .  j  ava 2  s  .  c  o m*/
 *
 * @param idleTimeMillis
 */
private void handleReactivation(long idleTimeMillis) {
    // We want only one dialog open.
    if (dialogIsOpen) {
        return;
    }
    synchronized (this) {
        if (idleTimeMillis < lastIdleTime && lastIdleTime > IDLE_INTERVAL) {
            // If we have an active task
            ITask task = TasksUi.getTaskActivityManager().getActiveTask();
            if (task != null && Activator.getValue(task, Activator.START) != null) {
                dialogIsOpen = true;
                String tickString = Activator.getValue(task, Activator.TICK);
                LocalDateTime started = getActiveSince();
                LocalDateTime ticked = LocalDateTime.parse(tickString);
                LocalDateTime lastTick = ticked;
                // Subtract the IDLE_INTERVAL time the computer _was_
                // idle while counting up to the threshold. During this
                // period fields were updated. Thus must be adjusted for.
                ticked = ticked.minusNanos(IDLE_INTERVAL);
                String time = DurationFormatUtils.formatDuration(lastIdleTime, "H:mm:ss", true);

                StringBuilder sb = new StringBuilder();
                if (task.getTaskKey() != null) {
                    sb.append(task.getTaskKey());
                    sb.append(": ");
                }
                sb.append(task.getSummary());
                MessageDialog md = new MessageDialog(Display.getCurrent().getActiveShell(),
                        "Disregard idle time?", null,
                        MessageFormat.format(
                                "The computer has been idle since {0}, more than {1}. The active task \"{2}\" was started on {3}. Deactivate the task and disregard the idle time?",
                                ticked.format(DateTimeFormatter.ofPattern("EEE e, HH:mm:ss", Locale.US)), time,
                                sb.toString(),
                                started.format(DateTimeFormatter.ofPattern("EEE e, HH:mm:ss", Locale.US))),
                        MessageDialog.QUESTION, new String[] { "No", "Yes" }, 1);
                int open = md.open();
                dialogIsOpen = false;
                if (open == 1) {
                    // Stop task, subtract initial idle time
                    TasksUi.getTaskActivityManager().deactivateTask(task);
                    reduceTime(task, ticked.toLocalDate().toString(), IDLE_INTERVAL / 1000);
                } else {
                    // Continue task, add idle time
                    LocalDateTime now = LocalDateTime.now();
                    long seconds = lastTick.until(now, ChronoUnit.MILLIS);
                    accumulateTime(task, ticked.toLocalDate().toString(), seconds);
                    Activator.setValue(task, Activator.TICK, now.toString());
                }
            }
        }
    }
}