Example usage for java.sql Timestamp Timestamp

List of usage examples for java.sql Timestamp Timestamp

Introduction

In this page you can find the example usage for java.sql Timestamp Timestamp.

Prototype

public Timestamp(long time) 

Source Link

Document

Constructs a Timestamp object using a milliseconds time value.

Usage

From source file:org.cloudfoundry.identity.uaa.audit.JdbcFailedLoginCountingAuditService.java

@Override
public void userAuthenticationFailure(UaaUser user, UaaAuthenticationDetails details) {
    if (user == null) {
        return;//from   w ww.ja va2 s .  c  o m
    }
    template.update("delete from sec_audit where created < ?",
            new Timestamp(System.currentTimeMillis() - saveDataPeriodMillis));
    template.update("insert into sec_audit (principal_id, event_type, origin, event_data) values (?,?,?,?)",
            user.getId(), AuditEventType.UserAuthenticationFailure.getCode(), getOrigin(details),
            user.getUsername());
}

From source file:com.leixl.easyframework.system.service.impl.EUserServiceImpl.java

public void updateLoginSuccess(Long userId, String ip) {
    EUser user = findById(userId);//from w w w .ja v a 2 s .  c  o  m
    Date now = new Timestamp(System.currentTimeMillis());

    user.setLoginCount(user.getLoginCount() + 1);
    user.setLastLoginIp(ip);
    user.setLastLoginTime(now);

    user.setErrorCount(0);
    user.setErrorTime(null);
    user.setErrorIp(null);
}

From source file:com.local.ask.controller.spring.SignUpController.java

@RequiresGuest
@RequestMapping(value = "/registered/confirm/{id}", method = RequestMethod.GET)
public String confirmRegistration(@PathVariable String id, Model m) throws Exception {
    try {//from www  . ja  va 2s  .  com
        UserTemp userTemp = dbHelper.getUserTemp(id);
        Long day = 24 * 60 * 60 * 1000L;
        if (userTemp != null && userTemp.getTimeJoined().after(new Timestamp(new Date().getTime() - day))) {
            dbHelper.addUser(userTemp);
            LoginUser loginUser = new LoginUser();
            loginUser.setEmail(userTemp.getEmail());
            m.addAttribute(loginUser);
            m.addAttribute(new SignUpUser());
            m.addAttribute("confirm", "message.confirmed");
            return "confirm";
        } else if (userTemp != null) {
            m.addAttribute("reconfirmUser", new ReconfirmUser());
            return REDIRECT + "/reconfirm";
        }
    } catch (UniqueCorruptionException ex) {
        //TODO database trigger.
        ex.printStackTrace();
    } catch (UserAlreadyExistException ex) {
        ex.printStackTrace();
        m.addAttribute("message", "It seems you're already registered.");
        throw new Exception();
    } catch (UserDoesNotExistException ex) {
        ex.printStackTrace();
        m.addAttribute("message", "This link is invalid.");
        throw new Exception();
    }
    return REDIRECT + "/error";
}

From source file:com.chevres.rss.restapi.controller.LoginController.java

@CrossOrigin
@RequestMapping(path = "/login", method = RequestMethod.POST)
@ResponseBody/*w w w  .jav  a  2  s . com*/
public ResponseEntity<String> login(@RequestBody User user, BindingResult bindingResult) {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

    userValidator.validate(user, bindingResult);

    if (bindingResult.hasErrors()) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("bad_params"), HttpStatus.BAD_REQUEST);
    }

    UserDAO userDAO = context.getBean(UserDAO.class);
    UserAuthDAO userAuthDAO = context.getBean(UserAuthDAO.class);

    User foundUser = userDAO.findByUsernameAndPassword(user.getUsername(), user.getPassword());
    if (foundUser == null) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("bad_credentials"), HttpStatus.BAD_REQUEST);
    }

    TokenGenerator tg = new TokenGenerator();
    Date date = new Date();
    Timestamp timestamp = new Timestamp(date.getTime());

    UserAuth userAuth = new UserAuth();
    userAuth.setIdUser(foundUser.getId());
    userAuth.setToken(tg.getToken());
    userAuth.setCreateDate(timestamp);
    userAuthDAO.create(userAuth);

    context.close();

    return new ResponseEntity(new SuccessLoginResponse(userAuth.getToken()), HttpStatus.OK);
}

