Example #1
0
 public boolean isCurrent() {
   Date currentDate = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
   Date established = DateUtils.truncate(getEstablished(), Calendar.DAY_OF_MONTH);
   Date dueTo = DateUtils.truncate(getDueTo(), Calendar.DAY_OF_MONTH);
   return isActive()
       && ((established.before(currentDate) || established.equals(currentDate))
           && (dueTo.after(currentDate) || dueTo.equals(currentDate)));
 }
Example #2
0
  /**
   * Get tow dates period as seconds, return -1 if the start or end is null
   *
   * @param start Start date
   * @param end End date
   * @return Period as days or -1
   */
  public static long periodAsSeconds(final Date start, final Date end) {
    if (start == null || end == null) {
      return -1;
    }
    Date truncatedStart = org.apache.commons.lang.time.DateUtils.truncate(start, Calendar.SECOND);
    Date truncatedEnd = org.apache.commons.lang.time.DateUtils.truncate(end, Calendar.SECOND);

    long periodAsMilliSeconds = truncatedEnd.getTime() - truncatedStart.getTime();
    return periodAsMilliSeconds / MILLISECOND_UNIT;
  }
Example #3
0
  @Test
  public void set_issue_fields() {
    Date createdAt = DateUtils.addDays(new Date(), -5);
    Date updatedAt = DateUtils.addDays(new Date(), -3);
    Date closedAt = DateUtils.addDays(new Date(), -1);

    IssueDto dto =
        new IssueDto()
            .setKee("100")
            .setRuleId(1)
            .setRuleKey_unit_test_only("squid", "AvoidCycle")
            .setComponentKey_unit_test_only("org.sonar.sample:Sample")
            .setRootComponentKey_unit_test_only("org.sonar.sample")
            .setComponentId(1l)
            .setRootComponentId(1l)
            .setStatus(Issue.STATUS_CLOSED)
            .setResolution(Issue.RESOLUTION_FALSE_POSITIVE)
            .setEffortToFix(15.0)
            .setTechnicalDebt(101010L)
            .setLine(6)
            .setSeverity("BLOCKER")
            .setMessage("message")
            .setManualSeverity(true)
            .setReporter("arthur")
            .setAssignee("perceval")
            .setIssueAttributes("key=value")
            .setAuthorLogin("pierre")
            .setIssueCreationDate(createdAt)
            .setIssueUpdateDate(updatedAt)
            .setIssueCloseDate(closedAt);

    DefaultIssue issue = dto.toDefaultIssue();
    assertThat(issue.key()).isEqualTo("100");
    assertThat(issue.ruleKey().toString()).isEqualTo("squid:AvoidCycle");
    assertThat(issue.componentKey()).isEqualTo("org.sonar.sample:Sample");
    assertThat(issue.projectKey()).isEqualTo("org.sonar.sample");
    assertThat(issue.status()).isEqualTo(Issue.STATUS_CLOSED);
    assertThat(issue.resolution()).isEqualTo(Issue.RESOLUTION_FALSE_POSITIVE);
    assertThat(issue.effortToFix()).isEqualTo(15.0);
    assertThat(issue.technicalDebt()).isEqualTo(WorkDayDuration.of(10, 10, 10));
    assertThat(issue.line()).isEqualTo(6);
    assertThat(issue.severity()).isEqualTo("BLOCKER");
    assertThat(issue.message()).isEqualTo("message");
    assertThat(issue.manualSeverity()).isTrue();
    assertThat(issue.reporter()).isEqualTo("arthur");
    assertThat(issue.assignee()).isEqualTo("perceval");
    assertThat(issue.attribute("key")).isEqualTo("value");
    assertThat(issue.authorLogin()).isEqualTo("pierre");
    assertThat(issue.creationDate()).isEqualTo(DateUtils.truncate(createdAt, Calendar.SECOND));
    assertThat(issue.updateDate()).isEqualTo(DateUtils.truncate(updatedAt, Calendar.SECOND));
    assertThat(issue.closeDate()).isEqualTo(DateUtils.truncate(closedAt, Calendar.SECOND));
    assertThat(issue.isNew()).isFalse();
  }
 private boolean isPeriodeCouranteConges(Date date) {
   Date dateFinPeriodeCourante =
       getDateFinPeriodeConges(DateUtils.truncate(new Date(), Calendar.DATE));
   // ajout d'1 jur car la comparaison des dates doit être <= et la méthode before n'a pas ce
   // comportement par défaut
   return date.before(DateUtils.addSeconds(dateFinPeriodeCourante, 1));
 }
 private Date getCalendarDate(Date date, int calendar) {
   Calendar cal = Calendar.getInstance();
   cal.setTime(date);
   if (calendar == Calendar.WEEK_OF_MONTH) {
     while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
       cal.add(Calendar.DAY_OF_MONTH, -1);
     }
     return cal.getTime();
   } else if (calendar == Calendar.MONTH) {
     return DateUtils.truncate(cal, Calendar.MONTH).getTime();
   } else if (calendar == Calendar.YEAR) {
     return DateUtils.truncate(cal, Calendar.YEAR).getTime();
   } else {
     return null;
   }
 }
