Example usage for java.time Instant now

List of usage examples for java.time Instant now

Introduction

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

Prototype

public static Instant now() 

Source Link

Document

Obtains the current instant from the system clock.

Usage

From source file:Index.RegisterUserServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww w  .j av  a2 s . c om*/
 *
 * @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");

    PrintWriter out = response.getWriter();

    try {
        String errorMessage;

        if (request.getParameter("user") != null && request.getParameter("password") != null
                && request.getParameter("email") != null && request.getParameter("passwordConfirmation") != null
                && request.getParameter("name") != null && request.getParameter("address") != null
                && request.getParameter("lastName") != null && request.getParameter("dateBorn") != null) {

            String user = request.getParameter("user");
            String password = request.getParameter("password");
            String passwordConfirmation = request.getParameter("passwordConfirmation");
            String email = request.getParameter("email");
            String name = request.getParameter("name");
            String address = request.getParameter("address");
            String lastName = request.getParameter("lastName");
            String dateBorn = request.getParameter("dateBorn");

            if (user.equalsIgnoreCase("") || password.equalsIgnoreCase("")
                    || passwordConfirmation.equalsIgnoreCase("") || email.equalsIgnoreCase("")
                    || name.equalsIgnoreCase("")) {

                errorMessage = "Ingrese todos los datos.";
                request.setAttribute("error", errorMessage);
                request.setAttribute("funcionalidad", "Registro");

                request.getRequestDispatcher("/Login.jsp").forward(request, response);
            } else {
                if (password.equals(passwordConfirmation)) {
                    QuickOrderWebService webService = new QuickOrderWebService();
                    ControllerInterface port = webService.getQuickOrderWebServicePort();
                    webservice.Cliente listCli = port.infoCliente(user);

                    if (listCli != null && listCli.getApellido() != null) {

                        errorMessage = "Ya existe un usuario con ese nickname";
                        request.setAttribute("error", errorMessage);
                        request.setAttribute("funcionalidad", "Registro");
                        request.getRequestDispatcher("/Login.jsp").forward(request, response);
                    } else {
                        webservice.Cliente usr = new webservice.Cliente();
                        usr.setNickname(user);
                        usr.setNombre(name);
                        usr.setEmail(email);
                        usr.setDireccion(address);
                        usr.setImagen(user + ".jpg");
                        usr.setApellido(lastName);

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

                        usr.setPassword(password);
                        Date dt;
                        try {
                            dt = new Date(dateBorn);
                        } catch (Exception ex) {
                            dt = Date.from(Instant.now());
                        }

                        GregorianCalendar c = new GregorianCalendar();
                        c.setTime(dt);
                        XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
                        usr.setFechaNac(date2);

                        String result = port.registrarCliente(usr);

                        if (result.equals("")) {
                            request.setAttribute("error", null);
                            request.setAttribute("funcionalidad", "Imagen");
                            request.getSession().setAttribute("userName", user);
                        } else {
                            request.setAttribute("error", "Surgio un error al registrar el cliente");
                            request.setAttribute("funcionalidad", "Registro");
                        }
                        request.getRequestDispatcher("/Login.jsp").forward(request, response);
                    }
                } else {
                    errorMessage = "Las contraseas no cohinciden";
                    request.setAttribute("error", errorMessage);
                    request.setAttribute("funcionalidad", "Registro");
                    request.getRequestDispatcher("/Login.jsp").forward(request, response);
                }

            }
        } else {
            errorMessage = "Error al realizar el registro.";
            request.setAttribute("error", errorMessage);
            request.setAttribute("funcionalidad", "Registro");
            request.getRequestDispatcher("/Login.jsp").forward(request, response);
        }
    } catch (Exception ex) {
        out.print("Error en proceso de registro: " + ex.getMessage());
    } finally {
        out.close();
    }
}

From source file:org.jimsey.project.turbine.spring.controller.TickControllerTest.java

