List of usage examples for java.sql Timestamp getTime
public long getTime()
From source file:org.projectforge.business.task.TaskDao.java
/** * Gets the total duration of all time sheets of all tasks (excluding the child tasks). * /*from w w w. j av a 2s . c o m*/ * @param node * @return */ @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public List<Object[]> readTotalDurations() { log.debug("Calculating duration for all tasks"); final String intervalInSeconds = DatabaseSupport.getInstance().getIntervalInSeconds("startTime", "stopTime"); if (intervalInSeconds != null) { @SuppressWarnings("unchecked") final List<Object[]> list = (List<Object[]>) getHibernateTemplate().find("select " + intervalInSeconds + ", task.id from TimesheetDO where deleted=false group by task.id"); return list; } @SuppressWarnings("unchecked") final List<Object[]> result = (List<Object[]>) getHibernateTemplate() .find("select startTime, stopTime, task.id from TimesheetDO where deleted=false order by task.id"); final List<Object[]> list = new ArrayList<Object[]>(); if (CollectionUtils.isEmpty(result) == false) { Integer currentTaskId = null; long totalDuration = 0; for (final Object[] oa : result) { final Timestamp startTime = (Timestamp) oa[0]; final Timestamp stopTime = (Timestamp) oa[1]; final Integer taskId = (Integer) oa[2]; final long duration = (stopTime.getTime() - startTime.getTime()) / 1000; if (currentTaskId == null || currentTaskId.equals(taskId) == false) { if (currentTaskId != null) { list.add(new Object[] { totalDuration, currentTaskId }); } // New row. currentTaskId = taskId; totalDuration = 0; } totalDuration += duration; } if (currentTaskId != null) { list.add(new Object[] { totalDuration, currentTaskId }); } } return list; }
From source file:org.apache.gobblin.metastore.MysqlStateStore.java
/** * Gets entry managers for all tables matching the predicate * @param predicate Predicate used to filter tables. To allow state stores to push down predicates, use native extensions * of {@link StateStorePredicate}. * @throws IOException/* ww w. j av a2s . c om*/ */ @Override public List<? extends StateStoreEntryManager> getMetadataForTables(StateStorePredicate predicate) throws IOException { List<MysqlStateStoreEntryManager> entryManagers = Lists.newArrayList(); try (Connection connection = dataSource.getConnection(); PreparedStatement queryStatement = connection.prepareStatement(SELECT_METADATA_SQL)) { String storeName = predicate instanceof StoreNamePredicate ? ((StoreNamePredicate) predicate).getStoreName() : "%"; queryStatement.setString(1, storeName); try (ResultSet rs = queryStatement.executeQuery()) { while (rs.next()) { String rsStoreName = rs.getString(1); String rsTableName = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); StateStoreEntryManager entryManager = new MysqlStateStoreEntryManager(rsStoreName, rsTableName, timestamp.getTime(), this); if (predicate.apply(entryManager)) { entryManagers.add(new MysqlStateStoreEntryManager(rsStoreName, rsTableName, timestamp.getTime(), this)); } } } } catch (SQLException e) { throw new IOException("failure getting metadata for tables", e); } return entryManagers; }
From source file:org.apache.syncope.core.util.ImportExport.java
private String getValues(final ResultSet rs, final String columnName, final Integer columnType) throws SQLException { String res = null;//from w w w .jav a2 s. c om try { switch (columnType) { case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: final InputStream is = rs.getBinaryStream(columnName); if (is != null) { res = new String(Hex.encode(IOUtils.toByteArray(is))); } break; case Types.BLOB: final Blob blob = rs.getBlob(columnName); if (blob != null) { res = new String(Hex.encode(IOUtils.toByteArray(blob.getBinaryStream()))); } break; case Types.BIT: case Types.BOOLEAN: if (rs.getBoolean(columnName)) { res = "1"; } else { res = "0"; } break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: final Timestamp timestamp = rs.getTimestamp(columnName); if (timestamp != null) { res = DATE_FORMAT.get().format(new Date(timestamp.getTime())); } break; default: res = rs.getString(columnName); } } catch (IOException e) { LOG.error("Error retrieving hexadecimal string", e); } return res; }
From source file:edu.northwestern.bioinformatics.studycalendar.service.SubjectService.java
Date shiftDayByOne(Date date) { java.sql.Timestamp timestampTo = new java.sql.Timestamp(date.getTime()); long oneDay = 24 * 60 * 60 * 1000; timestampTo.setTime(timestampTo.getTime() + oneDay); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String dateString = df.format(timestampTo); Date d1;/*from w w w .j a v a 2 s . com*/ try { d1 = df.parse(dateString); } catch (ParseException e) { log.debug("Exception " + e); d1 = date; } return d1; }
From source file:fr.paris.lutece.plugins.mylutece.modules.database.authentication.BaseAuthentication.java
/** * This methods checks the login info in the database * * @param strUserName The username//from w w w. ja va2 s. c om * @param strUserPassword The password * @param request The HttpServletRequest * @return A LuteceUser object corresponding to the login * @throws LoginException The LoginException */ @Override public LuteceUser login(String strUserName, String strUserPassword, HttpServletRequest request) throws LoginException { DatabaseService databaseService = DatabaseService.getService(); Plugin pluginMyLutece = PluginService.getPlugin(MyLutecePlugin.PLUGIN_NAME); Plugin plugin = PluginService.getPlugin(DatabasePlugin.PLUGIN_NAME); // Creating a record of connections log ConnectionLog connectionLog = new ConnectionLog(); connectionLog.setIpAddress(SecurityUtil.getRealIp(request)); connectionLog.setDateLogin(new java.sql.Timestamp(new java.util.Date().getTime())); // Test the number of errors during an interval of minutes int nMaxFailed = DatabaseUserParameterHome.getIntegerSecurityParameter(PROPERTY_MAX_ACCESS_FAILED, plugin); int nMaxFailedCaptcha = 0; int nIntervalMinutes = DatabaseUserParameterHome.getIntegerSecurityParameter(PROPERTY_INTERVAL_MINUTES, plugin); boolean bEnableCaptcha = false; if (PluginService.isPluginEnable(PLUGIN_JCAPTCHA)) { nMaxFailedCaptcha = DatabaseUserParameterHome .getIntegerSecurityParameter(PROPERTY_ACCESS_FAILED_CAPTCHA, plugin); } Locale locale = request.getLocale(); if (((nMaxFailed > 0) || (nMaxFailedCaptcha > 0)) && (nIntervalMinutes > 0)) { int nNbFailed = ConnectionLogHome.getLoginErrors(connectionLog, nIntervalMinutes, pluginMyLutece); if ((nMaxFailedCaptcha > 0) && (nNbFailed >= nMaxFailedCaptcha)) { bEnableCaptcha = true; } if ((nMaxFailed > 0) && (nNbFailed >= nMaxFailed)) { if (nNbFailed == nMaxFailed) { ReferenceItem item = DatabaseUserParameterHome.findByKey(PARAMETER_ENABLE_UNBLOCK_IP, plugin); if ((item != null) && item.isChecked()) { sendUnlockLinkToUser(strUserName, nIntervalMinutes, request, plugin); } } Object[] args = { Integer.toString(nIntervalMinutes) }; String strMessage = I18nService.getLocalizedString(PROPERTY_TOO_MANY_FAILURES, args, locale); if (bEnableCaptcha) { throw new FailedLoginCaptchaException(strMessage, bEnableCaptcha); } else { throw new FailedLoginException(strMessage); } } } BaseUser user = DatabaseHome.findLuteceUserByLogin(strUserName, plugin, this); // Unable to find the user if ((user == null) || !databaseService.isUserActive(strUserName, plugin)) { AppLogService.info("Unable to find user in the database : " + strUserName); if (bEnableCaptcha) { throw new FailedLoginCaptchaException( I18nService.getLocalizedString(PROPERTY_MESSAGE_USER_NOT_FOUND_DATABASE, locale), bEnableCaptcha); } else { throw new FailedLoginException( I18nService.getLocalizedString(PROPERTY_MESSAGE_USER_NOT_FOUND_DATABASE, locale)); } } // Check password if (!databaseService.checkPassword(strUserName, strUserPassword, plugin)) { AppLogService.info("User login : Incorrect login or password" + strUserName); if (bEnableCaptcha) { throw new FailedLoginCaptchaException( I18nService.getLocalizedString(PROPERTY_MESSAGE_USER_NOT_FOUND_DATABASE, locale), bEnableCaptcha); } else { throw new FailedLoginException( I18nService.getLocalizedString(PROPERTY_MESSAGE_USER_NOT_FOUND_DATABASE, locale)); } } // Get roles List<String> arrayRoles = DatabaseHome.findUserRolesFromLogin(strUserName, plugin); if (!arrayRoles.isEmpty()) { user.setRoles(arrayRoles); } // Get groups List<String> arrayGroups = DatabaseHome.findUserGroupsFromLogin(strUserName, plugin); if (!arrayGroups.isEmpty()) { user.setGroups(arrayGroups); } // We update the status of the user if his password has become obsolete Timestamp passwordMaxValidDate = DatabaseHome.findPasswordMaxValideDateFromLogin(strUserName, plugin); if ((passwordMaxValidDate != null) && (passwordMaxValidDate.getTime() < new java.util.Date().getTime())) { DatabaseHome.updateResetPasswordFromLogin(strUserName, Boolean.TRUE, plugin); } int nUserId = DatabaseHome.findUserIdFromLogin(strUserName, plugin); databaseService.updateUserExpirationDate(nUserId, plugin); return user; }
From source file:edu.ku.brc.specify.datamodel.SpecifyUser.java
/** * @param loginOutTime the loginOutTime to set *///from ww w .j a v a 2s . c o m public void setLoginOutTime(Timestamp loginOutTime) { if (loginOutTime != null && loginOutTime.getTime() > 0) { this.loginOutTime = loginOutTime; } }
From source file:org.cloudfoundry.identity.uaa.integration.codestore.ExpiringCodeStoreMockMvcTests.java
@Test public void testGenerateCode() throws Exception { Timestamp ts = new Timestamp(System.currentTimeMillis() + 60000); ExpiringCode code = new ExpiringCode(null, ts, "{}"); String requestBody = new ObjectMapper().writeValueAsString(code); MockHttpServletRequestBuilder post = post("/Codes").header("Authorization", "Bearer " + loginToken) .contentType(APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).content(requestBody); mockMvc.perform(post).andExpect(status().isCreated()).andExpect(jsonPath("$.code").exists()) .andExpect(jsonPath("$.expiresAt").value(ts.getTime())).andExpect(jsonPath("$.data").value("{}")); }
From source file:de.iisys.schub.processMining.similarity.AlgoController.java
private double printTimestamp(boolean showDuration) { DecimalFormat df = new DecimalFormat("#0.000"); double duration = 0; Timestamp time = new Timestamp(Calendar.getInstance().getTime().getTime()); if (showDuration && this.lastTimestamp != null) { duration = (time.getTime() - this.lastTimestamp.getTime()) / 1000f; System.out.print(time.toString() + " (" + df.format((Math.round(duration * 1000) / 1000.0)) + " s)"); } else//from w ww. j av a 2 s .co m System.out.print(time); this.lastTimestamp = time; return Math.round(duration * 1000) / 1000.0; }
From source file:netflow.DatabaseProxy.java
public java.util.Date getMaxDate() { java.util.Date result = null; String sql = getQuery("max.date.get"); try {/*from w ww. jav a 2 s. co m*/ PreparedStatement pstmt = con.prepareStatement(sql); result = doWithStatement(pstmt, new ResultSetProcessor<Date>() { @Override public Date process(ResultSet rs) throws SQLException { java.util.Date result = null; if (rs.next()) { Timestamp t = rs.getTimestamp(1); if (t != null) { result = new java.util.Date(); result.setTime(t.getTime()); } } return result; } }); } catch (SQLException e) { log.error(e); e.printStackTrace(); } return result; }
From source file:com.webpagebytes.cms.local.WPBLocalDataStoreDao.java
private <T> T copyResultSetToObject(ResultSet resultSet, Class<T> kind) throws SQLException, WPBSerializerException { try {/*w ww .ja v a2s . c o m*/ T result = kind.newInstance(); Field[] fields = kind.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); boolean storeField = (field.getAnnotation(WPBAdminFieldKey.class) != null) || (field.getAnnotation(WPBAdminFieldStore.class) != null) || (field.getAnnotation(WPBAdminFieldTextStore.class) != null); if (storeField) { String fieldName = field.getName(); String fieldNameUpperCase = field.getName().toUpperCase(); PropertyDescriptor pd = new PropertyDescriptor(fieldName, kind); // get the field type if (field.getType() == Long.class) { Long value = resultSet.getLong(fieldNameUpperCase); pd.getWriteMethod().invoke(result, value); } else if (field.getType() == String.class) { String value = resultSet.getString(fieldNameUpperCase); pd.getWriteMethod().invoke(result, value); } else if (field.getType() == Integer.class) { Integer value = resultSet.getInt(fieldNameUpperCase); pd.getWriteMethod().invoke(result, value); } else if (field.getType() == Date.class) { Timestamp ts = resultSet.getTimestamp(fieldNameUpperCase); Date value = new Date(ts.getTime()); pd.getWriteMethod().invoke(result, value); } } } return result; } catch (Exception e) { throw new WPBSerializerException("Cannot deserialize from Result Set", e); } }