예제 #1
0
파일: DateTest.java 프로젝트: djbone/j2objc
 /** @tests java.util.Date#after(java.util.Date) */
 public void test_afterLjava_util_Date() {
   // Test for method boolean java.util.Date.after(java.util.Date)
   Date d1 = new Date(0);
   Date d2 = new Date(1900000);
   assertTrue("Older was returned as newer", d2.after(d1));
   assertTrue("Newer was returned as older", !d1.after(d2));
 }
  @Override
  @Transactional
  public VisitDomainWrapper createRetrospectiveVisit(
      Patient patient, Location location, Date startDatetime, Date stopDatetime)
      throws ExistingVisitDuringTimePeriodException {

    if (startDatetime.after(new Date())) {
      throw new IllegalArgumentException("emrapi.retrospectiveVisit.startDateCannotBeInFuture");
    }

    if (stopDatetime.after(new Date())) {
      throw new IllegalArgumentException("emrapi.retrospectiveVisit.stopDateCannotBeInFuture");
    }

    if (startDatetime.after(stopDatetime)) {
      throw new IllegalArgumentException("emrapi.retrospectiveVisit.endDateBeforeStartDateMessage");
    }

    if (hasVisitDuring(patient, location, startDatetime, stopDatetime)) {
      throw new ExistingVisitDuringTimePeriodException(
          "emrapi.retrospectiveVisit.patientAlreadyHasVisit");
    }

    Visit visit = buildVisit(patient, location, startDatetime);
    visit.setStopDatetime(stopDatetime);

    return wrap(visitService.saveVisit(visit));
  }
 // See one project
 @RequestMapping(value = "viewproject", method = RequestMethod.GET)
 public ModelAndView viewproject(Integer id) throws Exception {
   ModelAndView mav = new ModelAndView();
   ProjectWrapper pw = projectDao.getProjectWrapperById(id);
   mav.addObject("pw", pw);
   Date now = new Date();
   DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
   if (!pw.getProject().getEndDate().trim().equals("")) {
     boolean expired = now.after(df.parse(pw.getProject().getEndDate()));
     mav.addObject("expired", expired);
   }
   for (RPLink r : pw.getRpLinks()) {
     if (!r.getResearcher().getEndDate().trim().equals("")) {
       if (now.after(df.parse(r.getResearcher().getEndDate()))) {
         r.getResearcher().setFullName(r.getResearcher().getFullName() + " (expired)");
       }
     }
   }
   for (APLink a : pw.getApLinks()) {
     if (a.getAdviser().getEndDate() != null && !a.getAdviser().getEndDate().trim().equals("")) {
       if (now.after(df.parse(a.getAdviser().getEndDate()))) {
         a.getAdviser().setFullName(a.getAdviser().getFullName() + " (expired)");
       }
     }
   }
   mav.addObject("jobauditBaseProjectUrl", this.jobauditBaseProjectUrl);
   return mav;
 }
예제 #4
0
 private void validateDateActivated(Order order, Errors errors) {
   Date dateActivated = order.getDateActivated();
   if (dateActivated != null) {
     if (dateActivated.after(new Date())) {
       errors.rejectValue("dateActivated", "Order.error.dateActivatedInFuture");
       return;
     }
     Date dateStopped = order.getDateStopped();
     if (dateStopped != null && dateActivated.after(dateStopped)) {
       errors.rejectValue("dateActivated", "Order.error.dateActivatedAfterDiscontinuedDate");
       errors.rejectValue("dateStopped", "Order.error.dateActivatedAfterDiscontinuedDate");
     }
     Date autoExpireDate = order.getAutoExpireDate();
     if (autoExpireDate != null && dateActivated.after(autoExpireDate)) {
       errors.rejectValue("dateActivated", "Order.error.dateActivatedAfterAutoExpireDate");
       errors.rejectValue("autoExpireDate", "Order.error.dateActivatedAfterAutoExpireDate");
     }
     Encounter encounter = order.getEncounter();
     if (encounter != null
         && encounter.getEncounterDatetime() != null
         && encounter.getEncounterDatetime().after(dateActivated)) {
       errors.rejectValue("dateActivated", "Order.error.dateActivatedAfterEncounterDatetime");
     }
   }
 }
