Ejemplo n.º 1
1
 public static Date getFirstDayOfMonth(Calendar c) {
   int year = c.get(Calendar.YEAR);
   int month = c.get(Calendar.MONTH);
   int day = 1;
   c.set(year, month, day, 0, 0, 0);
   return c.getTime();
 }
Ejemplo n.º 2
1
 private void updateTime() {
   Calendar cal = GregorianCalendar.getInstance();
   cal.setTime(new Date());
   mTvCurrentTime.setText(
       String.format("%02d:%02d", cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE)));
   mHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, 5000);
 }
Ejemplo n.º 3
0
  public ArrayList<SmallPrayer> getTodayServices() {
    ArrayList<String> services = new ArrayList<String>();

    AppUser appUserInstance = AppUser.getInstance();
    ArrayList<DailyEvents> dailyEvents = appUserInstance.getCurrentCommunity().getDailyEvents();

    Calendar calendar = Calendar.getInstance();
    String day = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
    String month = String.valueOf(calendar.get(Calendar.MONTH) + 1);
    String year = String.valueOf(calendar.get(Calendar.YEAR));

    if (Integer.valueOf(day) < 10) day = "0" + day;

    if (Integer.valueOf(month) < 10) month = "0" + month;

    String todayDateString =
        String.valueOf(
            String.valueOf(day) + "/" + String.valueOf(month) + "/" + String.valueOf(year));

    for (int i = 0; i < dailyEvents.size(); i++) {
      DailyEvents singleDay = dailyEvents.get(i);
      if (todayDateString.equals(singleDay.getDate())) {
        if (singleDay.getPrayers().size() > 0) {
          return singleDay.getPrayers().get(0).getSmallPrayers();
        }
      }
    }

    return null;
  }
Ejemplo n.º 4
0
 private static void zeroDate(Calendar date) {
   date.set(Calendar.HOUR, 0);
   date.set(Calendar.MINUTE, 0);
   date.set(Calendar.SECOND, 0);
   date.set(Calendar.MILLISECOND, 0);
   date.set(Calendar.AM_PM, Calendar.AM);
 }
Ejemplo n.º 5
0
 /**
  * method to get current date and time
  *
  * @return
  */
 public static String getDateTime(boolean seperator) {
   Calendar c = Calendar.getInstance();
   SimpleDateFormat sdf;
   if (seperator) sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   else sdf = new SimpleDateFormat("yyyyMMddHHmmss");
   return sdf.format(c.getTime());
 }
Ejemplo n.º 6
0
  protected Calendar getCalendar(Date date, int when) {
    Calendar calendar = new GregorianCalendar();

    calendar.setTime(new Date(date.getTime() + Time.MINUTE * when * 5));

    return calendar;
  }
Ejemplo n.º 7
0
 // TODO check if minimum required fields are set?
 @Override
 public int sendMail() {
   int sendResult = -999;
   if (mail != null) {
     LOGGER.trace(
         "Sending Mail: \nfrom = '"
             + mail.getFrom()
             + "'\n"
             + "replyTo='"
             + mail.getTo()
             + "'\n"
             + "\n"
             + mail);
     MailSenderPluginApi mailPlugin =
         (MailSenderPluginApi) getContext().getWiki().getPluginApi("mailsender", getContext());
     sendResult = mailPlugin.sendMail(mail, getMailConfiguration());
     LOGGER.info(
         "Sent Mail from '"
             + mail.getFrom()
             + "' to '"
             + mail.getTo()
             + "'. Result was '"
             + sendResult
             + "'. Time: "
             + Calendar.getInstance().getTimeInMillis());
   } else {
     LOGGER.info(
         "Mail Object is null. Send result was '"
             + sendResult
             + "'. Time: "
             + Calendar.getInstance().getTimeInMillis());
   }
   return sendResult;
 }
Ejemplo n.º 8
0
 /**
  * 시스템의 현재 일시를 지정된 날짜 포멧(SimpleDateFormat참조)으로 변환하여 반환함
  *
  * @param dateFormat String SimpleDateFormat 의 날짜 포멧(예: yyyyMMdd HHmmssSSS)
  * @return String 현재일자
  */
 private String getCurrentTime(String dateFormat) {
   Calendar rightNow = Calendar.getInstance();
   SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
   Date currentTime = rightNow.getTime();
   String dateString = formatter.format(currentTime);
   return dateString;
 }