@Test
public void testGetAllTicksGreaterThanDate() throws Exception {
    // use this for a spy...
    // Mockito.doReturn(123l).when(ping).ping();
    // String result =
    // "{\"date\":1437757461193,\"open\":93.31372449905724,\"high\":94.64656138818943,\"low\":92.35919077806433,\"close\":94.08436014274173,\"volume\":97.2503072332036,\"symbol\":\"ABC\",\"market\":\"FTSE100\",\"timestamp\":\"2015-07-24T18:04:21.193+01:00\"},
    // {\"date\":1437757457169,\"open\":95.76421881828955,\"high\":98.67332820497525,\"low\":92.87399277681914,\"close\":95.30416761402581,\"volume\":96.25382742497295,\"symbol\":\"ABC\",\"market\":\"FTSE100\",\"timestamp\":\"2015-07-24T18:04:17.169+01:00\"},
    // {\"date\":1437757455156,\"open\":95.20691875293008,\"high\":96.33109747791707,\"low\":95.03864535693057,\"close\":95.76421881828955,\"volume\":104.54628090784864,\"symbol\":\"ABC\",\"market\":\"FTSE100\",\"timestamp\":\"2015-07-24T18:04:15.156+01:00\"},
    // {\"date\":1437757459179,\"open\":95.30416761402581,\"high\":95.88765706158829,\"low\":92.37627010410178,\"close\":93.31372449905724,\"volume\":92.83201741698048,\"symbol\":\"ABC\",\"market\":\"FTSE100\",\"timestamp\":\"2015-07-24T18:04:19.179+01:00\"}";

    Mockito.when(elasticsearch.findTicksByMarketAndSymbolAndDateGreaterThan(Mockito.anyString(),
            Mockito.anyString(), Mockito.any(Long.class))).thenReturn(ticks);

    String expected = json.writeValueAsString(new Object() {
        @JsonProperty("ticks")
        List<TickJson> tickz = ticks;
    });//from www.j a  v a  2  s. c o  m

    long date = Instant.now().minus(1, ChronoUnit.MINUTES).toEpochMilli();

    String restUri = String.format("%s/any/any/%s", TurbineCondenserConstants.REST_ROOT_TICKS, date);

    mvc.perform(MockMvcRequestBuilders.get(restUri).accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk()).andExpect(content().string(equalTo(expected)));
}

From source file:com.vmware.photon.controller.api.client.resource.ClusterRestApiTest.java

@Test
public void testResize() throws IOException {
    Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    ClusterApi clusterApi = new ClusterRestApi(restClient);

    Task task = clusterApi.resize("dummy-cluster-id", 100);
    assertEquals(task, responseTask);/*from   w  ww .j  a  va 2  s.  c o m*/
}

From source file:org.noorganization.instalist.server.api.IngredientResourceTest.java

@Test
public void testGetIngredients() throws Exception {
    String url = "/groups/%d/ingredients";

    Instant preUpdate = Instant.now();

    Response notAuthorizedResponse = target(String.format(url, mGroup.getId())).request().get();
    assertEquals(401, notAuthorizedResponse.getStatus());

    Response wrongAuthResponse = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token wrongauth").get();
    assertEquals(401, wrongAuthResponse.getStatus());

    Response wrongGroupResponse = target(String.format(url, mNAGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).get();
    assertEquals(401, wrongGroupResponse.getStatus());

    Response okResponse1 = target(String.format(url, mGroup.getId())).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).get();
    assertEquals(200, okResponse1.getStatus());
    IngredientInfo[] allIngredientInfo = okResponse1.readEntity(IngredientInfo[].class);
    assertEquals(2, allIngredientInfo.length);
    for (IngredientInfo current : allIngredientInfo) {
        if (mIngredient.getUUID().equals(UUID.fromString(current.getUUID()))) {
            assertEquals(mIngredient.getUpdated(), current.getLastChanged().toInstant());
            assertEquals(mRecipe.getUUID(), UUID.fromString(current.getRecipeUUID()));
            assertEquals(mProduct.getUUID(), UUID.fromString(current.getProductUUID()));
            assertEquals(1f, current.getAmount(), 0.001f);
            assertFalse(current.getDeleted());
        } else if (mDeletedIngredient.getUUID().equals(UUID.fromString(current.getUUID()))) {
            assertNull(current.getRecipeUUID());
            assertNull(current.getProductUUID());
            assertNull(current.getAmount());
            assertEquals(mDeletedIngredient.getUpdated(), current.getLastChanged().toInstant());
            assertTrue(current.getDeleted());
        } else/*from w w w . j a  va 2s .  c  o  m*/
            fail("Unexpected Entry.");
    }

    mManager.getTransaction().begin();
    mIngredient.setUpdated(Instant.now());
    mManager.getTransaction().commit();
    Response okResponse2 = target(String.format(url, mGroup.getId()))
            .queryParam("changedsince", ISO8601Utils.format(Date.from(preUpdate), true)).request()
            .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).get();
    assertEquals(200, okResponse2.getStatus());
    IngredientInfo[] oneIngredientInfo = okResponse2.readEntity(IngredientInfo[].class);
    assertEquals(1, oneIngredientInfo.length);
    assertEquals(mIngredient.getUUID(), UUID.fromString(oneIngredientInfo[0].getUUID()));
    assertFalse(oneIngredientInfo[0].getDeleted());
}

