Example usage for java.time Instant EPOCH

List of usage examples for java.time Instant EPOCH

Introduction

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

Prototype

Instant EPOCH

To view the source code for java.time Instant EPOCH.

Click Source Link

Document

Constant for the 1970-01-01T00:00:00Z epoch instant.

Usage

From source file:org.ulyssis.ipp.processor.Processor.java

private void processEvent(Event event) {
    logProcessEvent(event);/*  w  w  w  .  j av a2 s . c  o m*/
    Connection connection = null;
    Snapshot oldSnapshot = this.snapshot;
    try {
        connection = Database.createConnection(EnumSet.of(READ_WRITE));
        Event firstEvent = event;
        if (event.isUnique()) {
            Optional<Event> other = Event.loadUnique(connection, event.getClass());
            if (other.isPresent()) {
                other.get().setRemoved(connection, true);
                if (!other.get().getTime().isAfter(event.getTime())) {
                    firstEvent = other.get();
                }
            }
        }
        event.save(connection);
        Snapshot snapshotToUpdateFrom = this.snapshot;
        if (!firstEvent.getTime().isAfter(this.snapshot.getSnapshotTime())) {
            LOG.debug("Event before current snapshot, loading snapshot before");
            Optional<Snapshot> s = Snapshot.loadBefore(connection, firstEvent.getTime());
            if (s.isPresent())
                snapshotToUpdateFrom = s.get();
            else
                snapshotToUpdateFrom = new Snapshot(Instant.EPOCH);
        }
        List<Event> events;
        Snapshot.deleteAfter(connection, snapshotToUpdateFrom);
        LOG.debug("Updating from snapshot: {}", snapshotToUpdateFrom.getId());
        if (snapshotToUpdateFrom.getId().isPresent()) {
            assert snapshotToUpdateFrom.getEventId().isPresent();
            events = Event.loadAfter(connection, snapshotToUpdateFrom.getSnapshotTime(),
                    snapshotToUpdateFrom.getEventId().get());
        } else {
            events = Event.loadAll(connection);
        }
        for (Event e : events) {
            if (!e.isRemoved()) {
                snapshotToUpdateFrom = e.apply(snapshotToUpdateFrom);
                snapshotToUpdateFrom.save(connection);
            }
        }
        LOG.debug("Updated up to snapshot: {}", snapshotToUpdateFrom.getId().get());
        this.snapshot = snapshotToUpdateFrom;
        connection.commit();
        // TODO: Provide a sensible message for NEW_SNAPSHOT?
        statusReporter.broadcast(new StatusMessage(StatusMessage.MessageType.NEW_SNAPSHOT, "New snapshot!"));
        if (eventCallbacks.containsKey(event)) {
            eventCallbacks.get(event).accept(true);
            eventCallbacks.remove(event);
        }
    } catch (SQLException | IOException e) {
        LOG.error("Error when handling event!", e);
        this.snapshot = oldSnapshot;
        try {
            if (connection != null)
                connection.rollback();
        } catch (SQLException e2) {
            LOG.error("Error in rollback after previous error!", e2);
        }
        // TODO(Roel): Reschedule event!
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                LOG.error("Error while closing connection", e);
            }
        }
    }
}

From source file:com.netflix.genie.web.controllers.JobRestControllerIntegrationTest.java