예제 #5
0
  public static List<Vehicule> getAvailableVehiculesByAgence(
      Date startDate, Date endDate, Agence agence) {
    List<Vehicule> listVehiculesByAgence = Vehicule.getVehiculesByAgence(agence);
    List<Vehicule> listAvailableVehicules = new ArrayList<Vehicule>();
    List<Session> listSessionsByAgence = Session.getSessionsByAgence(agence);
    List<Revision> listRevisionsByVehicule;
    Calendar calendar = new GregorianCalendar();
    Date startRevision;
    Date endRevision;

    for (Vehicule vehicule : listVehiculesByAgence) {
      boolean isAvailable = true;
      listRevisionsByVehicule = Revision.getRevisionsByVehicule(vehicule);
      for (Revision revision : listRevisionsByVehicule) {
        startRevision = revision.date;
        calendar.setTime(revision.date);
        calendar.add(Calendar.DATE, 7);
        endRevision = calendar.getTime();

        if (startDate.equals(startRevision)
            || endDate.equals(startRevision)
            || startDate.equals(endRevision)
            || endDate.equals(endRevision)
            || (startDate.after(startRevision) && startDate.before(endRevision))
            || (endDate.after(startRevision) && endDate.before(endRevision))) {

          isAvailable = false;
        }
      }

      if (isAvailable) {
        for (Session session : listSessionsByAgence) {
          if (startDate.equals(session.dateDepart)
              || endDate.equals(session.dateDepart)
              || startDate.equals(session.dateFin)
              || endDate.equals(session.dateFin)
              || (startDate.after(session.dateDepart) && startDate.before(session.dateFin))
              || (endDate.after(session.dateDepart) && endDate.before(session.dateFin))) {
            if (session.vehicule.id == vehicule.id) {
              isAvailable = false;
            }
          }
        }
      }

      if (isAvailable) {
        listAvailableVehicules.add(vehicule);
      }
    }

    return listAvailableVehicules;
  }
예제 #6
0
 public boolean isBetween(final Date from, final Date to) {
   final Date date = getDate();
   if (from == null) {
     if (to == null) {
       return false;
     }
     return date.after(to) == false;
   }
   if (to == null) {
     return date.before(from) == false;
   }
   return !(date.after(to) == true || date.before(from) == true);
 }
