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.azaptree.services.security.dao.HashedCredentialDAO.java

@Override
public HashedCredential create(final HashedCredential hashedCredential) {
    Assert.notNull(hashedCredential, "hashedCredential is required");

    final Optional<Date> expiresOn = hashedCredential.getExpiresOn();
    final Date expiresOnValue = expiresOn.isPresent() ? expiresOn.get() : null;

    final HashedCredentialImpl entity = new HashedCredentialImpl(hashedCredential.getSubjectId(),
            hashedCredential.getName(), hashedCredential.getHashServiceConfigurationId(),
            hashedCredential.getHash(), hashedCredential.getHashAlgorithm(),
            hashedCredential.getHashIterations(), hashedCredential.getSalt(), expiresOnValue);

    entity.created();/*  w ww . ja  v a2s .  co m*/
    final String sql = "insert into t_hashed_credential "
            + "(entity_id,entity_version,entity_created_on,entity_created_by,entity_updated_on,entity_updated_by,name,subject_id,hash,hash_algorithm,hash_iterations,salt,hash_service_config_id,expires_on)"
            + " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

    final Optional<UUID> createdBy = entity.getCreatedByEntityId();
    final UUID createdByUUID = createdBy.isPresent() ? createdBy.get() : null;
    jdbc.update(sql, entity.getEntityId(), entity.getEntityVersion(),
            new Timestamp(entity.getEntityCreatedOn()), createdByUUID,
            new Timestamp(entity.getEntityUpdatedOn()), createdByUUID, entity.getName(), entity.getSubjectId(),
            entity.getHash(), entity.getHashAlgorithm(), entity.getHashIterations(), entity.getSalt(),
            entity.getHashServiceConfigurationId(), expiresOnValue);
    return entity;
}

From source file:com.mapd.bench.BenchmarkCloud.java

void doWork(String[] args, int query) {

    //Grab parameters from args
    // parm0 number of iterations per query
    // parm1 file containing sql queries {contains quoted query, expected result count]
    // parm2 table name
    // parm3 run label
    // parm4 gpu count
    // parm5 optional query and result machine
    // parm6 optional DB URL
    // parm7 optional JDBC Driver class name
    // parm8 optional user
    // parm9 optional passwd
    int iterations = Integer.valueOf(args[0]);
    logger.debug("Iterations per query is " + iterations);

    String queryFile = args[1];//from w w  w  .j  a  v a2s.co  m
    tableName = args[2];
    label = args[3];
    gpuCount = args[4];

    //int expectedResults = Integer.valueOf(args[2]);
    queryResultMachine = (args.length > 5) ? args[5] : QUERY_RESULT_MACHINE;
    url = (args.length > 6) ? args[6] : DB_URL;
    driver = (args.length > 7) ? args[7] : JDBC_DRIVER;

    iUser = (args.length > 8) ? args[8] : USER;
    iPasswd = (args.length > 9) ? args[9] : PASS;

    //register the driver
    try {
        //Register JDBC driver
        Class.forName(driver);
    } catch (ClassNotFoundException ex) {
        logger.error("Could not load class " + driver + " " + ex.getMessage());
        System.exit(1);
    }

    UUID uuid = UUID.randomUUID();
    rid = uuid.toString();
    java.util.Date date = new java.util.Date();
    Timestamp t = new Timestamp(date.getTime());
    rTimestamp = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(t);

    System.out.println("run id is " + rid + " date is " + rTimestamp);

    // read from query file and execute queries
    String sCurrentLine;
    List<String> resultArray = new ArrayList();
    Map<String, String> queryIDMap = new LinkedHashMap();
    BufferedReader br;
    try {
        br = new BufferedReader(new FileReader(queryFile));

        while ((sCurrentLine = br.readLine()) != null) {

            queryIDMap.put(sCurrentLine, null);
        }
        br.close();

    } catch (FileNotFoundException ex) {
        logger.error("Could not find file " + queryFile + " " + ex.getMessage());
        System.exit(2);
    } catch (IOException ex) {
        logger.error("IO Exeception " + ex.getMessage());
        System.exit(3);
    }

    bencherCon = getConnection("jdbc:mapd:" + queryResultMachine + ":9091:mapd", "mapd", "HyperInteractive");

    getQueries(queryIDMap, bencherCon, tableName);

    runQueries(resultArray, queryIDMap, iterations);

    // if all completed ok store the results
    storeResults();

    // All done dump out results
    System.out.println(header2);
    for (String s : resultArray) {
        System.out.println(s);
    }

}

From source file:se.crisp.codekvast.warehouse.file_import.ImportDAOImpl.java

