Example usage for java.time LocalDateTime from

List of usage examples for java.time LocalDateTime from

Introduction

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

Prototype

public static LocalDateTime from(TemporalAccessor temporal) 

Source Link

Document

Obtains an instance of LocalDateTime from a temporal object.

Usage

From source file:com.cohesionforce.dis.ConvertCSV.java

public void run() {

    int count = 0;

    System.out.println("Opening file to convert: " + inputFile);
    BufferedReader br;/*  w  w w  .j a  va  2 s  . c  o m*/
    try {
        br = new BufferedReader(new FileReader(inputFile));
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        return;
    }

    startWriters();
    marking.setCharacterSet(0);

    dr.setDeadReckoningAlgorithm(2);
    dr.setEntityLinearAcceleration(zeroVector);
    dr.setEntityAngularVelocity(zeroVector);

    System.out.println("Starting to convert PDUs");

    while (done == false) {
        String line = null;
        try {
            line = br.readLine(); // throw away header

            // medallion, hack_license, vendor_id, rate_code,
            // store_and_fwd_flag,pickup_datetime,dropoff_datetime,passenger_count,
            // trip_time_in_secs,trip_distance,pickup_longitude,pickup_latitude,
            // dropoff_longitude,dropoff_latitude
            while ((line = br.readLine()) != null) {
                String[] pieces = line.split(cvsSplitBy);

                String medallion = pieces[0];

                LocalDateTime localTime = LocalDateTime.from(formatter.parse(pieces[5]));
                ZonedDateTime zoneTime = localTime.atZone(ZoneId.of("America/New_York"));
                long ts = zoneTime.toInstant().toEpochMilli();

                EntityStatePdu output = getNewEntityState(medallion);
                output.setTimestamp(ts);

                // Create EntityLocation from string
                double plon = Double.parseDouble(pieces[10]);
                double plat = Double.parseDouble(pieces[11]);
                Vector3Double loc = getLocation(plon, plat);
                output.setEntityLocation(loc);

                logPdu(output, 1);

                if (++count % 100000 == 0) {
                    System.out.println("Converted " + count + " PDUs");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        done = true;
    } // end
    try {
        br.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    System.out.print("Waiting on writers to clear their queues");

    boolean emptyQueue = false;
    while (!emptyQueue)

    {
        emptyQueue = true;
        for (LogWriter<?> writer : writers) {
            // If any queue is not empty, sleep and check again
            if (!writer.getQueue().isEmpty()) {
                try {
                    emptyQueue = false;
                    System.out.print(".");
                    Thread.sleep(1000);
                    break;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    System.out.println("");
    System.out.println("PDUs converted: " + count);
    System.out.println("Shutting down logging threads");
    threadGroup.interrupt();

    int tries = 0;
    while (threadGroup.activeCount() > 0 && tries < 10)

    {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
        }
        ++tries;
    }
    System.out.println("Completed logging threads shutdown");

}

From source file:com.gigglinggnus.controllers.CheckinController.java

private JSONArray getAppointments(User user, Term term, Clock clk) {
    Instant now = Instant.now(clk);
    //return a list of appointments in this term
    List<Appointment> appts = user.getAppointments().stream().filter(appt -> appt.getTerm().equals(term))
            .filter(appt -> !appt.isStudentCheckedIn()).collect(Collectors.toList());
    //sorted by distance to current time
    Collections.sort(appts,/*w w  w.j  av a 2  s.  c o m*/
            (Appointment a1, Appointment a2) -> Duration.between(now, a1.getInterval().getStart()).abs()
                    .compareTo(Duration.between(now, a1.getInterval().getStart()).abs()));

    JSONArray json = new JSONArray();

    for (Appointment appt : appts) {
        String examId = appt.getExam().getExamId();
        String startTime = LocalDateTime.from(appt.getInterval().getStart().atZone(ZoneId.systemDefault()))
                .toString();
        String seatNum = appt.prettySeat();
        //write JSON
        JSONObject elem = new JSONObject();
        elem.put("exam", examId);
        elem.put("start", startTime);
        elem.put("seat", seatNum);
        json.put(elem);
    }
    return json;
}

From source file:msi.gama.util.GamaDate.java

public GamaDate(final IScope scope, final GamaDate other) {
    this(scope, LocalDateTime.from(other));
}

From source file:com.orange.clara.cloud.servicedbdumper.task.job.JobFactory.java

@Transactional
public void purgeErroredJobs() {
    LocalDateTime whenRemoveDateTime;
    List<Job> jobs = jobRepo.findByJobEventOrderByUpdatedAtDesc(JobEvent.ERRORED);
    for (Job job : jobs) {
        whenRemoveDateTime = LocalDateTime.from(job.getUpdatedAt().toInstant().atZone(ZoneId.systemDefault()))
                .plusDays(this.jobErroredDeleteExpirationDays);
        if (LocalDateTime.from(Calendar.getInstance().toInstant().atZone(ZoneId.systemDefault()))
                .isBefore(whenRemoveDateTime)) {
            continue;
        }//from w ww  .j  a  v a  2  s . c  om
        this.jobRepo.delete(job);
    }
}

From source file:com.orange.clara.cloud.servicedbdumper.task.job.JobFactory.java

@Transactional
public void purgeFinishedJob() {
    LocalDateTime whenRemoveDateTime;
    List<Job> jobs = jobRepo.findByJobEventOrderByUpdatedAtDesc(JobEvent.FINISHED);
    for (Job job : jobs) {
        whenRemoveDateTime = LocalDateTime.from(job.getUpdatedAt().toInstant().atZone(ZoneId.systemDefault()))
                .plusMinutes(this.jobFinishedDeleteExpirationMinutes);
        if (LocalDateTime.from(Calendar.getInstance().toInstant().atZone(ZoneId.systemDefault()))
                .isBefore(whenRemoveDateTime)
                && (job.getDatabaseRefSrc() != null || job.getDbDumperServiceInstance() != null
                        || job.getDatabaseRefTarget() != null)) {
            continue;
        }//  w w  w .j av a  2  s . c  om
        this.jobRepo.delete(job);
    }
}

From source file:org.openmrs.module.operationtheater.api.impl.OperationTheaterServiceImpl.java

@Override
public Interval getLocationAvailableTime(Location location, LocalDate date) {
    Date date1 = Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant());
    Date date2 = Date.from(date.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
    List<AppointmentBlock> blocks = appointmentService.getAppointmentBlocks(date1, date2,
            location.getId() + ",", null, null);
    //      List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();

    if (blocks.size() == 1) {
        //         return new Interval(new DateTime(blocks.get(0).getStartDate()), new DateTime(blocks.get(0).getEndDate()));
        Instant startInstant = LocalDateTime.from(blocks.get(0).getStartDate().toInstant())
                .toInstant(ZoneOffset.UTC);
        Instant endInstant = LocalDateTime.from(blocks.get(0).getEndDate().toInstant())
                .toInstant(ZoneOffset.UTC);
        return Interval.of(startInstant, endInstant);
    } else if (blocks.size() > 1) {
        throw new APIException("There shouldn't be multiple appointment blocks per location and date");
    }/*from w w w .ja  v  a 2 s  . c  om*/

    DateTimeFormatter timeFormatter = OTMetadata.AVAILABLE_TIME_FORMATTER;
    LocalDateTime availableStart = null;
    LocalDateTime availableEnd = null;
    for (LocationAttribute attribute : location.getAttributes()) {
        if (attribute.getAttributeType().getUuid().equals(OTMetadata.DEFAULT_AVAILABLE_TIME_BEGIN_UUID)) {
            LocalTime beginTime = LocalTime.parse((String) attribute.getValue(), timeFormatter);
            //            availableStart = date.withTime(beginTime.getHourOfDay(), beginTime.getMinuteOfHour(), 0, 0);
            availableStart = date.atTime(beginTime.getHour(), beginTime.getMinute());
        } else if (attribute.getAttributeType().getUuid().equals(OTMetadata.DEFAULT_AVAILABLE_TIME_END_UUID)) {
            LocalTime endTime = LocalTime.parse((String) attribute.getValue(), timeFormatter);
            //            availableEnd = date.withTime(endTime.getHourOfDay(), endTime.getMinuteOfHour(), 0, 0);
            availableEnd = date.atTime(endTime.getHour(), endTime.getMinute());
        }
    }

    if (availableStart != null && availableEnd != null) {
        return Interval.of(availableStart.toInstant(ZoneOffset.UTC), availableEnd.toInstant(ZoneOffset.UTC));
    }

    throw new APIException("Available times not defined. please make sure that the attributes "
            + "'default available time begin' and 'default available time end' for the location "
            + location.getName() + " are defined");

}

From source file:msi.gama.util.GamaDate.java

private static Temporal parse(final IScope scope, final String original, final DateTimeFormatter df) {
    if (original == null || original.isEmpty() || original.equals("now")) {
        return LocalDateTime.now(GamaDateType.DEFAULT_ZONE);
    }/*from   ww w.j  av a  2s  .  co  m*/
    Temporal result = null;

    if (df != null) {
        try {
            final TemporalAccessor ta = df.parse(original);
            if (ta instanceof Temporal) {
                return (Temporal) ta;
            }
            if (!ta.isSupported(ChronoField.YEAR) && !ta.isSupported(ChronoField.MONTH_OF_YEAR)
                    && !ta.isSupported(ChronoField.DAY_OF_MONTH)) {
                if (ta.isSupported(ChronoField.HOUR_OF_DAY)) {
                    return LocalTime.from(ta);
                }
            }
            if (!ta.isSupported(ChronoField.HOUR_OF_DAY) && !ta.isSupported(ChronoField.MINUTE_OF_HOUR)
                    && !ta.isSupported(ChronoField.SECOND_OF_MINUTE)) {
                return LocalDate.from(ta);
            }
            return LocalDateTime.from(ta);
        } catch (final DateTimeParseException e) {
            e.printStackTrace();
        }
        GAMA.reportAndThrowIfNeeded(scope,
                GamaRuntimeException.warning(
                        "The date " + original + " can not correctly be parsed by the pattern provided", scope),
                false);
        return parse(scope, original, null);
    }

    String dateStr;
    try {
        // We first make sure all date fields have the correct length and
        // the string is correctly formatted
        String string = original;
        if (!original.contains("T") && original.contains(" ")) {
            string = StringUtils.replaceOnce(original, " ", "T");
        }
        final String[] base = string.split("T");
        final String[] date = base[0].split("-");
        String other;
        if (base.length == 1) {
            other = "00:00:00";
        } else {
            other = base[1];
        }
        String year, month, day;
        if (date.length == 1) {
            // ISO basic date format
            year = date[0].substring(0, 4);
            month = date[0].substring(4, 6);
            day = date[0].substring(6, 8);
        } else {
            year = date[0];
            month = date[1];
            day = date[2];
        }
        if (year.length() == 2) {
            year = "20" + year;
        }
        if (month.length() == 1) {
            month = '0' + month;
        }
        if (day.length() == 1) {
            day = '0' + day;
        }
        dateStr = year + "-" + month + "-" + day + "T" + other;
    } catch (final Exception e1) {
        throw GamaRuntimeException.error("The date " + original
                + " is not correctly formatted. Please refer to the ISO date/time format", scope);
    }

    try {
        result = LocalDateTime.parse(dateStr);
    } catch (final DateTimeParseException e) {
        try {
            result = OffsetDateTime.parse(dateStr);
        } catch (final DateTimeParseException e2) {
            try {
                result = ZonedDateTime.parse(dateStr);
            } catch (final DateTimeParseException e3) {
                throw GamaRuntimeException.error(
                        "The date " + original
                                + " is not correctly formatted. Please refer to the ISO date/time format",
                        scope);
            }
        }
    }

    return result;
}

From source file:org.talend.dataprep.transformation.actions.date.ComputeTimeSince.java

@Override
public void applyOnColumn(DataSetRow row, ActionContext context) {
    RowMetadata rowMetadata = context.getRowMetadata();
    Map<String, String> parameters = context.getParameters();
    String columnId = context.getColumnId();

    final String newColumnId = context.column("result");

    TemporalUnit unit = ChronoUnit.valueOf(parameters.get(TIME_UNIT_PARAMETER).toUpperCase());
    String newValue;/* w  ww .  ja v a2 s . com*/
    try {
        String mode = context.get(SINCE_WHEN_PARAMETER);
        LocalDateTime since;
        switch (mode) {
        case OTHER_COLUMN_MODE:
            ColumnMetadata selectedColumn = rowMetadata.getById(parameters.get(SELECTED_COLUMN_PARAMETER));
            String dateToCompare = row.get(selectedColumn.getId());
            since = Providers.get().parse(dateToCompare, selectedColumn);
            break;
        case SPECIFIC_DATE_MODE:
        case NOW_SERVER_SIDE_MODE:
        default:
            since = context.get(SINCE_DATE_PARAMETER);
            break;
        }

        // parse the date
        if (since == null) {
            newValue = StringUtils.EMPTY;
        } else {
            String value = row.get(columnId);
            LocalDateTime temporalAccessor = Providers.get().parse(value,
                    context.getRowMetadata().getById(columnId));
            Temporal valueAsDate = LocalDateTime.from(temporalAccessor);
            newValue = String.valueOf(unit.between(valueAsDate, since));
        }
    } catch (DateTimeException e) {
        LOGGER.trace("Error on dateTime parsing", e);
        // Nothing to do: in this case, temporalAccessor is left null
        newValue = StringUtils.EMPTY;
    }
    row.set(newColumnId, newValue);
}

From source file:com.orange.clara.cloud.servicedbdumper.task.job.JobFactoryTest.java

@Test
public void when_purge_errored_jobs_and_jobs_in_error_exist_it_should_delete_job_which_pass_expiration() {
    Job jobNotExpired = new Job();
    jobNotExpired.setUpdatedAt(new Date());

    Date date = new Date();
    LocalDateTime localDateTime = LocalDateTime.from(date.toInstant().atZone(ZoneId.systemDefault()))
            .minusDays(jobErroredDeleteExpirationDays + 1);
    Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
    Job jobExpired = new Job();
    jobExpired.setUpdatedAt(Date.from(instant));

    when(jobRepo.findByJobEventOrderByUpdatedAtDesc(anyObject()))
            .thenReturn(Arrays.asList(jobNotExpired, jobExpired));
    jobFactory.purgeErroredJobs();/*w  w  w.  ja v  a  2 s  . c  o  m*/
    verify(jobRepo, times(1)).delete((Job) notNull());
}

From source file:com.orange.clara.cloud.servicedbdumper.task.job.JobFactoryTest.java

@Test
public void when_purge_finished_jobs_and_jobs_in_error_exist_it_should_delete_job_which_pass_expiration_and_have_null_database_target_and_source_and_service_instance() {
    Job jobNotExpired = new Job();
    jobNotExpired.setUpdatedAt(new Date());
    jobNotExpired.setDatabaseRefSrc(new DatabaseRef());

    Date date = new Date();
    LocalDateTime localDateTime = LocalDateTime.from(date.toInstant().atZone(ZoneId.systemDefault()))
            .minusMinutes(jobFinishedDeleteExpirationMinutes + 1);
    Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
    Job jobExpired = new Job();
    jobExpired.setUpdatedAt(Date.from(instant));

    when(jobRepo.findByJobEventOrderByUpdatedAtDesc(anyObject()))
            .thenReturn(Arrays.asList(jobNotExpired, jobExpired));
    jobFactory.purgeFinishedJob();//from  w ww. ja  v a  2 s .c o m
    verify(jobRepo, times(1)).delete((Job) notNull());
}