Example #6
0
 public void setCloseDate(DefaultIssue issue, @Nullable Date d, IssueChangeContext context) {
   Date dateWithoutMilliseconds = d == null ? null : DateUtils.truncate(d, Calendar.SECOND);
   if (!Objects.equal(dateWithoutMilliseconds, issue.closeDate())) {
     issue.setCloseDate(d);
     issue.setUpdateDate(context.date());
     issue.setChanged(true);
   }
 }
Example #7
0
 protected void init() {
   paging = wrapPaging();
   if (to == null) {
     to = new Date(DateUtils.truncate(new Date(), Calendar.DATE).getTime() + 86400000);
   }
   if (from == null) {
     from = DateUtils.addDays(to, -30);
   }
 }
Example #8
0
  /**
   * Checks whether the given date is included in this period. When the useTime flag is true, the
   * time of the parameter (date) and the time of the begin and end dates of the period are taken
   * into account to compute the result. When the useTime flag is false, the dates are truncated to
   * compute the result.
   */
  public boolean includes(final Calendar date) {

    if (date == null) {
      return false;
    } else if (begin == null && end == null) {
      return true;
    } else {

      if (useTime) {
        if (begin == null) {
          return !date.after(end);
        } else if (end == null) {
          return !date.before(begin);
        } else {
          return !date.before(begin) && !date.after(end);
        }
      } else {

        final Calendar tDate = DateUtils.truncate(date, Calendar.DATE);
        Calendar tBegin = begin;
        Calendar tEnd = end;

        if (begin != null) {
          tBegin = DateUtils.truncate(begin, Calendar.DATE);
        }
        if (end != null) {
          // If not using time, we'll asume the end of the interval is
          // the instant before the next day.
          tEnd = DateHelper.truncateNextDay(end);
        }

        if (tBegin == null) {
          // it's included if the date is an instant before the next day.
          return tDate.before(tEnd);
        } else if (tEnd == null) {
          // it's included if the date is not before the begin
          return !tDate.before(tBegin);
        } else {
          return !tDate.before(tBegin) && tDate.before(tEnd);
        }
      }
    }
  }
 @Before
 public void setUp() throws Exception {
   MockitoAnnotations.initMocks(this);
   Date now = DateUtils.truncate(new Date(), Calendar.DATE);
   for (int i = 0; i < 10; i++) {
     messages.add(
         buildMessage(
             DateUtils.addDays(now, i >> 2),
             (i & 1) > 0 ? MessagePriority.HIGH : MessagePriority.LOW));
   }
 }
Example #10
0
 public static CoveringInfo getYearlyCoveringInfo(Date from, Date to) {
   CoveringInfo monthlyCoveringInfo = getMonthlyCoveringInfo(from, to);
   if (monthlyCoveringInfo.getCountBetween() < 12) {
     return new CoveringInfo(0, false);
   }
   boolean coverable = monthlyCoveringInfo.isCoverable();
   if (!from.equals(DateUtils.truncate(from, MONTH))) {
     from = DateUtils.addMonths(DateUtils.truncate(from, MONTH), 1);
     coverable = false;
   }
   Calendar cal = Calendar.getInstance();
   cal.setTime(from);
   int fromMonth = cal.get(MONTH);
   int beginOffset = (12 - fromMonth % 12) % 12;
   int endOffset = (monthlyCoveringInfo.getCountBetween() - beginOffset) % 12;
   if (beginOffset > 0 || endOffset > 0) {
     coverable = false;
   }
   return new CoveringInfo(
       (monthlyCoveringInfo.getCountBetween() - beginOffset - endOffset) / 12, coverable);
 }