예제 #7
0
  private Vector<Properties> spTimeCheck(Properties time1, Properties time2) {
    Vector<Properties> vec = new Vector<Properties>();

    String time1Start = time1.getProperty("stime");
    String time1End = time1.getProperty("etime");
    String time2Start = time2.getProperty("stime");
    String time2End = time2.getProperty("etime");

    Calendar cal = new GregorianCalendar();
    SimpleDateFormat df = new SimpleDateFormat("HH:mm");

    Date startTime1 = df.parse(time1Start, new ParsePosition(0));
    Date endTime1 = df.parse(time1End, new ParsePosition(0));
    Date startTime2 = df.parse(time2Start, new ParsePosition(0));
    Date endTime2 = df.parse(time2End, new ParsePosition(0));

    if ((startTime2.after(startTime1) && startTime2.before(endTime1))
        || (endTime2.after(startTime1) && endTime2.before(endTime1))
        || (startTime1.after(startTime2) && startTime1.before(endTime2))
        || (endTime1.after(startTime2) && endTime1.before(endTime2))
        || startTime1.equals(startTime2)
        || endTime1.equals(endTime2)
        || startTime1.equals(endTime2)
        || endTime1.equals(startTime2)) {
      String stime = null;
      String etime = null;

      if (startTime2.after(startTime1)) {
        stime = time1Start;
      } else {
        stime = time2Start;
      }

      if (endTime2.before(endTime1)) {
        etime = time1End;
      } else {
        etime = time2End;
      }

      Properties time3 = new Properties();
      time3.setProperty("stime", stime);
      time3.setProperty("etime", etime);

      vec.add(time3);

    } else {
      vec.add(time1);
      vec.add(time2);
    }
    return vec;
  }
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode != PublicIntent.REQUESTCODE_SAVE_BACK
        && requestCode != PublicIntent.REQUESTCODE_DECRYPTED) {
      return;
    }

    final File dlFile = localFile;

    if (dlFile == null) {
      return;
    }

    long datetime = dlFile.lastModified();
    Date d = new Date(datetime);
    boolean modified = false;
    final Uri lUri = favoriteUri;

    switch (requestCode) {
      case PublicIntent.REQUESTCODE_SAVE_BACK:
        modified = (d != null && downloadDateTime != null) ? d.after(downloadDateTime) : false;

        if (modified) {
          // Update to Pending
          ContentValues cValues = new ContentValues();
          cValues.put(SynchroSchema.COLUMN_STATUS, Operation.STATUS_PENDING);
          getActivity().getContentResolver().update(lUri, cValues, null, null);

          // Start sync if possible
          if (SynchroManager.getInstance(getActivity()).canSync(acc)) {
            SynchroManager.getInstance(getActivity()).sync(acc);
          }
        }
        break;
      case PublicIntent.REQUESTCODE_DECRYPTED:
        modified = (d != null && decryptDateTime != null) ? d.after(decryptDateTime) : false;
        if (modified) {
          // If modified by user, we flag the uri
          // The next sync will update the content.
          ContentValues cValues = new ContentValues();
          cValues.put(SynchroSchema.COLUMN_STATUS, SyncOperation.STATUS_MODIFIED);
          getActivity().getContentResolver().update(lUri, cValues, null, null);
        }

        DataProtectionManager.getInstance(getActivity()).checkEncrypt(acc, dlFile);

        break;
      default:
        break;
    }
  }
 public List<Reservation> findActiveByPeriod(Date start, Date end) {
   List<Reservation> reservationsList = new ArrayList<>();
   for (Reservation reservation : storage.values()) {
     Date arrivalDate = reservation.getArrivalDateTime();
     Date departureDate = reservation.getDepartureDateTime();
     if (reservation.isActive()
         && ((arrivalDate.after(start) && arrivalDate.before(end))
             || (departureDate.after(start) && departureDate.before(end))
             || (arrivalDate.before(start) && departureDate.after(end)))) {
       reservationsList.add(reservation);
     }
   }
   return reservationsList;
 }
  protected boolean doRedirectToLoginPage(
      ServerManager manager, ParameterList requestParameters, IWContext iwc, String realm) {
    boolean goToLogin = true;
    // Log user out if this is an authentication request for a new association
    // (i.e. another Relying Party or an expired association) or if this is a new request
    // after a completed successful one (loginExpireTime is removed on successful login)
    String loginExpireHandle =
        requestParameters.hasParameter(OpenIDConstants.PARAMETER_ASSOCIATE_HANDLE)
            ? "openid-login-"
                + requestParameters.getParameterValue(OpenIDConstants.PARAMETER_ASSOCIATE_HANDLE)
            : null;
    Date currentTime = new Date();
    if (loginExpireHandle == null) {
      String simpleRegHandle = "openid-simpleRegHandle-" + realm;
      Date loginExpirationTime = (Date) iwc.getSessionAttribute(simpleRegHandle);

      if (loginExpirationTime == null || currentTime.after(loginExpirationTime)) {
        if (iwc.isLoggedOn()) {
          // Make user log in again
          LoginBusinessBean loginBusiness = getLoginBusiness(iwc.getRequest());
          loginBusiness.logOutUser(iwc);
        }
        int expireInMilliSeconds = manager.getExpireIn() * 1000;
        iwc.setSessionAttribute(
            simpleRegHandle, new Date(currentTime.getTime() + expireInMilliSeconds));
        goToLogin = true;
      } else {
        // coming here again in the same request/association
        goToLogin = !iwc.isLoggedOn();
      }
    } else {
      Date loginExpirationTime = (Date) iwc.getSessionAttribute(loginExpireHandle);

      if (loginExpirationTime == null || currentTime.after(loginExpirationTime)) {
        if (iwc.isLoggedOn()) {
          // Make user log in again
          LoginBusinessBean loginBusiness = getLoginBusiness(iwc.getRequest());
          loginBusiness.logOutUser(iwc);
        }
        int expireInMilliSeconds = manager.getExpireIn() * 1000;
        iwc.setSessionAttribute(
            loginExpireHandle, new Date(currentTime.getTime() + expireInMilliSeconds));
        goToLogin = true;
      } else {
        // coming here again in the same request/association
        goToLogin = !iwc.isLoggedOn();
      }
    }
    return goToLogin;
  }