From source file:com.orange.cepheus.broker.LocalRegistrations.java

/**
 * Find the providingApplication of a context element
 * @param searchEntityId the entity id to search
 * @param searchAttributes the attributes to search
 * @return list of matching providing applications
 *//* www  .ja  va2s. c om*/
public Iterator<URI> findProvidingApplication(EntityId searchEntityId, Set<String> searchAttributes) {

    // Filter out expired registrations
    Predicate<Registration> filterExpired = registration -> registration.getExpirationDate()
            .isAfter(Instant.now());

    // Filter only matching entity ids
    Predicate<EntityId> filterEntityId = patterns.getFilterEntityId(searchEntityId);

    // Only filter by attributes if search is looking for them
    final boolean noAttributes = searchAttributes == null || searchAttributes.size() == 0;

    // Filter each registration (remove expired) and return its providing application
    // if at least one of its listed entities matches the searched context element
    // and if all searched attributes are defined in the registration (if any)
    return registrations.values().stream().filter(filterExpired)
            .map(registration -> registration.getRegisterContext().getContextRegistrationList())
            .flatMap(List::stream)
            .filter(c -> c.getEntityIdList().stream().filter(filterEntityId).findFirst().isPresent()
                    && (noAttributes || allContextRegistrationAttributes(c).containsAll(searchAttributes)))
            .map(ContextRegistration::getProvidingApplication).iterator();
}

From source file:io.dropwizard.revolver.persistence.AeroSpikePersistenceProvider.java

@Override
public void saveRequest(String requestId, String mailboxId, RevolverCallbackRequest request) {
    final Key key = new Key(mailBoxConfig.getNamespace(), MAILBOX_SET_NAME, requestId);
    try {/*www.  j  a  v a  2 s  . c om*/
        final Bin service = new Bin(BinNames.SERVICE, request.getService());
        final Bin api = new Bin(BinNames.API, request.getApi());
        final Bin mode = new Bin(BinNames.MODE, request.getMode().toUpperCase());
        final Bin method = new Bin(BinNames.METHOD,
                Strings.isNullOrEmpty(request.getMethod()) ? null : request.getMethod().toUpperCase());
        final Bin path = new Bin(BinNames.PATH, request.getPath());
        final Bin mailBoxId = new Bin(BinNames.MAILBOX_ID, mailboxId == null ? "NONE" : mailboxId);
        final Bin queryParams = new Bin(BinNames.QUERY_PARAMS,
                objectMapper.writeValueAsString(request.getQueryParams()));
        final Bin callbackUri = new Bin(BinNames.CALLBACK_URI,
                request.getCallbackUri() != null ? request.getCallbackUri() : null);
        final Bin requestHeaders = new Bin(BinNames.REQUEST_HEADERS,
                objectMapper.writeValueAsString(request.getHeaders()));
        final Bin requestBody = new Bin(BinNames.REQUEST_BODY, request.getBody());
        final Bin requestTime = new Bin(BinNames.REQUEST_TIME, Instant.now().toEpochMilli());
        final Bin created = new Bin(BinNames.CREATED, Instant.now().toEpochMilli());
        final Bin updated = new Bin(BinNames.UPDATED, Instant.now().toEpochMilli());
        final Bin state = new Bin(BinNames.STATE, RevolverRequestState.RECEIVED.name());
        AerospikeConnectionManager.getClient().put(null, key, service, api, mode, method, path, mailBoxId,
                queryParams, callbackUri, requestHeaders, requestBody, requestTime, created, updated, state);
    } catch (JsonProcessingException e) {
        log.warn("Error encoding request", e);
    }
}

