/**
   * Defines the magnitudes that can be added to the timestamp
   *
   * @param token token of form "[number][magnitude]" (ex. "1d")
   * @return integer indicating the magnitude of the date for the calendar system
   */
  public static ReadablePeriod getTimePeriod(String token) {
    String valString = token.substring(0, token.length() - 1);
    int value = Integer.parseInt(valString);
    char mag = token.charAt(token.length() - 1);

    ReadablePeriod period;

    switch (mag) {
      case 's':
        period = Seconds.seconds(value);
        break;
      case 'm':
        period = Minutes.minutes(value);
        break;
      case 'h':
        period = Hours.hours(value);
        break;
      case 'd':
        period = Days.days(value);
        break;
      case 'M':
        period = Months.months(value);
        break;
      case 'y':
        period = Years.years(value);
        break;
      default:
        logger.warn("Invalid date magnitude: {}. Defaulting to seconds.", mag);
        period = Seconds.seconds(value);
        break;
    }

    return period;
  }
Example #2
0
 /**
  * 计算两个日期之间的时间间隔(不计算毫秒数)
  *
  * @param date1,date2
  * @param timeType
  * @return int
  */
 public static int periodBtDate(Date date1, Date date2, TimeType timeType) {
   if (date1 == null || date2 == null) {
     throw new IllegalArgumentException("date param can not be null");
   }
   DateTime start = fromDate(date1);
   DateTime end = fromDate(date2);
   int period = 0;
   switch (timeType.getCode()) {
     case "Y":
       period = Years.yearsBetween(start, end).getYears();
       break;
     case "M":
       period = Months.monthsBetween(start, end).getMonths();
       break;
     case "W":
       period = Weeks.weeksBetween(start, end).getWeeks();
       break;
     case "D":
       period = Days.daysBetween(start, end).getDays();
       break;
     case "H":
       period = Hours.hoursBetween(start, end).getHours();
       break;
     case "MIN":
       period = Minutes.minutesBetween(start, end).getMinutes();
       break;
     case "S":
       period = Seconds.secondsBetween(start, end).getSeconds();
       break;
     default:
       break;
   }
   return Math.abs(period);
 }
Example #3
0
 // http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
 public static int getHoursBetween(final String date1, final String date2, String format) {
   try {
     final DateTimeFormatter fmt =
         DateTimeFormat.forPattern(format)
             .withChronology(LenientChronology.getInstance(GregorianChronology.getInstance()));
     return Hours.hoursBetween(fmt.parseDateTime(date1), fmt.parseDateTime(date2)).getHours();
   } catch (Exception ex) {
     ex.printStackTrace();
     return 0;
   }
 }