Ejemplo n.º 9
0
 private Date getPublichEndDate() {
   Calendar calendar = Calendar.getInstance();
   int day = calendar.get(Calendar.DAY_OF_YEAR);
   calendar.set(Calendar.DAY_OF_YEAR, day + end_date);
   Date date = calendar.getTime();
   return date;
 }
Ejemplo n.º 10
0
 private void trim(Calendar calendar) {
   int hours = calendar.get(Calendar.HOUR_OF_DAY);
   int minutes = calendar.get(Calendar.MINUTE);
   calendar.setTimeInMillis(0);
   calendar.set(Calendar.HOUR_OF_DAY, hours);
   calendar.set(Calendar.MINUTE, minutes);
 }
Ejemplo n.º 11
0
  @Test
  public void testBadPattern() {
    final Calendar cal = Calendar.getInstance();
    cal.set(2001, Calendar.FEBRUARY, 3, 4, 5, 6);
    cal.set(Calendar.MILLISECOND, 789);
    final long timestamp = cal.getTimeInMillis();

    final List<PatternFormatter> formatters = parser.parse(badPattern);
    assertNotNull(formatters);
    final Throwable t = new Throwable();
    final StackTraceElement[] elements = t.getStackTrace();
    final LogEvent event =
        Log4jLogEvent.newBuilder() //
            .setLoggerName("a.b.c") //
            .setLoggerFqcn(Logger.class.getName()) //
            .setLevel(Level.INFO) //
            .setMessage(new SimpleMessage("Hello, world")) //
            .setThreadName("Thread1") //
            .setSource(elements[0]) //
            .setTimeMillis(timestamp) //
            .build();
    final StringBuilder buf = new StringBuilder();
    for (final PatternFormatter formatter : formatters) {
      formatter.format(event, buf);
    }
    final String str = buf.toString();

    // eats all characters until the closing '}' character
    final String expected = "[2001-02-03 04:05:06,789] - Hello, world";
    assertTrue(
        "Expected to start with: " + expected + ". Actual: " + str, str.startsWith(expected));
  }
Ejemplo n.º 12
0
    @Test
    public void shouldReturnDateFieldObject() throws Exception {
      String xsd =
          "<root available-locales=\"en_US\" default-locale=\"en_US\"> "
              + "<dynamic-element "
              + "dataType=\"date\" "
              + "fieldNamespace=\"ddm\" "
              + "type=\"ddm-date\" "
              + "name=\"A_Date\" > "
              + "<meta-data locale=\"en_US\"> "
              + "<entry name=\"predefinedValue\"><![CDATA[06/19/2004]]></entry> "
              + "</meta-data> "
              + "</dynamic-element>"
              + "</root>";

      List<Field> resultList = new XSDParser().parse(xsd, US_LOCALE);

      assertNotNull(resultList);
      assertEquals(1, resultList.size());

      Field resultField = resultList.get(0);
      assertTrue(resultField instanceof DateField);
      DateField dateField = (DateField) resultField;

      assertEquals(Field.DataType.DATE.getValue(), dateField.getDataType().getValue());
      assertEquals(Field.EditorType.DATE.getValue(), dateField.getEditorType().getValue());
      assertEquals("A_Date", dateField.getName());

      Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
      calendar.setTimeInMillis(1087603200000L);

      assertEquals(calendar.getTime(), dateField.getCurrentValue());
      assertEquals(dateField.getCurrentValue(), dateField.getPredefinedValue());
    }
 /**
  * JavaSource_Calendar: The default constructor uses the current Gregorian date to initialize the
  * other private memebers of the class (Iranian and Julian dates).
  */
 public CalendarTool() {
   Calendar calendar = new GregorianCalendar();
   setGregorianDate(
       calendar.get(Calendar.YEAR),
       calendar.get(Calendar.MONTH) + 1,
       calendar.get(Calendar.DAY_OF_MONTH));
 }
Ejemplo n.º 14
0
  boolean colonoscopywith5(ArrayList<Map<String, Object>> list, Date asofDate) {
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();
    cal.setTime(asofDate);
    cal.add(Calendar.YEAR, -5);
    Date fiveyearcutoff = cal.getTime();
    for (int i = 0; i < list.size(); i++) {
      Map<String, Object> h = list.get(i);
      if (h.get("refused") != null && ((String) h.get("refused")).equals("0")) {

        String prevDateStr = (String) h.get("prevention_date");
        Date prevDate = null;
        try {
          prevDate = formatter.parse(prevDateStr);
        } catch (Exception e) {
          // empty
        }

        if (fiveyearcutoff.before(prevDate)) {
          log.debug(
              "Colonoscopy within 5 years: Last colonoscopy "
                  + formatter.format(prevDate)
                  + " 5 year mark "
                  + formatter.format(fiveyearcutoff));
          return true;
        }
      }
    }
    return false;
  }