@Override
public boolean saveInvocation(Invocation invocation, ImportContext context) {
    long applicationId = context.getApplicationId(invocation.getLocalApplicationId());
    long methodId = context.getMethodId(invocation.getLocalMethodId());
    long jvmId = context.getJvmId(invocation.getLocalJvmId());
    Timestamp invokedAt = new Timestamp(invocation.getInvokedAtMillis());

    Timestamp oldInvokedAt = queryForTimestamp(
            "SELECT invokedAtMillis FROM invocations WHERE applicationId = ? AND methodId = ? AND jvmId = ? ",
            applicationId, methodId, jvmId);

    boolean databaseTouched = false;
    if (oldInvokedAt == null) {
        jdbcTemplate.update(/*from  www .java  2  s.com*/
                "INSERT INTO invocations(applicationId, methodId, jvmId, invokedAtMillis, invocationCount, status) "
                        + "VALUES(?, ?, ?, ?, ?, ?) ",
                applicationId, methodId, jvmId, invokedAt.getTime(), invocation.getInvocationCount(),
                invocation.getStatus().name());
        log.trace("Inserted invocation {}:{}:{} {}", applicationId, methodId, jvmId, invokedAt);
        databaseTouched = true;
    } else if (invokedAt.after(oldInvokedAt)) {
        jdbcTemplate.update(
                "UPDATE invocations SET invokedAtMillis = ?, invocationCount = invocationCount + ?, status = ? "
                        + "WHERE applicationId = ? AND methodId = ? AND jvmId = ? ",
                invokedAt.getTime(), invocation.getInvocationCount(), invocation.getStatus().name(),
                applicationId, methodId, jvmId);
        log.trace("Updated invocation {}:{}:{} {}", applicationId, methodId, jvmId, invokedAt);
        databaseTouched = true;
    } else if (oldInvokedAt.equals(invokedAt)) {
        log.trace("Ignoring invocation, same row exists in database");
    } else {
        log.trace("Ignoring invocation, a newer row exists in database");
    }
    return databaseTouched;
}

From source file:com.matrimony.database.UserDAO.java

public static boolean hasExpiries(User user) {
    Timestamp now = new Timestamp(System.currentTimeMillis());
    if (user.getExpiries().after(now))
        return true;
    else/*w w  w .ja  va 2s  .c o m*/
        return false;
}

From source file:gov.nih.nci.cadsr.sentinel.tool.AlertRec.java

/**
 * Copy a time stamp. This guarantees the time is preset so the copy matches
 * the original value./*from ww w.j  a v a2  s. com*/
 * 
 * @param v_
 *        The Timestamp to copy.
 * @return The new Timestamp.
 */
private Timestamp copy(Timestamp v_) {
    if (v_ == null)
        return null;
    return new Timestamp(v_.getTime());
}

From source file:com.adanac.module.blog.dao.AnswerDao.java

public Integer save(final Integer questionId, final String visitorIp, final Date answerDate,
        final String answer, final String username, final Integer referenceAnswerId) {
    return execute(new TransactionalOperation<Integer>() {
        @Override//  w w  w . j a va2  s  .  c  o m
        public Integer doInConnection(Connection connection) {
            try {
                PreparedStatement statement = null;
                if (referenceAnswerId == null) {
                    statement = connection.prepareStatement(
                            "insert into answers (visitor_ip,city,answer,question_id,"
                                    + "answer_date,username) values (?,?,?,?,?,?)",
                            Statement.RETURN_GENERATED_KEYS);
                } else {
                    statement = connection.prepareStatement(
                            "insert into answers (visitor_ip,city,answer,question_id,"
                                    + "answer_date,username,reference_answer_id) values (?,?,?,?,?,?,?)",
                            Statement.RETURN_GENERATED_KEYS);
                }
                statement.setString(1, visitorIp);
                statement.setString(2,
                        Configuration.isProductEnv() ? HttpApiHelper.getCity(visitorIp) : "?");
                statement.setString(3, answer);
                statement.setInt(4, questionId);
                Date finalCommentDate = answerDate;
                if (answerDate == null) {
                    finalCommentDate = new Date();
                }
                statement.setTimestamp(5, new Timestamp(finalCommentDate.getTime()));
                statement.setString(6, username);
                if (referenceAnswerId != null) {
                    statement.setInt(7, referenceAnswerId);
                }
                int result = statement.executeUpdate();
                if (result > 0) {
                    ResultSet resultSet = statement.getGeneratedKeys();
                    if (resultSet.next()) {
                        return resultSet.getInt(1);
                    }
                }
            } catch (SQLException e) {
                error("save answers failed ...", e);
            }
            return null;
        }
    });
}

From source file:com.bdx.rainbow.service.etl.analyze.SYJHttpAnalyze.java

/**
 * ?/*from  www  .ja v  a 2s.c  o m*/
 * 
 * @param document
 * @return
 * @throws Exception
 */