예제 #11
0
  public boolean isactive(Date atThisDate) {
    if (atThisDate == null) atThisDate = new Date();

    if (start_time == null) {
      return false;
    }

    Date fur = new Date(start_time.getTime() + duration * 60000);
    boolean boo = fur.after(atThisDate);
    if (fur.after(atThisDate)) {
      return true;
    } else {
      return false;
    }
  }
  /**
   * Validates the given Encounter. Currently checks if the patient has been set and also ensures
   * that the patient for an encounter and the visit it is associated to if any, are the same.
   *
   * @param obj The encounter to validate.
   * @param errors Errors
   * @see org.springframework.validation.Validator#validate(java.lang.Object,
   *     org.springframework.validation.Errors)
   * @should fail if the patients for the visit and the encounter dont match
   * @should fail if patient is not set
   * @should fail if encounter dateTime is after current dateTime
   * @should fail if encounter dateTime is before visit startDateTime
   * @should fail if encounter dateTime is after visit stopDateTime
   */
  public void validate(Object obj, Errors errors) throws APIException {
    if (log.isDebugEnabled()) {
      log.debug(this.getClass().getName() + ".validate...");
    }

    if (obj == null || !(obj instanceof Encounter)) {
      throw new IllegalArgumentException(
          "The parameter obj should not be null and must be of type " + Encounter.class);
    }

    Encounter encounter = (Encounter) obj;

    ValidationUtils.rejectIfEmpty(
        errors, "patient", "Encounter.error.patient.required", "Patient is required");
    if (encounter.getVisit() != null
        && !ObjectUtils.equals(encounter.getVisit().getPatient(), encounter.getPatient())) {
      errors.rejectValue(
          "visit",
          "Encounter.visit.patients.dontMatch",
          "The patient for the encounter and visit should be the same");
    }

    Date encounterDateTime = encounter.getEncounterDatetime();

    if (encounterDateTime != null && encounterDateTime.after(new Date())) {
      errors.rejectValue(
          "encounterDatetime",
          "Encounter.datetimeShouldBeBeforeCurrent",
          "The encounter datetime should be before the current date.");
    }

    Visit visit = encounter.getVisit();
    if (visit != null && encounterDateTime != null) {
      if (visit.getStartDatetime() != null && encounterDateTime.before(visit.getStartDatetime())) {
        errors.rejectValue(
            "encounterDatetime",
            "Encounter.datetimeShouldBeInVisitDatesRange",
            "The encounter datetime should be between the visit start and stop dates.");
      }

      if (visit.getStopDatetime() != null && encounterDateTime.after(visit.getStopDatetime())) {
        errors.rejectValue(
            "encounterDatetime",
            "Encounter.datetimeShouldBeInVisitDatesRange",
            "The encounter datetime should be between the visit start and stop dates.");
      }
    }
  }
  @SuppressWarnings("deprecation")
  @Override
  protected ModelAndView onSubmit(
      HttpServletRequest request,
      HttpServletResponse response,
      Object command,
      BindException errors)
      throws Exception {

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("command", command);

    EditPublishingCommand publishCommand = (EditPublishingCommand) command;
    if (publishCommand.getUpdateAction() != null) {

      Date publishDate = null;
      if (publishCommand.getPublishDateValue() != null) {
        publishDate = publishCommand.getPublishDateValue().getDateValue();
        setPropertyDateValue(publishDatePropDef, publishDate);
      } else {
        removePropertyValue(publishDatePropDef);
      }

      Date unpublishDate = null;
      if (publishCommand.getUnpublishDateValue() != null) {
        unpublishDate = publishCommand.getUnpublishDateValue().getDateValue();
        if (publishDate != null && unpublishDate.after(publishDate)) {
          setPropertyDateValue(unpublishDatePropDef, unpublishDate);
        }
      } else {
        removePropertyValue(unpublishDatePropDef);
      }
    }
    return new ModelAndView(getSuccessView(), model);
  }
예제 #14
0
 @Override
 public int compareTo(TweetSlideEvent lEntry) {
   try {
     Date dateLEntry =
         new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH)
             .parse(lEntry.createdAt);
     Date dateREntry =
         new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH).parse(createdAt);
     if (dateLEntry.before(dateREntry)) {
       return -1;
     } else if (dateLEntry.after(dateREntry)) {
       return 1;
     } else {
       if (lEntry.id < id) {
         return -1;
       } else if (lEntry.id > id) {
         return 1;
       } else {
         if (lEntry.userId < userId) {
           return -1;
         } else if (lEntry.userId > userId) {
           return 1;
         }
       }
     }
   } catch (ParseException e) {
     logger.error("Error when comparing", e);
   }
   return 0;
 }
