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:com.luna.common.repository.search.SearchUserRepositoryIT.java

@Test
public void testLtAndGtForDate() throws ParseException {
    int count = 15;
    String dateStr = "2012-01-15 16:59:00";
    String dateStrFrom = "2012-01-15 16:58:00";
    String dateStrEnd = "2012-01-15 16:59:01";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    for (int i = 0; i < count; i++) {
        User user = createUser();/*from w  w  w  .  j  av  a 2 s.  c om*/
        user.getBaseInfo().setBirthday(new Timestamp(df.parse(dateStr).getTime()));
        userRepository.save(user);
    }
    Map<String, Object> searchParams = new HashMap<String, Object>();
    searchParams.put("baseInfo.birthday_gt", dateStrFrom);
    searchParams.put("baseInfo.birthday_lt", dateStrEnd);
    Searchable search = Searchable.newSearchable(searchParams);
    assertEquals(count, userRepository.count(search));
}

From source file:com.ss.Controller.T4uCURDScheduleServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w ww  .  j a va 2  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 {
    HttpSession session = request.getSession(true);
    T4uUser user = (T4uUser) session.getAttribute(T4uConstants.T4uUser);
    if (user == null) { // User not logged in
        LOGGER.debug("User has not yet logged in.");
        String requestUri = request.getRequestURI();
        LOGGER.debug(String.format("Redirecting to /login.jsp?redirect=%s.", requestUri));
        request.setAttribute(T4uConstants.T4U_LOGINREDIRECT, requestUri);
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/login.jsp");
        dispatcher.forward(request, response);
    } else if (!user.getUserGroup().equals("admin")) { // Logged in as a normal user
        request.setAttribute("error", T4uConstants.ExUserNotAuthorised);
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp");
        dispatcher.forward(request, response);
    } else { // Logged in as admin
        // Get request
        String action = request.getParameter("action");
        if (action != null) {
            String oSeats = null;
            int versionId = 0;
            int houseId = 0;
            SimpleDateFormat sourceFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a", Locale.US);
            Date date = null;
            java.sql.Date sqlDate = null;
            Timestamp scheduleTimeslot = null;
            //
            if (action != null) {
                switch (action) {
                case "insert":
                    versionId = Integer.parseInt(request.getParameter("versionId"));
                    houseId = Integer.parseInt(request.getParameter("houseId"));
                    String dateInsert = request.getParameter("scheduleTimeslot");
                    try {
                        date = sourceFormat.parse(dateInsert);
                        scheduleTimeslot = new Timestamp(date.getTime());
                    } catch (ParseException ex) {
                        java.util.logging.Logger.getLogger(T4uRegisterServlet.class.getName()).log(Level.SEVERE,
                                null, ex);
                    }
                    if (T4uScheduleDAO.insertSchedule(versionId, houseId, scheduleTimeslot) > 0) {
                        // Successfully insert
                        List<Integer> allScheduleIds = T4uScheduleDAO.getAllScheduleIds();
                        List<T4uSchedule> allSchedules = new ArrayList<T4uSchedule>();
                        for (int scheduleId : allScheduleIds)
                            allSchedules.add(T4uScheduleDAO.getScheduleById(scheduleId));
                        session.setAttribute(T4uConstants.T4uAllSchedules, allSchedules);
                        request.setAttribute("success", T4uConstants.ExScheduleSuccess);
                        RequestDispatcher dispatcher = getServletContext()
                                .getRequestDispatcher("/schedules.jsp");
                        dispatcher.forward(request, response);
                    } else {
                        // Error
                        request.setAttribute("error", T4uConstants.ExScheduleError);
                        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp");
                        dispatcher.forward(request, response);
                    }
                    break;
                case "update":
                    int scheduleIdUpdate = Integer.parseInt(request.getParameter("scheduleIdUpdate"));
                    oSeats = T4uScheduleDAO.getOSeatsById(scheduleIdUpdate);
                    if (oSeats == null || oSeats.equals("")) {
                        // No seats occupied, allow update
                        versionId = Integer.parseInt(request.getParameter("versionId"));
                        houseId = Integer.parseInt(request.getParameter("houseId"));
                        String dateUpdate = request.getParameter("scheduleTimeslot");
                        try {
                            date = sourceFormat.parse(dateUpdate);
                            scheduleTimeslot = new Timestamp(date.getTime());
                        } catch (ParseException ex) {
                            java.util.logging.Logger.getLogger(T4uRegisterServlet.class.getName())
                                    .log(Level.SEVERE, null, ex);
                        }
                        if (T4uScheduleDAO.updateSchedule(scheduleIdUpdate, versionId, houseId,
                                scheduleTimeslot)) {
                            // Successfully insert
                            List<Integer> allScheduleIds = T4uScheduleDAO.getAllScheduleIds();
                            List<T4uSchedule> allSchedules = new ArrayList<T4uSchedule>();
                            for (int scheduleId : allScheduleIds)
                                allSchedules.add(T4uScheduleDAO.getScheduleById(scheduleId));
                            session.setAttribute(T4uConstants.T4uAllSchedules, allSchedules);
                            request.setAttribute("success", T4uConstants.ExScheduleSuccess);
                            RequestDispatcher dispatcher = getServletContext()
                                    .getRequestDispatcher("/schedules.jsp");
                            dispatcher.forward(request, response);
                        } else {
                            // Error
                            request.setAttribute("error", T4uConstants.ExScheduleError);
                            RequestDispatcher dispatcher = getServletContext()
                                    .getRequestDispatcher("/error.jsp");
                            dispatcher.forward(request, response);
                        }
                    } else {
                        // Not allow update
                        request.setAttribute("error", T4uConstants.ExScheduleAlreadyOccupied);
                        RequestDispatcher dispatcher = getServletContext()
                                .getRequestDispatcher("/schedules.jsp");
                        dispatcher.forward(request, response);
                    }
                    break;
                case "delete":
                    int scheduleIdDelete = Integer.parseInt(request.getParameter("scheduleIdDelete"));
                    oSeats = T4uScheduleDAO.getOSeatsById(scheduleIdDelete);
                    if (oSeats == null || oSeats.equals("")) {
                        // No seats occupied, allow delete
                        if (T4uScheduleDAO.deleteSchedule(scheduleIdDelete)) {
                            // Successfully insert
                            List<Integer> allScheduleIds = T4uScheduleDAO.getAllScheduleIds();
                            List<T4uSchedule> allSchedules = new ArrayList<T4uSchedule>();
                            for (int scheduleId : allScheduleIds)
                                allSchedules.add(T4uScheduleDAO.getScheduleById(scheduleId));
                            session.setAttribute(T4uConstants.T4uAllSchedules, allSchedules);
                            request.setAttribute("success", T4uConstants.ExScheduleSuccess);
                            RequestDispatcher dispatcher = getServletContext()
                                    .getRequestDispatcher("/schedules.jsp");
                            dispatcher.forward(request, response);
                        } else {
                            // Error
                            request.setAttribute("error", T4uConstants.ExScheduleError);
                            RequestDispatcher dispatcher = getServletContext()
                                    .getRequestDispatcher("/error.jsp");
                            dispatcher.forward(request, response);
                        }
                    } else {
                        // Not allow update
                        request.setAttribute("error", T4uConstants.ExScheduleAlreadyOccupied);
                        RequestDispatcher dispatcher = getServletContext()
                                .getRequestDispatcher("/schedules.jsp");
                        dispatcher.forward(request, response);
                    }
                    break;
                }
            }
        } else {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/schedules.jsp");
            dispatcher.forward(request, response);
        }

    }

    //        HttpSession session = request.getSession(true);
    //        session.setAttribute(T4uConstants.T4uAllSchedules,allSchedules );
    //        session.setAttribute(T4uConstants.T4uAllHouses, allHouses);
    //        session.setAttribute(T4uConstants.T4uAllMovies, allMovies);
    //        json.put("allMovies", allMovies);
    //        json.put("allHouses", allHouses);
}