Example #11
0
  public static CoveringInfo getMonthlyCoveringInfo(Date from, Date to) {
    // Move 'from' to end of month, unless its the first day of month
    boolean coverable = true;
    if (!from.equals(DateUtils.truncate(from, MONTH))) {
      from = DateUtils.addMonths(DateUtils.truncate(from, MONTH), 1);
      coverable = false;
    }

    // Move 'to' to beginning of next month, unless its the first day of the month
    if (!to.equals(DateUtils.truncate(to, MONTH))) {
      to = DateUtils.truncate(to, MONTH);
      coverable = false;
    }

    int months = 0;
    while (from.before(to)) {
      from = DateUtils.addMonths(from, 1);
      months++;
    }
    return new CoveringInfo(months, coverable);
  }
 @Override
 public String getIndexResult(String[] brands, Date date) {
   if (date != null) {
     DayStatus ds = dataDaoV2.getDayStatus(date);
     if (ds == null || ds.getStatus() == null || ds.getStatus() == 0) {
       SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
       return this.getErrorResult(3002, sdf.format(date) + "没有相关数据,请重新选择日期");
     }
   }
   Date yesterday = getYesterday(date);
   Set<String> bSet = new HashSet<String>();
   for (String brand : brands) {
     bSet.add(brand);
   }
   List<BrandResult> indexBrandResults = dataDaoV2.getBrandResult(yesterday, brands);
   for (BrandResult ibr : indexBrandResults) {
     if (springProperty.isMockValue()) {
       ibr.setDayAmount(10000L);
     }
     bSet.remove(ibr.getBrand());
   }
   for (String brand : bSet) {
     BrandResult ibr = new BrandResult(brand, "", 0);
     indexBrandResults.add(ibr);
   }
   IndexStatResult ir = new IndexStatResult();
   ir.setBrands(indexBrandResults);
   ir.setResult(0);
   ir.setDate(yesterday);
   ir.setClientVersion(springProperty.getClientVersion());
   Date realYesterday =
       DateUtils.addDays(DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH), -1);
   DayStatus ds = dataDaoV2.getDayStatus(realYesterday);
   if (ds != null && ds.getStatus() != null && ds.getStatus().intValue() != 0) {
     ir.setYesterday(true);
   } else {
     ir.setYesterday(false);
   }
   List<Date> availableDates = dataDaoV2.getAvailableDates(realYesterday);
   List<String> ads = new ArrayList<String>();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   for (Date ad : availableDates) {
     ads.add(sdf.format(ad));
   }
   ir.setAvailableDates(ads);
   JsonConfig jsonConfig = new JsonConfig();
   jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
   jsonConfig.registerJsonValueProcessor(Integer.class, new IntegerJsonValueProcessor());
   String result = JSONObject.fromObject(ir, jsonConfig).toString();
   return result;
 }