private void checkJob(final int documentationId, final String id, final List<String> commandArgs,
        final boolean archiveJob) {
    final RestDocumentationFilter getResultFilter = RestAssuredRestDocumentation.document(
            "{class-name}/" + documentationId + "/getJob/", Snippets.ID_PATH_PARAM, // Path parameters
            Snippets.HAL_CONTENT_TYPE_HEADER, // Response Headers
            Snippets.getJobResponsePayload(), // Response fields
            Snippets.JOB_LINKS // Links
    );//ww w  . j  av  a 2s  .co  m
    RestAssured.given(this.getRequestSpecification()).filter(getResultFilter).when().port(this.port)
            .get(JOBS_API + "/{id}", id).then().statusCode(Matchers.is(HttpStatus.OK.value()))
            .contentType(Matchers.is(MediaTypes.HAL_JSON_UTF8_VALUE)).body(ID_PATH, Matchers.is(id))
            .body(CREATED_PATH, Matchers.notNullValue()).body(UPDATED_PATH, Matchers.notNullValue())
            .body(VERSION_PATH, Matchers.is(JOB_VERSION)).body(USER_PATH, Matchers.is(JOB_USER))
            .body(NAME_PATH, Matchers.is(JOB_NAME)).body(DESCRIPTION_PATH, Matchers.is(JOB_DESCRIPTION))
            .body(METADATA_PATH + "." + SCHEDULER_JOB_NAME_KEY, Matchers.is(this.schedulerJobName))
            .body(METADATA_PATH + "." + SCHEDULER_RUN_ID_KEY, Matchers.is(this.schedulerRunId))
            .body(COMMAND_ARGS_PATH, Matchers.is(StringUtils.join(commandArgs, StringUtils.SPACE)))
            .body(STATUS_PATH, Matchers.is(JobStatus.SUCCEEDED.toString()))
            .body(STATUS_MESSAGE_PATH, Matchers.is(JOB_STATUS_MSG))
            .body(STARTED_PATH, Matchers.not(Instant.EPOCH)).body(FINISHED_PATH, Matchers.notNullValue())
            // TODO: Flipped during V4 migration to always be on to replecate expected behavior of V3 until clients
            //       can be migrated
            //            .body(ARCHIVE_LOCATION_PATH, archiveJob ? Matchers.notNullValue() : Matchers.isEmptyOrNullString())
            .body(ARCHIVE_LOCATION_PATH, Matchers.notNullValue())
            .body(CLUSTER_NAME_PATH, Matchers.is(CLUSTER1_NAME)).body(COMMAND_NAME_PATH, Matchers.is(CMD1_NAME))
            .body(TAGS_PATH, Matchers.contains(JOB_TAG_1, JOB_TAG_2))
            .body(GROUPING_PATH, Matchers.is(JOB_GROUPING))
            .body(GROUPING_INSTANCE_PATH, Matchers.is(JOB_GROUPING_INSTANCE))
            .body(LINKS_PATH + ".keySet().size()", Matchers.is(9))
            .body(LINKS_PATH, Matchers.hasKey(SELF_LINK_KEY)).body(LINKS_PATH, Matchers.hasKey("request"))
            .body(LINKS_PATH, Matchers.hasKey("execution")).body(LINKS_PATH, Matchers.hasKey("output"))
            .body(LINKS_PATH, Matchers.hasKey("status")).body(LINKS_PATH, Matchers.hasKey("cluster"))
            .body(LINKS_PATH, Matchers.hasKey("command")).body(LINKS_PATH, Matchers.hasKey("applications"))
            .body(LINKS_PATH, Matchers.hasKey("metadata"))
            .body(JOB_CLUSTER_LINK_PATH, EntityLinkMatcher.matchUri(JOBS_API, "cluster", null, id))
            .body(JOB_COMMAND_LINK_PATH, EntityLinkMatcher.matchUri(JOBS_API, "command", null, id))
            .body(JOB_APPLICATIONS_LINK_PATH,
                    EntityLinkMatcher.matchUri(JOBS_API, APPLICATIONS_LINK_KEY, null, id));
}

From source file:org.codice.ddf.security.servlet.expiry.SessionManagementServiceTest.java

@Test
public void testGetExpiry() throws IOException {
    sessionManagementService.setClock(Clock.fixed(Instant.EPOCH, ZoneId.of("UTC")));
    Response expiry = sessionManagementService.getExpiry(request);
    assertThat(expiry.getStatus(), is(200));
    assertThat(IOUtils.toString(new InputStreamReader((ByteArrayInputStream) expiry.getEntity())),
            is("4522435794788"));
}

From source file:org.codice.ddf.security.servlet.expiry.SessionManagementServiceTest.java

@Test
public void testGetExpirySoonest() throws IOException, ParserConfigurationException, SAXException {
    sessionManagementService.setClock(Clock.fixed(Instant.EPOCH, ZoneId.of("UTC")));
    SecurityToken soonerToken = mock(SecurityToken.class);
    String saml = IOUtils//from ww w.jav a  2s .  c  o  m
            .toString(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("saml.xml")));
    saml = saml.replace("2113", "2103");
    when(soonerToken.getToken()).thenReturn(readXml(IOUtils.toInputStream(saml, "UTF-8")).getDocumentElement());
    SecurityToken laterToken = mock(SecurityToken.class);
    saml = IOUtils.toString(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("saml.xml")));
    saml = saml.replace("2113", "2213");
    when(laterToken.getToken()).thenReturn(readXml(IOUtils.toInputStream(saml, "UTF-8")).getDocumentElement());
    HashMap<String, SecurityToken> tokenMap = new HashMap<>();
    tokenMap.put("jaas", laterToken);
    tokenMap.put("idp", token);
    tokenMap.put("karaf", soonerToken);
    when(tokenHolder.getRealmTokenMap()).thenReturn(tokenMap);
    Response expiry = sessionManagementService.getExpiry(request);
    assertThat(expiry.getStatus(), is(200));
    assertThat(IOUtils.toString(new InputStreamReader((ByteArrayInputStream) expiry.getEntity())),
            is("4206816594788"));
}