From source file:com.htm.taskinstance.jpa.TaskInstanceFactoryJPA.java

@Override
public ITaskInstance createTaskInstance(String taskModelName, String taskInstanceName, Object input,
        String taskParentId, Set<ICorrelationProperty> correlationProperties, Timestamp expirationTime)
        throws HumanTaskManagerException {

    /*//from   w w  w.j  a v  a  2 s  .  co m
       * Naturally the underlying task model is required to instantiate the
       * task
       */
    ITaskModel taskModel = dataAccessProvider.getHumanTaskModel(taskModelName);

    if (taskModel == null) {
        String errorMsg = "No task model with the name '" + taskModelName + "' could be found.";
        log.error(errorMsg);
        throw new UserException(errorMsg);
    }

    /* Task instance is automatically set to the state CREATED */
    ITaskInstance taskInstance = new TaskInstanceWrapper(taskInstanceName);

    taskInstance.setTaskModel(taskModel);
    taskInstance.setName(taskInstanceName);

    /* Set the createdOn field with the current time */
    taskInstance.setCreatedOn(new Timestamp(Calendar.getInstance().getTimeInMillis()));

    taskInstance.setExpirationTime(expirationTime);

    /*
       * The order of setting the values is important since some queries base
       * on values of other properties. E.g. priority queries base on input
       * data thus input data have to be set before.
       */

    /* Input data passed by the task parent */
    taskInstance.setInputData(input);

    /* Set properties required for task parent callback */
    taskInstance.setTaskParentId(taskParentId);
    taskInstance.setCorrelationProperties(correlationProperties);

    /* The priority */
    taskInstance.setPriority(evaluatePriorityQuery(taskModel.getPriority(), taskInstance));

    /* Evaluate whether the task is skipable or not */
    taskInstance.setSkipable(evaluateSkipableQuery(taskModel.getSkipable(), taskInstance));

    evaluatePositionQueries(taskModel, taskInstance);

    evaluateDurationQueries(taskModel, taskInstance);

    /* Set and evaluate deadlines */
    Timestamp startBy = evaluateTimestampQuery(taskModel.getStartBy(), taskInstance);
    if (startBy != null) {
        log.debug("Result of StartBy query : " + startBy);
        taskInstance.setStartBy(startBy);
    }
    Timestamp completeBy = evaluateTimestampQuery(taskModel.getCompleteBy(), taskInstance);
    // TODO
    if (completeBy != null) {
        log.debug("Result of CompleteBy query : " + completeBy);
        taskInstance.setCompleteBy(completeBy);
    }

    /*
       * Set presentation properties (title, subject, description) TODO
       * Queries in presentation models have to be supported TODO Criteria
       * have to be added to select appropriate presentation model
       */
    IPresentationModel presentModel = taskModel.getPresentationModel();

    if (presentModel != null) {
        taskInstance.setPresentationTitle(presentModel.getTitle());
        taskInstance.setPresentationSubject(presentModel.getSubject());
        taskInstance.setPresentationDescription(presentModel.getDescription());
    }

    return taskInstance;
}