Example #13
0
  public static Date resolveRelativeDate(String str, Date now) throws SemanticException {
    if (StringUtils.isBlank(str)) {
      throw new SemanticException(ErrorMsg.NULL_DATE_VALUE);
    }

    // Resolve NOW with proper granularity
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(now);

    str = str.toLowerCase();
    Matcher relativeMatcher = P_RELATIVE.matcher(str);
    if (relativeMatcher.find()) {
      String nowWithGranularity = relativeMatcher.group();
      nowWithGranularity = nowWithGranularity.replaceAll("now", "");
      nowWithGranularity = nowWithGranularity.replaceAll("\\.", "");

      Matcher granularityMatcher = P_UNIT.matcher(nowWithGranularity);
      if (granularityMatcher.find()) {
        String unit = granularityMatcher.group().toLowerCase();
        if ("year".equals(unit)) {
          calendar = DateUtils.truncate(calendar, YEAR);
        } else if ("month".equals(unit)) {
          calendar = DateUtils.truncate(calendar, MONTH);
        } else if ("week".equals(unit)) {
          calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
          calendar = DateUtils.truncate(calendar, DAY_OF_MONTH);
        } else if ("day".equals(unit)) {
          calendar = DateUtils.truncate(calendar, DAY_OF_MONTH);
        } else if ("hour".equals(unit)) {
          calendar = DateUtils.truncate(calendar, Calendar.HOUR_OF_DAY);
        } else if ("minute".equals(unit)) {
          calendar = DateUtils.truncate(calendar, Calendar.MINUTE);
        } else if ("second".equals(unit)) {
          calendar = DateUtils.truncate(calendar, Calendar.SECOND);
        } else {
          throw new SemanticException(ErrorMsg.INVALID_TIME_UNIT, unit);
        }
      }
    }

    // Get rid of 'now' part and whitespace
    String diffStr = str.replaceAll(RELATIVE, "").replace(WSPACE, "");
    TimeDiff diff = TimeDiff.parseFrom(diffStr);
    return diff.offsetFrom(calendar.getTime());
  }
 private Date getYesterday(Date date) {
   if (date != null) {
     return date;
   }
   Date yesterday = null;
   try {
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
     if (StringUtils.isNotEmpty(springProperty.getYesterday())) {
       yesterday = sdf.parse(springProperty.getYesterday());
     } else {
       yesterday = this.dataDaoV2.getPreviousDate();
       if (yesterday == null) {
         yesterday = DateUtils.addDays(DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH), -1);
       }
     }
   } catch (Exception e) {
     log.error("", e);
   }
   return yesterday;
 }