From source file:org.codice.ddf.security.session.management.impl.SessionManagementServiceImplTest.java

@Test
public void testGetExpiry() {
    sessionManagementServiceImpl.setClock(Clock.fixed(Instant.EPOCH, ZoneId.of("UTC")));
    String expiryString = sessionManagementServiceImpl.getExpiry(request);
    assertThat(expiryString, is("4522435794788"));
}

From source file:org.codice.ddf.security.session.management.impl.SessionManagementServiceImplTest.java

@Test
public void testGetExpirySoonest() throws IOException, ParserConfigurationException, SAXException {
    sessionManagementServiceImpl.setClock(Clock.fixed(Instant.EPOCH, ZoneId.of("UTC")));
    SecurityToken soonerToken = mock(SecurityToken.class);
    String saml = IOUtils//from w  ww .ja  va  2  s  .co m
            .toString(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("saml.xml")));
    saml = saml.replace("2113", "2103");
    when(soonerToken.getToken()).thenReturn(readXml(IOUtils.toInputStream(saml, "UTF-8")).getDocumentElement());
    SecurityToken laterToken = mock(SecurityToken.class);
    saml = IOUtils.toString(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("saml.xml")));
    saml = saml.replace("2113", "2213");
    when(laterToken.getToken()).thenReturn(readXml(IOUtils.toInputStream(saml, "UTF-8")).getDocumentElement());
    when(tokenHolder.getSecurityToken()).thenReturn(soonerToken);
    String expiryString = sessionManagementServiceImpl.getExpiry(request);
    assertThat(expiryString, is("4206816594788"));
}

From source file:org.qcert.camp.translator.SemRule2CAMP.java

/**
 * Incomplete but evolving translation for object allocations involving temporal constructs
 * @param ast the object allocation (SemNewObject)
 * @return the translation//from w  w  w . ja  va2  s  . c  o m
 */
private CampPattern translateTemporalAllocation(SemNewObject ast) {
    List<SemValue> args = ast.getArguments();
    if (DATE_TYPE.equals(ast.getType().getDisplayName())) {
        Iterator<SemValue> argIter = args.iterator();
        ZonedDateTime translation = ZonedDateTime.ofInstant(Instant.EPOCH, ZoneId.systemDefault())
                .withYear(intFrom(argIter.next())).withMonth(intFrom(argIter.next()))
                .withDayOfMonth(intFrom(argIter.next()));
        if (argIter.hasNext())
            translation = translation.withHour(intFrom(argIter.next()));
        if (argIter.hasNext())
            translation = translation.withMinute(intFrom(argIter.next()));
        if (argIter.hasNext())
            translation = translation.withSecond(intFrom(argIter.next()));
        ConstPattern constant = new ConstPattern(translation.toString());
        return new UnaryPattern(UnaryOperator.ATimeFromString, constant);
    }
    if (TIME_TYPE.equals(ast.getType().getDisplayName()) && args.size() == 1) {
        long epochMilli = longFrom(args.get(0));
        LocalTime translation = ZonedDateTime.ofInstant(Instant.ofEpochMilli(epochMilli), ZoneOffset.UTC)
                .toLocalTime();
        // TODO this should really be a unique CAMP type corresponding to the TTRL type for LocalTimeComponentValue
        return new ConstPattern(translation.toString());
    }
    return notImplemented("Translation of temporal allocation: " + ast);
}

From source file:org.sakaiproject.sitestats.impl.event.detailed.refresolvers.PodcastReferenceResolver.java

/**
 * Utility method to retrieve the 'published' date of a given Podcast.
 * @param podcastResource The podcast resource
 * @param podServ The Podcast service object
 * @return A string representation of the podcast's publish date/time, matching the format from the Podcast tool
 *///from w w w  . j  a v  a  2s .  c  o  m
private static Instant getPodcastPublishDateTime(ContentResource podcastResource, PodcastService podServ) {
    if (podcastResource == null) {
        return Instant.EPOCH;
    }

    Date releaseDateTime;
    if (podcastResource.getReleaseDate() == null) {
        try {
            ResourceProperties podcastProperties = podcastResource.getProperties();
            releaseDateTime = podServ
                    .getGMTdate(podcastProperties.getTimeProperty(PodcastService.DISPLAY_DATE).getTime());
        } catch (EntityPropertyNotDefinedException | EntityPropertyTypeException ex) {
            log.warn("Unable to retrieve release date for resource with ID = " + podcastResource.getId(), ex);
            return Instant.EPOCH;
        }
    } else {
        releaseDateTime = new Date(podcastResource.getReleaseDate().getTime());
    }

    return releaseDateTime.toInstant();
}

From source file:org.springframework.session.web.http.DefaultCookieSerializer.java