Ejemplo n.º 15
0
  public ChmItsfHeader(ByteBuffer bb) {
    byte[] sbuf = new byte[4];
    bb.get(sbuf);
    signature = new String(sbuf);

    version = bb.getInt();
    header_len = bb.getInt();
    unknown_000c = bb.getInt();
    last_modified = ByteBufferHelper.parseBigEndianInt(bb);
    Calendar c = Calendar.getInstance();
    c.set(1970, Calendar.JANUARY, 1);
    c.add(Calendar.SECOND, 0x3DB0C239);
    timestamp = c.getTime();
    // DateFormat f = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    // System.out.println("Last modified: " + f.format(timestamp));

    lang_id = bb.getInt();
    bb.get(new byte[32]);
    unknown_len = bb.getLong();
    unknown_offset = bb.getLong();
    dir_offset = bb.getLong();
    dir_len = bb.getLong();
    data_offset = 0; // TODO:
    if (version >= 3) {
      data_offset = bb.getLong();
    }
  }
  /**
   * Sets the Date header for the HTTP response
   *
   * @param response HTTP response
   */
  private static void setDateHeader(FullHttpResponse response) {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

    Calendar time = new GregorianCalendar();
    response.headers().set(DATE, dateFormatter.format(time.getTime()));
  }
 @Override
 public Object getValueAt(int rowIndex, int columnIndex) {
   WeeklyEvent we = weeklyEvents.get(rowIndex);
   Calendar cal;
   switch (columnIndex) {
     case 0:
       cal = we.getStartTime();
       String time =
           cal.get(Calendar.HOUR_OF_DAY)
               + ":00 - "
               + we.getEndTime().get(Calendar.HOUR_OF_DAY)
               + ":00";
       return time;
     case 1:
       cal = we.getStartTime();
       return DateFunctions.getDayOfWeek(cal);
     case 2:
       if (we.getCourse() != null) {
         return we.getCourse().getName();
       } else {
         return "";
       }
     case 3:
       return we.getRoom().getRoomName();
     default:
       return "";
   }
 }
Ejemplo n.º 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;
  }
Ejemplo n.º 19
0
 public void drawString(Graphics g) {
   Font Amonth = new Font("Century Gothic", Font.PLAIN, 45);
   g.setColor(Color.gray);
   g.setFont(Amonth);
   g.drawString(month.format(today.getTime()), 150, 45);
   Month = present.format(today.getTime());
 }
Ejemplo n.º 20
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;
  }
Ejemplo n.º 21
0
  /**
   * @param n
   * @throws RepositoryException
   */
  private void addFile(ContentResource n) {
    ResourceProperties rp = n.getProperties();
    Calendar lastModified = new GregorianCalendar();
    try {
      Time lastModifiedTime = rp.getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
      lastModified.setTimeInMillis(lastModifiedTime.getTime());
    } catch (EntityPropertyNotDefinedException e) {
      // default to now
    } catch (EntityPropertyTypeException e) {
      // default to now
    }
    long contentLength = n.getContentLength();
    String mimeType = n.getContentType();
    put("lastModified", lastModified.getTime());
    put("mimeType", mimeType);
    put("length", String.valueOf(contentLength));

    put("available", n.isAvailable());
    put("hidden", n.isHidden());
    if (!n.isHidden()) {
      Time releaseDate = n.getReleaseDate();
      if (releaseDate != null) {
        put("releaseDate", releaseDate.getTime());
      }
      Time retractDate = n.getRetractDate();
      if (retractDate != null) {
        put("retractDate", retractDate.getTime());
      }
    }
  }
  public ExportOptions(List<String> optinonsLine) throws Exception {
    assert optinonsLine != null || optinonsLine.isEmpty();

    APIUrl = new URL(optinonsLine.get(0));
    userName = optinonsLine.get(1);
    password = optinonsLine.get(2);
    surveyId = Integer.valueOf(optinonsLine.get(3));
    pageNumber = Integer.valueOf(optinonsLine.get(4));
    resultsPerPage = Integer.valueOf(optinonsLine.get(5));
    filterField = optinonsLine.get(6);
    filterValue = optinonsLine.get(7);
    if (filterValue.equals("Yesterday")) {
      DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
      Calendar cal = Calendar.getInstance();
      cal.add(Calendar.DATE, -1);
      filterValue = df.format(cal.getTime());
    }
    sortField = optinonsLine.get(8);
    sortAscending = Boolean.valueOf(optinonsLine.get(9));
    period = Integer.valueOf(optinonsLine.get(10));
    dtStart = parseStringToXMLGregorianCalendar(optinonsLine.get(11), DATE_FORMAT_PATTERN);
    dtEnd = parseStringToXMLGregorianCalendar(optinonsLine.get(12), DATE_FORMAT_PATTERN);
    detailedResponseInfo = Boolean.valueOf(optinonsLine.get(13));
    detailedUserInfo = Boolean.valueOf(optinonsLine.get(14));
    includeOpenEndedResults = Boolean.valueOf(optinonsLine.get(15));
    includeAliases = Boolean.valueOf(optinonsLine.get(16));
    includeHiddenItems = Boolean.valueOf(optinonsLine.get(17));
    includeIncompleteResponses = Boolean.valueOf(optinonsLine.get(18));
    stripHTMLTagsFromAnswers = Boolean.valueOf(optinonsLine.get(19));
    stripHTMLTagsFromQuestions = Boolean.valueOf(optinonsLine.get(20));
    mergeAnswersForSelectMany = Boolean.valueOf(optinonsLine.get(21));
    csvFileName = optinonsLine.get(22);
  }