Example #15
0
  @Override
  @Authenticated
  public String generateSampleData(int numberOfDaysBack) {
    if (numberOfDaysBack < 1 || numberOfDaysBack > 1000) {
      return "numberOfDaysBack must be between 1 and 1000";
    }
    Date startDate =
        DateUtils.truncate(
            DateUtils.addDays(timeSource.currentTimestamp(), -numberOfDaysBack),
            Calendar.DAY_OF_MONTH);

    try {
      Context context = new Context();
      createCurrencies(context);
      createAccounts(context);
      createCategories(context);
      createOperations(startDate, numberOfDaysBack, context);

      return "Done";
    } catch (Throwable e) {
      log.error("Error", e);
      return ExceptionUtils.getStackTrace(e);
    }
  }
  /**
   * permet de recupérer les dernières infos d'absences lié à un utilisateur et de calculer les nb
   * de jours de congés/rtt restant
   *
   * @param utilisateur
   * @return
   * @throws AbsenceException
   */
  public SessionUtilisateur loadSessionUtilisateur(Long utilisateurId, Date dateAbsence)
      throws Exception {

    // date du jour
    Date now = new Date();
    now = DateUtils.truncate(now, Calendar.DATE);

    Utilisateur utilisateur = utilisateurRepository.findOne(utilisateurId);

    SessionUtilisateur session = new SessionUtilisateur();
    session.setUtilisateur(utilisateur);

    // recuperation des rtt de l'utilisateur sur la période liée à la date d'absence souhaitée
    List<DemandeAbsence> rtts =
        absenceRepository.findByUtilisateur(
            utilisateur.getId(),
            getDateDebutPeriodeRTT(dateAbsence),
            getDateFinPeriodeRTT(dateAbsence),
            TypeAbsence.RTT);

    // recuperation des conges de l'utilisateur sur la période liée à la date d'absence souhaitée
    List<DemandeAbsence> conges =
        absenceRepository.findByUtilisateur(
            utilisateur.getId(),
            getDateDebutPeriodeConges(dateAbsence),
            getDateFinPeriodeConges(dateAbsence),
            TypeAbsence.CONGE);

    // recuperation des conges de l'utilisateur sur la période liée à la date d'absence souhaitée
    List<DemandeAbsence> autresConges =
        absenceRepository.findByUtilisateur(
            utilisateur.getId(), now, DateUtils.addYears(now, 1), TypeAbsence.AUTRE);

    // init des compteurs par rapport aux infos utilisateurs (congés/RTT de l'année + deltas
    // éventuels)
    CompteurConges compteurs = new CompteurConges();
    session.setCompteurs(compteurs);
    compteurs.setCongesAposer(utilisateur.getNbConges());
    compteurs.setRttAposer(utilisateur.getNbRTT());

    // prise en compte des deltas si la date de l'absence se trouve dans la période courante
    if (isPeriodeCouranteConges(dateAbsence)) {
      compteurs.setCongesAposer(compteurs.getCongesAposer() + utilisateur.getDeltaJoursConges());
    }
    if (isPeriodeCouranteRTT(dateAbsence)) {
      compteurs.setRttAposer(compteurs.getRttAposer() + utilisateur.getDeltaJoursRTT());
    }

    // maj des compteurs par rapport à la liste des absences
    // TODO gérer les cas de 80%
    for (DemandeAbsence rtt : rtts) {
      if (!rtt.getStatut().equals(StatutAbsence.REFUSE)) {
        float nbJours = getNbJoursForAbsence(rtt);
        compteurs.setRttAposer(compteurs.getRttAposer() - nbJours);
        if (rtt.getStatut().equals(StatutAbsence.POSE)) {
          compteurs.setRttEnAttente(compteurs.getRttEnAttente() + nbJours);
        }
      }
      if (rtt.getDateDebut().after(now)) {
        session.getAbsences().add(rtt);
      }
    }

    for (DemandeAbsence conge : conges) {
      if (!conge.getStatut().equals(StatutAbsence.REFUSE)) {
        float nbJours = getNbJoursForAbsence(conge);
        compteurs.setCongesAposer(compteurs.getCongesAposer() - nbJours);
        if (conge.getStatut().equals(StatutAbsence.POSE)) {
          compteurs.setCongesEnAttente(compteurs.getCongesEnAttente() + nbJours);
        }
      }
      if (conge.getDateDebut().after(now)) {
        session.getAbsences().add(conge);
      }
    }

    for (DemandeAbsence conge : autresConges) {
      if (conge.getDateDebut().after(now)) {
        session.getAbsences().add(conge);
      }
    }

    Collections.sort(session.getAbsences());

    // ajout des absences sur la période suivante
    List<DemandeAbsence> rttFuturs =
        absenceRepository.findByUtilisateur(
            utilisateur.getId(),
            DateUtils.addDays(getDateFinPeriodeRTT(dateAbsence), 1),
            TypeAbsence.RTT);
    List<DemandeAbsence> congesFuturs =
        absenceRepository.findByUtilisateur(
            utilisateur.getId(),
            DateUtils.addDays(getDateFinPeriodeConges(dateAbsence), 1),
            TypeAbsence.CONGE);
    List<DemandeAbsence> autresCongesFuturs =
        absenceRepository.findByUtilisateur(
            utilisateur.getId(),
            DateUtils.addDays(getDateFinPeriodeConges(dateAbsence), 1),
            TypeAbsence.AUTRE);
    session.getAbsencesFutures().addAll(rttFuturs);
    session.getAbsencesFutures().addAll(congesFuturs);
    session.getAbsencesFutures().addAll(autresCongesFuturs);
    Collections.sort(session.getAbsencesFutures());

    return session;
  }
Example #17
0
 public boolean isPast() {
   Date currentDate = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
   return DateUtils.truncate(getEstablished(), Calendar.DAY_OF_MONTH).before(currentDate);
 }
 private Date getDateDebutPeriodeRTT(Date date) {
   // doit correspondre au 1 janvier de l'année courante
   return DateUtils.truncate(new Date(), Calendar.YEAR);
 }
Example #19
0
 public static Date stripTime(final Date date) {
   return DateUtils.truncate(date, Calendar.DAY_OF_MONTH);
 }
