Example usage for java.time Instant from

List of usage examples for java.time Instant from

Introduction

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

Prototype

public static Instant from(TemporalAccessor temporal) 

Source Link

Document

Obtains an instance of Instant from a temporal object.

Usage

From source file:Main.java

public static void main(String[] args) {
    Instant instant = Instant.from(ZonedDateTime.now());
    System.out.println(instant.getEpochSecond());

}

From source file:com.rcs.shoe.shop.fx.utils.DateUtils.java

public static Date convert(LocalDate localDate) {
    Instant instant = Instant.from(localDate.atStartOfDay(ZoneId.systemDefault()));
    return Date.from(instant);
}

From source file:fr.lepellerin.ecole.service.internal.CantineServiceImpl.java

@Override
@Transactional(readOnly = true)/*from   w w w  . j  a v  a 2s  . c  o  m*/
public PlanningDto getDateOuvert(final YearMonth anneeMois, final Famille famille) throws TechnicalException {
    final Date startDate = Date.from(Instant.from(anneeMois.atDay(1).atStartOfDay(ZoneId.systemDefault())));
    final Date endDate = Date.from(Instant.from(anneeMois.atEndOfMonth().atStartOfDay(ZoneId.systemDefault())));

    final Activite activite = getCantineActivite();

    final LocalDateTime heureH = LocalDateTime.now();
    final List<Inscription> icts = this.ictRepository.findByActiviteAndFamille(activite, famille);

    final PlanningDto planning = new PlanningDto();

    icts.forEach(ict -> {
        planning.getHeaders().add(ict.getIndividu().getPrenom());
        final List<Consommation> consos = this.consommationRepository
                .findByFamilleInscriptionActiviteUniteEtatsPeriode(famille, activite, ict.getGroupe(),
                        Arrays.asList("reservation"), startDate, endDate);
        final List<Ouverture> ouvertures = this.ouvertureRepository.findByActiviteAndGroupeAndPeriode(activite,
                ict.getGroupe(), startDate, endDate);
        ouvertures.forEach(o -> {
            final LocalDate date = LocalDate.from(((java.sql.Date) o.getDate()).toLocalDate());
            final LocalDateTime heureResa = this.getLimiteResaCantine(date);
            final LigneDto ligne = planning.getOrCreateLigne(date);
            final CaseDto c = new CaseDto();
            c.setDate(date);
            c.setIndividu(ict.getIndividu());
            c.setActivite(o.getActivite());
            c.setUnite(o.getUnite());
            c.setReservable(heureResa.isAfter(heureH));
            final Optional<Consommation> cOpt = consos.stream().filter(conso -> {
                final LocalDate dateConso = LocalDate.from(((java.sql.Date) conso.getDate()).toLocalDate());
                return dateConso.equals(date);
            }).findAny();
            c.setReserve(cOpt.isPresent());
            ligne.getCases().add(c);
        });
    });

    return planning;
}

From source file:no.ssb.jsonstat.v2.deser.DatasetDeserializer.java

Instant parseEcmaDate(String value) {
    return Instant.from(ECMA_FORMATTER.parse(value));
}

From source file:controllers.VersionSpecificationController.java

/**
 * The primary endpoint for Evergreen. Given a set of host attributes, this endpoint returns the
 * appropriate version set as determined by the set of <code>VersionSpecifications</code> and their
 * associated <code>VersionSets</code>. See the README.md for more information.
 *
 * @return <code>Result</code> VersionSet
 *//*from w  w w.  j  a  va2s .  c o  m*/
public Result lookupHostVersionSet() {

    // If the queryString contains multiple values for a single parameter, select the last parameter.
    final Map<String, String> hostAttributes = selectLastQueryParams(request().queryString());

    Optional<Instant> ifModifiedSince = Optional.empty();
    if (request().hasHeader(IF_MODIFIED_SINCE)) {
        ifModifiedSince = Optional
                .of(Instant.from(RFC_1123_DATE_TIME.parse(request().getHeader(IF_MODIFIED_SINCE))));
    }

    final VersionSetLookupResult versionSetResult = _versionSpecificationRepository
            .lookupVersionSetByHostAttributes(hostAttributes, ifModifiedSince);

    if (versionSetResult.isNotFound()) {
        // This is an error in the Evergreen dataset: there should always be a default/fallback version set specified.
        LOGGER.error().setMessage("No VersionSet found for host attributes")
                .addData("hostAttributes", hostAttributes).log();
        return internalServerError();
    } else if (versionSetResult.isNotModified()) {
        return status(304, "Not Modified");
    } else if (!versionSetResult.getVersionSet().isPresent()) {
        // Unknown result must have been added to VersionSetLookupResult
        LOGGER.error().setMessage("Unknown result from lookupVersionSetByHostAttributes()").log();
        return internalServerError();
    }
    response().setHeader(LAST_MODIFIED, RFC_1123_DATE_TIME.format(versionSetResult.getLastModified().get()));
    return ok(Json.toJson(internalToViewModel(versionSetResult.getVersionSet().get())));
}