Example #4
0
 /**
  * 求两个直接的日期差,月份.
  *
  * @param tDate
  * @param txDate
  * @param type 选择 DAYS||MONTHS||YEARS||HOURS||MSECONDS||MINUTES||SECONDS
  * @return
  */
 public static int diff(Date tDate, Date txDate, String type) {
   if (txDate != null && tDate != null) {
     DateTime txDT = new DateTime(txDate);
     DateTime tDT = new DateTime(tDate);
     if (type != null) {
       if (type.toUpperCase().endsWith("DAYS") || type.toUpperCase().endsWith("D")) {
         return Days.daysBetween(txDT, tDT).getDays();
       } else if (type.toUpperCase().endsWith("MONTHS")) {
         return Months.monthsBetween(txDT, tDT).getMonths();
       } else if (type.toUpperCase().endsWith("YEARS") || type.toUpperCase().endsWith("Y")) {
         return Years.yearsBetween(txDT, tDT).getYears();
       } else if (type.toUpperCase().endsWith("HOURS") || type.toUpperCase().endsWith("H")) {
         return Hours.hoursBetween(txDT, tDT).getHours();
       } else if (type.toUpperCase().endsWith("MSECONDS")) {
         return Seconds.secondsBetween(txDT, tDT).getSeconds();
       } else if (type.toUpperCase().endsWith("MINUTES")) {
         return Minutes.minutesBetween(txDT, tDT).getMinutes();
       } else if (type.toUpperCase().endsWith("SECONDS") || type.toUpperCase().endsWith("S")) {
         return Seconds.secondsBetween(txDT, tDT).getSeconds();
       }
     }
   }
   return 0;
 }
  void drawTimeLine() {

    // draw the base timeline

    int minorTickHeight = (int) (20 * scaleFactorY);
    int majorTickHeight = (int) (40 * scaleFactorY);
    parent.strokeWeight(10);
    parent.stroke(0);
    parent.line(lineStart, lineY, lineStop, lineY);
    // draw days
    // int maxDays = Days.daysBetween(timelineStartDate,
    // timelineEndDate).getDays();
    int maxHours = Hours.hoursBetween(timelineStartDate, timelineEndDate).getHours();
    // println("Interval  is " + fullTimeInterval);
    // println("Period is " + Days.daysBetween(minDate, maxDate).getDays());
    // println("Max days is " + maxDays);

    DateTime tempdt = new DateTime(timelineStartDate);
    String previousMonth = timelineStartDate.monthOfYear().getAsText();
    int previousDay = -1; // =tempdt.dayOfYear().get();
    int monthStart = lineStart;
    parent.textAlign(PConstants.CENTER, PConstants.TOP);

    for (int a = 0; a < maxHours; a++) {
      // println(a);
      parent.textAlign(PConstants.CENTER, PConstants.TOP);
      // draw label
      parent.textFont(parent.font);
      parent.textSize(10 * fontScale);

      if (tempdt.dayOfYear().get() != previousDay) {
        int tx = (int) (PApplet.map(a, 0, maxHours, lineStart, lineStop));
        // draw tick
        parent.strokeWeight(1);
        parent.line(tx, lineY, tx, lineY + minorTickHeight);
        previousDay = tempdt.dayOfYear().get();
        parent.fill(0);
        if (tempdt.dayOfMonth().get() == 1) {
          // special case!
          parent.textSize(14 * fontScale);
          parent.text(
              tempdt.dayOfMonth().getAsString(),
              tx,
              lineY + majorTickHeight + parent.textDescent());
        } else {
          parent.text(
              tempdt.dayOfMonth().getAsString(),
              tx,
              lineY + minorTickHeight + parent.textDescent());
        }

        // check if need to draw monthName
        if (!previousMonth.equals(tempdt.monthOfYear().getAsText())) {
          // draw some visual markers!
          // line(monthStart, lineY, monthStart,
          // lineY+majorTickHeight);
          parent.line(tx, lineY, tx, lineY + majorTickHeight);
          // position halfway between monthStart and tx, draw
          // monthname
          parent.textSize(18 * fontScale);
          // check! do we overlap the next month? if so, change
          // alignment
          if (parent.textWidth(previousMonth) / 2 + monthStart > tx) {
            parent.textAlign(PConstants.RIGHT, PConstants.TOP);
          }
          parent.text(
              previousMonth,
              (tx + monthStart) / 2,
              lineY + minorTickHeight + 2 * (parent.textAscent() + parent.textDescent()));
          previousMonth = tempdt.monthOfYear().getAsText();
          monthStart = tx;
        }
      }
      tempdt = tempdt.plus(Period.hours(1));
    }
    // draw final day
    parent.line(lineStop, lineY, lineStop, lineY + minorTickHeight);
    if (tempdt.dayOfMonth().get() == 1) {
      // special case!
      parent.text(
          tempdt.dayOfMonth().getAsString(),
          lineStop,
          lineY + majorTickHeight + parent.textDescent());
    } else {
      parent.text(
          tempdt.dayOfMonth().getAsString(),
          lineStop,
          lineY + minorTickHeight + parent.textDescent());
    }
    // draw final month!
    parent.textSize(18 * fontScale);
    parent.text(
        tempdt.monthOfYear().getAsText(),
        (lineStop + monthStart) / 2,
        lineY + minorTickHeight + 2 * (parent.textAscent() + parent.textDescent()));
  }
  public String perform(HttpServletRequest request) {
    HttpSession session = request.getSession();

    // If the user is not logged in, redirect to login screen
    User currUser = (User) session.getAttribute("user");
    if (currUser == null) {
      return "login.do";
    }

    List<String> errors = new ArrayList<String>();
    request.setAttribute("errors", errors);

    try {
      UpdateProviderForm form = formBeanFactory.create(request);

      Provider provider = providerDAO.read(Integer.parseInt(form.getProviderIdAsString()));

      if (provider == null) {
        errors.add(
            "ProviderId: "
                + form.getProviderIdAsString()
                + ", Zipcode: "
                + currUser.getZipcode()
                + ". Invalid provider selected (not in database)");
        return "error.jsp";
      } else {
        currUser.setProviderId(provider.getId());
      }

      DateTime lastSync = new DateTime(provider.getLastSync());
      DateTime now = new DateTime();

      int hours = Hours.hoursBetween(lastSync, now).getHours();
      if (hours >= 24) {
        File tempDir =
            (File) request.getServletContext().getAttribute("javax.servlet.context.tempdir");
        String contextPath = request.getServletContext().getRealPath("/");

        int hoursFromNow = Math.max(7 * 24 - hours, 0);
        int hoursDuration = Math.min(hours, 7 * 24);

        DatabaseSync.syncAirings(
            model,
            tempDir,
            contextPath,
            provider.getZipcode(),
            provider.getName(),
            hoursFromNow,
            24);

        /*
        int i;
        for (i = 0; i < hoursDuration - 24; i += 24) {
            DatabaseSync.syncAirings(model,
                                     tempDir,
                                     contextPath,
                                     provider.getZipcode(),
                                     provider.getName(),
                                     hoursFromNow + i,
                                     24);
        }

        DatabaseSync.syncAirings(model,
                                    tempDir,
                                    contextPath,
                                    provider.getZipcode(),
                                    provider.getName(),
                                    hoursFromNow + i,
                                    hoursDuration - i);
                                    */
      }

      userDAO.update(currUser);

      return "profile.do";
    } catch (Exception e) {
      errors.add(e.getClass().getName() + ": " + e.getMessage());
      return "error.jsp";
    }
  }