Example #20
0
 public static Date ignoreTime(Date date) throws Exception {
   return DateUtils.truncate(new Date(), DAY_OF_MONTH);
 }
  /**
   * permet de poser un nouvelle absence
   *
   * @throws AbsenceException
   */
  @Transactional
  public void poserAbsence(DemandeAbsence absence) throws Exception {

    absence.setStatut(StatutAbsence.POSE);

    // recuperation de l'objet utilisateur
    Utilisateur utilisateur = utilisateurRepository.findOne(absence.getUtilisateur().getId());
    absence.setUtilisateur(utilisateur);

    // verification des dates pour traiter le chevauchement de périodes pour les RTT
    if (absence.getType().equals(TypeAbsence.RTT)
        && isPeriodeCouranteRTT(absence.getDateDebut())
        && !isPeriodeCouranteRTT(absence.getDateFin())) {

      // division en 2 absences (1 par période)
      DemandeAbsence absencePeriodeCourante = absence.cloneAbsence();
      DemandeAbsence absencePeriodeSuivante = absence.cloneAbsence();
      absencePeriodeCourante.setDateFin(getDateFinPeriodeRTT(absence.getDateDebut()));
      absencePeriodeSuivante.setDateDebut(getDateDebutPeriodeRTT(absence.getDateFin()));

      poserAbsence(absencePeriodeSuivante);
      // return poserAbsence(absencePeriodeCourante);
    }

    // verification des dates pour traiter le chevauchement de périodes pour les Congés
    if ((absence.getType().equals(TypeAbsence.CONGE) || absence.getType().equals(TypeAbsence.AUTRE))
        && isPeriodeCouranteConges(absence.getDateDebut())
        && !isPeriodeCouranteConges(absence.getDateFin())) {

      // division en 2 absences (1 par période)
      DemandeAbsence absencePeriodeCourante = absence.cloneAbsence();
      DemandeAbsence absencePeriodeSuivante = absence.cloneAbsence();
      absencePeriodeCourante.setDateFin(getDateFinPeriodeConges(absence.getDateDebut()));
      absencePeriodeSuivante.setDateDebut(getDateDebutPeriodeConges(absence.getDateFin()));

      poserAbsence(absencePeriodeSuivante);
      // return poserAbsence(absencePeriodeCourante);
    }

    // date du jour
    Date now = new Date();
    now = DateUtils.truncate(now, Calendar.DATE);

    // recupération des infos utilisateur
    SessionUtilisateur session =
        loadSessionUtilisateur(absence.getUtilisateur().getId(), absence.getDateDebut());
    CompteurConges compteurs = session.getCompteurs();

    // verification des chevauchements de conges / rtt

    long valDebutTime = absence.getDateDebut().getTime();
    // on ajoute 12H si départ dans l'après midi (12 * 3600 * 1000)
    valDebutTime += (absence.getDebutPM()) ? 43200000 : 0;
    // permet de simplifier les comparaisons
    valDebutTime += 1;

    long valFinTime = DateUtils.addDays(absence.getDateFin(), 1).getTime();
    // on retire 12H si départ dans l'après midi (12 * 3600 * 1000)
    valFinTime -= (absence.getFinAM()) ? 43200000 : 0;
    valFinTime -= 1;

    List<DemandeAbsence> absencesPeriode =
        absenceRepository.findByUtilisateur(
            utilisateur.getId(), absence.getDateDebut(), absence.getDateFin());

    for (DemandeAbsence absencePeriode : absencesPeriode) {

      long tmpValDebutTime = absencePeriode.getDateDebut().getTime();
      tmpValDebutTime += (absencePeriode.getDebutPM()) ? 43200000 : 0;

      long tmpValFinTime = DateUtils.addDays(absencePeriode.getDateFin(), 1).getTime();
      tmpValFinTime -= (absencePeriode.getFinAM()) ? 43200000 : 0;

      if ((valDebutTime >= tmpValDebutTime && valDebutTime <= tmpValFinTime)
          || (valFinTime >= tmpValDebutTime && valFinTime <= tmpValFinTime)
          || (valDebutTime <= tmpValDebutTime && valFinTime >= tmpValFinTime)) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        throw new AbsenceException(
            "L'absence ne peut etre posee car elle se chevauche avec l'absence suivante "
                + "[ "
                + absencePeriode.getType()
                + " du "
                + sdf.format(absencePeriode.getDateDebut())
                + " au "
                + sdf.format(absencePeriode.getDateFin())
                + "]");
      }
    }

    // nombre de jours d'écart entre datedeb et dateFin
    float nbJours = getNbJoursForAbsence(absence);

    // cas des RTT
    if (absence.getType().equals(TypeAbsence.RTT)) {
      if (compteurs.getRttAposer() < nbJours) {
        throw new AbsenceException("Le nombre de RTT restants est insuffisant");
      }
    }

    // cas des Congés
    if (absence.getType().equals(TypeAbsence.CONGE)) {
      if (compteurs.getCongesAposer() < nbJours) {
        throw new AbsenceException("Le nombre de conges restants est insuffisant");
      }
    }

    // si date debut absence < date du jour
    if (absence.getDateDebut().before(now)
        || absence.getUtilisateur().getRole().equals(UserRole.responsable)) {
      // validation automatique
      absence.setStatut(StatutAbsence.VALIDE);
    }

    // sauvegarde de l'absence
    absenceRepository.saveAndFlush(absence);

    // envoi du mail au responsable
    if (!absence.getStatut().equals(StatutAbsence.VALIDE)) {
      mailService.notifierCreationAbsence(absence);
    }

    // création de l'événement dans la calendrier google
    sendToGoogleCalendar(utilisateur, absence, false);
  }