예제 #15
0
파일: Bot.java 프로젝트: dims12/program-ab
  /**
   * Constructor
   *
   * @param name name of bot
   * @param path root path of Program AB
   * @param action Program AB action
   */
  public Bot(String name, String path, String action) {
    int cnt = 0;
    int elementCnt = 0;
    this.name = name;
    setAllPaths(path, name);
    this.brain = new Graphmaster(this);

    this.learnfGraph = new Graphmaster(this, "learnf");
    this.learnGraph = new Graphmaster(this, "learn");
    //      this.unfinishedGraph = new Graphmaster(this);
    //  this.categories = new ArrayList<Category>();

    preProcessor = new PreProcessor(this);
    addProperties();
    cnt = addAIMLSets();
    if (MagicBooleans.trace_mode) System.out.println("Loaded " + cnt + " set elements.");
    cnt = addAIMLMaps();
    if (MagicBooleans.trace_mode) System.out.println("Loaded " + cnt + " map elements");
    this.pronounSet = getPronouns();
    AIMLSet number = new AIMLSet(MagicStrings.natural_number_set_name, this);
    setMap.put(MagicStrings.natural_number_set_name, number);
    AIMLMap successor = new AIMLMap(MagicStrings.map_successor, this);
    mapMap.put(MagicStrings.map_successor, successor);
    AIMLMap predecessor = new AIMLMap(MagicStrings.map_predecessor, this);
    mapMap.put(MagicStrings.map_predecessor, predecessor);
    AIMLMap singular = new AIMLMap(MagicStrings.map_singular, this);
    mapMap.put(MagicStrings.map_singular, singular);
    AIMLMap plural = new AIMLMap(MagicStrings.map_plural, this);
    mapMap.put(MagicStrings.map_plural, plural);
    // System.out.println("setMap = "+setMap);
    Date aimlDate = new Date(new File(aiml_path).lastModified());
    Date aimlIFDate = new Date(new File(aimlif_path).lastModified());
    if (MagicBooleans.trace_mode)
      System.out.println("AIML modified " + aimlDate + " AIMLIF modified " + aimlIFDate);
    // readUnfinishedIFCategories();
    MagicStrings.pannous_api_key = Utilities.getPannousAPIKey(this);
    MagicStrings.pannous_login = Utilities.getPannousLogin(this);
    if (action.equals("aiml2csv")) addCategoriesFromAIML();
    else if (action.equals("csv2aiml")) addCategoriesFromAIMLIF();
    else if (action.equals("chat-app")) {
      if (MagicBooleans.trace_mode) System.out.println("Loading only AIMLIF files");
      cnt = addCategoriesFromAIMLIF();
    } else if (aimlDate.after(aimlIFDate)) {
      if (MagicBooleans.trace_mode) System.out.println("AIML modified after AIMLIF");
      cnt = addCategoriesFromAIML();
      writeAIMLIFFiles();
    } else {
      addCategoriesFromAIMLIF();
      if (brain.getCategories().size() == 0) {
        System.out.println("No AIMLIF Files found.  Looking for AIML");
        cnt = addCategoriesFromAIML();
      }
    }
    Category b =
        new Category(
            0, "PROGRAM VERSION", "*", "*", MagicStrings.program_name_version, "update.aiml");
    brain.addCategory(b);
    brain.nodeStats();
    learnfGraph.nodeStats();
  }
예제 #16
0
 public boolean hasExpired() {
   if (expires == null) {
     return false;
   }
   Date now = new Date();
   return now.after(expires);
 }
예제 #17
0
  private double calculatePriceProgress() {
    Price price = new Price();

    price.setEntityid(propertyId);

    ArrayList<Price> prices = sqlSession.getMapper(PriceMapper.class).readByEntityId(price);

    int numDaysAhead = 0;

    if (!prices.isEmpty()) {
      Date earliestDate = prices.get(0).getDate();
      Date latestDate = prices.get(0).getTodate();

      for (int i = 1; i < prices.size(); i++) {
        Date fromDate = prices.get(i).getDate();
        Date toDate = prices.get(i).getTodate();

        /* Determine earliest date*/
        if (fromDate.before(earliestDate)) {
          earliestDate = fromDate;
        }

        /* Determine latest date*/
        if (toDate.after(latestDate)) {
          latestDate = toDate;
        }
      }

      numDaysAhead = Model.getDuration(earliestDate, latestDate);
    }

    double progress = numDaysAhead < 180 ? numDaysAhead * 100.0 / 180.0 : 100.0;

    return progress * priceWeightage;
  }