Ejemplo n.º 23
0
 /**
  * @param weeks number of weeks pregnancy lengths
  * @param days number of days pregnancy lengths, should be in range from 0 to 6
  * @param current current date, must be not null
  */
 Pregnancy(int weeks, int days, Calendar current) {
   age = new Age(weeks, days);
   startPoint = (Calendar) current.clone();
   zeroDate(startPoint);
   startPoint.add(Calendar.DAY_OF_MONTH, -getDurationInDays());
   currentPoint = startPoint;
 }
Ejemplo n.º 24
0
  // DrawingPartListener methods
  public void stateChanged(DrawingPartEvent event) {
    String colors[] = {
      GradientColorModule.GREEN_GRADIENT_CONTEXT, GradientColorModule.RED_GRADIENT_CONTEXT,
    };

    Object key = event.getSource();
    MutableDrawingPart entry = actEntries_.get(key);
    // LongInterval li = (LongInterval)entry.getInterval()[0];
    // int idx = (int)(Math.round(Math.random()));
    // System.out.println("range:"+li.getRangeValue()+" idx:"+idx);
    // entry.setContext(key, colors[idx]);

    List changes = (List) (event.changes().next());

    int changeType = ((Integer) changes.get(0)).intValue();
    Long newValue = (Long) changes.get(1);
    Calendar calValue = new GregorianCalendar();
    calValue.setTime(new java.util.Date(newValue.longValue()));

    switch (changeType) {
      case MutableIntervalListener.START_CHANGED:
        model_.setActivityStart(key, calValue);
        break;
      case MutableIntervalListener.FINISH_CHANGED:
        model_.setActivityFinish(key, calValue);
        break;
      default:
        System.err.println("ERROR:Unknow MutableIntervalListener change:" + changeType);
    }
  }
 /**
  * return the expected end of the session if the session already made or the session is canceled,
  * return null.
  *
  * @return the expeted end of the session
  */
 public Calendar getExpectedSessionEnd() {
   Calendar result = this.getExpectedSessionStart();
   if (result != null) {
     result.add(Calendar.MINUTE, 60 / this.getQueueBasedBookingRule().getUnitsPerHourProcessed());
   }
   return result;
 }