Example #22
0
  @Test
  public void set_issue_fields() {
    Date createdAt = DateUtils.addDays(new Date(), -5);
    Date updatedAt = DateUtils.addDays(new Date(), -3);
    Date closedAt = DateUtils.addDays(new Date(), -1);

    IssueDto dto =
        new IssueDto()
            .setKee("100")
            .setType(RuleType.VULNERABILITY)
            .setRuleId(1)
            .setRuleKey("squid", "AvoidCycle")
            .setLanguage("xoo")
            .setComponentKey("org.sonar.sample:Sample")
            .setComponentUuid("CDEF")
            .setProjectUuid("GHIJ")
            .setModuleUuid("BCDE")
            .setModuleUuidPath("ABCD.BCDE.")
            .setProjectKey("org.sonar.sample")
            .setStatus(Issue.STATUS_CLOSED)
            .setResolution(Issue.RESOLUTION_FALSE_POSITIVE)
            .setGap(15.0)
            .setEffort(10L)
            .setLine(6)
            .setSeverity("BLOCKER")
            .setMessage("message")
            .setManualSeverity(true)
            .setAssignee("perceval")
            .setIssueAttributes("key=value")
            .setAuthorLogin("pierre")
            .setIssueCreationDate(createdAt)
            .setIssueUpdateDate(updatedAt)
            .setIssueCloseDate(closedAt);

    DefaultIssue issue = dto.toDefaultIssue();
    assertThat(issue.key()).isEqualTo("100");
    assertThat(issue.type()).isEqualTo(RuleType.VULNERABILITY);
    assertThat(issue.ruleKey().toString()).isEqualTo("squid:AvoidCycle");
    assertThat(issue.language()).isEqualTo("xoo");
    assertThat(issue.componentUuid()).isEqualTo("CDEF");
    assertThat(issue.projectUuid()).isEqualTo("GHIJ");
    assertThat(issue.componentKey()).isEqualTo("org.sonar.sample:Sample");
    assertThat(issue.moduleUuid()).isEqualTo("BCDE");
    assertThat(issue.moduleUuidPath()).isEqualTo("ABCD.BCDE.");
    assertThat(issue.projectKey()).isEqualTo("org.sonar.sample");
    assertThat(issue.status()).isEqualTo(Issue.STATUS_CLOSED);
    assertThat(issue.resolution()).isEqualTo(Issue.RESOLUTION_FALSE_POSITIVE);
    assertThat(issue.gap()).isEqualTo(15.0);
    assertThat(issue.effort()).isEqualTo(Duration.create(10L));
    assertThat(issue.line()).isEqualTo(6);
    assertThat(issue.severity()).isEqualTo("BLOCKER");
    assertThat(issue.message()).isEqualTo("message");
    assertThat(issue.manualSeverity()).isTrue();
    assertThat(issue.assignee()).isEqualTo("perceval");
    assertThat(issue.attribute("key")).isEqualTo("value");
    assertThat(issue.authorLogin()).isEqualTo("pierre");
    assertThat(issue.creationDate()).isEqualTo(DateUtils.truncate(createdAt, Calendar.SECOND));
    assertThat(issue.updateDate()).isEqualTo(DateUtils.truncate(updatedAt, Calendar.SECOND));
    assertThat(issue.closeDate()).isEqualTo(DateUtils.truncate(closedAt, Calendar.SECOND));
    assertThat(issue.isNew()).isFalse();
  }