From source file:dk.dbc.rawrepo.oai.ResumptionTokenTest.java

@Test
public void testXmlExpiration() throws Exception {
    ObjectNode jsonOriginal = (ObjectNode) new ObjectMapper().readTree("{\"foo\":\"bar\"}");

    long now = Instant.now().getEpochSecond();
    ResumptionTokenType token = ResumptionToken.toToken(jsonOriginal, 0);

    OAIPMH oaipmh = OBJECT_FACTORY.createOAIPMH();
    ListRecordsType getRecord = OBJECT_FACTORY.createListRecordsType();
    oaipmh.setListRecords(getRecord);/*from   w w w  .j ava2 s  .  co m*/
    getRecord.setResumptionToken(token);
    JAXBContext context = JAXBContext.newInstance(OAIPMH.class);
    StringWriter writer = new StringWriter();
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(oaipmh, writer);
    String xml = writer.getBuffer().toString();
    System.out.println("XML is:\n" + xml);
    int start = xml.indexOf("expirationDate=\"") + "expirationDate=\"".length();
    int end = xml.indexOf("\"", start);
    String timestamp = xml.substring(start, end);
    System.out.println("timestamp = " + timestamp);

    assertTrue("Timestamp should be in ISO_INSTANT ending with Z", timestamp.endsWith("Z"));
    TemporalAccessor parse = DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.systemDefault()).parse(timestamp);
    long epochSecond = Instant.from(parse).getEpochSecond();
    long diff = Math.abs(now - epochSecond);
    System.out.println("diff = " + diff);
    assertTrue("Difference between expirationdate and now should be 10 sec or less", diff <= 10);
}

From source file:com.sludev.mssqlapplylog.MSSQLApplyLog.java