예제 #18
0
  /**
   * 计算两个日期(不包括时间)之间相差的周年数
   *
   * @param date1
   * @param date2
   * @return
   */
  public static int getYearDiff(Date date1, Date date2) {
    if (date1 == null || date2 == null) {
      throw new InvalidParameterException("date1 and date2 cannot be null!");
    }
    if (date1.after(date2)) {
      throw new InvalidParameterException("date1 cannot be after date2!");
    }

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date1);
    int year1 = calendar.get(Calendar.YEAR);
    int month1 = calendar.get(Calendar.MONTH);
    int day1 = calendar.get(Calendar.DATE);

    calendar.setTime(date2);
    int year2 = calendar.get(Calendar.YEAR);
    int month2 = calendar.get(Calendar.MONTH);
    int day2 = calendar.get(Calendar.DATE);

    int result = year2 - year1;
    if (month2 < month1) {
      result--;
    } else if (month2 == month1 && day2 < day1) {
      result--;
    }
    return result;
  }
예제 #19
0
  @ResponseBody
  @RequestMapping("doneDBRepay")
  public JSONObject doneDBRepayManage(
      RepayPlanQueryOrder queryOrder, PageParam pageParam, Model model) throws Exception {
    JSONObject jsonObject = new JSONObject();
    queryOrder.setPageSize(pageParam.getPageSize());
    queryOrder.setPageNumber(pageParam.getPageNo());
    List<String> status = new ArrayList<String>(1);
    status.add(RepayPlanStatusEnum.REPAY_SUCCESS.getCode());
    queryOrder.setGuaranteeId(getGuaranteeUserId());
    queryOrder.setStatusList(status);
    QueryBaseBatchResult<RepayPlanInfo> queryBaseBatchResult =
        repayPlanService.queryRepayPlanInfoGuarantee(queryOrder);
    Map<String, String> map = new HashMap<String, String>();
    List<RepayPlanInfo> recordList = queryBaseBatchResult.getPageList();
    if (ListUtil.isNotEmpty(recordList)) {
      for (RepayPlanInfo item : recordList) {
        Date date = new Date();
        if (date.after(item.getRepayDate())) {
          item.setCanPay("Y");
          getTradeLoanDemandId(map, item.getTradeId());
        }
      }
    }

    jsonObject.put("map", map);
    jsonObject.put("page", PageUtil.getCovertPage(queryBaseBatchResult));
    jsonObject.put("queryConditions", queryOrder);
    return jsonObject;
  }
  private void viewReport() throws Exception {
    Date fromDate = fromDatePicker.getDate();
    Date toDate = toDatePicker.getDate();

    if (fromDate.after(toDate)) {
      POSMessageDialog.showError(
          BackOfficeWindow.getInstance(),
          com.floreantpos.POSConstants.FROM_DATE_CANNOT_BE_GREATER_THAN_TO_DATE_);
      return;
    }

    fromDate = DateUtil.startOfDay(fromDate);
    toDate = DateUtil.endOfDay(toDate);

    ReportService reportService = new ReportService();
    MenuUsageReport report = reportService.getMenuUsageReport(fromDate, toDate);

    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("reportTitle", "========= LAPORAN PENJUALAN PER MENU ==========");
    map.put("fromDate", ReportService.formatShortDate(fromDate));
    map.put("toDate", ReportService.formatShortDate(toDate));
    map.put("reportTime", ReportService.formatFullDate(new Date()));

    JasperReport jasperReport =
        (JasperReport)
            JRLoader.loadObject(
                getClass().getResource("/com/floreantpos/ui/report/menu_usage_report.jasper"));
    JasperPrint jasperPrint =
        JasperFillManager.fillReport(
            jasperReport, map, new JRTableModelDataSource(report.getTableModel()));
    JRViewer viewer = new JRViewer(jasperPrint);
    reportContainer.removeAll();
    reportContainer.add(viewer);
    reportContainer.revalidate();
  }
 /**
  * Get the email received date from message header if it can not get directly.
  *
  * @param message
  * @return
  * @throws MessagingException
  * @throws ParseException
  */
 protected Date resolveReceivedDate(MimeMessage message)
     throws MessagingException, ParseException {
   if (message.getReceivedDate() != null) {
     return message.getReceivedDate();
   }
   String[] receivedHeaders = message.getHeader("Received");
   if (receivedHeaders == null) {
     return Calendar.getInstance().getTime();
   }
   SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
   Date finalDate = Calendar.getInstance().getTime();
   finalDate.setTime(0l);
   boolean found = false;
   for (String receivedHeader : receivedHeaders) {
     Pattern pattern = Pattern.compile("^[^;]+;(.+)$");
     Matcher matcher = pattern.matcher(receivedHeader);
     if (matcher.matches()) {
       String regexpMatch = matcher.group(1);
       if (regexpMatch != null) {
         regexpMatch = regexpMatch.trim();
         Date parsedDate = sdf.parse(regexpMatch);
         if (parsedDate.after(finalDate)) {
           // finding the later date mentioned in received header
           finalDate = parsedDate;
           found = true;
         }
       } else {
         LOG.error("Unable to match received date in header string: " + receivedHeader);
       }
     }
   }
   return found ? finalDate : Calendar.getInstance().getTime();
 }