Ejemplo n.º 26
0
  protected void makeGantt() {
    gantt_ = new GanttTable(makeTableModel(model_));

    // System.out.println("model rows:"+model.getTableModel().getRowCount());
    TableColumnModel columnModel = gantt_.getColumnModel(1);
    TableColumn column = columnModel.getColumn(0);

    // Enable drag and drop
    TableCellEditor editor = gantt_.getDefaultEditor(1, AbstractDrawingState.class);
    column.setCellEditor(editor);

    gantt_
        .getDrawingContext()
        .put(ContextConstants.EDITING_AXIS, ContextResources.OTHER_PROPERTY, GanttTable.TIME_AXIS);

    gantt_
        .getDrawingContext()
        .put(
            ContextConstants.EDITING_MODE,
            ContextResources.OTHER_PROPERTY,
            EditorDrawingModule.MOVE_RESIZE_EDITOR);

    // Display timeline at the top
    column.setHeaderValue(GanttEntryHelper.createCalendar());
    gantt_.setTimeRange(start_.getTime(), end_.getTime());
    gantt_.addMouseMotionListener(this);

    /* TODO: Disable row selection?
    JTable activityTable = gantt_.getTableComponent(1);
    activityTable.setRowSelectionAllowed(false);
    activityTable.setColumnSelectionAllowed(false);
    activityTable.setCellSelectionEnabled(false);
    */
  }
  protected JFreeChart constructChart(Iteration iteration, Integer timeZoneOffset) {
    // get server timezone
    Calendar cal = Calendar.getInstance();
    TimeZone localTimeZone = cal.getTimeZone();

    // server timezone offset in minutes
    int rawOffset = localTimeZone.getRawOffset() / 60000;

    // get offset difference in minutes
    timeDifferenceMinutes = rawOffset - timeZoneOffset.intValue();

    JFreeChart burndown =
        ChartFactory.createTimeSeriesChart(
            "'" + iteration.getName() + "' burndown",
            DATE_AXIS_LABEL,
            EFFORT_AXIS_LABEL,
            getDataset(iteration),
            true,
            true,
            false);

    formatChartAxes(
        burndown,
        new DateTime(iteration.getStartDate().minusMinutes(timeDifferenceMinutes)),
        new DateTime(iteration.getEndDate()).minusMinutes(timeDifferenceMinutes));

    formatChartStyle(burndown);

    return burndown;
  }
Ejemplo n.º 28
0
  @Override
  public Map<String, List<Application>> getInactiveAgents(
      String applicationName, int durationDays) {
    if (applicationName == null) {
      throw new NullPointerException("applicationName must not be null");
    }
    if (durationDays < 30) {
      throw new IllegalArgumentException("duration may not be less than 30 days");
    }
    if (durationDays > 180) {
      throw new IllegalArgumentException("duration may not be greater than 180 days");
    }
    List<String> agentIds = this.applicationIndexDao.selectAgentIds(applicationName);
    if (CollectionUtils.isEmpty(agentIds)) {
      return Collections.emptyMap();
    }

    final long toTimestamp = System.currentTimeMillis();
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, durationDays * -1);
    final long fromTimestamp = cal.getTimeInMillis();
    Range queryRange = new Range(fromTimestamp, toTimestamp);

    Map<String, List<Application>> agentIdMap = this.getAgentIdMap();

    Map<String, List<Application>> inactiveAgentMap = new TreeMap<>(Ordering.usingToString());
    for (String agentId : agentIds) {
      boolean dataExists = this.agentStatDao.agentStatExists(agentId, queryRange);
      if (!dataExists) {
        List<Application> applications = agentIdMap.get(agentId);
        inactiveAgentMap.put(agentId, applications);
      }
    }
    return inactiveAgentMap;
  }
Ejemplo n.º 29
0
 public static Calendar getCalendarFromString(String userTime) throws ParseException {
   DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   Date date = dateFormat.parse(userTime);
   Calendar cal = Calendar.getInstance();
   cal.setTimeInMillis(date.getTime());
   return cal;
 }
Ejemplo n.º 30
0
  public static final void login(String username, MapleClient c, String pwd) {
    String login = username;
    int loginok = 0;
    boolean isBanned = c.hasBannedIP() || c.hasBannedMac() || c.hasProxyBan();
    loginok = c.login(login, pwd, isBanned);
    Calendar tempbannedTill = c.getTempBanCalendar();

    if ((loginok == 0) && (isBanned)) {
      loginok = 3;
    }
    if (loginok != 0) {
      if (!loginFailCount(c)) {
        c.clearInformation();
        c.getSession().write(LoginPacket.getLoginFailed(loginok));
      } else {
        c.getSession().close(true);
      }
    } else if (tempbannedTill.getTimeInMillis() != 0L) {
      if (!loginFailCount(c)) {
        c.clearInformation();
        c.getSession()
            .write(
                LoginPacket.getTempBan(
                    PacketHelper.getTime(tempbannedTill.getTimeInMillis()), c.getBanReason()));
      } else {
        c.getSession().close(true);
      }
    } else {
      c.loginAttempt = 0;
      LoginWorker.registerClient(c);
    }
  }