@Override
public void writeCookieValue(CookieValue cookieValue) {
    HttpServletRequest request = cookieValue.getRequest();
    HttpServletResponse response = cookieValue.getResponse();

    StringBuilder sb = new StringBuilder();
    sb.append(this.cookieName).append('=');
    String value = getValue(cookieValue);
    if (value != null && value.length() > 0) {
        validateValue(value);/*w w  w.  jav a  2s  . com*/
        sb.append(value);
    }
    int maxAge = getMaxAge(cookieValue);
    if (maxAge > -1) {
        sb.append("; Max-Age=").append(cookieValue.getCookieMaxAge());
        OffsetDateTime expires = (maxAge != 0) ? OffsetDateTime.now().plusSeconds(maxAge)
                : Instant.EPOCH.atOffset(ZoneOffset.UTC);
        sb.append("; Expires=").append(expires.format(DateTimeFormatter.RFC_1123_DATE_TIME));
    }
    String domain = getDomainName(request);
    if (domain != null && domain.length() > 0) {
        validateDomain(domain);
        sb.append("; Domain=").append(domain);
    }
    String path = getCookiePath(request);
    if (path != null && path.length() > 0) {
        validatePath(path);
        sb.append("; Path=").append(path);
    }
    if (isSecureCookie(request)) {
        sb.append("; Secure");
    }
    if (this.useHttpOnlyCookie) {
        sb.append("; HttpOnly");
    }
    if (this.sameSite != null) {
        sb.append("; SameSite=").append(this.sameSite);
    }

    response.addHeader("Set-Cookie", sb.toString());
}

From source file:Presentacion.FUsuarios.java

private void btnRegistrarClienteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnRegistrarClienteMouseClicked
    if (fc == null || !fc.getSelectedFile().isFile()) {
        JOptionPane.showMessageDialog(this, "Debe seleccionar una imagen", "Alerta",
                JOptionPane.WARNING_MESSAGE);
    } else {//from  w  w w  .  j av a 2  s .  com

        if (txtApellido.getText().isEmpty() || txtDireccion.getText().isEmpty() || txtEmail.getText().isEmpty()
                || txtNickName.getText().isEmpty() || txtNombre.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Debe ingresar todos los datos", "Alerta",
                    JOptionPane.WARNING_MESSAGE);
        } else {
            webservice.Cliente user = new Cliente();
            user.setDireccion(txtDireccion.getText());
            user.setEmail(txtEmail.getText());
            user.setNickname(txtNickName.getText());
            user.setNombre(txtNombre.getText());
            user.setApellido(txtApellido.getText());

            //PORCEDIMIENTO PARA ENCRIPTAR LA CLAVE INGRESADA CUANDO INICIA SESIN UN USUARIO.
            String pass = jPasswordField2.getText();
            String encriptMD5 = DigestUtils.md5Hex(pass);
            pass = "md5:" + encriptMD5;

            user.setPassword(pass);

            try {
                int year = Integer.getInteger(drpYear.getToolTipText());
                int day = Integer.getInteger(drpDay.getModel().getValue().toString());
                int month = Integer.getInteger(drpMes.getValue().toString());

                GregorianCalendar c = new GregorianCalendar();
                c.setTime(new Date(year, month, day));
                XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);

                user.setFechaNac(date2);
            } catch (Exception ex) {
                GregorianCalendar c = new GregorianCalendar();
                c.setTime(Date.from(Instant.EPOCH));

                try {
                    XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
                    user.setFechaNac(date2);
                } catch (Exception ex2) {
                    System.out.println("Error en fecha");
                }
            }

            user.setImagen(txtNickName.getText() + ".jpg");

            QuickOrderWebService webService = new QuickOrderWebService();
            ControllerInterface port = webService.getQuickOrderWebServicePort();

            String result = port.registrarCliente(user);
            if (result.isEmpty()) {

                JOptionPane.showMessageDialog(this, "Usuario ingresado correctamente");
                txtApellido.setText("");
                txtDireccion.setText("");
                txtEmail.setText("");
                txtNickName.setText("");
                txtNombre.setText("");
                jPasswordField2.setText("");
            } else {
                if (result.equals("emailError1")) {
                    JOptionPane.showMessageDialog(this,
                            "El email ya se encuentra registrado, por favor ingrese otro.", "Alerta",
                            JOptionPane.WARNING_MESSAGE);
                }
                if (result.equals("nicknameError1")) {
                    JOptionPane.showMessageDialog(this,
                            "El nickname no se encuentra disponible, por favor ingrese otro.", "Alerta",
                            JOptionPane.WARNING_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(this, "Error al ingresar el cliente", "Error",
                            JOptionPane.ERROR_MESSAGE);
                }
            }

        }
    }
}