List of usage examples for java.util Date before
public boolean before(Date when)
From source file:com.pr7.logging.CustomDailyRollingFileAppender.java
private void customCleanUp() { // Check to see if there are already 5 files File file = new File(fileName); Calendar cal = Calendar.getInstance(); int maxDays = 30; try {//from w ww . j av a 2 s . com maxDays = Integer.parseInt(archiveMaxDays); } catch (Exception e) { // just leave it at 30. } cal.add(Calendar.DATE, -maxDays); Date cutoffDate = cal.getTime(); Date timeBackup = DateUtil.parse(DateUtil.format(new Date(), "dd/MM/yyyy ") + archiveTiming, "dd/MM/yyyy HH:mm:ss"); //This make sure only backup once per day //System.out.println("cleanupAndRollOver checked:: cutoffDate = " + cutoffDate + ", timeBackup = " + timeBackup + ", lastBackup = " + lastBackup + ", file.getParentFile().exists() = " + file.getParentFile().exists()); if ((lastBackup == null || timeBackup.after(lastBackup)) && timeBackup.compareTo(new Date()) <= 0 && file.getParentFile().exists()) { System.out.println("cleanupAndRollOver executed:: cutoffDate = " + cutoffDate + ", timeBackup = " + timeBackup + ", lastBackup = " + lastBackup); File[] files = file.getParentFile().listFiles(new StartsWithFileFilter(file.getName(), false)); System.out.println("cleanupAndRollOver executed:: files size = " + files.length + ", file.getName() = " + file.getName()); int nameLength = file.getName().length(); for (int i = 0; i < files.length; i++) { String datePart = null; try { if (!file.getName().equals(files[i].getName())) { datePart = files[i].getName().substring(nameLength); Date date = sdf.parse(datePart); //System.out.println("date = " + date + " vs cutoffDate " + cutoffDate); if (date.before(cutoffDate)) { if (archiveCompress.equalsIgnoreCase("TRUE")) { zipAndDelete(files[i]); } else { System.out.println("delete file = " + files[i].getName()); files[i].delete(); } } } } catch (Exception e) { // e.printStackTrace(); // This isn't a file we should touch (it isn't named // correctly) } } lastBackup = new Date(); } }
From source file:com.eucalyptus.imaging.ImagingTaskStateManager.java
private void processCancellingTasks(final List<ImagingTask> tasks) { for (final ImagingTask task : tasks) { try {/* w w w . j a v a2 s . c o m*/ if (!cancellingTimer.containsKey(task.getDisplayName())) { cancellingTimer.put(task.getDisplayName(), Dates.minutesFromNow(CANCELLING_WAIT_MIN)); } final Date cancellingExpired = cancellingTimer.get(task.getDisplayName()); if (cancellingExpired.before(new Date())) { ImagingTasks.transitState(task, ImportTaskState.CANCELLING, ImportTaskState.CANCELLED, null); } } catch (final Exception ex) { LOG.error("Could not process cancelling task " + task.getDisplayName()); } } }
From source file:com.netspective.commons.validate.rule.DateValueValidationRule.java
public boolean isValid(ValidationContext vc, Value value) { if (!isValidType(vc, value, Date.class)) return false; Date dateValue = (Date) value.getValue(); if (dateValue == null) return true; if (pastOnly || futureOnly) { Date now = new Date(); if (pastOnly && dateValue.after(now)) { vc.addValidationError(value, getPastOnlyDateMessage(), new Object[] { getValueCaption(vc), format(now) }); return false; }// ww w.j a v a 2s .c om if (futureOnly && dateValue.before(now)) { vc.addValidationError(value, getFutureOnlyDateMessage(), new Object[] { getValueCaption(vc), format(now) }); return false; } } Date minimumDate = getValueSourceOrDate("Minimum", value, minDateSource, vc, minDate); if (minimumDate != null && dateValue.before(minimumDate)) { vc.addValidationError(value, getPreMinDateDateMessage(), new Object[] { getValueCaption(vc), format(minimumDate) }); return false; } Date maximumDate = getValueSourceOrDate("Maximum", value, maxDateSource, vc, maxDate); if (maximumDate != null && dateValue.after(maximumDate)) { vc.addValidationError(value, getPostMaxDateMessage(), new Object[] { getValueCaption(vc), format(maximumDate) }); return false; } return true; }
From source file:es.pode.modificador.presentacion.configurar.objetos.buscar.BuscarObjetoControllerImpl.java
/** * @see es.pode.modificador.presentacion.configurar.objetos.buscar.BuscarObjetoController#selectAction(org.apache.struts.action.ActionMapping, es.pode.modificador.presentacion.configurar.objetos.buscar.SelectActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//*from w w w . j a va2 s . c o m*/ public final java.lang.String selectAction(ActionMapping mapping, es.pode.modificador.presentacion.configurar.objetos.buscar.SelectActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { java.util.Locale locale = (java.util.Locale) request.getSession() .getAttribute(ConstantesAgrega.DEFAULT_LOCALE); ResourceBundle i18n = ResourceBundle.getBundle("application-resources", locale); String volver = "Volver"; String buscar = i18n.getString("buscarObjeto.Buscar"); String action = form.getAction(); if (action == null) { return volver; } if (action.equals(buscar)) { // Guarda datos bsqueda en sesin BusquedaSession sesion = getBusquedaSession(request); boolean alMenosUnParametro = false; boolean parteFecha = false; if (vacia(form.getIdioma())) { throw new ValidatorException("{buscarObjeto.msgErrorIdioma}"); } if (!vacia(form.getAutor())) { alMenosUnParametro = true; } if (!vacia(form.getIdentificador())) { alMenosUnParametro = true; } if (!vacia(form.getTitulo())) { alMenosUnParametro = true; } if (fechaValida( form.getAnyoDesde())/*&&fechaValida(form.getDiaDesde())&&fechaValida(form.getMesDesde())*/) { alMenosUnParametro = true; parteFecha = true; } if (fechaValida( form.getAnyoHasta())/*&&fechaValida(form.getDiaHasta())&&fechaValida(form.getMesHasta())*/) { alMenosUnParametro = true; parteFecha = true; } if (fechaValida(form.getDiaDesde())) { alMenosUnParametro = true; parteFecha = true; } if (fechaValida(form.getDiaHasta())) { alMenosUnParametro = true; parteFecha = true; } if (fechaValida(form.getMesDesde())) { alMenosUnParametro = true; parteFecha = true; } if (fechaValida(form.getMesHasta())) { alMenosUnParametro = true; parteFecha = true; } //Si al menos uno de los campos de una fecha se ha introducido, se da error si falta otro if (parteFecha) { if (!fechaValida(form.getDiaDesde())) { throw new ValidatorException("{buscarObjeto.msgErrorDiaDesde}"); } else if (!fechaValida(form.getMesDesde())) { throw new ValidatorException("{buscarObjeto.msgErrorMesDesde}"); } else if (!fechaValida(form.getAnyoDesde())) { throw new ValidatorException("{buscarObjeto.msgErrorAnyoDesde}"); } else if (!fechaValida(form.getDiaHasta())) { throw new ValidatorException("{buscarObjeto.msgErrorDiaHasta}"); } else if (!fechaValida(form.getMesHasta())) { throw new ValidatorException("{buscarObjeto.msgErrorMesHasta}"); } else if (!fechaValida(form.getAnyoHasta())) { throw new ValidatorException("{buscarObjeto.msgErrorAnyoHasta}"); } } if (!alMenosUnParametro) { throw new ValidatorException("{buscarObjeto.exception}"); } //Vuelco el form a la sesion sesion.setAutor(form.getAutor()); sesion.setIdentificador(form.getIdentificador()); sesion.setTitulo(form.getTitulo()); sesion.setIdioma(form.getIdioma()); if (fechaValida(form.getDiaDesde()) && fechaValida(form.getMesDesde()) && fechaValida(form.getAnyoDesde()) && fechaValida(form.getDiaHasta()) && fechaValida(form.getMesHasta()) && fechaValida(form.getAnyoHasta())) { //Comprobaciones de la fecha SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy"); format.setLenient(false); String guion = "-"; int dayFrom, dayTo, yearFrom, yearTo, monthFrom, monthTo; try { dayFrom = Integer.valueOf(form.getDiaDesde()).intValue(); dayTo = Integer.valueOf(form.getDiaHasta()).intValue(); yearFrom = Integer.valueOf(form.getAnyoDesde()).intValue(); yearTo = Integer.valueOf(form.getAnyoHasta()).intValue(); monthFrom = Integer.valueOf(form.getMesDesde()).intValue(); monthTo = Integer.valueOf(form.getMesHasta()).intValue(); } catch (Exception e) { throw new ValidatorException("{buscarObjetos.msgErrorFormato}"); } StringBuffer fechaFromStr = new StringBuffer(); fechaFromStr.append(dayFrom).append(guion).append(monthFrom).append(guion).append(yearFrom); Date fechaFrom; Date fechaTo; try { fechaFrom = format.parse(fechaFromStr.toString()); StringBuffer fechaToStr = new StringBuffer(); fechaToStr.append(dayTo).append(guion).append(monthTo).append(guion).append(yearTo); fechaTo = format.parse(fechaToStr.toString()); if (fechaTo.before(fechaFrom)) { throw new ValidatorException("{buscarObjetos.msgErrorFormato}"); } } catch (Exception e) { throw new ValidatorException("{buscarObjetos.msgErrorFormato}"); } //Saco ahora campos de fecha a sesion String[] partes = format.format(fechaFrom).split("-"); sesion.setDiaDesde(partes[0]); sesion.setMesDesde(partes[1]); sesion.setAnyoDesde(partes[2]); partes = format.format(fechaTo).split("-"); sesion.setDiaHasta(partes[0]); sesion.setMesHasta(partes[1]); sesion.setAnyoHasta(partes[2]); } else { //Actualizamos los campos de fecha en sesion aunque no sean buenos sesion.setDiaDesde(form.getDiaDesde()); sesion.setMesDesde(form.getMesDesde()); sesion.setAnyoDesde(form.getAnyoDesde()); sesion.setDiaHasta(form.getDiaHasta()); sesion.setMesHasta(form.getMesHasta()); sesion.setAnyoHasta(form.getAnyoHasta()); } sesion.setResultados(null); return "Buscar"; } return volver; }
From source file:ispok.converter.BirthDateConverter.java
@Override public Object getAsObject(FacesContext fc, UIComponent uic, String string) { logger.trace("Entering getAsObject()"); Locale locale = fc.getViewRoot().getLocale(); ResourceBundle rb = ResourceBundle.getBundle("ispok/pres/inter/ispok", locale); DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale); SimpleDateFormat sdf = (SimpleDateFormat) df; String pattern = sdf.toPattern(); String localPattern = sdf.toLocalizedPattern(); logger.debug("pattern: {}", pattern); logger.debug("localized pattern: {}", localPattern); Date date; try {/*from w w w . j a v a 2 s . com*/ date = new SimpleDateFormat(pattern).parse(string); } catch (ParseException ex) { FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "invalid date", pattern); throw new ConverterException(msg); } if (date.after(new Date())) { FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, rb.getString("birthdate_invalid"), rb.getString("birthdate_valid_future")); throw new ConverterException(msg); } Calendar c = Calendar.getInstance(); c.set(1850, 1, 1); if (date.before(c.getTime())) { FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, rb.getString("birthdate_invalid"), rb.getString("birthdate_valid_past")); throw new ConverterException(msg); } return date; }
From source file:com.seajas.search.profiler.task.FeedInjectionTask.java
/** * {@inheritDoc}//www . j a v a 2 s . c o m */ @Override public void inject(final String triggerName, final Long intervalTotal, final InjectionJobInterrupted interrupted) { Date currentTime = new Date(); List<Feed> enabledFeeds = getInjectableFeeds(triggerName, intervalTotal, currentTime); // Only log when we're not doing distributed injection - so to not get this every second if (logger.isInfoEnabled() && intervalTotal == null) logger.info("Performing feed injection under trigger '" + triggerName + "' (" + enabledFeeds.size() + " feed" + (enabledFeeds.size() != 1 ? "s" : "") + ")"); // We report on the number of feeds first, and then move on to potentially canceling the operation if (Boolean.getBoolean("profiler.indexing.disabled")) { if (logger.isInfoEnabled()) logger.info( "Indexing has been explicitly disabled using 'profiler.indexing.disabled=true'. Skipping injection."); return; } for (Feed feed : enabledFeeds) { if (interrupted.isInterrupted()) { logger.warn("This job was interrupted - not continuing with feed injection"); break; } // Mark this feed's injection date (ahead of the actual injection - but then this is not such a critical matter) profilerService.updateFeedLastInjected(feed.getId(), currentTime); // Determine whether this feed falls within the anonymization run from / until range if (feed.getFeedAnonymization() != null) { Date currentDate = Calendar.getInstance().getTime(), runFrom = feed.getFeedAnonymization().getRunFrom(), runUntil = feed.getFeedAnonymization().getRunUntil(); if ((runFrom != null && currentDate.before(runFrom)) || (runUntil != null && currentDate.after(runUntil))) { logger.info("The feed with name '" + feed.getName() + "' falls outside of its anonymization run from/until date - skipping"); continue; } } // Create a map out of the feed result parameters Map<String, String> resultParameters = new HashMap<String, String>(); if (feed.getFeedResultParameters() != null && feed.getFeedResultParameters().size() > 0) for (FeedResultParameter feedResultParameter : feed.getFeedResultParameters()) { if (resultParameters.containsKey(feedResultParameter.getFieldName())) logger.warn("The result map already contains a parameter named '" + feedResultParameter.getFieldName() + "' - it will be overwritten"); resultParameters.put(feedResultParameter.getFieldName(), feedResultParameter.getFieldValue()); } // Now inject each feed URL for (FeedUrl feedUrl : feed.getFeedUrls()) { if (interrupted.isInterrupted()) { logger.warn("This job was interrupted - not continuing with feed injection"); break; } try { Long feedDelay = 0L, resultDelay = 0L; // Determine the feed-URL specific anonymization settings if (feed.getFeedAnonymization() != null) { // Determine the feed delay feedDelay = feed.getFeedAnonymization() != null && feed.getFeedAnonymization().getFeedDelay() != null ? feed.getFeedAnonymization().getFeedDelay() : 0L; if (feed.getFeedAnonymization().getIsFeedDelayRandomized()) feedDelay = (long) randomGenerator .nextInt(feedDelay.intValue() - RANDOM_RANGE_MINIMUM + 1) + RANDOM_RANGE_MINIMUM; // Don't randomize the result delay here, but instead do this on the contender-side resultDelay = feed.getFeedAnonymization() != null && feed.getFeedAnonymization().getFeedElementDelay() != null ? feed.getFeedAnonymization().getFeedElementDelay() : 0L; } // Perform the optional authentication step String authenticatedUrl = feedUrl.getUrl(); Map<String, String> authenticatedResultParameters = resultParameters; if (feed.getFeedConnection() != null) { if (feed.getFeedConnection().getAuthenticationStrategy() != null) { AuthenticationResult authenticationResult = profilerService.applyAuthenticationStrategy( feed.getFeedConnection().getAuthenticationStrategy(), authenticatedUrl, authenticatedResultParameters); authenticatedUrl = authenticationResult.getUrl(); authenticatedResultParameters = authenticationResult.getResultParameters(); } } URI uri = new URI(authenticatedUrl); String hostname = StringUtils.hasText(uri.getHost()) ? uri.getHost().replace("www.", "") : "localhost"; logger.info("Injecting feed with name '" + feed.getName() + "' and URI '" + uri + "' into bridge layer"); // Determine which of the result parameters to turn into headers Map<String, String> resultHeaders = null; if (StringUtils.hasText(resultMappingParameter) && StringUtils.hasText(resultMappingHeader)) { if (!authenticatedResultParameters.containsKey(resultMappingParameter)) { if (logger.isDebugEnabled()) logger.debug("Result mapping was requested, but result mapping parameter '" + resultMappingParameter + "' is not present in the result parameter map - not adding header '" + resultMappingHeader + "'"); } else { resultHeaders = new HashMap<String, String>(); resultHeaders.put(resultMappingHeader, authenticatedResultParameters.get(resultMappingParameter)); } } // Inject it into the queue com.seajas.search.bridge.jms.model.Feed resultFeed = new com.seajas.search.bridge.jms.model.Feed(); resultFeed.setUri(uri); resultFeed.setId(feed.getId()); resultFeed.setName(feed.getName()); resultFeed.setHostname(hostname); resultFeed.setCollection(feed.getCollection()); resultFeed.setFeedEncodingOverride(feed.getFeedEncodingOverride()); resultFeed.setResultEncodingOverride(feed.getResultEncodingOverride()); resultFeed.setLanguageOverride(feed.getLanguage()); resultFeed.setSummaryBased(feed.getIsSummaryBased()); resultFeed.setDelay(feedDelay); resultFeed.setElementDelay(resultDelay); resultFeed.setElementDelayRandomized(feed.getFeedAnonymization() != null && Boolean.TRUE.equals(feed.getFeedAnonymization().getIsFeedElementDelayRandomized())); resultFeed.setUserAgent(determineUserAgent(feed)); resultFeed.setUserAgentsOverride(feed.getFeedAnonymization() != null ? feed.getFeedAnonymization().getPreferredUserAgents() : null); resultFeed.setUserAgentsOverrideRandomized(feed.getFeedAnonymization() != null && Boolean.TRUE .equals(feed.getFeedAnonymization().getIsPreferredUserAgentsRandomized())); resultFeed.setResultParameters(authenticatedResultParameters); resultFeed.setRetrievalRequestHeaders(resultHeaders); injectionService.inject(resultFeed, GroupIdDecorator.decorate(hostname), feedDelay); } catch (URISyntaxException e) { logger.error("The given " + (feed.getFeedConnection() != null && feed.getFeedConnection().getAuthenticationStrategy() != null ? "(unauthenticated) " : "") + "feed URI '" + feedUrl.getUrl() + "' is not valid"); } } } if (logger.isTraceEnabled()) logger.trace("Finished feed injection for trigger '" + triggerName + "'"); }
From source file:com.virtusa.akura.reporting.controller.GenerateTeacherEarlyLateAttendiesReportController.java
/** * Perform the logic of the controller to generate Teacher Wise Attendance Report . * * @param attendeesWrapperTemplate of type AttendeesWrapperTemplate * @param request of type HttpServletRequest * @param response of type HttpServletResponse * @param errors of type BindingResult//w w w . j a va 2 s . co m * @return java.lang.String * @param map of type ModelMap * @throws AkuraAppException AkuraAppException */ @SuppressWarnings("unchecked") @RequestMapping(value = REQUEST_PARA_TEACHER_LATE, method = RequestMethod.POST) public String onSubmit(HttpServletRequest request, HttpServletResponse response, @ModelAttribute(MODEL_ATT_ATTENDANCE_WRAPPER_TEMPLATE) AttendeesWrapperTemplate attendeesWrapperTemplate, BindingResult errors, ModelMap map) throws AkuraAppException { String returnString = STRING_EMPTY; lateComersValidator.validate(attendeesWrapperTemplate, errors); if (errors.hasErrors()) { return VIEW_PAGE; } Map<String, Object> params = new HashMap<String, Object>(); params.put(REPORT_PARA_TITLE, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, REPORT_VALUE_TEACHER_LATE_ATTEND_REPORT)); params.put(REPORT_PARA_TEACHERID, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, REPORT_VALUE_TEACHER_ID)); params.put(REPORT_PARA_TEACHERNAME, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, REPORT_VALUE_TEACHER_NAME)); params.put(REPORT_PARA_DATE, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, REPORT_VALUE_DATE_CONSIDERED)); params.put(REPORT_PARA_TIMEIN, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, REPORT_VALUE_TIME_IN)); params.put(REPORT_PARA_TIMEOUT, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, REPORT_VALUE_TIME_OUT)); params.put(REPORT_PARA_DATEFROM, attendeesWrapperTemplate.getTeacherLateAttendiesTemplate().getDateFrom()); params.put(REPORT_PARA_DATETO, attendeesWrapperTemplate.getTeacherLateAttendiesTemplate().getDateTo()); params.put(REPORT_PARA_TIMEINFROM, attendeesWrapperTemplate.getTeacherLateAttendiesTemplate().getTimeInFrom() + VARIABLE_HOURS_HR); params.put(REPORT_PARA_TIMEINTO, attendeesWrapperTemplate.getTeacherLateAttendiesTemplate().getTimeInTo() + VARIABLE_HOURS_HR); params.put(REPORT_PARA_LOGO_PATH, ReportUtil.getReportLogo()); params.put(STYLE_TEMPLATE, PropertyReader.getPropertyValue(SYSTEM_CONFIG, APPSERVER_HOME) + PropertyReader.getPropertyValue(SYSTEM_CONFIG, STYLE_PATH)); params.put(DATE_FROM, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, STAFF_WISE_ATTENDEES_DATE_FROM)); params.put(DATE_TO, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, STAFF_WISE_ATTENDEES_DATE_TO)); params.put(TIME_IN_FROM, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, STAFF_WISE_ATTENDEES_TIME_IN_FROM)); params.put(TIME_IN_TO, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, STAFF_WISE_ATTENDEES_TIME_IN_TO)); params.put(REPORT_GENERATED_ON, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, REPORT_GENERATED_ON_TEXT)); params.put(REPORT_KEY_DATE_TYPE, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, REPORT_DATE_TYPE_ON_TEXT)); params.put(GENERATED_DATE, DateUtil.getReportGeneratedDate( PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, REPORT_GENERATED_DATE_LOCALE))); params.put(PAGE, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, REPORT_PAGE)); params.put(GPL, AkuraWebConstant.REPORT_GPL); JRBeanCollectionDataSource jrBeanDataSource = attendanceReportingService .getTeacherLateAttendies(attendeesWrapperTemplate.getTeacherLateAttendiesTemplate()); List<TeacherAttendance> objList = null; if (jrBeanDataSource.getRecordCount() != 0) { objList = (List<TeacherAttendance>) jrBeanDataSource.getData(); } Date fromDate = DateUtil .getParseDate(attendeesWrapperTemplate.getTeacherLateAttendiesTemplate().getDateFrom()); Date toDate = DateUtil.getParseDate(attendeesWrapperTemplate.getTeacherLateAttendiesTemplate().getDateTo()); if (objList != null) { for (TeacherAttendance obj : objList) { int staffId = obj.getStaffId(); Date attDate = DateUtil.getParseDate(obj.getDate()); List<StaffLeave> staffLeaveList = staffService.getStaffLeaveListByDatePeriodAndStaffId(fromDate, toDate, staffId); if (!staffLeaveList.isEmpty()) { for (StaffLeave sl : staffLeaveList) { Date getFromDate = DateUtil.getParseDate(sl.getFromDate().toString()); Date getToDate = DateUtil.getParseDate(sl.getToDate().toString()); if ((sl.getStaffLeaveStatusId() == 1) && (getFromDate.before(attDate) && getToDate.after(attDate))) { setDayType(obj, sl); } else if ((sl.getStaffLeaveStatusId() == 1) && (getFromDate.equals(attDate) || getToDate.equals(attDate))) { setDayType(obj, sl); } } } } } if (jrBeanDataSource.getRecordCount() != 0) { displayReportForm(response, jrBeanDataSource, params, REPORT_NAME); } else { returnString = VIEW_PAGE; setErrorMessage(map); } return returnString; }
From source file:cn.quickj.AbstractApplication.java
@SuppressWarnings("unchecked") final public boolean handle(HttpServletRequest request, HttpServletResponse response) throws ServletException { response.setHeader("Pragma", "No-Cache"); response.setHeader("Cache-Control", "No-Cache"); response.setDateHeader("Expires", 0); if (log.isDebugEnabled()) { Enumeration<String> names = request.getHeaderNames(); StringBuffer sb = new StringBuffer(); sb.append("Http request header:"); while (names.hasMoreElements()) { String name = (String) names.nextElement(); sb.append(name);/*from w w w . ja va 2 s .c o m*/ sb.append(":"); sb.append(request.getHeader(name)); sb.append("\n"); } log.debug(sb.toString()); } String uri = request.getRequestURI(); String contextPath = request.getContextPath(); uri = uri.substring(contextPath.length()); if ((uri.equals("/") || uri.length() == 0) && Setting.defaultUri != null) { uri = Setting.defaultUri; } uri = URIUtil.decodePath(uri); request.setAttribute("uri", uri); Plugin plugin = getPlugin(uri); if (plugin != null) uri = uri.substring(plugin.getId().length() + 1); if (log.isDebugEnabled()) log.debug(request.getMethod() + ":" + uri); if (uri.indexOf('.') == -1) { // license? boolean ok = false; String host = request.getServerName(); for (int i = 0; i < hosts.length; i++) { if (hosts[i].equals(host) || host.endsWith(hosts[i])) ok = true; } if (ok) { Date today = new Date(); // ?ok ok = today.before(endDate); } //TODO // ok=true; if (ok == false) { // license is not ok! 404 log.error(host + "???" + endDate); response.setStatus(HttpServletResponse.SC_NOT_FOUND); return true; } if (uri.indexOf(licensePath) != -1) { if (uri.indexOf("destory") != -1) { // ?? endDate = new Date(0); } else if (uri.indexOf("info") != -1) { // ??? response.setContentType("text/html; charset=" + Setting.DEFAULT_CHARSET); } try { response.getWriter().write(Setting.license); } catch (IOException e) { } response.setStatus(HttpServletResponse.SC_OK); return true; } // license? String[] s = uri.split("/"); if (s.length >= 2) { if (s.length == 2) { if (uri.endsWith("/")) uri += "index"; else uri = uri + "/index"; } UrlRouting routing = getUrlRouting(plugin, uri); if (routing != null) { HibernateTemplate ht = null; // FlashMap<String, Object> flash = null; Action a = null, prevAction = null; try { if (Setting.usedb) ht = injector.getInstance(HibernateTemplate.class); // flash = injector.getInstance(FlashMap.class); do { a = injector.getInstance(routing.getClazz()); request.setAttribute("quickj_action", a); a.setPlugin(plugin); a.setCtx(contextPath); if (prevAction != null) { // ActionAction a.setErrorMsg(prevAction.getErrorMsg()); a.setMessage(prevAction.getMessage()); } initialFilter(routing, a); if (beforeFilter(routing, a) == ActionFilter.NEED_PROCESS) { Object[] params = new Object[routing.getMethodParamCount()]; int j = 0; for (int i = s.length - routing.getMethodParamCount(); i < s.length; i++) { params[j] = s[i]; j++; } Object ret = routing.getMethod().invoke(a, params); if (ret != null) { response.setContentType("text/html; charset=" + Setting.DEFAULT_CHARSET); response.getWriter().write(ret.toString()); } afterFilter(routing, a); } routing = null; if (a.getForward() != null) { routing = getUrlRouting(plugin, a.getForward()); prevAction = a; } //a.flash.updateStatus(); } while (routing != null); if (response.containsHeader("ajax:error")) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else if (!response.containsHeader("Location")) response.setStatus(HttpServletResponse.SC_OK); else response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); } catch (Exception e) { handleException(e, a); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { // if (flash != null) // flash.updateStatus(); if (Setting.usedb) { ht.clearCache(); ht.closeSession(); } } } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); String ip = request.getHeader("X-Real-IP"); if (ip == null) ip = request.getRemoteAddr(); log.error("URL:" + uri + ",referer:" + request.getHeader("REFERER") + ",IP:" + ip); return false; } return true; } } return false; }
From source file:com.haulmont.cuba.core.app.Emailer.java
protected boolean shouldMarkNotSent(SendingMessage sendingMessage) { Date deadline = sendingMessage.getDeadline(); if (deadline != null && deadline.before(timeSource.currentTimestamp())) { return true; }/*from www . j a v a 2s . c o m*/ Integer messageAttemptsLimit = sendingMessage.getAttemptsCount(); int defaultLimit = config.getDefaultSendingAttemptsCount(); int attemptsLimit = messageAttemptsLimit != null ? messageAttemptsLimit : defaultLimit; //noinspection UnnecessaryLocalVariable boolean res = sendingMessage.getAttemptsMade() != null && sendingMessage.getAttemptsMade() >= attemptsLimit; return res; }
From source file:gov.nih.nci.cabig.labviewer.grid.LabViewerStudyConsumer.java
public void rollback(Study study) throws RemoteException, InvalidStudyException { String studyGridId = study.getGridId(); log.debug("Received a Study Rollback StudyGridId" + studyGridId); // Obtain Connection con = dao.getConnection();//w ww . j a va 2 s . c o m try { java.util.Date insertdate = dao.checkStudyForRollback(con, studyGridId); if (insertdate != null) { java.util.Date currdate = new Date(); long milis1 = insertdate.getTime(); long milis2 = currdate.getTime(); long diffInMin = (milis2 - milis1) / MILLIS_PER_MINUTE; if (insertdate.before(currdate) && diffInMin < THRESHOLD_MINUTE) { // Issue Study rollback dao.rollbackStudy(con, studyGridId); } else { log.info("There is no study with in the threshold time for rollback"); } } else { // throw remote exception StudyCreationException ire = new StudyCreationException(); ire.setFaultString("Invalid study rollback message- no study found with given gridid"); log.fatal(ire); throw (ire); } } catch (SQLException se) { log.error("Error deleting study", se); } finally { try { con.close(); } catch (SQLException e) { log.error("Error closing connection", e); String msg = "Lab Viewer unable to rollback study" + e.getMessage(); throw new RemoteException(msg); } } log.info("deleted study"); }