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.cretz.sbnstat.gource.Gourcer.java

@Override
public void run(Arguments args) {
    try {/*from   ww w .  j ava  2 s .  c  o m*/
        //ok, we're gonna dump to a custom file format
        //dates
        Calendar from = DateUtils.toBeginningOfDayCalendar(args.getFrom());
        Calendar to = DateUtils.toEndOfDayCalendar(args.getTo());
        logger.info("Dumping gource custom log from {} to {}", from.getTime(), to.getTime());
        //build connection
        Connection conn = JdbcUtils.connectToMySqlDatabase(args.getDatabaseHost(), args.getDatabasePort(),
                args.getDatabaseName(), args.getDatabaseUser(), args.getDatabasePass());
        //maps to hold data
        final NavigableSet<CommentState> allComments = new TreeSet<CommentState>();
        final Map<Long, CommentState> mappedComments = new HashMap<Long, CommentState>();
        final Map<String, PostState> mappedPosts = new HashMap<String, PostState>();
        try {
            //load data
            new SbnStatDao(conn).readComments(new Timestamp(from.getTimeInMillis()),
                    new Timestamp(to.getTimeInMillis()), new CommentHandler() {
                        @Override
                        public void onComment(CommentInfo info) throws Exception {
                            PostState post = mappedPosts.get(info.getPostUrl());
                            if (post == null) {
                                post = new PostState(info.getPostUrl(), info.getPostTitle(),
                                        info.getPostUsername(), info.getPostDate());
                                mappedPosts.put(post.url, post);
                            }
                            CommentState state = new CommentState(info.getId(), post,
                                    mappedComments.get(info.getParentId()), info.getDate(),
                                    info.getCommentUsername(), info.getSubject(),
                                    info.getCommentUserThumbnail());
                            allComments.add(state);
                            mappedComments.put(state.id, state);
                        }
                    });
        } finally {
            JdbcUtils.closeQuietly(conn);
        }
        //loop through and write lines
        PrintStream out;
        if (args.getOut() != null) {
            out = new PrintStream(new File(args.getOut()));
        } else {
            out = System.out;
        }
        try {
            Set<String> processedPosts = new HashSet<String>();
            File dir = args.getDir() == null ? null : new File(args.getDir());
            if (dir != null && !dir.exists()) {
                dir.mkdirs();
            }
            List<String> lines = new ArrayList<String>();
            for (CommentState comment : allComments) {
                //let's grab the user avatar image
                if (dir != null && comment.thumbnail != null) {
                    saveUserAvatar(dir, comment);
                }
                String title;
                if (comment.post.title != null) {
                    title = comment.post.title;
                } else {
                    title = "";
                }
                if (!processedPosts.contains(comment.post.url)) {
                    //add a post
                    lines.add(getGourceLine(comment.post.date, comment.post.username, 'A',
                            "/" + title.replace('/', ' ')));
                    processedPosts.add(comment.post.url);
                }
                //make the parent string (bad performance)
                String path = "";
                CommentState parent = comment;
                while (parent != null) {
                    path = "/" + parent.subject.replace('/', ' ') + path;
                    parent = parent.parent;
                }
                lines.add(getGourceLine(comment.date, comment.username, comment.parent == null ? 'A' : 'M',
                        "/" + title.replace('/', ' ') + path));
            }
            Collections.sort(lines);
            for (String line : lines) {
                out.println(line);
            }
        } finally {
            Closeables.closeQuietly(out);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.concursive.connect.web.modules.fileattachments.jobs.CleanupTempFilesJob.java

public void execute(JobExecutionContext context) throws JobExecutionException {
    SchedulerContext schedulerContext = null;
    Connection db = null;/*  ww w  .j a v a2 s .  com*/
    try {
        schedulerContext = context.getScheduler().getContext();
        ApplicationPrefs prefs = (ApplicationPrefs) schedulerContext.get("ApplicationPrefs");
        String fs = System.getProperty("file.separator");
        db = SchedulerUtils.getConnection(schedulerContext);
        LOG.debug("Checking temporary files...");
        FileItemList tempFiles = new FileItemList();
        tempFiles.setLinkModuleId(Constants.TEMP_FILES);
        tempFiles.setAlertRangeEnd(new Timestamp(System.currentTimeMillis() - (60L * 60L * 1000L)));
        tempFiles.buildList(db);
        tempFiles.delete(db, prefs.get("FILELIBRARY") + "1" + fs + "projects" + fs);
    } catch (Exception e) {
        LOG.error("CleanupTempFilesJob Exception", e);
        throw new JobExecutionException(e.getMessage());
    } finally {
        SchedulerUtils.freeConnection(schedulerContext, db);
    }
}

From source file:com.bitranger.parknshop.buyer.controller.MakeComment.java

@RequestMapping("/makeComment")
public String makeComment(HttpServletRequest req, Integer psItemId, Integer scoreItem, Integer scoreShop,
        String content) {//from  w ww  .j  a va 2  s  .  c  o  m
    if (psItemId == null || scoreItem == null || scoreShop == null || content == null)
        return Utility.error("Parameter Not Enough");
    if (scoreItem.compareTo(0) < 0 || scoreItem.compareTo(5) > 0 || scoreShop.compareTo(0) < 0
            || scoreShop.compareTo(5) > 0)
        return Utility.error("Wrong Parameter.");
    PsCustomer currentCustomer = (PsCustomer) req.getSession().getAttribute("currentCustomer");
    if (currentCustomer == null) {
        return Utility.error("User haven't logged in.");
    }
    PsItem psItem = psItemDao.findById(psItemId);
    if (psItem == null)
        return Utility.error("PsItem Incorrect.");
    PsComment psComment = new PsComment();
    psComment.setContent(content);
    psComment.setScoreItem(scoreItem);
    psComment.setScoreShop(scoreShop);
    psComment.setPsItem(psItem);
    psComment.setTimeCreated(new Timestamp(System.currentTimeMillis()));
    psComment.setPsCustomer(currentCustomer);
    psCommentDao.save(psComment);
    return "success";
}

From source file:com.asakusafw.testdriver.JobFlowTestDriver.java

/**
 * ???????/*from  w  ww .j a  va  2s. c  o  m*/
 * @param jobFlowDescriptionClass ?
 * @throws RuntimeException ?????
 */
public void runTest(Class<? extends FlowDescription> jobFlowDescriptionClass) {

    try {
        JobflowExecutor executor = new JobflowExecutor(driverContext);

        // ?
        executor.cleanWorkingDirectory();

        // ???Excel???
        storeDatabase();
        setLastModifiedTimestamp(new Timestamp(0L));

        // ?
        JobFlowDriver jobFlowDriver = JobFlowDriver.analyze(jobFlowDescriptionClass);
        assertFalse(jobFlowDriver.getDiagnostics().toString(), jobFlowDriver.hasError());
        JobFlowClass jobFlowClass = jobFlowDriver.getJobFlowClass();

        String flowId = jobFlowClass.getConfig().name();
        File compileWorkDir = driverContext.getCompilerWorkingDirectory();
        if (compileWorkDir.exists()) {
            FileUtils.forceDelete(compileWorkDir);
        }

        FlowGraph flowGraph = jobFlowClass.getGraph();
        JobflowInfo jobflowInfo = DirectFlowCompiler.compile(flowGraph, batchId, flowId, "test.jobflow",
                Location.fromPath(driverContext.getClusterWorkDir(), '/'), compileWorkDir,
                Arrays.asList(new File[] { DirectFlowCompiler.toLibraryPath(jobFlowDescriptionClass) }),
                jobFlowDescriptionClass.getClassLoader(), driverContext.getOptions());

        driverContext.prepareCurrentJobflow(jobflowInfo);

        executor.runJobflow(jobflowInfo);

        // ???Excel??DB??
        loadDatabase();
        if (!testUtils.inspect()) {
            Assert.fail(testUtils.getCauseMessage());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        driverContext.cleanUpTemporaryResources();
    }
}

From source file:fr.hoteia.qalingo.web.service.impl.AbstractWebCommerceServiceImpl.java

/**
 * //  www . ja va  2 s .c om
 */
public CustomerCredential flagCustomeCredentialWithToken(final HttpServletRequest request,
        final RequestData requestData, final Customer customer) throws Exception {
    if (customer != null) {
        String token = UUID.randomUUID().toString();
        CustomerCredential customerCredential = customer.getCurrentCredential();
        customerCredential.setResetToken(token);
        Date date = new Date();
        customerCredential.setTokenTimestamp(new Timestamp(date.getTime()));
        customerService.saveOrUpdateCustomerCredential(customerCredential);
        return customerCredential;
    }
    return null;
}

From source file:fr.paris.lutece.plugins.workflow.modules.ticketing.service.task.TaskReply.java

@Override
protected String processTicketingTask(int nIdResourceHistory, HttpServletRequest request, Locale locale) {
    String strTaskInformation = StringUtils.EMPTY;

    // We get the ticket to modify
    Ticket ticket = getTicket(nIdResourceHistory);

    if (ticket != null) {
        String strUserMessage = request.getParameter(PARAMETER_USER_MESSAGE);
        ticket.setUserMessage(strUserMessage);

        TaskReplyConfig config = _taskConfigService.findByPrimaryKey(this.getId());

        if (MessageDirection.AGENT_TO_USER == config.getMessageDirection()) {
            ticket.setTicketStatus(TicketingConstants.TICKET_STATUS_CLOSED);
            ticket.setDateClose(new Timestamp(new java.util.Date().getTime()));
        }/*from www .  j  a v a 2 s . co m*/

        TicketHome.update(ticket);

        if (StringUtils.isEmpty(strUserMessage)) {
            strUserMessage = I18nService.getLocalizedString(MESSAGE_REPLY_INFORMATION_NO_MESSAGE,
                    Locale.FRENCH);
        }

        strTaskInformation = MessageFormat.format(
                I18nService.getLocalizedString(MESSAGE_REPLY_INFORMATION_PREFIX
                        + config.getMessageDirection().toString().toLowerCase(), Locale.FRENCH),
                strUserMessage);
    }

    return strTaskInformation;
}

From source file:org.ala.spatial.services.dao.ApplicationDAOImpl.java

@Override
public void addApplication(Application app) {
    logger.info("Adding a new application " + app.getName() + " by " + app.getOrganisation() + " ("
            + app.getEmail() + ") ");

    app.setRegtime(new Timestamp(new Date().getTime()));
    try {//  w  w  w  .ja  v  a  2  s  . c o m
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update((app.getName() + app.getEmail() + app.getRegtime()).getBytes());
        byte byteData[] = md.digest();

        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
            sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
        app.setAppid(sb.toString());
    } catch (NoSuchAlgorithmException ex) {
        java.util.logging.Logger.getLogger(ApplicationDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println(app.toString());

    SqlParameterSource parameters = new BeanPropertySqlParameterSource(app);
    Number appUid = insertApplication.executeAndReturnKey(parameters);
    app.setId(appUid.longValue());
}

From source file:org.cloudfoundry.identity.uaa.oauth.approval.JdbcApprovalStoreTests.java

@Test
public void testAddAndGetApproval() {
    String userName = "user";
    String clientId = "client";
    String scope = "uaa.user";
    long expiresIn = 1000l;
    Date lastUpdatedAt = new Date();
    ApprovalStatus status = APPROVED;/*  ww  w .j av  a  2 s .  c om*/

    Date expiresAt = new Timestamp(new Date().getTime() + expiresIn);
    Approval newApproval = new Approval(userName, clientId, scope, expiresAt, status, lastUpdatedAt);
    dao.addApproval(newApproval);
    List<Approval> approvals = dao.getApprovals(userName, clientId);

    Approval approval = approvals.get(0);
    assertEquals(clientId, approval.getClientId());
    assertEquals(userName, approval.getUserName());
    assertEquals(Math.round(expiresAt.getTime() / 1000), Math.round(approval.getExpiresAt().getTime() / 1000));
    assertEquals(Math.round(lastUpdatedAt.getTime() / 1000),
            Math.round(approval.getLastUpdatedAt().getTime() / 1000));
    assertEquals(scope, approval.getScope());
    assertEquals(status, approval.getStatus());
}

From source file:adalid.commons.util.TimeUtils.java

public static synchronized Timestamp getTimestamp(Date date) {
    return date == null ? currentTimestamp() : new Timestamp(date.getTime());
}

From source file:airport.database.services.users.UsersDaoOnlineImpl.java

@Override
public void updateTimer(User user) {
    MapSqlParameterSource parameterSource = new MapSqlParameterSource();
    parameterSource.addValue("last_visit", new Timestamp(new Date().getTime()));
    parameterSource.addValue("id_session", user.getId());

    jdbcTemplate.update(SQL_QUERY_UPDATE_LAS_VISIT, parameterSource);

    if (LOG.isInfoEnabled()) {
        LOG.info("update time of user. User : " + user);
    }//  w ww . j av a2s. c  o m
}