List of usage examples for java.util Calendar equals
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass") @Override public boolean equals(Object obj)
Calendar
to the specified Object
. From source file:org.apache.oozie.coord.CoordELFunctions.java
/** * Takes two offset times and returns a list of multiples of the frequency offset from the effective nominal time that occur * between them. The caller should make sure that startCal is earlier than endCal. * <p>//from w w w . j a v a 2 s . com * As a simple example, assume its the same day: startCal is 1:00, endCal is 2:00, frequency is 20min, and effective nominal * time is 1:20 -- then this method would return a list containing: -20, 0, 20, 40, 60 * * @param startCal The earlier offset time * @param endCal The later offset time * @param eval The ELEvaluator to use; cannot be null * @return A list of multiple of the frequency offset from the effective nominal time that occur between the startCal and endCal */ public static List<Integer> expandOffsetTimes(Calendar startCal, Calendar endCal, ELEvaluator eval) { List<Integer> expandedFreqs = new ArrayList<Integer>(); // Use eval because the "current" eval isn't set int freq = getDSFrequency(eval); TimeUnit freqUnit = getDSTimeUnit(eval); Calendar cal = getCurrentInstance(getActionCreationtime(eval), null, eval); int totalFreq = 0; if (startCal.before(cal)) { while (cal.after(startCal)) { cal.add(freqUnit.getCalendarUnit(), -freq); totalFreq += -freq; } if (cal.before(startCal)) { cal.add(freqUnit.getCalendarUnit(), freq); totalFreq += freq; } } else if (startCal.after(cal)) { while (cal.before(startCal)) { cal.add(freqUnit.getCalendarUnit(), freq); totalFreq += freq; } } // At this point, cal is the smallest multiple of the dataset frequency that is >= to the startCal and offset from the // effective nominal time. Now we can find all of the instances that occur between startCal and endCal, inclusive. while (cal.before(endCal) || cal.equals(endCal)) { expandedFreqs.add(totalFreq); cal.add(freqUnit.getCalendarUnit(), freq); totalFreq += freq; } return expandedFreqs; }
From source file:stg.utils.immutable.Day.java
/** * The number of months between this and day parameter * //from w w w . j av a2s . c om * @param b * any date * @return the number of days between this and day parameter and b (> 0 if * this day comes after b) */ public int monthsBetween(Day b) { Calendar gcThisDay = getCalendarInstance(tzone); gcThisDay.setTime(this.getUtilDate()); Calendar gcTarget = getCalendarInstance(tzone); gcTarget.setTime(b.getUtilDate()); int iMonthsBetween = 0; if (gcThisDay.after(gcTarget)) { while (gcThisDay.after(gcTarget)) { gcTarget.add(Calendar.MONTH, 1); if (gcThisDay.after(gcTarget)) iMonthsBetween++; if (gcThisDay.equals(gcTarget)) { iMonthsBetween++; break; } } } else if (gcThisDay.before(gcTarget)) { while (gcThisDay.before(gcTarget)) { gcThisDay.add(Calendar.MONTH, 1); if (gcThisDay.before(gcTarget)) { iMonthsBetween++; } else if (gcThisDay.equals(gcTarget)) { iMonthsBetween++; break; } } } return (iMonthsBetween); }
From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.tabs.charts.ChartHelper.java
/*********************************************************************************************** * Crop the specified Vector of CalendarisedData to the range given by the start and end Calendars. * Return the cropped CalendarisedData, or NULL on failure. * * @param calendariseddata/*from ww w. jav a2 s . c o m*/ * @param startcalendar * @param endcalendar * * @return Vector<Object> */ public static Vector<Object> cropCalendarisedDataToRange(final Vector<Object> calendariseddata, final Calendar startcalendar, final Calendar endcalendar) { Vector<Object> vecCropped; vecCropped = null; if ((calendariseddata != null) && (!calendariseddata.isEmpty()) && (startcalendar != null) && (endcalendar != null)) { vecCropped = new Vector<Object>(calendariseddata.size()); for (int intDataIndex = 0; intDataIndex < calendariseddata.size(); intDataIndex++) { final Vector<Object> vecRow; final Calendar calendarRow; vecRow = (Vector) calendariseddata.get(intDataIndex); // We can safely assume that the data Vector is calendarised calendarRow = (Calendar) vecRow.get(DataTranslatorInterface.INDEX_TIMESTAMPED_CALENDAR); if ((calendarRow.equals(startcalendar) || calendarRow.after(startcalendar)) && (calendarRow.before(endcalendar) || calendarRow.equals(endcalendar))) { vecCropped.add(vecRow); } } } // Did we gather any data? if ((vecCropped != null) && (vecCropped.isEmpty())) { // Return NULL on failure vecCropped = null; } return (vecCropped); }
From source file:com.square.core.service.implementations.ActionServiceImplementation.java
@Override public ActionResultatDto modifierAction(ActionModificationDto actionModificationDto) { // Dto null//w w w .j av a 2 s .co m if (actionModificationDto == null) { throw new BusinessException(messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_DTO_NULL)); } // Identifiant de l'action null if (actionModificationDto.getIdAction() == null) { throw new BusinessException(messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_IDACTION_NULL)); } // Rcupration de l'action correspondant final Action actionAModifier = actionDao.rechercherActionParId(actionModificationDto.getIdAction()); if (actionAModifier == null) { throw new BusinessException(messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_INEXISTANTE)); } if (logger.isDebugEnabled()) { logger.debug("bug 0008864 : modifierAction(ActionModificationDto)"); logger.debug("recuperation de l'action : " + actionModificationDto.getIdAction()); logger.debug("dateCreation = " + (actionAModifier.getDateCreation() != null ? SDF.format(actionAModifier.getDateCreation().getTime()) : "null")); } Agence agence = null; if (actionModificationDto.getAgence() != null && actionModificationDto.getAgence().getIdentifiant() != null) { agence = agenceDao.rechercheAgenceParId(actionModificationDto.getAgence().getIdentifiant()); if (agence == null) { logger.error( "L'agence id = " + actionModificationDto.getAgence().getIdentifiant() + "n'existe pas."); throw new TechnicalException( messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_AGENCE_INEXISTANTE)); } } // Rcupration de la ressource correspondant au commercial (on permet dsormais le changement de ressource mme si existant) Ressource commercial = null; if (actionAModifier.getActionAttribution() != null && actionModificationDto.getRessource() != null && actionModificationDto.getRessource().getIdentifiant() != null) { commercial = ressourceDao .rechercherRessourceParId(actionModificationDto.getRessource().getIdentifiant()); if (commercial == null) { logger.error( "La ressource " + actionModificationDto.getRessource().getIdentifiant() + " n'existe pas"); throw new BusinessException( messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_COMMERCIAL_INEXISTANTE)); } } // Rcupration de la dure ActionDuree dureeAction = null; if (actionModificationDto.getIdDuree() != null) { dureeAction = actionDureeDao.rechercherDureeActionParId(actionModificationDto.getIdDuree()); if (dureeAction == null) { throw new BusinessException( messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_DUREE_INEXISTANTE)); } } final RapportDto rapport = new RapportDto(); // Vrification de la nature if (actionModificationDto.getNatureAction() == null || actionModificationDto.getNatureAction().getIdentifiant() == null) { rapport.ajoutRapport(ActionModificationDto.class.getSimpleName() + ".nature", messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_NATURE_ACTION_NULL), true); } // Pour une action de nature "tlphone sortant" passant au statut "termin" if (actionModificationDto.getNatureAction() != null && squareMappingService.getIdNatureActionTelephoneSortant() .equals(actionModificationDto.getNatureAction().getIdentifiant()) && actionModificationDto.getStatut() != null && squareMappingService.getIdStatutActionTermine() .equals(actionModificationDto.getStatut().getIdentifiant())) { // On vrifie que le rsultat de la nature est renseign if (actionModificationDto.getNatureResultat() == null || actionModificationDto.getNatureResultat().getIdentifiant() == null) { rapport.ajoutRapport(ActionModificationDto.class.getSimpleName() + ".natureResultat", messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_NATURE_RESULTAT_ACTION_NULL), true); } } // vrification que la nature de resultat est selectionne pour la nature d'action visite sortante si on demande la vrification if (!BooleanUtils.isFalse(actionModificationDto.getVerifierResultatNatureAction()) && actionModificationDto.getNatureAction() != null && squareMappingService.getIdNatureActionVisiteSortante() .equals(actionModificationDto.getNatureAction().getIdentifiant()) && actionModificationDto.getNatureResultat() == null && squareMappingService .getIdStatutActionTermine().equals(actionModificationDto.getStatut().getIdentifiant())) { throw new BusinessException( messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_NATURE_RESULTAT_VISITE_SORTANTE)); } // Contrle du statut final ValidationExpressionProp[] propsAction = new ValidationExpressionProp[] { new ValidationExpressionProp("statut", null, messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_STATUT_NULL)), new ValidationExpressionProp("dateAction", null, messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_DATE_ACTION_NULL)) }; validationExpressionUtil.verifierSiVide(rapport, actionModificationDto, propsAction); if (actionModificationDto.getDateAction() != null) { // On copie la date de l'action enregistre en base final Calendar ancienneDateAction = DateUtils.truncate((Calendar) actionAModifier.getDate().clone(), Calendar.HOUR); // On copie la nouvelle date d'action final Calendar nouvelleDateAction = DateUtils .truncate((Calendar) actionModificationDto.getDateAction().clone(), Calendar.HOUR); // Si la date de l'action est modifie if (!ancienneDateAction.equals(nouvelleDateAction)) { // On vrifie que la date d'action est postrieure la date courante if (DateUtils.truncate(nouvelleDateAction, Calendar.DAY_OF_MONTH) .before(DateUtils.truncate(Calendar.getInstance(), Calendar.DAY_OF_MONTH))) { rapport.ajoutRapport(actionModificationDto.getClass().getSimpleName() + ".dateAction", messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_DATE_ACTION_INVALIDE), true); } } } // Une action ne peut tre termine sans tre attribue if (actionModificationDto.getStatut() != null && squareMappingService.getIdStatutActionTermine() .equals(actionModificationDto.getStatut().getIdentifiant()) && (actionModificationDto.getRessource() == null || actionModificationDto.getRessource().getIdentifiant() == null)) { rapport.ajoutRapport(ActionModificationDto.class.getSimpleName() + ".statut", messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_TERMINEE_SANS_ATTRIBUTION), true); } // On ne peut rendre visible une action dans l'agenda que si elle a une date de dbut, une dure if (actionModificationDto.getVisibleAgenda() != null && actionModificationDto.getVisibleAgenda().booleanValue() && (actionModificationDto.getDateAction() == null || actionModificationDto.getIdDuree() == null)) { rapport.ajoutRapport(actionModificationDto.getClass().getSimpleName() + ".isVisibleAgenda", messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_IMPOSSIBLE_VISIBLE_AGENDA), true); } // Prsence d'erreurs empchant la modification de l'action if (rapport.getEnErreur()) { // On retourne le rapport d'erreur RapportUtil.logRapport(rapport, logger); throw new ControleIntegriteException(rapport); } // Vrification de l'existance des nouveaux champs verificationExistanceModification(actionModificationDto, actionAModifier); // Vrification de la rgle de gestion de l'opportunit en cours if (Boolean.TRUE.equals(actionModificationDto.getVerifierRegleGestionOpportuniteEnCours())) { verifierRegleGestionOpportuniteOuverte(actionModificationDto, actionAModifier); } // Modification de l'action if (actionModificationDto.getNatureAction() != null && actionModificationDto.getNatureAction().getIdentifiant() != null) { final ActionNature nature = actionNatureDao .rechercherNatureActionParId(actionModificationDto.getNatureAction().getIdentifiant()); if (nature == null) { throw new TechnicalException( messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_ACTION_NATURE_ACTION_INEXISTANT)); } actionAModifier.setNature(nature); } // modification du type d'action final IdentifiantLibelleDto typeAction = actionModificationDto.getTypeAction(); if (actionModificationDto.getTypeAction() != null && typeAction.getIdentifiant() != null) { actionAModifier.setType(actionTypeDao.rechercherTypeActionParId(typeAction.getIdentifiant())); } // modificatio de l'objet d'action final IdentifiantLibelleDto objetAction = actionModificationDto.getObjetAction(); if (actionModificationDto.getObjetAction() != null && objetAction.getIdentifiant() != null) { actionAModifier.setObjet(actionObjetDao.rechercherObjetActionParId(objetAction.getIdentifiant())); } // affectation au pot commun if (actionModificationDto.getAffectationPotCommun() != null && actionModificationDto.getAffectationPotCommun()) { actionAModifier.getActionAttribution() .setAgence(agenceDao.rechercheAgenceParId(squareMappingService.getIdentifiantAgenceFrance())); actionAModifier.getActionAttribution().setRessource(null); } if (actionModificationDto.getRappelMail() != null) { actionAModifier.setMailNotification(actionModificationDto.getRappelMail()); } // action tlphone sortant ou visite sortante if (actionModificationDto.getNatureAction() != null && (squareMappingService.getIdNatureActionTelephoneSortant() .equals(actionModificationDto.getNatureAction().getIdentifiant()) || squareMappingService.getIdNatureActionVisiteSortante() .equals(actionModificationDto.getNatureAction().getIdentifiant()))) { if (actionModificationDto.getNatureResultat() != null && actionModificationDto.getNatureResultat().getIdentifiant() != null) { actionAModifier.setNatureResultat(actionNatureResultatDao.rechercherNatureResultatActionById( actionModificationDto.getNatureResultat().getIdentifiant())); } else { actionAModifier.setNatureResultat(null); } } if (agence != null) { // si on affecte une action de relance (qui n'avait pas d'agence) une agence, on affecte aussi l'opp l'agence if (actionAModifier.getActionAttribution().getAgence() == null && actionAModifier.getType().getId().equals(squareMappingService.getIdTypeActionRelance()) && actionAModifier.getActionAffectation().getOpportunite() != null) { actionAModifier.getActionAffectation().getOpportunite().getOpportuniteAttribution() .setAgence(agence); } actionAModifier.getActionAttribution().setAgence(agence); } if (commercial != null) { // si on affecte une action de relance (qui n'avait pas de ressource) une ressource, on affecte aussi l'opp la ressource if (actionAModifier.getActionAttribution().getRessource() == null && actionAModifier.getType().getId().equals(squareMappingService.getIdTypeActionRelance()) && actionAModifier.getActionAffectation().getOpportunite() != null) { actionAModifier.getActionAffectation().getOpportunite().getOpportuniteAttribution() .setRessource(commercial); } actionAModifier.getActionAttribution().setRessource(commercial); } final Long idStatutTermine = squareMappingService.getIdStatutTerminer(); // Rsultat // Cration d'une opportunit si le rsultat passe opportunit OpportuniteDto opportuniteCree = null; if (actionAModifier.getResultat() == null) { if (actionModificationDto.getResultat() != null && actionModificationDto.getResultat().getIdentifiant() .equals(squareMappingService.getIdResultatOpportunite())) { actionAModifier.setStatut(actionStatutDao.rechercherStatutActionParId(idStatutTermine)); opportuniteCree = creationOpportunite(actionAModifier); } else if (actionModificationDto.getResultat() != null && actionModificationDto.getResultat() .getIdentifiant().equals(squareMappingService.getIdResultatRelance())) { actionAModifier.setStatut(actionStatutDao.rechercherStatutActionParId(idStatutTermine)); } else { actionAModifier.setStatut(actionStatutDao .rechercherStatutActionParId(actionModificationDto.getStatut().getIdentifiant())); } if (actionModificationDto.getResultat() != null) { actionAModifier.setResultat(actionResultatDao .rechercherActionResultatParId(actionModificationDto.getResultat().getIdentifiant())); } } else { if (actionModificationDto.getResultat() != null && actionModificationDto.getResultat().getIdentifiant() .equals(squareMappingService.getIdResultatOpportunite())) { if (!actionAModifier.getResultat().getId() .equals(squareMappingService.getIdResultatOpportunite())) { actionAModifier.setStatut(actionStatutDao.rechercherStatutActionParId(idStatutTermine)); opportuniteCree = creationOpportunite(actionAModifier); } } else if (actionModificationDto.getResultat() != null && actionModificationDto.getResultat() .getIdentifiant().equals(squareMappingService.getIdResultatRelance())) { actionAModifier.setStatut(actionStatutDao.rechercherStatutActionParId(idStatutTermine)); } else { actionAModifier.setStatut(actionStatutDao .rechercherStatutActionParId(actionModificationDto.getStatut().getIdentifiant())); } if (actionModificationDto.getResultat() != null) { actionAModifier.setResultat(actionResultatDao .rechercherActionResultatParId(actionModificationDto.getResultat().getIdentifiant())); } } // Mise jour de la date de l'action if (idStatutTermine.equals(actionModificationDto.getStatut().getIdentifiant())) { // Si l'action passe au statut "termin", on met jour la date termine de l'action en prenant la date courante actionAModifier.setDateTerminee(Calendar.getInstance()); } else { actionAModifier.setDate(actionModificationDto.getDateAction()); } // Priorit if (actionModificationDto.getPriorite() != null && actionModificationDto.getPriorite().getIdentifiant() != null) { // Rcupration de la priorit final ActionPriorite priorite = actionPrioriteDao .rechercherPrioriteActionParId(actionModificationDto.getPriorite().getIdentifiant()); if (priorite != null) { actionAModifier.setPriorite(priorite); } } // Dure de l'action if (dureeAction != null) { actionAModifier.setDuree(dureeAction); } // Action visible ou non dans l'agenda actionAModifier.setVisibleAgenda(actionModificationDto.getVisibleAgenda() != null && actionModificationDto.getVisibleAgenda().booleanValue()); // Construction de la date de notification if (actionModificationDto.getRappel() != null && actionModificationDto.getRappel()) { if (actionModificationDto.getIdNotification() != null) { final ActionNotificationInfosDto notification = squareMappingService .getActionNotificationParId(actionModificationDto.getIdNotification()); final Calendar soustraction = Calendar.getInstance(); soustraction.clear(); final Long dateTime = -notification.getNotification().getTimeInMillis() + actionAModifier.getDate().getTimeInMillis(); soustraction.setTimeInMillis(dateTime); actionAModifier.setDateNotification(soustraction); } else { actionAModifier.setDateNotification(null); } } else { actionAModifier.setDateNotification(null); } // Constuction du commentaire if (actionModificationDto.getCommentaire() != null) { final Commentaire commentaire = mapperDozerBean.map(actionModificationDto.getCommentaire(), Commentaire.class); if (actionModificationDto.getCommentaire().getRessource() != null) { final Ressource ressource = ressourceDao .rechercherRessourceParId(actionModificationDto.getCommentaire().getRessource().getId()); commentaire.setRessource(ressource); } if (actionAModifier.getCommentaires() == null) { final List<Commentaire> list = new ArrayList<Commentaire>(); list.add(commentaire); actionAModifier.setCommentaires(list); } else { actionAModifier.getCommentaires().add(commentaire); } } // Envoi d'un email si demand if (actionAModifier.isMailNotification() && squareMappingService.getIdStatutActionTermine().equals(actionAModifier.getStatut().getId())) { if (actionAModifier.getRessource() != null) { final Ressource createur = actionAModifier.getRessource(); if (createur.getEmail() == null || "".equals(createur.getEmail())) { throw new BusinessException( messageSourceUtil.get(ActionKeyUtil.MESSAGE_ERREUR_EMAIL_CREATEUR_ACTION_VIDE)); } final List<String> listeDestinataires = new ArrayList<String>(); listeDestinataires.add(createur.getEmail()); final String titre = messageSourceUtil.get(ActionKeyUtil.TITRE_EMAIL_FIN_ACTION); String personneAction = ""; String type = ""; String objet = ""; String sousObjet = ""; String nature = ""; String campagne = ""; if (actionAModifier.getActionAffectation() != null && actionAModifier.getActionAffectation().getPersonne() != null) { final Personne personne = actionAModifier.getActionAffectation().getPersonne(); if (personne instanceof PersonnePhysique) { final PersonnePhysique personnePhysique = (PersonnePhysique) actionAModifier .getActionAffectation().getPersonne(); personneAction = personnePhysique.getNom() + ESPACE + personnePhysique.getPrenom(); } else if (personne instanceof PersonneMorale) { final PersonneMorale personneMorale = (PersonneMorale) actionAModifier .getActionAffectation().getPersonne(); personneAction = personneMorale.getRaisonSociale(); } } if (actionAModifier.getType() != null) { type = actionAModifier.getType().getLibelle(); } if (actionAModifier.getObjet() != null) { objet = actionAModifier.getObjet().getLibelle(); } if (actionAModifier.getSousObjet() != null) { sousObjet = actionAModifier.getSousObjet().getLibelle(); } if (actionAModifier.getNature() != null) { nature = actionAModifier.getNature().getLibelle(); } if (actionAModifier.getCampagne() != null) { campagne = actionAModifier.getCampagne().getLibelle(); } final String message = messageSourceUtil.get(ActionKeyUtil.MESSAGE_EMAIL_FIN_ACTION, new String[] { personneAction, type, objet, sousObjet, nature, campagne }); final MailDto mailDto = new MailDto(expediteurNoReply, listeDestinataires, titre, message, null, false); emailSquarePlugin.envoyerEmail(mailDto); } } // Renseignement de la date de modification actionAModifier.setDateModification(Calendar.getInstance()); final ActionResultatDto resultat = new ActionResultatDto(); if (opportuniteCree != null) { resultat.setIdOpportunite(opportuniteCree.getIdOpportunite()); } return resultat; }
From source file:mvc.OrderController.java
private String getJsonStringByDateList(Date dateFrom, Date dateTo, List<Map> listByDates) { String json = ""; Calendar cl = Calendar.getInstance(); cl.setTime(dateFrom);/*from w w w. j a v a2 s .c o m*/ setStartOfDay(cl); Calendar end = Calendar.getInstance(); end.setTime(dateTo); setStartOfDay(end); // ? ? for (; cl.before(end) || cl.equals(end); cl.add(Calendar.DAY_OF_MONTH, 1)) { int year = cl.get(Calendar.YEAR); int month = cl.get(Calendar.MONTH) + 1; int day = cl.get(Calendar.DAY_OF_MONTH); json += getJsonByDate(listByDates, day, month, year); } return json; }
From source file:edu.jhuapl.openessence.controller.ReportController.java
/** * Extracts AccumPoint from a Collection of <code>records</code> where * * @param principal, used for logging// w ww. java2s . c o m */ private List<AccumPoint> extractAccumulationPoints(String principal, DataSeriesSource ds, final Collection<Record> records, Date startDate, Date endDate, List<Dimension> accumulations, final GroupingImpl group, Map<String, ResolutionHandler> resolutionHandlers) { log.info(LogStatements.TIME_SERIES.getLoggingStmt() + principal); int startDayCal = getCalWeekStartDay(resolutionHandlers); int startDay = getWeekStartDay(resolutionHandlers); String resolution = group.getResolution(); final String groupId = group.getId(); int zeroFillInterval = intervalMap.keySet().contains(resolution) ? intervalMap.get(resolution) : -1; GroupingDimension grpdim = ds.getGroupingDimension(group.getId()); if (zeroFillInterval != -1 && (grpdim.getSqlType() == FieldType.DATE || grpdim.getSqlType() == FieldType.DATE_TIME)) { ArrayList<AccumPoint> fullVector = new ArrayList<AccumPoint>(records.size()); //create zero points for each accumulation Map<String, Number> zeroes = new HashMap<String, Number>(); for (Dimension accumulation : accumulations) { zeroes.put(accumulation.getId(), 0); } if (records.size() > 0) { final Calendar cal = new GregorianCalendar(); cal.setTime(startDate); Iterator<Record> recordsIterator = records.iterator(); Record currRecord = (recordsIterator.hasNext()) ? recordsIterator.next() : null; //currently iterates over data incrementing cal by the resolution (weekly, daily etc) for (int i = 1; !cal.getTime().after(endDate); i++) { // if (DAILY.equalsIgnoreCase(resolution)) { boolean addRecord = false; if (currRecord != null) { // 2013/03/25, SCC, GGF, There are some weird edge cases with selecting data ranges that span // the EDT/EST cross-overs. Sometimes the "filter" will have the "23:00" and the data will have // "00:00". So, since we only care about the "date" anyway, clear out any subordinate fields. // Database record date (set hour, minute, second, millisec to 0) final Calendar rowValue = Calendar.getInstance(); rowValue.setTime((Date) currRecord.getValue(groupId)); rowValue.set(Calendar.HOUR_OF_DAY, 0); rowValue.set(Calendar.MINUTE, 0); rowValue.set(Calendar.SECOND, 0); rowValue.set(Calendar.MILLISECOND, 0); // looping variable date (set hour, minute, second, millisec to 0) final Calendar calValue = Calendar.getInstance(); calValue.setTime(cal.getTime()); calValue.set(Calendar.HOUR_OF_DAY, 0); calValue.set(Calendar.MINUTE, 0); calValue.set(Calendar.SECOND, 0); calValue.set(Calendar.MILLISECOND, 0); if (resolution.equalsIgnoreCase(DAILY) && rowValue.equals(calValue)) { addRecord = true; } else { Calendar currRecCalendar = new GregorianCalendar(); currRecCalendar.setTime((Date) currRecord.getValue(groupId)); if (resolution.equalsIgnoreCase(WEEKLY)) { if (PgSqlDateHelper.getYear(startDay, cal) == PgSqlDateHelper.getYear(startDay, currRecCalendar) && PgSqlDateHelper.getWeekOfYear(startDay, cal) == PgSqlDateHelper .getWeekOfYear(startDay, currRecCalendar)) { addRecord = true; } } else if (resolution.equalsIgnoreCase(MONTHLY)) { if (cal.get(Calendar.YEAR) == currRecCalendar.get(Calendar.YEAR) && cal.get(Calendar.MONTH) == currRecCalendar.get(Calendar.MONTH)) { addRecord = true; } } } if (addRecord) { //if the current record matches the date put it in fullVector.add(createAccumulationPoint(currRecord, accumulations)); currRecord = (recordsIterator.hasNext()) ? recordsIterator.next() : null; } } if (!addRecord) { //add a zero fill Map<String, Dimension> m = new HashMap<String, Dimension>(); m.put(groupId, ds.getResultDimension(groupId)); HashMap<String, Object> map = new HashMap<String, Object>(); map.put(groupId, cal.getTime()); Record r = new QueryRecord(m, map); fullVector.add(new AccumPointImpl(zeroes, r)); } if (resolution.equalsIgnoreCase(WEEKLY)) { // add 7 days if current date falls on week start date if (i != 1) { cal.add(Calendar.WEEK_OF_YEAR, 1); } else { cal.add(Calendar.DAY_OF_YEAR, 1); while (cal.get(Calendar.DAY_OF_WEEK) != startDayCal) { cal.add(Calendar.DAY_OF_YEAR, 1); } } } else { // reset the date each time to account for +month oddness cal.setTime(startDate); // increment the interval cal.add(zeroFillInterval, 1 * i); } } } return fullVector; } else { //pretty sure this is raw non filled List<AccumPoint> rawVector = new ArrayList<AccumPoint>(records.size()); for (Record record : records) { rawVector.add(createAccumulationPoint(record, accumulations)); } return rawVector; } }
From source file:com.square.core.service.implementations.PersonneServiceImplementation.java
/** * Test si une relation est active ou pas la date du jour. * @param dateDebut date de dbut de la relation * @param dateFin date de fin de la relation * @return true si la relation est active, false sinon *//*from w w w .ja v a2 s. c om*/ private boolean isRelationActive(Calendar dateDebut, Calendar dateFin) { final Calendar dateDuJour = Calendar.getInstance(); final int jour = dateDuJour.get(Calendar.DATE); final int mois = dateDuJour.get(Calendar.MONTH); final int annee = dateDuJour.get(Calendar.YEAR); dateDuJour.clear(); dateDuJour.set(annee, mois, jour); return (dateDebut == null || dateDebut.before(dateDuJour) || dateDebut.equals(dateDuJour)) && (dateFin == null || dateFin.after(dateDuJour)); }
From source file:org.kuali.kfs.module.tem.document.service.impl.TravelDocumentServiceImpl.java
@Override public Integer calculatePerDiemPercentageFromTimestamp(PerDiemExpense perDiemExpense, Timestamp tripEnd) { if (perDiemExpense.getMileageDate() != null) { try {/*from w w w .j av a 2 s .com*/ Collection<String> quarterTimes = parameterService.getParameterValuesAsString( TemParameterConstants.TEM_DOCUMENT.class, TravelParameters.QUARTER_DAY_TIME_TABLE); // Take date and compare to the quadrant specified. Calendar prorateDate = new GregorianCalendar(); prorateDate.setTime(perDiemExpense.getMileageDate()); int quadrantIndex = 4; for (String qT : quarterTimes) { String[] indexTime = qT.split("="); String[] hourMinute = indexTime[1].split(":"); Calendar qtCal = new GregorianCalendar(); qtCal.setTime(perDiemExpense.getMileageDate()); qtCal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hourMinute[0])); qtCal.set(Calendar.MINUTE, Integer.parseInt(hourMinute[1])); if (prorateDate.equals(qtCal) || prorateDate.before(qtCal)) { quadrantIndex = Integer.parseInt(indexTime[0]); break; } } // Prorate on trip begin. (12:01 AM arrival = 100%, 11:59 PM arrival = 25%) if (tripEnd != null && !KfsDateUtils.isSameDay(prorateDate.getTime(), tripEnd)) { return 100 - ((quadrantIndex - 1) * TemConstants.QUADRANT_PERCENT_VALUE); } else { // Prorate on trip end. (12:01 AM departure = 25%, 11:59 PM arrival = 100%). return quadrantIndex * TemConstants.QUADRANT_PERCENT_VALUE; } } catch (IllegalArgumentException e2) { LOG.error("IllegalArgumentException.", e2); } } return 100; }
From source file:org.simbasecurity.core.saml.SAMLResponseHandlerImpl.java
@Override public boolean isValid(String... requestId) { try {/*from ww w . j av a 2s . c o m*/ Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC")); if (this.document == null) { throw new Exception("SAML Response is not loaded"); } if (this.currentUrl == null || this.currentUrl.isEmpty()) { throw new Exception("The URL of the current host was not established"); } // Check SAML version if (!rootElement.getAttribute("Version").equals("2.0")) { throw new Exception("Unsupported SAML Version."); } // Check ID in the response if (!rootElement.hasAttribute("ID")) { throw new Exception("Missing ID attribute on SAML Response."); } checkStatus(); if (!this.validateNumAssertions()) { throw new Exception("SAML Response must contain 1 Assertion."); } NodeList signNodes = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); ArrayList<String> signedElements = new ArrayList<>(); for (int i = 0; i < signNodes.getLength(); i++) { signedElements.add(signNodes.item(i).getParentNode().getLocalName()); } if (!signedElements.isEmpty()) { if (!this.validateSignedElements(signedElements)) { throw new Exception("Found an unexpected Signature Element. SAML Response rejected"); } } Document res = Utils.validateXML(this.document, "saml-schema-protocol-2.0.xsd"); if (res == null) { throw new Exception("Invalid SAML Response. Not match the saml-schema-protocol-2.0.xsd"); } if (rootElement.hasAttribute("InResponseTo")) { String responseInResponseTo = document.getDocumentElement().getAttribute("InResponseTo"); if (requestId.length > 0 && responseInResponseTo.compareTo(requestId[0]) != 0) { throw new Exception("The InResponseTo of the Response: " + responseInResponseTo + ", does not match the ID of the AuthNRequest sent by the SP: " + requestId[0]); } } // Validate Assertion timestamps if (!this.validateTimestamps()) { throw new Exception("Timing issues (please check your clock settings)"); } // EncryptedAttributes are not supported NodeList encryptedAttributeNodes = this .queryAssertion("/saml:AttributeStatement/saml:EncryptedAttribute"); if (encryptedAttributeNodes.getLength() > 0) { throw new Exception("There is an EncryptedAttribute in the Response and this SP not support them"); } // Check destination // TODO: lenneh: bktis: currentUrl is http:// and the destination is https:// // if (rootElement.hasAttribute("Destination")) { // String destinationUrl = rootElement.getAttribute("Destination"); // if (destinationUrl != null) { // if (!destinationUrl.equals(currentUrl)) { // throw new Exception("The response was received at " + currentUrl + " instead of " + destinationUrl); // } // } // } // Check Audience // TODO: lenneh: bktis: currentUrl is http:// and audienceUrl is https:// // Set<String> validAudiences = this.getAudiences(); // // if (validAudiences.isEmpty() || !this.audienceUrl.equals(currentUrl)) { // throw new Exception(this.audienceUrl + " is not a valid audience for this Response"); // } // Check the issuers Set<String> issuers = this.getIssuers(); for (String issuer : issuers) { if (issuer.isEmpty()) { throw new Exception("Invalid issuer in the Assertion/Response"); } } // Check the session Expiration Calendar sessionExpiration = this.getSessionNotOnOrAfter(); if (sessionExpiration != null) { if (now.equals(sessionExpiration) || now.after(sessionExpiration)) { throw new Exception( "The attributes have expired, based on the SessionNotOnOrAfter of the AttributeStatement of this Response"); } } // Check SubjectConfirmation, at least one SubjectConfirmation must be valid boolean validSubjectConfirmation = true; NodeList subjectConfirmationNodes = this.queryAssertion("/saml:Subject/saml:SubjectConfirmation"); for (int i = 0; i < subjectConfirmationNodes.getLength(); i++) { Node scn = subjectConfirmationNodes.item(i); Node method = scn.getAttributes().getNamedItem("Method"); if (method != null && !method.getNodeValue().equals(SAMLConstants.CM_BEARER)) { continue; } NodeList subjectConfirmationDataNodes = scn.getChildNodes(); for (int c = 0; c < subjectConfirmationDataNodes.getLength(); c++) { Node subjectConfirmationData = subjectConfirmationDataNodes.item(c); if (subjectConfirmationData.getNodeType() == Node.ELEMENT_NODE && subjectConfirmationData.getLocalName().equals("SubjectConfirmationData")) { // TODO: lenneh: bktis: currentUrl is http:// and the recipient is https:// // Node recipient = subjectConfirmationData.getAttributes().getNamedItem("Recipient"); // if (recipient != null && !recipient.getNodeValue().equals(currentUrl)) { // validSubjectConfirmation = false; // } Node notOnOrAfter = subjectConfirmationData.getAttributes().getNamedItem("NotOnOrAfter"); if (notOnOrAfter != null) { Calendar noa = javax.xml.bind.DatatypeConverter .parseDateTime(notOnOrAfter.getNodeValue()); if (now.equals(noa) || now.after(noa)) { validSubjectConfirmation = false; } } Node notBefore = subjectConfirmationData.getAttributes().getNamedItem("NotBefore"); if (notBefore != null) { Calendar nb = javax.xml.bind.DatatypeConverter.parseDateTime(notBefore.getNodeValue()); if (now.before(nb)) { validSubjectConfirmation = false; } } } } } if (!validSubjectConfirmation) { throw new Exception("A valid SubjectConfirmation was not found on this Response"); } if (signedElements.isEmpty()) { throw new Exception("No Signature found. SAML Response rejected"); } else { if (!Utils.validateSign(signNodes.item(0), certificate)) { throw new Exception("Signature validation failed. SAML Response rejected"); } } return true; } catch (Error e) { error.append(e.getMessage()); return false; } catch (Exception e) { e.printStackTrace(); error.append(e.getMessage()); return false; } }
From source file:rems.Global.java
public static boolean isTransPrmttd(int accntID, String trnsdate, double amnt, String outptMsg[]) { try {//w ww . ja v a2 s .c o m //trnsdate = DateTime.ParseExact( //trnsdate, "dd-MMM-yyyy HH:mm:ss", //System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss"); //Transaction date must be >= the latest prd start date if (accntID <= 0 || trnsdate.equals("")) { return false; } SimpleDateFormat frmtr = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); SimpleDateFormat frmtr1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat frmtr2 = new SimpleDateFormat("dd-MMM-yyyy"); SimpleDateFormat frmtr3 = new SimpleDateFormat("dddd"); Calendar trnsDte = Calendar.getInstance(); trnsDte.setTime(frmtr.parse(trnsdate)); Calendar dte1 = Calendar.getInstance(); dte1.setTime(frmtr.parse(Global.getLtstPrdStrtDate())); Calendar dte1Or = Calendar.getInstance(); dte1Or.setTime(frmtr.parse(Global.getLastPrdClseDate())); Calendar dte2 = Calendar.getInstance(); dte2.setTime(frmtr.parse(Global.getLtstPrdEndDate())); if (trnsDte.equals(dte1Or) || trnsDte.before(dte1Or)) { outptMsg[0] += "Transaction Date cannot be On or Before " + frmtr.format(dte1Or); return false; } if (trnsDte.before(dte1)) { outptMsg[0] += "Transaction Date cannot be before " + frmtr.format(dte1); return false; } if (trnsDte.after(dte2)) { outptMsg[0] += "Transaction Date cannot be after " + frmtr.format(dte2); return false; } //Check if trnsDate exists in an Open Period long prdHdrID = Global.getPrdHdrID(Global.UsrsOrg_ID); //Global.showMsg(Global.Org_iString.valueOf(d) + "-" + prdHdrID.ToString(), 0); if (prdHdrID > 0) { //Global.showMsg(trnsDte.ToString("yyyy-MM-dd HH:mm:ss") + "-" + prdHdrID.ToString(), 0); if (Global.getTrnsDteOpenPrdLnID(prdHdrID, frmtr1.format(trnsDte)) < 0) { outptMsg[0] += "Cannot use a Transaction Date (" + frmtr.format(trnsDte) + ") which does not exist in any OPEN period!"; return false; } //Check if Date is not in Disallowed Dates String noTrnsDatesLov = Global.getGnrlRecNm("accb.accb_periods_hdr", "periods_hdr_id", "no_trns_dates_lov_nm", prdHdrID); String noTrnsDayLov = Global.getGnrlRecNm("accb.accb_periods_hdr", "periods_hdr_id", "no_trns_wk_days_lov_nm", prdHdrID); //Global.showMsg(noTrnsDatesLov + "-" + noTrnsDayLov + "-" + trnsDte.ToString("dddd").ToUpper() + "-" + trnsDte.ToString("dd-MMM-yyyy").ToUpper(), 0); if (!noTrnsDatesLov.equals("")) { if (Global.getEnbldPssblValID(frmtr2.format(trnsDte).toUpperCase(), Global.getEnbldLovID(noTrnsDatesLov)) > 0) { outptMsg[0] += "Transactions on this Date (" + frmtr.format(trnsDte) + ") have been banned on this system!"; return false; } } //Check if Day of Week is not in Disaalowed days if (!noTrnsDatesLov.equals("")) { if (Global.getEnbldPssblValID(frmtr3.format(trnsDte).toUpperCase(), Global.getEnbldLovID(noTrnsDayLov)) > 0) { outptMsg[0] += "Transactions on this Day of Week (" + frmtr3.format(trnsDte) + ") have been banned on this system!"; return false; } } } //Amount must not disobey budget settings on that account long actvBdgtID = Global.getActiveBdgtID(Global.UsrsOrg_ID); double amntLmt = Global.getAcntsBdgtdAmnt(actvBdgtID, accntID, frmtr.format(trnsDte)); Calendar bdte1 = Calendar.getInstance(); bdte1.setTime(frmtr.parse(Global.getAcntsBdgtStrtDte(actvBdgtID, accntID, frmtr.format(trnsDte)))); Calendar bdte2 = Calendar.getInstance(); bdte2.setTime(frmtr.parse(Global.getAcntsBdgtEndDte(actvBdgtID, accntID, frmtr.format(trnsDte)))); double crntBals = Global.getTrnsSum(accntID, frmtr.format(bdte1), frmtr.format(bdte2), "1"); String actn = Global.getAcntsBdgtLmtActn(actvBdgtID, accntID, trnsdate); if ((amnt + crntBals) > amntLmt) { if (actn.equals("Disallow")) { outptMsg[0] += "This transaction will cause budget on \r\nthe chosen account to be exceeded! "; return false; } else if (actn.equals("Warn")) { outptMsg[0] += "This is just to WARN you that the budget on \r\nthe chosen account will be exceeded!"; return true; } else if (actn.equals("Congratulate")) { outptMsg[0] += "This is just to CONGRATULATE you for exceeding the targetted Amount! "; return true; } else { return true; } } return true; } catch (Exception ex) { outptMsg[0] += Arrays.toString(ex.getStackTrace()) + "\r\n" + ex.getMessage(); return false; } }