From source file:com.evolveum.midpoint.report.impl.ReportUtils.java

public static Timestamp convertDateTime(XMLGregorianCalendar dateTime) {
    Timestamp timestamp = new Timestamp(System.currentTimeMillis());
    try {/* w ww .  j  av a 2  s  . c o  m*/
        timestamp = new Timestamp(dateTime.toGregorianCalendar().getTimeInMillis());
    } catch (Exception ex) {
        LOGGER.trace("Incorrect date time value {}", dateTime);
    }

    return timestamp;
}

From source file:ch.bfh.srs.srv.service.ReservationServiceTest.java

@Test(expected = NotImplementedException.class)
public void testAddRecurringReservation() {
    DateTime from = DateTime.now();/*from ww w  .j  av  a  2 s  .c o  m*/
    DateTime to = DateTime.now().plus(Period.hours(2));
    boolean performed = service.addRecurringReservation(1, from, to, false, 1, null, null);
    assertEquals(true, performed);
    Reservation reservationEntity = service.getById(Reservation.class, 1);
    assertNotNull(reservationEntity);
    assertEquals(new Timestamp(from.getMillis()), reservationEntity.getFrom());
    assertEquals(new Timestamp(to.getMillis()), reservationEntity.getTo());
    assertFalse(reservationEntity.getFullDay());
    //TODO: Recurring field assertion (no entity object so far)
}

From source file:dk.nsi.minlog.export.dao.ebean.StatusDaoEBean.java

@Override
@Transactional//from  w w w  .j  a va2  s  .c o m
public void setLastUpdated(DateTime lastUpdated) {
    //Create an entry or update existing
    SqlUpdate update = ebeanServer.createSqlUpdate(
            "INSERT INTO status (id, lastUpdated) VALUES(1, :lastUpdated) ON DUPLICATE KEY UPDATE lastUpdated = :lastUpdated");
    update.setParameter("lastUpdated", new Timestamp(lastUpdated.getMillis()));

    update.execute();

}

From source file:org.zenoss.zep.dao.impl.RangePartitionerIT.java

@Test
public void testRangePartitioner() {
    RangePartitioner partitioner = databaseCompatibility.getRangePartitioner(this.dataSource, "range_partition",
            "col_ts", 1, TimeUnit.DAYS);
    assertEquals(0, partitioner.listPartitions().size());
    /*//from   ww  w . j a  v  a2s.  co m
     * Initialize partitions with 5 previous days partitions and 10 future
     * partitions.
     */
    int numBefore = 0, numAfter = 0;
    partitioner.createPartitions(5, 10);
    Timestamp time = new Timestamp(System.currentTimeMillis());
    List<Partition> partitions = partitioner.listPartitions();
    assertEquals(15, partitions.size());
    for (Partition partition : partitions) {
        if (partition.getRangeLessThan().before(time)) {
            numBefore++;
        } else {
            numAfter++;
        }
    }
    assertEquals(5, numBefore);
    assertEquals(10, numAfter);

    // Try to create partitions which overlap existing ranges and verify it doesn't create any.
    assertEquals(0, partitioner.createPartitions(10, 10));
    assertEquals(0, partitioner.createPartitions(0, 5));

    // Create two additional ones in the future and verify it only creates those two
    assertEquals(2, partitioner.createPartitions(5, 12));
    assertEquals(17, partitioner.listPartitions().size());

    // Test pruning partitions older than 3 days ago
    numBefore = 0;
    numAfter = 0;
    partitioner.pruneAndCreatePartitions(3, TimeUnit.DAYS, 0, 0);
    partitions = partitioner.listPartitions();
    assertEquals(15, partitions.size());
    for (Partition partition : partitions) {
        if (partition.getRangeLessThan().before(time)) {
            numBefore++;
        } else {
            numAfter++;
        }
    }
    assertEquals(3, numBefore);
    assertEquals(12, numAfter);

    // Test pruning partitions again, expecting same results
    numBefore = 0;
    numAfter = 0;
    partitioner.pruneAndCreatePartitions(3, TimeUnit.DAYS, 0, 0);
    partitions = partitioner.listPartitions();
    assertEquals(15, partitions.size());
    for (Partition partition : partitions) {
        if (partition.getRangeLessThan().before(time)) {
            numBefore++;
        } else {
            numAfter++;
        }
    }
    assertEquals(3, numBefore);
    assertEquals(12, numAfter);

    // Test dropping partitions
    partitioner.removeAllPartitions();
    assertEquals(0, partitioner.listPartitions().size());
}