From source file:co.runrightfast.vertx.core.eventbus.ProtobufMessageProducer.java

public void send(@NonNull final A msg, @NonNull final DeliveryOptions options) {
    eventBus.send(address, msg, addRunRightFastHeaders(options));
    this.messageSent.mark();
    this.messageLastSent = Instant.now();
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Given a certificate signing request, produce a signed certificate.
 *
 * @param caKey//from  w w  w  .j a v  a 2 s .c om
 * @param caCert
 * @param r
 * @param makeAuthority
 * @return
 */
public static X509Certificate fulfillCertRequest(PrivateKey caKey, X509Certificate caCert,
        PKCS10CertificationRequest r, boolean makeAuthority) {
    X509v3CertificateBuilder b = new JcaX509v3CertificateBuilder(new X500Name(caCert.getSubjectDN().getName()), // the order of O,OU,CN returned is very important
            BigInteger.probablePrime(128, new SecureRandom()), Date.from(Instant.now().minusSeconds(1)),
            Date.from(LocalDateTime.now().plusYears(3).toInstant(ZoneOffset.UTC)), r.getSubject(),
            getPublicKeyFromInfo(r.getSubjectPublicKeyInfo()));

    try {
        b.addExtension(Extension.basicConstraints, true, new BasicConstraints(makeAuthority));
    } catch (CertIOException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider("BC").build(caKey);
        X509CertificateHolder build = b.build(signer);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(build);
    } catch (OperatorCreationException | CertificateException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:h2backup.BackupTimerService.java

@PostConstruct
public void init() {
    if (!enabled) {
        log.info("H2 database backup is disabled");
        return;//w ww.ja v a  2  s. co m
    }

    if (StringUtils.isEmpty(methodName)) {
        log.warn("No H2 database backup methods were specified");
        return;
    }
    method = BackupMethod.valueOf(methodName);

    if (StringUtils.isEmpty(directory)) {
        directory = System.getProperty("user.dir");
    }

    toList = asList(to.split(LIST_DELIMITER));

    if (text == null) {
        text = StringUtils.EMPTY;
    }

    String timerInfoName = getTimerInfoName();

    for (Timer timer : timerService.getAllTimers()) {
        if (timer.getInfo() instanceof BackupTimerInfo) {
            BackupTimerInfo timerInfo = (BackupTimerInfo) timer.getInfo();
            if (StringUtils.equals(timerInfoName, timerInfo.getName())) {
                log.info("H2 database backup is already scheduled: {}", timerInfo);
                return;
            }
        }
    }

    ScheduleExpression scheduleExpression = new ScheduleExpression();
    if (StringUtils.isNoneEmpty(year)) {
        scheduleExpression.year(year);
    }
    if (StringUtils.isNoneEmpty(month)) {
        scheduleExpression.month(month);
    }
    if (StringUtils.isNoneEmpty(dayOfMonth)) {
        scheduleExpression.dayOfMonth(dayOfMonth);
    }
    if (StringUtils.isNoneEmpty(dayOfWeek)) {
        scheduleExpression.dayOfWeek(dayOfWeek);
    }
    if (StringUtils.isNoneEmpty(hour)) {
        scheduleExpression.hour(hour);
    }
    if (StringUtils.isNoneEmpty(minute)) {
        scheduleExpression.minute(minute);
    }
    if (StringUtils.isNoneEmpty(second)) {
        scheduleExpression.second(second);
    }
    if (StringUtils.isNoneEmpty(timezone)) {
        scheduleExpression.timezone(timezone);
    }

    BackupTimerInfo timerInfo = new BackupTimerInfo(timerInfoName, scheduleExpression, Instant.now());

    TimerConfig timerConfig = new TimerConfig();
    timerConfig.setInfo(timerInfo);
    timerConfig.setPersistent(true);

    timerService.createCalendarTimer(scheduleExpression, timerConfig);

    log.info("Scheduled H2 database backup: {}", timerInfo);
}

From source file:com.netflix.genie.common.dto.JobTest.java

/**
 * Test to make sure can build a valid Job with optional parameters.
 *//*from  w w w  . j a  v  a  2  s  . co m*/
@Test
@SuppressWarnings("deprecation")
public void canBuildJobWithOptionalsDeprecated() {
    final Job.Builder builder = new Job.Builder(NAME, USER, VERSION);

    builder.withCommandArgs(StringUtils.join(COMMAND_ARGS, StringUtils.SPACE));

    final String archiveLocation = UUID.randomUUID().toString();
    builder.withArchiveLocation(archiveLocation);

    final String clusterName = UUID.randomUUID().toString();
    builder.withClusterName(clusterName);

    final String commandName = UUID.randomUUID().toString();
    builder.withCommandName(commandName);

    final Instant finished = Instant.now();
    builder.withFinished(finished);

    final Instant started = Instant.now();
    builder.withStarted(started);

    builder.withStatus(JobStatus.SUCCEEDED);

    final String statusMsg = UUID.randomUUID().toString();
    builder.withStatusMsg(statusMsg);

    final Instant created = Instant.now();
    builder.withCreated(created);

    final String description = UUID.randomUUID().toString();
    builder.withDescription(description);

    final String id = UUID.randomUUID().toString();
    builder.withId(id);

    final Set<String> tags = Sets.newHashSet(UUID.randomUUID().toString(), UUID.randomUUID().toString(),
            UUID.randomUUID().toString());
    builder.withTags(tags);

    final Instant updated = Instant.now();
    builder.withUpdated(updated);

    final String grouping = UUID.randomUUID().toString();
    builder.withGrouping(grouping);

    final String groupingInstance = UUID.randomUUID().toString();
    builder.withGroupingInstance(groupingInstance);

    final Job job = builder.build();
    Assert.assertThat(job.getName(), Matchers.is(NAME));
    Assert.assertThat(job.getUser(), Matchers.is(USER));
    Assert.assertThat(job.getVersion(), Matchers.is(VERSION));
    Assert.assertThat(job.getCommandArgs().orElseThrow(IllegalArgumentException::new),
            Matchers.is(StringUtils.join(COMMAND_ARGS, StringUtils.SPACE)));
    Assert.assertThat(job.getArchiveLocation().orElseThrow(IllegalArgumentException::new),
            Matchers.is(archiveLocation));
    Assert.assertThat(job.getClusterName().orElseThrow(IllegalArgumentException::new),
            Matchers.is(clusterName));
    Assert.assertThat(job.getCommandName().orElseThrow(IllegalArgumentException::new),
            Matchers.is(commandName));
    Assert.assertThat(job.getFinished().orElseThrow(IllegalArgumentException::new), Matchers.is(finished));
    Assert.assertThat(job.getStarted().orElseThrow(IllegalArgumentException::new), Matchers.is(started));
    Assert.assertThat(job.getStatus(), Matchers.is(JobStatus.SUCCEEDED));
    Assert.assertThat(job.getStatusMsg().orElseThrow(IllegalArgumentException::new), Matchers.is(statusMsg));
    Assert.assertThat(job.getCreated().orElseThrow(IllegalArgumentException::new), Matchers.is(created));
    Assert.assertThat(job.getDescription().orElseThrow(IllegalArgumentException::new),
            Matchers.is(description));
    Assert.assertThat(job.getId().orElseThrow(IllegalArgumentException::new), Matchers.is(id));
    Assert.assertThat(job.getTags(), Matchers.is(tags));
    Assert.assertThat(job.getUpdated().orElseThrow(IllegalArgumentException::new), Matchers.is(updated));
    Assert.assertThat(job.getRuntime(),
            Matchers.is(Duration.ofMillis(finished.toEpochMilli() - started.toEpochMilli())));
    Assert.assertThat(job.getGrouping().orElseThrow(IllegalArgumentException::new), Matchers.is(grouping));
    Assert.assertThat(job.getGroupingInstance().orElseThrow(IllegalArgumentException::new),
            Matchers.is(groupingInstance));
}