List of usage examples for java.sql Timestamp getTime
public long getTime()
From source file:com.funambol.foundation.items.dao.PIMCalendarDAO.java
/** * Retrieves the UID list of the calendars considered to be "twins" of a * given calendar./*from w ww . j a v a 2s .c om*/ * * @param c the Calendar object representing the calendar whose twins * need be found. In the present implementation, only the following * data matter: * <BR>for events <UL><LI>date start<LI>date end<LI>subject</UL> * for tasks <UL><LI>date end<LI>subject</UL> * @throws DAOException * @return a List of UIDs (as String objects) that may be empty but not null */ public List getTwinItems(Calendar c) throws DAOException { if (log.isTraceEnabled()) { log.trace("PIMCalendarDAO getTwinItems begin"); } LinkedList<String> twins = new LinkedList<String>(); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; if (!isTwinSearchAppliableOn(c)) { if (log.isTraceEnabled()) { log.trace("Item with no dtStart, dtEnd, summary: twin search skipped."); } return twins; } try { // Looks up the data source when the first connection is created con = getUserDataSource().getRoutedConnection(userId); con.setReadOnly(true); Date dtStart; Date dtEnd; Date dueTomorrowNoon = null; Date dueYesterdayNoon = null; dtStart = getDateFromString(c.getCalendarContent().isAllDay(), Property.stringFrom(c.getCalendarContent().getDtStart()), "000000"); dtEnd = getDateFromString(c.getCalendarContent().isAllDay(), Property.stringFrom(c.getCalendarContent().getDtEnd()), "235900"); if ((dtEnd != null) && (c.getCalendarContent() instanceof Task)) { java.util.Calendar noon = new GregorianCalendar(TimeZone.getTimeZone("UTC")); noon.setTime(dtEnd); noon.set(java.util.Calendar.HOUR_OF_DAY, 12); noon.set(java.util.Calendar.MINUTE, 0); noon.set(java.util.Calendar.MILLISECOND, 0); noon.add(java.util.Calendar.DATE, +1); dueTomorrowNoon = noon.getTime(); noon.add(java.util.Calendar.DATE, -2); // go back and another -1 dueYesterdayNoon = noon.getTime(); } StringBuffer sqlGetCalendarTwinList = new StringBuffer(SQL_GET_FNBL_PIM_CALENDAR_ID_LIST_BY_USER); String subject = Property.stringFrom(c.getCalendarContent().getSummary(), true); // Empty implies null; if ("null".equals(subject)) { subject = null; } if (subject == null) { sqlGetCalendarTwinList.append(SQL_AND_NO_SUBJECT_IS_SET); } else { sqlGetCalendarTwinList.append(SQL_AND_SUBJECT_EQUALS_QUESTIONMARK); } if (c.getCalendarContent() instanceof Event) { if (dtStart == null) { sqlGetCalendarTwinList.append(SQL_AND_NO_DSTART_IS_SET); } else { sqlGetCalendarTwinList.append(SQL_AND_DSTART_EQUALS_QUESTIONMARK); } } if (dtEnd == null) { // In method updateItems() while storing the Event in the db, if // the End Date is empty it is filled with the Start Date. // Filling the empty EndDate with the StartDate is done only for // Events and not for Tasks. // See "Fix for Siemens S56 end date issue" in method // updateItems(). // So in order to find the twins, if the incoming Event has an // empty EndDate we seek into the db for Events with EndDate // equal to the StartDate value. if (c.getCalendarContent() instanceof Task) { sqlGetCalendarTwinList.append(SQL_AND_NO_DEND_IS_SET); } else { sqlGetCalendarTwinList.append(SQL_AND_DEND_EQUALS_QUESTIONMARK); } } else { if (c.getCalendarContent() instanceof Task) { sqlGetCalendarTwinList.append(SQL_AND_DEND_IN_INTERVAL); } else { sqlGetCalendarTwinList.append(SQL_AND_DEND_EQUALS_QUESTIONMARK); } } if (c.getCalendarContent() instanceof Event) { sqlGetCalendarTwinList.append(SQL_FILTER_BY_TYPE[CALENDAR_EVENT_TYPE]); } else { sqlGetCalendarTwinList.append(SQL_FILTER_BY_TYPE[CALENDAR_TASK_TYPE]); } // // If funambol is not in the debug mode it is not possible to print // the calendar info because it contains sensitive data. // if (Configuration.getConfiguration().isDebugMode()) { if (log.isTraceEnabled()) { StringBuilder sb = new StringBuilder(100); sb.append("Looking for items having: "); if (subject == null || subject.length() == 0) { sb.append("\n> subject: <N/A>"); } else { sb.append("\n> subject: '").append(subject).append('\''); } if (c.getCalendarContent() instanceof Event) { if (dtStart == null) { sb.append("\n> start date: <N/A>"); } else { sb.append("\n> start date: ").append(dtStart); } if (dtEnd == null) { sb.append("\n> end date: <N/A>"); } else { sb.append("\n> end date: ").append(dtEnd); } } else { // It's a task if (dtEnd == null) { sb.append("\n> due date: <N/A>"); } else { sb.append("\n> due date: between ").append(dueYesterdayNoon) .append("\n> and ").append(dueTomorrowNoon) .append(",\n> possibly ").append(dtEnd); } } log.trace(sb.toString()); } } sqlGetCalendarTwinList.append(SQL_ORDER_BY_ID); ps = con.prepareStatement(sqlGetCalendarTwinList.toString()); int k = 1; ps.setString(k++, userId); if (subject != null) { ps.setString(k++, subject.toLowerCase(Locale.ENGLISH)); } if (dtStart != null) { if (c.getCalendarContent() instanceof Event) { ps.setTimestamp(k++, new Timestamp(dtStart.getTime())); } } if (dtEnd != null) { if (c.getCalendarContent() instanceof Task) { ps.setTimestamp(k++, new Timestamp(dueYesterdayNoon.getTime())); ps.setTimestamp(k++, new Timestamp(dueTomorrowNoon.getTime())); } else { ps.setTimestamp(k++, new Timestamp(dtEnd.getTime())); } } else { // In method updateItems() while storing the Event in the db, if // the End Date is empty it is filled with the Start Date. // Filling the empty EndDate with the StartDate is done only for // Events and not for Tasks. // See "Fix for Siemens S56 end date issue" in method // updateItems(). // So in order to find the twins, if the incoming Event has an // empty EndDate we seek into the db for Events with EndDate // equal to the StartDate value. if (c.getCalendarContent() instanceof Event) { ps.setTimestamp(k++, new Timestamp(dtStart.getTime())); } } rs = ps.executeQuery(); long twinId; Timestamp twinDueDate; while (rs.next()) { if (c.getCalendarContent() instanceof Event) { twinId = rs.getLong(1); // dend is not relevant in this case if (log.isTraceEnabled()) { log.trace("Twin event found: " + twinId); } twins.add(Long.toString(twinId)); } else { // it's a Task twinId = rs.getLong(1); twinDueDate = rs.getTimestamp(2); if (log.isTraceEnabled()) { log.trace("Twin task found: " + twinId); } if ((dtEnd != null) && (twinDueDate != null) && twinDueDate.getTime() == dtEnd.getTime()) { twins.addFirst(Long.toString(twinId)); if (log.isTraceEnabled()) { log.trace("Item " + twinId + " is an exact due-date match."); } } else { twins.addLast(Long.toString(twinId)); } } } } catch (Exception e) { throw new DAOException("Error retrieving twin. ", e); } finally { DBTools.close(con, ps, rs); } if (log.isTraceEnabled()) { log.trace("PIMCalendarDAO getTwinItems end"); } return twins; }
From source file:org.ramadda.repository.database.DatabaseManager.java
/** * _more_/*from ww w . j a v a 2 s . c om*/ * * @param os _more_ * @param all _more_ * @param actionId _more_ * * @throws Exception _more_ */ public void makeDatabaseCopy(OutputStream os, boolean all, Object actionId) throws Exception { XmlEncoder encoder = new XmlEncoder(); DataOutputStream dos = new DataOutputStream(os); Connection connection = getConnection(); try { HashSet<String> skip = new HashSet<String>(); skip.add(Tables.SESSIONS.NAME); List<TableInfo> tableInfos = getTableInfos(connection, false); String xml = encoder.toXml(tableInfos, false); writeString(dos, xml); int rowCnt = 0; System.err.println("Exporting database"); for (TableInfo tableInfo : tableInfos) { if (tableInfo.getName().equalsIgnoreCase("base")) { continue; } if (tableInfo.getName().equalsIgnoreCase("agggregation")) { continue; } if (tableInfo.getName().equalsIgnoreCase("entry")) { continue; } System.err.println("Exporting table: " + tableInfo.getName()); List<ColumnInfo> columns = tableInfo.getColumns(); List valueList = new ArrayList(); Statement statement = execute("select * from " + tableInfo.getName(), 10000000, 0); SqlUtil.Iterator iter = getIterator(statement); ResultSet results; dos.writeInt(DUMPTAG_TABLE); writeString(dos, tableInfo.getName()); if (skip.contains(tableInfo.getName().toLowerCase())) { continue; } while ((results = iter.getNext()) != null) { dos.writeInt(DUMPTAG_ROW); rowCnt++; if ((rowCnt % 1000) == 0) { if (actionId != null) { getActionManager().setActionMessage(actionId, "Written " + rowCnt + " database rows"); } System.err.println("rows:" + rowCnt); } for (int i = 1; i <= columns.size(); i++) { ColumnInfo colInfo = columns.get(i - 1); int type = colInfo.getType(); if (type == ColumnInfo.TYPE_TIMESTAMP) { Timestamp ts = results.getTimestamp(i); if (ts == null) { dos.writeLong((long) -1); } else { dos.writeLong(ts.getTime()); } } else if (type == ColumnInfo.TYPE_VARCHAR) { writeString(dos, results.getString(i)); } else if (type == ColumnInfo.TYPE_TIME) { //TODO: What is the format of a type time? // writeString(dos, results.getString(i)); } else if (type == ColumnInfo.TYPE_INTEGER) { writeInteger(dos, (Integer) results.getObject(i)); } else if (type == ColumnInfo.TYPE_DOUBLE) { writeDouble(dos, (Double) results.getObject(i)); } else if (type == ColumnInfo.TYPE_CLOB) { writeString(dos, results.getString(i)); } else if (type == ColumnInfo.TYPE_BLOB) { writeString(dos, results.getString(i)); } else if (type == ColumnInfo.TYPE_BIGINT) { writeLong(dos, results.getLong(i)); } else if (type == ColumnInfo.TYPE_SMALLINT) { dos.writeShort(results.getShort(i)); } else if (type == ColumnInfo.TYPE_TINYINT) { //TODO: //dos.write(results.getChar(i)); } else { Object object = results.getObject(i); throw new IllegalArgumentException( "Unknown type:" + type + " c:" + object.getClass().getName()); } } } } System.err.println("Wrote " + rowCnt + " rows"); } finally { closeConnection(connection); } //Write the end tag dos.writeInt(DUMPTAG_END); IOUtil.close(dos); }
From source file:com.pari.nm.utils.db.ReportDBHelper.java
public static final UserDefinedReport getUserDefinedReportByName(String reportIdentifier) throws Exception { String query = "select report_id, title, creator_name, created_time, report_definition, service_definition, decorator_definition from user_defined_reports where report_id = '" + reportIdentifier + "' "; ResultSet rs = null;/*from w w w . j av a 2s . c o m*/ try { rs = DBHelper.executeQuery(query); if (rs.next()) { UserDefinedReport report = new UserDefinedReport(); report.setIdentifier(rs.getString("report_id")); report.setTitle(rs.getString("title")); report.setCreatedUser(rs.getString("creator_name")); Timestamp ts = rs.getTimestamp("created_time"); if (ts != null) { report.setCreationTime(ts.getTime()); } String defintionXML = rs.getString("report_definition"); if ((defintionXML != null) && (defintionXML.length() > 0)) { report.importReportDefinitionFromXML(defintionXML); } String serviceXML = rs.getString("service_definition"); if ((serviceXML != null) && (serviceXML.length() > 0)) { report.setServiceDef(serviceXML); } String decoratorXML = rs.getString("decorator_definition"); if ((decoratorXML != null) && (decoratorXML.length() > 0)) { report.setDecoratorDef(decoratorXML); } return report; } return null; } catch (Exception ee) { String errorMessage = "Error while loading custom application: " + reportIdentifier; logger.warn(errorMessage, ee); throw new PariException(-1, errorMessage); } finally { try { rs.close(); } catch (Exception ee) { logger.debug("Error while closing result set", ee); } } }
From source file:com.pari.nm.utils.db.ReportDBHelper.java
public static final UserDefinedReport[] getAllUserDefinedReports() throws Exception { String query = "select report_id, title, creator_name, created_time, report_definition, service_definition, decorator_definition, customer_id from user_defined_reports order by title"; ArrayList<UserDefinedReport> appList = new ArrayList<UserDefinedReport>(); ResultSet rs = null;// www . j a v a 2 s . c o m try { rs = DBHelper.executeQuery(query); while (rs.next()) { UserDefinedReport report = new UserDefinedReport(); report.setIdentifier(rs.getString("report_id")); report.setTitle(rs.getString("title")); report.setCreatedUser(rs.getString("creator_name")); report.setCustomerId(rs.getInt("customer_id")); Timestamp ts = rs.getTimestamp("created_time"); if (ts != null) { report.setCreationTime(ts.getTime()); } String defintionXML = rs.getString("report_definition"); if ((defintionXML != null) && (defintionXML.length() > 0)) { report.importReportDefinitionFromXML(defintionXML); report.getReportDef().getProps().setId(report.getIdentifier()); appList.add(report); } String serviceXML = rs.getString("service_definition"); if ((serviceXML != null) && (serviceXML.length() > 0)) { report.setServiceDef(serviceXML); } String decoratorXML = rs.getString("decorator_definition"); if ((decoratorXML != null) && (decoratorXML.length() > 0)) { report.setDecoratorDef(decoratorXML); } } } catch (Exception ee) { logger.warn("Error while loading user defined reports.", ee); } finally { try { rs.close(); } catch (Exception ee) { logger.debug("Error while closing result set", ee); } } return appList.toArray(new UserDefinedReport[appList.size()]); }
From source file:com.pari.nm.utils.db.ReportDBHelper.java
public static List<UserDefinedReport> getAllUserDefinedReports(int start, int pageLength) { StringBuffer sb = MgmtReportsPaginationUtil.getQuery(start, pageLength, "user_defined_reports", null); ArrayList<UserDefinedReport> appList = new ArrayList<UserDefinedReport>(); ResultSet rs = null;//from www. j ava2s . co m try { rs = DBHelper.executeQuery(sb.toString()); while (rs.next()) { UserDefinedReport report = new UserDefinedReport(); report.setIdentifier(rs.getString("report_id")); report.setTitle(rs.getString("title")); report.setCreatedUser(rs.getString("creator_name")); Timestamp ts = rs.getTimestamp("created_time"); if (ts != null) { report.setCreationTime(ts.getTime()); } String defintionXML = rs.getString("report_definition"); if ((defintionXML != null) && (defintionXML.length() > 0)) { report.importReportDefinitionFromXML(defintionXML); report.getReportDef().getProps().setId(report.getIdentifier()); appList.add(report); } String serviceXML = rs.getString("service_definition"); if ((serviceXML != null) && (serviceXML.length() > 0)) { report.setServiceDef(serviceXML); } String decoratorXML = rs.getString("decorator_definition"); if ((decoratorXML != null) && (decoratorXML.length() > 0)) { report.setDecoratorDef(decoratorXML); } } } catch (Exception ee) { logger.warn("Error while loading user defined reports.", ee); } finally { try { rs.close(); } catch (Exception ee) { logger.debug("Error while closing result set", ee); } } return appList; }
From source file:edu.brown.hstore.HStoreSite.java
/** * Take snapshots// w w w . jav a2s . c o m */ private void takeSnapshot() { // Do this only on site lowest id Host catalog_host = this.getHost(); Integer lowest_site_id = Integer.MAX_VALUE, s_id; for (Site st : CatalogUtil.getAllSites(catalog_host)) { s_id = st.getId(); lowest_site_id = Math.min(s_id, lowest_site_id); } int m_siteId = this.getSiteId(); if (m_siteId == lowest_site_id) { if (debug.val) LOG.warn("Taking snapshot at site " + m_siteId); try { File snapshotDir = this.getSnapshotDir(); String path = snapshotDir.getAbsolutePath(); java.util.Date date = new java.util.Date(); Timestamp current = new Timestamp(date.getTime()); String nonce = Long.toString(current.getTime()); CatalogContext cc = this.getCatalogContext(); String procName = VoltSystemProcedure.procCallName(SnapshotSave.class); Procedure catalog_proc = cc.procedures.getIgnoreCase(procName); ParameterSet params = new ParameterSet(); params.setParameters(path, // snapshot dir nonce, // nonce - timestamp 1 // block ); int base_partition = Collections.min(this.local_partitions); RpcCallback<ClientResponseImpl> callback = new RpcCallback<ClientResponseImpl>() { @Override public void run(ClientResponseImpl parameter) { // Do nothing! } }; LocalTransaction ts = this.txnInitializer.createLocalTransaction(null, EstTime.currentTimeMillis(), 99999999, base_partition, catalog_proc, params, callback); LOG.warn("Queuing snapshot transaction : base partition : " + base_partition + " path :" + path + " nonce :" + nonce); // Queue @SnapshotSave transaction this.transactionQueue(ts); } catch (Exception ex) { ex.printStackTrace(); LOG.fatal("SnapshotSave exception: " + ex.getMessage()); this.hstore_coordinator.shutdown(); } } }
From source file:fr.paris.lutece.portal.service.daemon.AccountLifeTimeDaemon.java
/** * {@inheritDoc}//from www . jav a 2 s.c o m */ @SuppressWarnings("deprecation") @Override public void run() { StringBuilder sbLogs = null; StringBuilder sbResult = new StringBuilder(); Timestamp currentTimestamp = new Timestamp(new java.util.Date().getTime()); List<Integer> accountsToSetAsExpired = AdminUserHome.getIdUsersWithExpiredLifeTimeList(currentTimestamp); // We first set as expirated user that have reached their life time limit if ((accountsToSetAsExpired != null) && (accountsToSetAsExpired.size() > 0)) { int nbAccountToExpire = accountsToSetAsExpired.size(); String strBody = DatabaseTemplateService.getTemplateFromKey(PARAMETER_CORE_EXPIRATION_MAIL); DefaultUserParameter defaultUserParameter = DefaultUserParameterHome .findByKey(PARAMETER_EXPIRED_ALERT_MAIL_SENDER); String strSender = (defaultUserParameter == null) ? StringUtils.EMPTY : defaultUserParameter.getParameterValue(); defaultUserParameter = DefaultUserParameterHome.findByKey(PARAMETER_EXPIRED_ALERT_MAIL_SUBJECT); String strSubject = (defaultUserParameter == null) ? StringUtils.EMPTY : defaultUserParameter.getParameterValue(); for (Integer nIdUser : accountsToSetAsExpired) { try { AdminUser user = AdminUserHome.findByPrimaryKey(nIdUser); String strUserMail = user.getEmail(); if ((strUserMail != null) && StringUtils.isNotBlank(strUserMail)) { Map<String, String> model = new HashMap<String, String>(); addParametersToModel(model, nIdUser); HtmlTemplate template = AppTemplateService.getTemplateFromStringFtl(strBody, user.getLocale(), model); MailService.sendMailHtml(strUserMail, strSender, strSender, strSubject, template.getHtml()); } } catch (Exception e) { AppLogService.error("AccountLifeTimeDaemon - Error sending expiration alert to admin user : " + e.getMessage(), e); } } AdminUserHome.updateUserStatus(accountsToSetAsExpired, AdminUser.EXPIRED_CODE); sbLogs = new StringBuilder(); sbLogs.append("AccountLifeTimeDaemon - "); sbLogs.append(Integer.toString(nbAccountToExpire)); sbLogs.append(" account(s) have expired"); AppLogService.info(sbLogs.toString()); sbResult.append(sbLogs.toString()); sbResult.append("\n"); accountsToSetAsExpired = null; } else { AppLogService.info("AccountLifeTimeDaemon - No expired admin user found"); sbResult.append("AccountLifeTimeDaemon - No expired admin user found\n"); } // We send first alert to users long nbDaysBeforeFirstAlert = AdminUserService .getIntegerSecurityParameter(PARAMETER_TIME_BEFORE_ALERT_ACCOUNT); Timestamp firstAlertMaxDate = new Timestamp( currentTimestamp.getTime() + DateUtil.convertDaysInMiliseconds(nbDaysBeforeFirstAlert)); if (nbDaysBeforeFirstAlert <= 0) { AppLogService.info("AccountLifeTimeDaemon - First alert deactivated, skipping"); sbResult.append("AccountLifeTimeDaemon - First alert deactivated, skipping\n"); } else { List<Integer> userIdListToSendFirstAlert = AdminUserHome.getIdUsersToSendFirstAlert(firstAlertMaxDate); if ((userIdListToSendFirstAlert != null) && (userIdListToSendFirstAlert.size() > 0)) { int nbFirstAlertSent = userIdListToSendFirstAlert.size(); String strBody = DatabaseTemplateService.getTemplateFromKey(PARAMETER_CORE_FIRST_ALERT_MAIL); DefaultUserParameter defaultUserParameter = DefaultUserParameterHome .findByKey(PARAMETER_FIRST_ALERT_MAIL_SENDER); String strSender = (defaultUserParameter == null) ? StringUtils.EMPTY : defaultUserParameter.getParameterValue(); defaultUserParameter = DefaultUserParameterHome.findByKey(PARAMETER_FIRST_ALERT_MAIL_SUBJECT); String strSubject = (defaultUserParameter == null) ? StringUtils.EMPTY : defaultUserParameter.getParameterValue(); for (Integer nIdUser : userIdListToSendFirstAlert) { try { AdminUser user = AdminUserHome.findByPrimaryKey(nIdUser); String strUserMail = user.getEmail(); if ((strUserMail != null) && StringUtils.isNotBlank(strUserMail)) { Map<String, String> model = new HashMap<String, String>(); addParametersToModel(model, nIdUser); HtmlTemplate template = AppTemplateService.getTemplateFromStringFtl(strBody, user.getLocale(), model); MailService.sendMailHtml(strUserMail, strSender, strSender, strSubject, template.getHtml()); } } catch (Exception e) { AppLogService.error("AccountLifeTimeDaemon - Error sending first alert to admin user : " + e.getMessage(), e); } } AdminUserHome.updateNbAlert(userIdListToSendFirstAlert); sbLogs = new StringBuilder(); sbLogs.append("AccountLifeTimeDaemon - "); sbLogs.append(Integer.toString(nbFirstAlertSent)); sbLogs.append(" first alert(s) have been sent"); AppLogService.info(sbLogs.toString()); sbResult.append(sbLogs.toString()); sbResult.append("\n"); userIdListToSendFirstAlert = null; } else { AppLogService.info("AccountLifeTimeDaemon - No first alert to send"); sbResult.append("AccountLifeTimeDaemon - No first alert to send\n"); } } // We send other alert to users int maxNumberOfAlerts = AdminUserService.getIntegerSecurityParameter(PARAMETER_NB_ALERT_ACCOUNT); int nbDaysBetweenAlerts = AdminUserService .getIntegerSecurityParameter(PARAMETER_TIME_BETWEEN_ALERTS_ACCOUNT); Timestamp timeBetweenAlerts = new Timestamp(DateUtil.convertDaysInMiliseconds(nbDaysBetweenAlerts)); if ((maxNumberOfAlerts <= 0) || (nbDaysBetweenAlerts <= 0)) { AppLogService.info("AccountLifeTimeDaemon - Other alerts deactivated, skipping"); sbResult.append("AccountLifeTimeDaemon - Other alerts deactivated, skipping\n"); } else { List<Integer> userIdListToSendNextAlert = AdminUserHome.getIdUsersToSendOtherAlert(firstAlertMaxDate, timeBetweenAlerts, maxNumberOfAlerts); if ((userIdListToSendNextAlert != null) && (userIdListToSendNextAlert.size() > 0)) { int nbOtherAlertSent = userIdListToSendNextAlert.size(); String strBody = DatabaseTemplateService.getTemplateFromKey(PARAMETER_CORE_OTHER_ALERT_MAIL); DefaultUserParameter defaultUserParameter = DefaultUserParameterHome .findByKey(PARAMETER_OTHER_ALERT_MAIL_SENDER); String strSender = (defaultUserParameter == null) ? StringUtils.EMPTY : defaultUserParameter.getParameterValue(); defaultUserParameter = DefaultUserParameterHome.findByKey(PARAMETER_OTHER_ALERT_MAIL_SUBJECT); String strSubject = (defaultUserParameter == null) ? StringUtils.EMPTY : defaultUserParameter.getParameterValue(); for (Integer nIdUser : userIdListToSendNextAlert) { try { AdminUser user = AdminUserHome.findByPrimaryKey(nIdUser); String strUserMail = user.getEmail(); if ((strUserMail != null) && StringUtils.isNotBlank(strUserMail)) { Map<String, String> model = new HashMap<String, String>(); addParametersToModel(model, nIdUser); HtmlTemplate template = AppTemplateService.getTemplateFromStringFtl(strBody, user.getLocale(), model); MailService.sendMailHtml(strUserMail, strSender, strSender, strSubject, template.getHtml()); } } catch (Exception e) { AppLogService.error("AccountLifeTimeDaemon - Error sending next alert to admin user : " + e.getMessage(), e); } } AdminUserHome.updateNbAlert(userIdListToSendNextAlert); sbLogs = new StringBuilder(); sbLogs.append("AccountLifeTimeDaemon - "); sbLogs.append(Integer.toString(nbOtherAlertSent)); sbLogs.append(" next alert(s) have been sent"); AppLogService.info(sbLogs.toString()); sbResult.append(sbLogs.toString()); userIdListToSendNextAlert = null; } else { AppLogService.info("AccountLifeTimeDaemon - No next alert to send"); sbResult.append("AccountLifeTimeDaemon - No next alert to send"); } } if (AdminUserService.getBooleanSecurityParameter(PARAMETER_NOTIFY_USER_PASSWORD_EXPIRED)) { // We notify users with expired passwords List<Integer> accountsWithPasswordsExpired = AdminUserHome .getIdUsersWithExpiredPasswordsList(currentTimestamp); if ((accountsWithPasswordsExpired != null) && (accountsWithPasswordsExpired.size() > 0)) { String strSender = AdminUserService.getSecurityParameter(PARAMETER_PASSWORD_EXPIRED_MAIL_SENDER); String strSubject = AdminUserService.getSecurityParameter(PARAMETER_PASSWORD_EXPIRED_MAIL_SUBJECT); String strBody = DatabaseTemplateService .getTemplateFromKey(PARAMETER_CORE_PASSWORD_EXPIRED_ALERT_MAIL); if (StringUtils.isNotBlank(strBody)) { for (Integer nIdUser : accountsWithPasswordsExpired) { AdminUser user = AdminUserHome.findByPrimaryKey(nIdUser); String strUserMail = user.getEmail(); if (StringUtils.isNotBlank(strUserMail)) { Map<String, String> model = new HashMap<String, String>(); addParametersToModel(model, nIdUser); HtmlTemplate template = AppTemplateService.getTemplateFromStringFtl(strBody, Locale.getDefault(), model); MailService.sendMailHtml(strUserMail, strSender, strSender, strSubject, template.getHtml()); } } } AdminUserHome.updateChangePassword(accountsWithPasswordsExpired); sbLogs = new StringBuilder(); sbLogs.append("AccountLifeTimeDaemon - "); sbLogs.append(Integer.toString(accountsWithPasswordsExpired.size())); sbLogs.append(" user(s) have been notified their password has expired"); AppLogService.info(sbLogs.toString()); sbResult.append(sbLogs.toString()); sbResult.append("\n"); } else { AppLogService.info("AccountLifeTimeDaemon - No expired passwords"); sbResult.append("AccountLifeTimeDaemon - No expired passwords"); } } else { AppLogService.info("AccountLifeTimeDaemon - Expired passwords notification deactivated, skipping"); sbResult.append("AccountLifeTimeDaemon - Expired passwords notification deactivated, skipping"); } setLastRunLogs(sbResult.toString()); }
From source file:org.kuali.kfs.module.tem.document.service.impl.TravelDocumentServiceImpl.java
/** * Creates a date range for iterating over * * @param start of the date range//from ww w. ja v a 2 s . com * @param end of the date range * @return Collection for iterating */ protected Collection<Timestamp> dateRange(final Timestamp start, final Timestamp end) { final Collection<Timestamp> retval = new ArrayList<Timestamp>(); if (start != null && end != null) { final Calendar cal = getDateTimeService().getCurrentCalendar(); cal.setTime(start); for (; !cal.getTime().after(end) || KfsDateUtils.isSameDay(cal.getTime(), end); cal.add(Calendar.DATE, 1)) { if (KfsDateUtils.isSameDay(cal.getTime(), end)) { retval.add(new Timestamp(end.getTime())); } else { retval.add(new Timestamp(cal.getTime().getTime())); } } } return retval; }
From source file:fr.paris.lutece.plugins.mylutece.service.AbstractAccountLifeTimeDaemon.java
/** * {@inheritDoc}/* ww w . j a va 2 s . c o m*/ */ @SuppressWarnings("deprecation") @Override public void run() { StringBuilder sbLogs = null; IAccountLifeTimeService accountLifeTimeService = getAccountLifeTimeService(); IUserParameterService parameterService = getParameterService(); Plugin plugin = accountLifeTimeService.getPlugin(); Timestamp currentTimestamp = new Timestamp(new java.util.Date().getTime()); List<Integer> accountsToSetAsExpired = accountLifeTimeService .getIdUsersWithExpiredLifeTimeList(currentTimestamp); StringBuilder sbResult = new StringBuilder(); // We first set as expirated user that have reached their life time limit if ((accountsToSetAsExpired != null) && (accountsToSetAsExpired.size() > 0)) { int nbAccountToExpire = accountsToSetAsExpired.size(); String strBody = accountLifeTimeService.getExpirationtMailBody(); ReferenceItem referenceItem = parameterService.findByKey(PARAMETER_EXPIRED_ALERT_MAIL_SENDER, plugin); String strSenderName = (referenceItem == null) ? StringUtils.EMPTY : referenceItem.getName(); String strSenderEmail = MailService.getNoReplyEmail(); referenceItem = parameterService.findByKey(PARAMETER_EXPIRED_ALERT_MAIL_SUBJECT, plugin); String strSubject = (referenceItem == null) ? StringUtils.EMPTY : referenceItem.getName(); for (Integer nIdUser : accountsToSetAsExpired) { try { String strUserMail = accountLifeTimeService.getUserMainEmail(nIdUser); if ((strUserMail != null) && StringUtils.isNotBlank(strUserMail)) { Map<String, String> model = new HashMap<String, String>(); accountLifeTimeService.addParametersToModel(model, nIdUser); HtmlTemplate template = AppTemplateService.getTemplateFromStringFtl(strBody, Locale.getDefault(), model); MailService.sendMailHtml(strUserMail, strSenderName, strSenderEmail, strSubject, template.getHtml()); } } catch (Exception e) { AppLogService.error( getDaemonName() + " - Error sending expiration alert to user : " + e.getMessage(), e); } } accountLifeTimeService.setUserStatusExpired(accountsToSetAsExpired); accountsToSetAsExpired = null; sbLogs = new StringBuilder(); sbLogs.append(getDaemonName()); sbLogs.append(" - "); sbLogs.append(Integer.toString(nbAccountToExpire)); sbLogs.append(" account(s) have expired"); AppLogService.info(sbLogs.toString()); sbResult.append(sbLogs.toString()); sbResult.append("\n"); } else { AppLogService.info(getDaemonName() + " - No expired user found"); sbResult.append(getDaemonName() + " - No expired user found\n"); } // We send first alert to users long nbDaysBeforeFirstAlert = SecurityUtils.getIntegerSecurityParameter(parameterService, plugin, PARAMETER_TIME_BEFORE_ALERT_ACCOUNT); Timestamp firstAlertMaxDate = new Timestamp( currentTimestamp.getTime() + DateUtil.convertDaysInMiliseconds(nbDaysBeforeFirstAlert)); if (nbDaysBeforeFirstAlert <= 0) { AppLogService.info(getDaemonName() + " - First alert deactivated, skipping"); sbResult.append(getDaemonName() + " - First alert deactivated, skipping\n"); } else { List<Integer> listIdUserToSendFirstAlert = accountLifeTimeService .getIdUsersToSendFirstAlert(firstAlertMaxDate); if ((listIdUserToSendFirstAlert != null) && (listIdUserToSendFirstAlert.size() > 0)) { int nbFirstAlertSent = listIdUserToSendFirstAlert.size(); String strBody = accountLifeTimeService.getFirstAlertMailBody(); ReferenceItem referenceItem = parameterService.findByKey(PARAMETER_FIRST_ALERT_MAIL_SENDER, plugin); String strSenderName = (referenceItem == null) ? StringUtils.EMPTY : referenceItem.getName(); String strSenderEmail = MailService.getNoReplyEmail(); referenceItem = parameterService.findByKey(PARAMETER_FIRST_ALERT_MAIL_SUBJECT, plugin); String strSubject = (referenceItem == null) ? StringUtils.EMPTY : referenceItem.getName(); for (Integer nIdUser : listIdUserToSendFirstAlert) { try { String strUserMail = accountLifeTimeService.getUserMainEmail(nIdUser); if ((strUserMail != null) && StringUtils.isNotBlank(strUserMail)) { Map<String, String> model = new HashMap<String, String>(); accountLifeTimeService.addParametersToModel(model, nIdUser); HtmlTemplate template = AppTemplateService.getTemplateFromStringFtl(strBody, Locale.getDefault(), model); MailService.sendMailHtml(strUserMail, strSenderName, strSenderEmail, strSubject, template.getHtml()); } } catch (Exception e) { AppLogService.error( getDaemonName() + " - Error sending first alert to user : " + e.getMessage(), e); } } accountLifeTimeService.updateNbAlert(listIdUserToSendFirstAlert); sbLogs = new StringBuilder(); sbLogs.append("MyluteceAccountLifeTimeDaemon - "); sbLogs.append(Integer.toString(nbFirstAlertSent)); sbLogs.append(" first alert(s) have been sent"); AppLogService.info(sbLogs.toString()); sbResult.append(sbLogs.toString()); sbResult.append("\n"); } else { AppLogService.info(getDaemonName() + " - No first alert to send"); sbResult.append(getDaemonName() + " - No first alert to send\n"); } } // We send other alert to users int maxNumberOfAlerts = SecurityUtils.getIntegerSecurityParameter(parameterService, plugin, PARAMETER_NB_ALERT_ACCOUNT); int nbDaysBetweenAlerts = SecurityUtils.getIntegerSecurityParameter(parameterService, plugin, PARAMETER_TIME_BETWEEN_ALERTS_ACCOUNT); Timestamp timeBetweenAlerts = new Timestamp(DateUtil.convertDaysInMiliseconds(nbDaysBetweenAlerts)); if ((maxNumberOfAlerts <= 0) || (nbDaysBetweenAlerts <= 0)) { AppLogService.info(getDaemonName() + " - Other alerts deactivated, skipping"); sbResult.append(getDaemonName() + " - Other alerts deactivated, skipping"); } else { List<Integer> listIdUserToSendNextAlert = accountLifeTimeService .getIdUsersToSendOtherAlert(firstAlertMaxDate, timeBetweenAlerts, maxNumberOfAlerts); if ((listIdUserToSendNextAlert != null) && (listIdUserToSendNextAlert.size() > 0)) { int nbOtherAlertSent = listIdUserToSendNextAlert.size(); String strBody = accountLifeTimeService.getOtherAlertMailBody(); ReferenceItem referenceItem = parameterService.findByKey(PARAMETER_OTHER_ALERT_MAIL_SENDER, plugin); String strSenderName = (referenceItem == null) ? StringUtils.EMPTY : referenceItem.getName(); referenceItem = parameterService.findByKey(PARAMETER_OTHER_ALERT_MAIL_SUBJECT, plugin); String strSubject = (referenceItem == null) ? StringUtils.EMPTY : referenceItem.getName(); String strSenderEmail = MailService.getNoReplyEmail(); for (Integer nIdUser : listIdUserToSendNextAlert) { try { String strUserMail = accountLifeTimeService.getUserMainEmail(nIdUser); if ((strUserMail != null) && StringUtils.isNotBlank(strUserMail)) { Map<String, String> model = new HashMap<String, String>(); accountLifeTimeService.addParametersToModel(model, nIdUser); HtmlTemplate template = AppTemplateService.getTemplateFromStringFtl(strBody, Locale.getDefault(), model); MailService.sendMailHtml(strUserMail, strSenderName, strSenderEmail, strSubject, template.getHtml()); } } catch (Exception e) { AppLogService.error( getDaemonName() + " - Error sending next alert to user : " + e.getMessage(), e); } } accountLifeTimeService.updateNbAlert(listIdUserToSendNextAlert); sbLogs = new StringBuilder(); sbLogs.append(getDaemonName()); sbLogs.append(" - "); sbLogs.append(Integer.toString(nbOtherAlertSent)); sbLogs.append(" next alert(s) have been sent"); AppLogService.info(sbLogs.toString()); sbResult.append(sbLogs.toString()); sbResult.append("\n"); } else { AppLogService.info(getDaemonName() + " - No next alert to send"); sbResult.append(getDaemonName() + " - No next alert to send\n"); } } ReferenceItem referenceItem = parameterService.findByKey(PARAMETER_NOTIFY_USER_PASSWORD_EXPIRED, plugin); if ((referenceItem != null) && StringUtils.isNotEmpty(referenceItem.getName()) && referenceItem.isChecked()) { // We notify users with expired passwords List<Integer> accountsWithPasswordsExpired = accountLifeTimeService .getIdUsersWithExpiredPasswordsList(currentTimestamp); if ((accountsWithPasswordsExpired != null) && (accountsWithPasswordsExpired.size() > 0)) { referenceItem = parameterService.findByKey(PARAMETER_PASSWORD_EXPIRED_MAIL_SENDER, plugin); String strSenderName = (referenceItem == null) ? StringUtils.EMPTY : referenceItem.getName(); referenceItem = parameterService.findByKey(PARAMETER_PASSWORD_EXPIRED_MAIL_SUBJECT, plugin); String strSubject = (referenceItem == null) ? StringUtils.EMPTY : referenceItem.getName(); String strSenderEmail = MailService.getNoReplyEmail(); String strTemplate = accountLifeTimeService.getPasswordExpiredMailBody(); if (StringUtils.isNotBlank(strTemplate)) { for (Integer nIdUser : accountsWithPasswordsExpired) { String strUserMail = accountLifeTimeService.getUserMainEmail(nIdUser); if (StringUtils.isNotBlank(strUserMail)) { Map<String, String> model = new HashMap<String, String>(); accountLifeTimeService.addParametersToModel(model, nIdUser); HtmlTemplate template = AppTemplateService.getTemplateFromStringFtl(strTemplate, Locale.getDefault(), model); MailService.sendMailHtml(strUserMail, strSenderName, strSenderEmail, strSubject, template.getHtml()); } } } accountLifeTimeService.updateChangePassword(accountsWithPasswordsExpired); sbLogs = new StringBuilder(); sbLogs.append(getDaemonName()); sbLogs.append(" - "); sbLogs.append(Integer.toString(accountsWithPasswordsExpired.size())); sbLogs.append(" user(s) have been notified their password has expired"); AppLogService.info(sbLogs.toString()); sbResult.append(sbLogs.toString()); sbResult.append("\n"); } else { AppLogService.info(getDaemonName() + " - No expired passwords"); sbResult.append(getDaemonName() + " - No expired passwords"); } } else { AppLogService.info(getDaemonName() + " - Expired passwords notification deactivated, skipping"); sbResult.append(getDaemonName() + " - Expired passwords notification deactivated, skipping"); } this.setLastRunLogs(sbResult.toString()); }
From source file:edu.brown.hstore.HStoreSite.java
/** * Constructor/*from w w w. j a v a 2 s . c o m*/ * @param coordinators * @param p_estimator */ protected HStoreSite(int site_id, CatalogContext catalogContext, HStoreConf hstore_conf) { assert (hstore_conf != null); assert (catalogContext != null); this.hstore_conf = hstore_conf; this.catalogContext = catalogContext; this.catalog_site = this.catalogContext.getSiteById(site_id); if (this.catalog_site == null) throw new RuntimeException("Invalid site #" + site_id); this.catalog_host = this.catalog_site.getHost(); this.site_id = this.catalog_site.getId(); this.site_name = HStoreThreadManager.getThreadName(this.site_id, null); final int num_partitions = this.catalogContext.numberOfPartitions; this.local_partitions.addAll(CatalogUtil.getLocalPartitionIds(catalog_site)); int num_local_partitions = this.local_partitions.size(); for (Status s : Status.values()) { this.deletable_txns.put(s, new ConcurrentLinkedQueue<Long>()); } // FOR this.executors = new PartitionExecutor[num_partitions]; this.executor_threads = new Thread[num_partitions]; this.depTrackers = new DependencyTracker[num_partitions]; // Get the hasher we will use for this HStoreSite this.hasher = ClassUtil.newInstance(hstore_conf.global.hasher_class, new Object[] { this.catalogContext, num_partitions }, new Class<?>[] { CatalogContext.class, int.class }); this.p_estimator = new PartitionEstimator(this.catalogContext, this.hasher); this.remoteTxnEstimator = new RemoteEstimator(this.p_estimator); // ARIES if (hstore_conf.site.aries) { // Don't use both recovery modes assert (hstore_conf.site.snapshot == false); LOG.warn("Starting ARIES recovery at site"); String siteName = HStoreThreadManager.formatSiteName(this.getSiteId()); String ariesSiteDirPath = hstore_conf.site.aries_dir + File.separatorChar + siteName + File.separatorChar; this.m_ariesLogFileName = ariesSiteDirPath + m_ariesDefaultLogFileName; int numPartitionsPerSite = this.catalog_site.getPartitions().size(); int numSites = this.catalogContext.numberOfSites; LOG.warn("ARIES : Log Native creation :: numSites : " + numSites + " numPartitionsPerSite : " + numPartitionsPerSite); this.m_ariesLog = new AriesLogNative(numSites, numPartitionsPerSite, this.m_ariesLogFileName); this.m_recoveryLog = new VoltLogger("RECOVERY"); } // **IMPORTANT** // Always clear out the CatalogUtil and BatchPlanner before we start our new HStoreSite // TODO: Move this cache information into CatalogContext CatalogUtil.clearCache(this.catalogContext.database); BatchPlanner.clear(this.catalogContext.numberOfPartitions); TransactionCounter.resetAll(this.catalogContext); // Only preload stuff if we were asked to if (hstore_conf.site.preload) { if (debug.val) LOG.debug("Preloading cached objects"); try { // Don't forget our CatalogUtil friend! CatalogUtil.preload(this.catalogContext.database); // Load up everything the QueryPlanUtil PlanNodeUtil.preload(this.catalogContext.database); // Then load up everything in the PartitionEstimator this.p_estimator.preload(); } catch (Exception ex) { throw new RuntimeException("Failed to prepare HStoreSite", ex); } } // Offset Hack this.local_partition_offsets = new int[num_partitions]; Arrays.fill(this.local_partition_offsets, HStoreConstants.NULL_PARTITION_ID); int offset = 0; for (int partition : this.local_partitions) { this.local_partition_offsets[partition] = offset++; } // FOR // ------------------------------- // THREADS // ------------------------------- EventObserver<Pair<Thread, Throwable>> observer = new EventObserver<Pair<Thread, Throwable>>() { @Override public void update(EventObservable<Pair<Thread, Throwable>> o, Pair<Thread, Throwable> arg) { Thread thread = arg.getFirst(); Throwable error = arg.getSecond(); String threadName = "<unknown>"; if (thread != null) threadName = thread.getName(); LOG.fatal(String.format("Thread %s had a fatal error: %s", threadName, (error != null ? error.getMessage() : null))); error.printStackTrace(); hstore_coordinator.shutdownClusterBlocking(error); } }; this.exceptionHandler.addObserver(observer); Thread.setDefaultUncaughtExceptionHandler(this.exceptionHandler); // HStoreSite Thread Manager (this always get invoked first) this.threadManager = new HStoreThreadManager(this); // Distributed Transaction Queue Manager this.txnQueueManager = new TransactionQueueManager(this); // One Transaction Cleaner for every eight partitions int numCleaners = (int) Math.ceil(num_local_partitions / 8.0); for (int i = 0; i < numCleaners; i++) { this.txnCleaners.add(new TransactionCleaner(this)); } // FOR // MapReduce Transaction helper thread if (catalogContext.getMapReduceProcedures().isEmpty() == false) { this.mr_helper = new MapReduceHelperThread(this); } else { this.mr_helper = null; } // Separate TransactionIdManager per partition if (hstore_conf.site.txn_partition_id_managers) { this.txnIdManagers = new TransactionIdManager[num_partitions]; for (int partition : this.local_partitions) { this.txnIdManagers[partition] = new TransactionIdManager(partition); } // FOR } // Single TransactionIdManager for the entire site else { this.txnIdManagers = new TransactionIdManager[] { new TransactionIdManager(this.site_id) }; } // Command Logger if (hstore_conf.site.commandlog_enable) { // It would be nice if we could come up with a unique name for this // invocation of the system (like the cluster instanceId). But for now // we'll just write out to our directory... java.util.Date date = new java.util.Date(); Timestamp current = new Timestamp(date.getTime()); String nonce = Long.toString(current.getTime()); File logFile = new File(hstore_conf.site.commandlog_dir + File.separator + this.getSiteName().toLowerCase() + "_" + nonce + CommandLogWriter.LOG_OUTPUT_EXT); this.commandLogger = new CommandLogWriter(this, logFile); } else { this.commandLogger = null; } // AdHoc Support if (hstore_conf.site.exec_adhoc_sql) { this.asyncCompilerWorkThread = new AsyncCompilerWorkThread(this, this.site_id); } else { this.asyncCompilerWorkThread = null; } // The AntiCacheManager will allow us to do special things down in the EE // for evicted tuples if (hstore_conf.site.anticache_enable) { this.anticacheManager = new AntiCacheManager(this); } else { this.anticacheManager = null; } // ------------------------------- // NETWORK SETUP // ------------------------------- this.voltNetwork = new VoltNetwork(this); this.clientInterface = new ClientInterface(this, this.catalog_site.getProc_port()); // ------------------------------- // TRANSACTION ESTIMATION // ------------------------------- // Transaction Properties Initializer this.txnInitializer = new TransactionInitializer(this); // CACHED MESSAGES this.REJECTION_MESSAGE = "Transaction was rejected by " + this.getSiteName(); // ------------------------------- // STATS SETUP // ------------------------------- this.initTxnProcessors(); this.initStatSources(); // Profiling if (hstore_conf.site.profiling) { this.profiler = new HStoreSiteProfiler(); if (hstore_conf.site.status_exec_info) { this.profiler.network_idle.resetOnEventObservable(this.startWorkload_observable); } } else { this.profiler = null; } this.status_monitor = new HStoreSiteStatus(this, hstore_conf); LoggerUtil.refreshLogging(hstore_conf.global.log_refresh); }