예제 #22
0
  /**
   * Gets the most recently added item not rated yet (new item in the platform).
   *
   * @return The most recently added item not rated yet.
   */
  public Long getLastItemAddedNotRated() {
    Long lastItemAdded = null;
    Date threshold = null;

    for (Long itemId : idao.getItemIds()) {
      List<Rating> ratings = iedao.getEventsForItem(itemId, Rating.class);
      Date firstTimestamp = new Date(ratings.get(0).getTimestamp() * 1000);
      if (threshold == null) {
        threshold = firstTimestamp;
        lastItemAdded = itemId;
      }

      for (Rating r : ratings) {
        Date timestamp = new Date(r.getTimestamp() * 1000);
        if (timestamp.before(firstTimestamp)) firstTimestamp = timestamp;
      }

      if (firstTimestamp.after(threshold)) {
        threshold = firstTimestamp;
        lastItemAdded = itemId;
      }
    }

    return lastItemAdded;
  }
 public static List<Date> computeFireTimesBetween(
     OperableTrigger trigger, org.quartz.Calendar cal, Date from, Date to, int num) {
   LinkedList<Date> lst = new LinkedList<>();
   OperableTrigger t = (OperableTrigger) trigger.clone();
   if (t.getNextFireTime() == null) {
     t.setStartTime(from);
     t.setEndTime(to);
     t.computeFirstFireTime(cal);
   }
   for (int i = 0; i < num; i++) {
     Date d = t.getNextFireTime();
     if (d != null) {
       if (d.before(from)) {
         t.triggered(cal);
         continue;
       }
       if (d.after(to)) {
         break;
       }
       lst.add(d);
       t.triggered(cal);
     } else {
       break;
     }
   }
   return java.util.Collections.unmodifiableList(lst);
 }
  private void checkTimeout() {

    Date now = new Date();
    if (now.after(nextTimeout)) {

      // prevent: double tick, but no stream -> 2 files..
      while (nextTimeout.before(now)) {
        nextTimeout = new Date((nextTimeout.getTime() + interval));
      }

      // timeout -> change file
      file =
          new File(
              path
                  + "/"
                  + TimeStamp.createLong(new Date(nextTimeout.getTime() - interval))
                  + "_"
                  + this.hashtag
                  + ".json");

      try {
        file.createNewFile();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  @Override
  public boolean isDefaultUpdated() {
    if (!isCustomizedView() || !hasUserPreferences()) {
      return false;
    }

    String preferencesModifiedDateString =
        _portalPreferences.getValue(
            CustomizedPages.namespacePlid(getPlid()), _MODIFIED_DATE, _NULL_DATE);

    DateFormat dateFormat =
        DateFormatFactoryUtil.getSimpleDateFormat(PropsValues.INDEX_DATE_FORMAT_PATTERN);

    try {
      Date preferencesModifiedDate = dateFormat.parse(preferencesModifiedDateString);

      Layout layout = getLayout();

      String propertiesModifiedDateString =
          layout.getTypeSettingsProperty(_MODIFIED_DATE, _NULL_DATE);

      Date propertiesModifiedDate = dateFormat.parse(propertiesModifiedDateString);

      return propertiesModifiedDate.after(preferencesModifiedDate);
    } catch (Exception e) {
      _log.error(e, e);
    }

    return false;
  }
예제 #26
0
파일: Dates.java 프로젝트: Voos/portfolio
  public static int daysBetween(Date start, Date end) {
    int answer = 0;

    if (start.after(end)) {
      Date temp = start;
      start = end;
      end = temp;
    }

    Calendar c1 = Calendar.getInstance();
    c1.setTime(start);

    Calendar c2 = Calendar.getInstance();
    c2.setTime(end);

    while (c1.get(Calendar.YEAR) < c2.get(Calendar.YEAR)) {
      int dayOfYear = c1.get(Calendar.DAY_OF_YEAR);
      int daysInYear = c1.getActualMaximum(Calendar.DAY_OF_YEAR);

      answer += daysInYear - dayOfYear + 1;
      c1.set(Calendar.DATE, 1);
      c1.set(Calendar.MONDAY, Calendar.JANUARY);
      c1.add(Calendar.YEAR, 1);
    }

    answer += c2.get(Calendar.DAY_OF_YEAR) - c1.get(Calendar.DAY_OF_YEAR);

    return answer;
  }
예제 #27
0
  /**
   * 计算两个日期(不包括时间)之间相差的整月数
   *
   * @param date1
   * @param date2
   * @return
   */
  public static int getMonthDiff(Date date1, Date date2) {
    if (date1 == null || date2 == null) {
      throw new InvalidParameterException("date1 and date2 cannot be null!");
    }
    if (date1.after(date2)) {
      throw new InvalidParameterException("date1 cannot be after date2!");
    }

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date1);
    int year1 = calendar.get(Calendar.YEAR);
    int month1 = calendar.get(Calendar.MONTH);
    int day1 = calendar.get(Calendar.DATE);

    calendar.setTime(date2);
    int year2 = calendar.get(Calendar.YEAR);
    int month2 = calendar.get(Calendar.MONTH);
    int day2 = calendar.get(Calendar.DATE);

    int months = 0;
    if (day2 >= day1) {
      months = month2 - month1;
    } else {
      months = month2 - month1 - 1;
    }
    return (year2 - year1) * MONTHS_IN_A_YEAR + months;
  }
예제 #28
0
  public void addScoutsToClazz(Key<Clazz> clazzKey, List<Key<Scout>> scoutList) {
    Objectify ofy = ObjectifyService.begin();
    Clazz c = get(clazzKey);

    if (c == null) {
      throw new RuntimeException("Clazz " + clazzKey.getId() + " not found!");
    }

    Event e = ofy.get(c.getEvent());
    for (Key<Scout> scoutId : scoutList) {
      if (!c.getScoutIds().contains(scoutId)) {
        c.getScoutIds().add(scoutId);
      }
    }
    for (Key<Scout> s : scoutList) {
      TrackProgress tp = new TrackProgress();
      tp.setScoutKey(s);
      tp.setClazzKey(clazzKey);
      Date curDate = (Date) e.getStartDate().clone();
      List<DateAttendance> attendanceList = new ArrayList<DateAttendance>();
      while (!curDate.after(e.getEndDate())) {
        DateAttendance da = new DateAttendance();
        da.setDate((Date) curDate.clone());
        da.setPresent(false);
        curDate.setDate(curDate.getDate() + 1);
        attendanceList.add(da);
      }
      tp.setAttendanceList(attendanceList);
      MeritBadge mb = ofy.get(c.getMbId());
      tp.setRequirementList(buildRequirementList(mb.getRequirements(), "", 0));
      ofy.put(tp);
    }

    ofy.put(c);
  }
예제 #29
0
  /**
   * Get DAYS difference
   *
   * @param date1
   * @param date2
   * @return
   */
  public static synchronized Integer getDifferenceBetween(Date date1, Date date2) {

    if (date1.after(date2)) {
      Date swap = date1;
      date1 = date2;
      date2 = swap;
    }

    Calendar d1 = Calendar.getInstance();
    d1.setTime(date1);

    Calendar d2 = Calendar.getInstance();
    d2.setTime(date2);

    int days = d2.get(java.util.Calendar.DAY_OF_YEAR) - d1.get(java.util.Calendar.DAY_OF_YEAR);
    int y2 = d2.get(java.util.Calendar.YEAR);
    if (d1.get(java.util.Calendar.YEAR) != y2) {
      d1 = (java.util.Calendar) d1.clone();
      do {
        days += d1.getActualMaximum(java.util.Calendar.DAY_OF_YEAR);
        d1.add(java.util.Calendar.YEAR, 1);
      } while (d1.get(java.util.Calendar.YEAR) != y2);
    }
    return days;
  }
 static void validateDateOrder(
     Date startDate,
     Date endDate,
     String startDateName,
     String endDateName,
     boolean startDateRequired,
     boolean endDateRequired)
     throws CloudWatchException {
   if (startDate != null && endDate != null) {
     if (startDate.after(endDate)) {
       throw new InvalidParameterValueException(
           "The parameter " + endDateName + " must be greater than " + startDateName + ".");
     }
     if (startDate.equals(endDate)) {
       throw new InvalidParameterValueException(
           "The parameter " + startDateName + " must not equal parameter " + endDateName + ".");
     }
   }
   if (startDate == null && startDateRequired) {
     throw new MissingParameterException("The parameter " + startDateName + " is required.");
   }
   if (endDate == null && endDateRequired) {
     throw new MissingParameterException("The parameter " + endDateName + " is required.");
   }
 }