@Override
public Integer call() throws Exception {
    Integer res = 0;/*from   ww w.  j a va 2  s. c om*/

    String backupDirStr = config.getBackupDirStr();
    String fullBackupPathStr = config.getFullBackupPathStr();
    String fullBackupDatePatternStr = config.getFullBackupDatePatternStr();
    String laterThanStr = config.getLaterThanStr();
    String fullBackupPatternStr = config.getFullBackupPatternStr();
    String logBackupPatternStr = config.getLogBackupPatternStr();
    String logBackupDatePatternStr = config.getLogBackupDatePatternStr();

    String sqlHost = config.getSqlHost();
    String sqlDb = config.getSqlDb();
    String sqlUser = config.getSqlUser();
    String sqlPass = config.getSqlPass();
    String sqlURL = config.getSqlUrl();
    String sqlProcessUser = config.getSqlProcessUser();

    boolean useLogFileLastMode = BooleanUtils.isTrue(config.getUseLogFileLastMode());
    boolean doFullRestore = BooleanUtils.isTrue(config.getDoFullRestore());
    boolean monitorLogBackupDir = BooleanUtils.isTrue(config.getMonitorLogBackupDir());

    Path backupsDir = null;
    Instant laterThan = null;

    Path fullBackupPath = null;

    // Validate the Log Backup Directory
    if (StringUtils.isBlank(backupDirStr)) {
        LOGGER.error("Invalid blank/empty backup directory");

        return 1;
    }

    try {
        backupsDir = Paths.get(backupDirStr);
    } catch (Exception ex) {
        LOGGER.error(String.format("Error parsing Backup Directory '%s'", backupDirStr), ex);

        return 1;
    }

    if (Files.notExists(backupsDir)) {
        LOGGER.error(String.format("Invalid non-existant backup directory '%s'", backupsDir));

        return 1;
    }

    if (StringUtils.isBlank(logBackupPatternStr)) {
        LOGGER.warn(String.format(
                "\"Log Backup Pattern\" cannot be empty.  Defaulting to " + "%s regex in backup directory",
                DEFAULT_LOG_FILE_PATTERN_STR));

        logBackupPatternStr = DEFAULT_LOG_FILE_PATTERN_STR;
    }

    if (StringUtils.isNoneBlank(fullBackupPathStr)) {
        fullBackupPath = Paths.get(fullBackupPathStr);
        if (Files.notExists(fullBackupPath) || Files.isRegularFile(fullBackupPath) == false) {
            LOGGER.error(String.format("Invalid Full Backup file '%s'", backupDirStr));

            return 1;
        }
    }

    if (StringUtils.isNoneBlank(fullBackupDatePatternStr) && StringUtils.isBlank(laterThanStr)
            && fullBackupPath != null) {
        // Retrieve the "Later Than" date from the full backup file name
        laterThan = FSHelper.getTimestampFromFilename(fullBackupPatternStr, fullBackupDatePatternStr, 1,
                fullBackupPath);
        if (laterThan == null) {
            LOGGER.error("'Later Than' cannot be null");

            return 1;
        }
    } else {
        // Use the "Later Than" timestamp from the command line or properties
        // file.

        try {
            laterThan = Instant.from(DateTimeFormatter.ISO_INSTANT.parse(laterThanStr));
        } catch (Exception ex) {
            LOGGER.error(String.format("Error parsing 'Later Than' time '%s'", laterThanStr), ex);
        }
    }

    try {
        Class.forName("net.sourceforge.jtds.jdbc.Driver");
    } catch (ClassNotFoundException ex) {
        LOGGER.error("Error loading SQL Server driver [ net.sourceforge.jtds.jdbc.Driver ]", ex);

        return 1;
    }

    if (StringUtils.isBlank(sqlURL)) {
        // Build the SQL URL
        sqlURL = String.format("jdbc:jtds:sqlserver://%s;DatabaseName=master", sqlHost);
    }

    Properties props = new Properties();

    props.setProperty("user", sqlUser);
    props.setProperty("password", sqlPass);

    try (Connection conn = MSSQLHelper.getConn(sqlURL, props)) {
        if (conn == null) {
            LOGGER.error("Connection to MSSQL failed.");

            return 1;
        }

        if (doFullRestore) {
            LOGGER.info(String.format("\nStarting full restore of '%s'...", fullBackupPathStr));

            StopWatch sw = new StopWatch();

            sw.start();

            String strDevice = fullBackupPathStr;

            String query = String.format("RESTORE DATABASE %s FROM DISK='%s' WITH NORECOVERY, REPLACE", sqlDb,
                    strDevice);

            Statement stmt = null;

            try {
                stmt = conn.createStatement();
            } catch (SQLException ex) {
                LOGGER.debug("Error creating statement", ex);

                return 1;
            }

            try {
                boolean sqlRes = stmt.execute(query);
            } catch (SQLException ex) {
                LOGGER.error(String.format("Error executing...\n'%s'", query), ex);

                return 1;
            }

            sw.stop();

            LOGGER.debug(String.format("Query...\n'%s'\nTook %s", query, sw.toString()));
        }
    } catch (SQLException ex) {
        LOGGER.error("SQL Exception restoring the full backup", ex);
    }

    // Filter the log files.

    // Loop multiple times to catch new logs that have been transferred
    // while we process.
    List<Path> files = null;
    do {
        try {
            files = FSHelper.listLogFiles(backupsDir, laterThan, useLogFileLastMode, logBackupPatternStr,
                    logBackupDatePatternStr, files);
        } catch (IOException ex) {
            LOGGER.error("Log Backup file filter/sort failed", ex);

            return 1;
        }

        if (files == null || files.isEmpty()) {
            LOGGER.debug("No Log Backup files found this iteration.");

            continue;
        }

        StringBuilder msg = new StringBuilder();

        for (Path file : files) {
            msg.append(String.format("file : '%s'\n", file));
        }

        LOGGER.debug(msg.toString());

        // Restore all log files
        try (Connection conn = MSSQLHelper.getConn(sqlURL, props)) {
            for (Path p : files) {
                try {
                    MSSQLHelper.restoreLog(p, sqlProcessUser, sqlDb, conn);
                } catch (SQLException ex) {
                    LOGGER.error(String.format("SQL Exception restoring the log backup '%s'", p), ex);
                }
            }
        } catch (SQLException ex) {
            LOGGER.error("SQL Exception restoring the log backup", ex);
        }
    } while (files != null && files.isEmpty() == false);

    if (monitorLogBackupDir) {
        // Watch for new log files
        List<Path> paths = new ArrayList();
        paths.add(backupsDir);

        final Watch watch;
        final String currSQLDb = sqlDb;
        final String currSQLProcUser = sqlProcessUser;
        final String currSQLURL = sqlURL;
        final String currLogBackupPatternStr = logBackupPatternStr;

        try {
            watch = Watch.from(paths);
            watch.processEvents((WatchEvent<Path> event, Path path) -> {
                int watchRes = 0;

                if (event.kind() != StandardWatchEventKinds.ENTRY_CREATE) {
                    return watchRes;
                }

                Pattern fileMatcher = Pattern.compile(currLogBackupPatternStr);

                if (fileMatcher.matcher(path.getFileName().toString()).matches()) {
                    try (Connection conn = MSSQLHelper.getConn(currSQLURL, props)) {
                        MSSQLHelper.restoreLog(path, currSQLProcUser, currSQLDb, conn);
                    } catch (SQLException ex) {
                        // There's really no recovering from a failed log backup

                        LOGGER.error("SQL Exception restoring the log backup", ex);

                        System.exit(1);
                    }
                }

                return watchRes;
            });
        } catch (IOException | FileCheckException ex) {
            LOGGER.error(String.format("Error watching backup directory...\n'%s'", backupsDir), ex);

            return 1;
        } catch (InterruptedException ex) {
            LOGGER.info(String.format("Interrupted watching backup directory...\n'%s'", backupsDir), ex);
        }
    }

    return res;
}