From source file:Manager.addEmployee.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w  w  w  .ja  va2  s .  c o  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 {
    //json to pass back to our ajax request
    JSONArray jsonArray = new JSONArray();
    PrintWriter printout = response.getWriter();
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost;user=sa;password=nopw");

        Statement st = con.createStatement();
        String SSN = request.getParameter("SSN");
        String Password = request.getParameter("Password");
        String FirstName = request.getParameter("FirstName");
        String LastName = request.getParameter("LastName");
        String Street = request.getParameter("Street");
        String City = request.getParameter("City");
        String State = request.getParameter("State");
        String ZipCode = request.getParameter("ZipCode");
        String Email = request.getParameter("Email");
        String Telephone = request.getParameter("Telephone");
        String Role = request.getParameter("Role");
        String Rate = request.getParameter("Rate");
        Date currTime = new Date();
        Timestamp creationDate = new Timestamp(currTime.getTime());

        String query = "SELECT * FROM PERSON WHERE SSN = '" + SSN + "'";
        System.out.println(query);
        ResultSet rs = st.executeQuery(query);

        if (!rs.next()) {
            query = "INSERT INTO [MatchesFromAbove].[dbo].[Person] " + "VALUES('" + SSN + "', '" + Password
                    + "', '" + FirstName + "', '" + LastName + "','" + Street + "','" + City + "','" + State
                    + "'," + ZipCode + ",'" + Email + "','" + Telephone + "');\n"
                    + "INSERT INTO [MatchesFromAbove].[dbo].[Employee] " + "VALUES('" + SSN
                    + "', 'User-User', '" + creationDate + "'," + Rate + ", 1); ";
            System.out.println(query);
            st.executeUpdate(query);

        } else {

            query = "INSERT INTO [MatchesFromAbove].[dbo].[Employee] " + "VALUES('" + SSN + "', 'User-User', '"
                    + creationDate + "'," + Rate + ", 1); ";
            System.out.println(query);
            st.executeUpdate(query);
        }

        //set the content type of our response
        response.setContentType("application/json");
        //printout prints it to our ajax call and it shows up there as data. you can use this data in the success function.
        printout.print("success");
        printout.flush();
    } catch (Exception e) {
        printout.print("failure");
        System.out.println("NO IDEA - - - " + e);
    }
}

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.PasswordResetEndpointsTest.java

@Before
public void setUp() throws Exception {
    scimUserProvisioning = Mockito.mock(ScimUserProvisioning.class);
    expiringCodeStore = Mockito.mock(ExpiringCodeStore.class);
    PasswordResetEndpoints controller = new PasswordResetEndpoints(scimUserProvisioning, expiringCodeStore);
    mockMvc = MockMvcBuilders.standaloneSetup(controller).build();

    Mockito.when(expiringCodeStore.generateCode(eq("id001"), any(Timestamp.class))).thenReturn(
            new ExpiringCode("secret_code", new Timestamp(System.currentTimeMillis() + 1000), "id001"));
}