private Object analyzeLicenseDetail(HttpSeed seed) throws Exception {

    Document doc = parse(seed.getHtml());

    Elements eleTable = doc.select(".listmain table");
    // TR
    Elements eleTrs = eleTable.get(0).select("tr");

    // ?
    Object entity = AnalyzeUtil.getInstant(PREFIX_ENTITY_PATH + syjTableBean.getTableClass());

    // tr?trtd?
    int rowNo = 1;
    for (int i = 0; i < eleTrs.size(); i++) {
        Element eleTr = eleTrs.get(i);

        // ??trtd??nowrapnowrap?true
        if (i != eleTrs.size() - 1 && (!eleTr.select("td").get(0).hasAttr("nowrap")
                || !"true".equals(eleTr.select("td").get(0).attr("nowrap")))) {
            continue;
        }

        // td?
        String tdVal = parseDetailTr(eleTr);

        // TABLE7411??
        if (syjTableBean.getTableClass().equals("TABLE74") && rowNo == 11) {
            continue;
        }

        // entity
        AnalyzeUtil.executeMethod(entity, PREFIX_ATTRIBUTE + rowNo++, new Object[] { tdVal },
                new Class[] { String.class });
    }

    // ?ID, ?createEmpCode
    String regex = ".+?&Id=(.+?)";
    Object obj = AnalyzeUtil.regex(seed.getUrl(), regex);

    if (null == obj) {
        // ID
        AnalyzeUtil.executeMethod(entity, "setContentId", new Object[] { 0l }, new Class[] { Long.class });
    } else {
        // ID
        AnalyzeUtil.executeMethod(entity, "setContentId", new Object[] { Long.valueOf(obj.toString()) },
                new Class[] { Long.class });
    }

    // ?
    AnalyzeUtil.executeMethod(entity, "setCreateTime", new Object[] { new Timestamp(new Date().getTime()) },
            new Class[] { Timestamp.class });

    return entity;
}

From source file:fr.paris.lutece.plugins.workflow.modules.alert.service.TaskAlert.java

/**
 * {@inheritDoc}/*  w w  w  .  j  a va  2 s.  c  o m*/
 */
@Override
public void processTask(int nIdResourceHistory, HttpServletRequest request, Locale locale) {
    ResourceHistory resourceHistory = _resourceHistoryService.findByPrimaryKey(nIdResourceHistory);
    TaskAlertConfig config = _taskAlertConfigService.findByPrimaryKey(getId());

    if ((config != null) && (resourceHistory != null)
            && Record.WORKFLOW_RESOURCE_TYPE.equals(resourceHistory.getResourceType())) {
        Plugin pluginDirectory = PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME);

        // Record
        Record record = RecordHome.findByPrimaryKey(resourceHistory.getIdResource(), pluginDirectory);

        if (record != null) {
            Directory directory = DirectoryHome.findByPrimaryKey(record.getDirectory().getIdDirectory(),
                    pluginDirectory);

            if (directory != null) {
                Alert alert = _alertService.find(nIdResourceHistory, getId());

                if (alert == null) {
                    Long lDate = config.getDate(record);
                    alert = new Alert();
                    alert.setIdResourceHistory(nIdResourceHistory);
                    alert.setIdTask(getId());
                    alert.setDateReference(new Timestamp(lDate));
                    _alertService.create(alert);
                }
            }
        }
    }
}

From source file:ru.org.linux.tracker.TrackerController.java

@RequestMapping("/tracker")
public ModelAndView tracker(@RequestParam(value = "filter", defaultValue = "all") String filterAction,
        @RequestParam(value = "offset", required = false) Integer offset, HttpServletRequest request)
        throws Exception {

    if (offset == null) {
        offset = 0;/*  w w w.  j  a v a 2  s  .c o  m*/
    } else {
        if (offset < 0 || offset > 300) {
            throw new UserErrorException("?  offset");
        }
    }

    TrackerFilterEnum trackerFilter = getFilterValue(filterAction);

    Map<String, Object> params = new HashMap<>();
    params.put("mine", trackerFilter == TrackerFilterEnum.MINE);
    params.put("offset", offset);
    params.put("filter", trackerFilter.getValue());

    if (trackerFilter != TrackerFilterEnum.ALL) {
        params.put("addition_query", "&amp;filter=" + trackerFilter.getValue());
    } else {
        params.put("addition_query", "");
    }

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    if (trackerFilter == TrackerFilterEnum.MINE) {
        calendar.add(Calendar.MONTH, -6);
    } else {
        calendar.add(Calendar.HOUR, -24);
    }
    Timestamp dateLimit = new Timestamp(calendar.getTimeInMillis());

    Template tmpl = Template.getTemplate(request);
    int messages = tmpl.getProf().getMessages();
    int topics = tmpl.getProf().getTopics();

    params.put("topics", topics);

    User user = tmpl.getCurrentUser();

    if (trackerFilter == TrackerFilterEnum.MINE) {
        if (!tmpl.isSessionAuthorized()) {
            throw new UserErrorException("Not authorized");
        }
        params.put("title", "? ?? ( )");
    } else {
        params.put("title", "? ??");
    }
    params.put("msgs", trackerDao.getTrackAll(trackerFilter, user, dateLimit, topics, offset, messages));

    if (tmpl.isModeratorSession() && trackerFilter != TrackerFilterEnum.MINE) {
        params.put("newUsers", userDao.getNewUsers());
        params.put("deleteStats", deleteInfoDao.getRecentStats());
    }

    return new ModelAndView("tracker", params);
}