Example #7
0
  public FormRequest handle(RequestDetails request, String requestId) throws StatusCodeError {
    FormRequest formRequest = requestRepository.findOne(requestId);

    if (formRequest == null) {
      return null;
    }

    if (request != null) {
      if (request.getRemoteUser() != null
          && formRequest.getRemoteUser() != null
          && !request.getRemoteUser().equals(formRequest.getRemoteUser())) {
        LOG.error(
            "Wrong user viewing or submitting form: "
                + request.getRemoteUser()
                + " not "
                + formRequest.getRemoteUser());
        throw new ForbiddenError(Constants.ExceptionCodes.user_does_not_match);
      }

      if (request.getRemoteHost() != null
          && formRequest.getRemoteHost() != null
          && !request.getRemoteHost().equals(formRequest.getRemoteHost()))
        LOG.warn(
            "This should not happen -- submission remote host ("
                + request.getRemoteHost()
                + ") does not match request ("
                + formRequest.getRemoteHost()
                + ")");

      if (request.getRemoteAddr() != null
          && formRequest.getRemoteAddr() != null
          && !request.getRemoteAddr().equals(formRequest.getRemoteAddr()))
        LOG.warn(
            "This should not happen -- submission remote address ("
                + request.getRemoteAddr()
                + ") does not match request ("
                + formRequest.getRemoteAddr()
                + ")");

      if (formRequest.getCertificateIssuer() != null
          && formRequest.getCertificateSubject() != null) {
        String certificateIssuer = request.getCertificateIssuer();
        String certificateSubject = request.getCertificateSubject();

        if (StringUtils.isEmpty(certificateIssuer)
            || StringUtils.isEmpty(certificateSubject)
            || !certificateIssuer.equals(formRequest.getCertificateIssuer())
            || !certificateSubject.equals(formRequest.getCertificateSubject())) {
          LOG.error(
              "Wrong certificate submitting form: "
                  + certificateIssuer
                  + ":"
                  + certificateSubject
                  + " not "
                  + formRequest.getCertificateIssuer()
                  + ":"
                  + formRequest.getCertificateSubject());
          throw new ForbiddenError(Constants.ExceptionCodes.certificate_does_not_match);
        }
      }

      if (formRequest.getRequestDate() != null) {
        Hours hours =
            Hours.hoursBetween(new DateTime(formRequest.getRequestDate()), new DateTime());
        int h = hours.getHours();
        if (h > 1) {
          throw new ForbiddenError(Constants.ExceptionCodes.request_expired);
        }
      }
    }

    ProcessInstance instance = formRequest.getInstance();

    if (instance == null
        && StringUtils.isNotEmpty(formRequest.getProcessDefinitionKey())
        && StringUtils.isNotEmpty(formRequest.getProcessInstanceId()))
      instance =
          processInstanceService.read(
              formRequest.getProcessDefinitionKey(), formRequest.getProcessInstanceId(), false);

    FormRequest.Builder builder =
        new FormRequest.Builder(formRequest)
            .instance(instance)
            .task(taskService.read(instance, formRequest.getTaskId()));

    return builder.build();
  }