From source file:com.luna.common.repository.search.SearchUserRepository2WithRepository2ImpIT.java

@Test
public void testLtAndGtForDate() throws ParseException {
    int count = 15;
    String dateStr = "2012-01-15 16:59:00";
    String dateStrFrom = "2012-01-15 16:58:00";
    String dateStrEnd = "2012-01-15 16:59:01";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    for (int i = 0; i < count; i++) {
        User user = createUser();//w w w .  j  a  v a2s.co m
        user.getBaseInfo().setBirthday(new Timestamp(df.parse(dateStr).getTime()));
        userRepository2.save(user);
    }
    Map<String, Object> searchParams = new HashMap<String, Object>();
    searchParams.put("baseInfo.birthday_gt", dateStrFrom);
    searchParams.put("baseInfo.birthday_lt", dateStrEnd);
    Searchable search = Searchable.newSearchable(searchParams);
    assertEquals(count, userRepository2.count(search));
}

From source file:com.controller.schedule.ScheduleEmailServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  ww  . j a  v a  2s  .  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("application/json");
    try {
        if (!AuthenticationUtil.isUserLoggedIn(request)) {
            AuthenticationUtil.printAuthErrorToResponse(response);
            return;
        }
        Integer userId = AuthenticationUtil.getUUID(request);

        Map<String, Object> requestBodyMap = AppConstants.GSON.fromJson(new BufferedReader(request.getReader()),
                Map.class);
        if (requestBodyMap == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "Request body is missing");
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }

        List<String> errorMsgs = validateRequestBody(requestBodyMap);
        if (!errorMsgs.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", errorMsgs);
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }
        Double schedule = (Double) requestBodyMap.get("schedule_time");
        //As of now schedule description is not yet mandatory.
        String scheduleDesc = requestBodyMap.containsKey("schedule_desc")
                ? String.valueOf(requestBodyMap.get("schedule_desc"))
                : null;

        Map<String, Integer> idMap = ScheduleDAO.addToScheduledEmailList(userId,
                requestBodyMap.get("email_subject").toString(), requestBodyMap.get("email_body").toString(),
                requestBodyMap.get("from_email_address").toString(),
                requestBodyMap.get("email_list").toString(), requestBodyMap.get("from_name").toString(),
                requestBodyMap.get("reply_to_email_address").toString(),
                requestBodyMap.get("to_email_addresses").toString().split(","),
                requestBodyMap.get("schedule_title").toString(), scheduleDesc,
                new Timestamp(schedule.longValue()), TemplateStatus.template_saved.toString());
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(AppConstants.GSON.toJson(idMap));
        response.getWriter().flush();
    } catch (SQLException ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Invalid format for schedule time.");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
    } catch (Exception ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:daos.BetalingDaoTest.java

@Test
public void testUpdateBetaling() throws Exception {
    LOG.info("updateBetalingTest");
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();//from  w  w  w.ja  v a2 s .co  m
    testBetaling.setBetaalDatum(new Timestamp(date.getTime()));
    testBetaling.setBetaalwijze(bw);
    testBetaling.setKlant(klant);
    testBetaling.setFactuur(f1);
    session.save(testBetaling);
    session.getTransaction().commit();
    session.close();

    Betaling testBetaling2 = (Betaling) instance.readEntity(1);
    testBetaling2.setBetalingsGegevens("ik betaal niet");
    instance.updateEntity(testBetaling2);
    assertEquals("er schijnt nergens voor betaald te worden", "ik betaal niet",
            ((Betaling) instance.readEntity(1)).getBetalingsGegevens());
}

From source file:libepg.epg.util.datetime.DateTimeFieldConverterTest.java

/**
 * Test of BytesToSqlDateTime method, of class DateTimeFieldConverter.
 *
 * @throws java.lang.Exception//from ww w  .  ja v  a2  s .  co  m
 */
@Test
public void testBytesTOSqlDateTime1() throws Exception {
    LOG.info("BytesTOSqlDateTime1");
    byte[] source = Hex.decodeHex("C079124500".toCharArray());
    Timestamp expResult = new Timestamp(
            new java.text.SimpleDateFormat("yyyyMMddHHmmss").parse("19931013124500").getTime());
    Timestamp result = DateTimeFieldConverter.BytesToSqlDateTime(source);
    assertEquals(expResult, result);
}

From source file:org.kuali.mobility.push.service.CXFDeviceService.java

@GET
@Path("/count")
public String countDevices(@QueryParam(value = "data") String data) {
    LOG.info("-----Register----- " + data);
    if (data == null) {
        return "{\"status\":\"NO_CONTENT\"}";
    }//from  w  w  w  .  java  2  s  . com

    JSONObject queryParams;
    try {
        queryParams = (JSONObject) JSONSerializer.toJSON(data);
        LOG.info(queryParams.toString());
    } catch (JSONException je) {
        LOG.error("JSONException in :" + data + " : " + je.getMessage());
        return "{\"status\":\"BAD_REQUEST\"}";
    }
    String type = queryParams.getString("type");
    Long counted = 0l;
    if ("username".equals(type)) {
        String username = queryParams.getString("username");
        counted = this.getDeviceService().countDevicesWithUsername(username);
    } else if ("1month".equals(type)) {
        counted = this.getDeviceService()
                .countDevicesBefore(new Timestamp(System.currentTimeMillis() - ONE_MONTH));
    } else if ("3month".equals(type)) {
        counted = this.getDeviceService()
                .countDevicesBefore(new Timestamp(System.currentTimeMillis() - THREE_MONTHS));
    } else if ("6month".equals(type)) {
        counted = this.getDeviceService()
                .countDevicesBefore(new Timestamp(System.currentTimeMillis() - SIX_MONTHS));
    } else if ("1year".equals(type)) {
        counted = this.getDeviceService()
                .countDevicesBefore(new Timestamp(System.currentTimeMillis() - ONE_YEAR));
    } else if ("allios".equals(type)) {
        counted = this.getDeviceService().countDevices(Device.TYPE_IOS);
    } else if ("allandroid".equals(type)) {
        counted = this.getDeviceService().countDevices(Device.TYPE_ANDROID);
    } else if ("allblackberry".equals(type)) {
        counted = this.getDeviceService().countDevices(Device.TYPE_BLACKBERRY);
    } else if ("allwindows".equals(type)) {
        counted = this.getDeviceService().countDevices(Device.TYPE_WINDOWS);
    } else if ("all".equals(type)) {
        counted = this.getDeviceService().countDevices();
    }
    return "{\"status\":\"OK\", \"count\":\"" + counted + "\"}";
}

From source file:net.mindengine.oculus.frontend.service.project.build.JdbcBuildDAO.java

@Override
public long createBuild(Build build) throws Exception {
    String sql = "insert into builds (name, description, date, project_id) values (?,?,?,?)";
    PreparedStatement ps = getConnection().prepareStatement(sql);
    ps.setString(1, build.getName());//from  ww w.  j a va  2  s  .co m
    ps.setString(2, build.getDescription());
    ps.setTimestamp(3, new Timestamp(build.getDate().getTime()));
    ps.setLong(4, build.getProjectId());

    logger.info(ps);
    ps.execute();

    ResultSet rs = ps.getGeneratedKeys();
    if (rs.next()) {
        return rs.getLong(1);
    }
    return 0;
}

From source file:org.kuali.mobility.push.dao.PushDeviceTupleDaoImplTest.java

@Test
@DirtiesContext/*from   w ww  . ja  va  2  s . c  o  m*/
public void testUpdateTuple() {
    List<PushDeviceTuple> tuples = getDao().findUnsentTuples();
    PushDeviceTuple tuple = tuples.get(2);
    Calendar cal = Calendar.getInstance();
    tuple.setPostedTimestamp(new Timestamp(cal.getTimeInMillis()));
    Long oldId = tuple.getId();
    Long newId = getDao().saveTuple(tuple);
    assertTrue("Tuple was inserted, not updated.", oldId.compareTo(newId) == 0);
}