From source file:fr.lepellerin.ecole.service.internal.CantineServiceImpl.java

@Override
@Transactional(readOnly = false)//from   w  w w.  jav  a 2  s . c om
public String reserver(final LocalDate date, final int individuId, final Famille famille, final Boolean reserve)
        throws FunctionalException, TechnicalException {
    final LocalDateTime heureResa = this.getLimiteResaCantine(date);
    if (!heureResa.isAfter(LocalDateTime.now())) {
        throw new ActNonModifiableException("activite non reservable");
    }
    final Date d = Date.from(Instant.from(date.atStartOfDay(ZoneId.systemDefault())));
    final Activite activite = getCantineActivite();
    final List<Inscription> icts = this.ictRepository.findByActiviteAndFamille(activite, famille);
    final Inscription ict = icts.stream().filter(i -> individuId == i.getIndividu().getId()).findFirst().get();
    final List<Consommation> consos = this.consommationRepository.findByInscriptionActiviteUniteDate(ict,
            activite, ict.getGroupe(), d);
    final Unite unite = this.uniteRepository.findOneByActiviteAndType(ict.getActivite(), "Unitaire");
    if ((reserve == null && consos != null && !consos.isEmpty())
            || (reserve != null && reserve == false && consos != null && !consos.isEmpty())) {
        consos.forEach(c -> this.consommationRepository.delete(c));
        return "libre";
        // on supprime la conso
    } else if ((reserve == null && (consos == null || consos.isEmpty()))
            || (reserve == true && (consos == null || consos.isEmpty()))) {
        // cree la conso
        final Consommation conso = new Consommation();
        conso.setActivite(activite);
        conso.setDate(d);
        conso.setDateSaisie(new Date());
        conso.setEtat("reservation");
        conso.setGroupe(ict.getGroupe());
        conso.setIndividu(ict.getIndividu());
        conso.setInscription(ict);
        conso.setComptePayeur(ict.getComptePayeur());
        conso.setCategorieTarif(ict.getCategorieTarif());
        conso.setUnite(unite);
        conso.setHeureDebut(unite.getHeureDebut());
        conso.setHeureFin(unite.getHeureFin());

        this.consommationRepository.save(conso);
        return "reserve";
    }
    return "rien";

}

From source file:com.bdb.weather.display.stripchart.StripChart.java

/**
 * Add an item to a series.//from w w  w. j  a v  a2  s .  co m
 * 
 * @param seriesName The name of the series to which the data is to be added
 * @param time The time of the data
 * @param value The value of the data
 */
public void addItem(String seriesName, LocalDateTime time, double value) {
    TimeSeries timeSeries = series.get(seriesName);
    Instant instant = Instant.from(time.atZone(ZoneId.systemDefault()));
    Date res = Date.from(instant);

    if (timeSeries != null) {
        timeSeries.removeAgedItems(false);
        timeSeries.addOrUpdate(new Second(res), value);
        Calendar c = Calendar.getInstance();
        c.setTime(res);
        adjustDateAxis(c);
    }
}

From source file:com.att.aro.datacollector.ioscollector.utilities.AppSigningHelper.java

private boolean isProvProfileExpired() throws IOSAppException {
    DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
    Instant dateTime = Instant.from(formatter.parse(provProfile.getExpiration()));
    return dateTime.compareTo(Instant.now()) < 0;
}