/**
   * Places patient information at the top of the receipt. Places the Name, ID, and time spent in
   * the hospital.
   */
  public void loadPatientData() {

    ReceiptDataBean patientColumnTitles =
        new ReceiptDataBean(
            Messages.getString("patient"),
            Messages.getString("admissiondate"),
            Messages.getString("releaseDate"));
    addReceiptDataBean(patientColumnTitles);

    String patientName =
        patientBean.getFirstName()
            + " "
            + patientBean.getLastName()
            + " ID: "
            + patientBean.getPatientID();

    Timestamp admissionDate = patientBean.getAdmissionDate();
    SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy");
    String admissionDateString = format.format(new Date(admissionDate.getTime()));

    Timestamp releaseDate = patientBean.getReleaseDate();
    String releaseDateString = format.format(new Date(releaseDate.getTime()));

    ReceiptDataBean temp1 =
        new ReceiptDataBean(patientName, admissionDateString, releaseDateString);

    addReceiptDataBean(temp1);

    addBlankRow();
  }
  /** Filter the event if it has already been executed. */
  public ReplDBMSEvent filter(ReplDBMSEvent event)
      throws ReplicatorException, InterruptedException {
    totalEvents++;

    if (appliedTimes == null) appliedTimes = new TreeMap<Long, Timestamp>();

    Timestamp sourceTstamp = event.getDBMSEvent().getSourceTstamp();
    appliedTimes.put(event.getSeqno(), sourceTstamp);

    long currentTime = System.currentTimeMillis();
    prefetchLatency = currentTime - sourceTstamp.getTime();

    if (interval == 0 || lastChecked == 0 || (currentTime - lastChecked >= interval)) {
      // It is now time to check CommitSeqnoTable again
      checkSlavePosition(currentTime);
    }

    if (initTime == 0) initTime = sourceTstamp.getTime();

    if (event.getSeqno() <= currentSeqno) {
      if (logger.isDebugEnabled())
        logger.debug("Discarding event " + event.getSeqno() + " as it is already applied");
      return null;
    } else
      while (sourceTstamp.getTime() - initTime > (aheadMaxTime * 1000)) {
        if (logger.isDebugEnabled())
          logger.debug("Event is too far ahead of current slave position... sleeping");
        // this event is too far ahead of the CommitSeqnoTable position:
        // sleep some time and continue
        long sleepStartMillis = System.currentTimeMillis();
        try {

          prefetchState = PrefetchState.sleeping;
          Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
          return null;
        } finally {
          prefetchState = PrefetchState.active;
          sleepTimeMillis += (System.currentTimeMillis() - sleepStartMillis);
        }
        // Check again CommitSeqnoTable
        checkSlavePosition(System.currentTimeMillis());
        // and whereas the event got applied while sleeping
        if (event.getSeqno() <= currentSeqno) {
          if (logger.isDebugEnabled())
            logger.debug("Discarding event " + event.getSeqno() + " as it is already applied");
          return null;
        }
      }

    prefetchEvents++;
    if (logger.isDebugEnabled() && totalEvents % 20000 == 0)
      logger.debug(
          "Prefetched "
              + prefetchEvents
              + " events - Ratio "
              + (100 * prefetchEvents / totalEvents)
              + "%");
    return event;
  }
  private synchronized void checkTimeUpdate(long localTime, long utcTime) throws Exception {
    // broadcast
    _props.setProperty("utc", String.valueOf(utcTime));
    _props.setProperty("local", String.valueOf(localTime));

    TimeUpdateNotification notification =
        new TimeUpdateNotification(TimeUpdateNotification.UPDATE_UTC_TIME, _props);

    Notifier.getInstance().broadcast(notification);

    // wait
    try {
      wait(30000L); // 30 seconds
    } catch (Exception ex) {
    }

    // refreshTimeServer();
    // checkSuccess(_event, _sessions[0], _sm[0], IErrorCode.NO_ERROR);

    long offset = utcTime - localTime;
    Logger.debug("Input UTC Time = " + new Timestamp(utcTime));
    Logger.debug("Input Local Time = " + new Timestamp(localTime));
    Logger.debug("Expected offset: " + offset);

    // check local to utc
    Timestamp ts = TimeUtil.localToUtcTimestamp(_testDate);
    Logger.debug("Converted local to UTc timestamp: " + ts);
    assertEquals("LocalToUtc conversion fail", offset, ts.getTime() - _testDate.getTime());

    // check utc to local
    ts = TimeUtil.utcToLocalTimestamp(_testDate);
    Logger.debug("Converted utc to local timestamp: " + ts);
    assertEquals("UtcToLocal conversion fail", offset, _testDate.getTime() - ts.getTime());
  }
Beispiel #4
0
  protected Post makePost(ResultSet rs) throws SQLException {
    Post post = new Post();
    post.setId(rs.getInt("post_id"));
    post.setTopicId(rs.getInt("topic_id"));
    post.setForumId(rs.getInt("forum_id"));
    post.setUserId(rs.getInt("user_id"));

    Timestamp postTime = rs.getTimestamp("post_time");
    post.setTime(new Date(postTime.getTime()));
    post.setUserIp(rs.getString("poster_ip"));
    post.setBbCodeEnabled(rs.getInt("enable_bbcode") > 0);
    post.setHtmlEnabled(rs.getInt("enable_html") > 0);
    post.setSmiliesEnabled(rs.getInt("enable_smilies") > 0);
    post.setSignatureEnabled(rs.getInt("enable_sig") > 0);
    post.setEditCount(rs.getInt("post_edit_count"));

    Timestamp editTime = rs.getTimestamp("post_edit_time");
    post.setEditTime(editTime != null ? new Date(editTime.getTime()) : null);

    post.setSubject(rs.getString("post_subject"));
    post.setText(this.getPostTextFromResultSet(rs));
    post.setPostUsername(rs.getString("username"));
    post.hasAttachments(rs.getInt("attach") > 0);
    post.setModerate(rs.getInt("need_moderate") == 1);

    SimpleDateFormat df = new SimpleDateFormat(SystemGlobals.getValue(ConfigKeys.DATE_TIME_FORMAT));
    post.setFormatedTime(df.format(postTime));

    post.setKarma(DataAccessDriver.getInstance().newKarmaDAO().getPostKarma(post.getId()));

    return post;
  }
  @Override
  public ExpiringCode generateCode(String data, Timestamp expiresAt) {
    cleanExpiredEntries();

    if (data == null || expiresAt == null) {
      throw new NullPointerException();
    }

    if (expiresAt.getTime() < System.currentTimeMillis()) {
      throw new IllegalArgumentException();
    }

    int count = 0;
    while (count < 3) {
      count++;
      String code = generator.generate();
      try {
        int update = jdbcTemplate.update(insert, code, expiresAt.getTime(), data);
        if (update == 1) {
          ExpiringCode expiringCode = new ExpiringCode(code, expiresAt, data);
          return expiringCode;
        } else {
          logger.warn("Unable to store expiring code:" + code);
        }
      } catch (DataIntegrityViolationException x) {
        if (count == 3) {
          throw x;
        }
      }
    }

    return null;
  }
  /**
   * Add time to primary timesheets and move them to current timesheets if they're still active
   *
   * @param primaryTimesheets A list of timesheets that are currently getting the hours
   * @param currentTimesheets A list of timesheets that are still active
   * @param currentTime The current time to calculate hours and such from;
   */
  private void addTimeToPrimaryTimeSheets(
      ArrayList<Time_Sheet> primaryTimesheets,
      ArrayList<Time_Sheet> currentTimesheets,
      Timestamp currentTime) {
    // Do for all time sheets in primary time sheet
    for (int j = 0; j < primaryTimesheets.size(); j++) {

      Timestamp tempEnd = currentTime;
      Time_Sheet currentPrimaryTS = primaryTimesheets.get(j);
      // If the primary timesheet ended before the new current time, then remove it, add minutes and
      // check if any current timesheets are still active.
      if (currentPrimaryTS.getEndTime().getTime() <= currentTime.getTime()) {
        tempEnd = currentPrimaryTS.getEndTime();
        long millis =
            currentPrimaryTS.getEndTime().getTime()
                - currentPrimaryTS.getStartTimeForCurrentTimeAtAlarm().getTime();
        int minutes = (int) (millis / (60 * 1000));
        // split the time between all the primary time sheets
        for (Time_Sheet myTS : primaryTimesheets) {
          myTS.addMinute((minutes / primaryTimesheets.size()));
          myTS.setStartTimeForCurrentTimeAtAlarm(currentPrimaryTS.getEndTime());
        }
        boolean hasAddedNewTimeSheet = false;
        // If it's the last primary time sheet. Then move the last added current time sheet to
        // primary time sheets.
        if (primaryTimesheets.size() == 1 && !currentTimesheets.isEmpty()) {

          removeOldTimeSheets(currentTimesheets, currentPrimaryTS.getEndTime());

          primaryTimesheets.add(currentTimesheets.get(currentTimesheets.size() - 1));
          j++;
          primaryTimesheets.get(j).setStartTimeForCurrentTimeAtAlarm(currentPrimaryTS.getEndTime());
          currentTimesheets.remove(currentTimesheets.size() - 1);
          hasAddedNewTimeSheet = true;
        }
        // Remove the primary time sheet we have calculated time for
        if (hasAddedNewTimeSheet) {
          primaryTimesheets.remove(j - 1);
          j--;
        } else {
          primaryTimesheets.remove(j);
        }
        j--;

      } else { // if the primary time sheet ended after the current time, then add minutes and move
               // it to current time sheets

        long millis =
            tempEnd.getTime() - currentPrimaryTS.getStartTimeForCurrentTimeAtAlarm().getTime();
        int minutes = (int) (millis / (60 * 1000));

        currentPrimaryTS.addMinute(minutes);
        currentPrimaryTS.setStartTimeForCurrentTimeAtAlarm(currentTime);
        currentTimesheets.add(currentPrimaryTS);

        primaryTimesheets.remove(j);
        j--;
      }
    }
  }
    @Override
    public ChargeSession mapRow(ResultSet rs, int rowNum) throws SQLException {
      ChargeSession row = new ChargeSession();
      // Row order is: created, sessid_hi, sessid_lo, idtag, socketid, auth_status, xid, ended,
      // posted
      Timestamp ts = rs.getTimestamp(1, utcCalendar);
      if (ts != null) {
        row.setCreated(new Date(ts.getTime()));
      }
      row.setSessionId(new UUID(rs.getLong(2), rs.getLong(3)).toString());
      row.setIdTag(rs.getString(4));
      row.setSocketId(rs.getString(5));

      String s = rs.getString(6);
      if (s != null) {
        row.setStatus(AuthorizationStatus.valueOf(s));
      }

      Number n = (Number) rs.getObject(7);
      if (n != null) {
        row.setTransactionId(n.intValue());
      }

      ts = rs.getTimestamp(8, utcCalendar);
      if (ts != null) {
        row.setEnded(new Date(ts.getTime()));
      }

      ts = rs.getTimestamp(9, utcCalendar);
      if (ts != null) {
        row.setPosted(new Date(ts.getTime()));
      }

      return row;
    }
  public void set_plan(int name, int my_plan) {
    System.out.println("12. set_plan (\\/)");
    Date date = new Date(System.currentTimeMillis() - 2 * 60 * 60 * 1000);
    Timestamp time = new Timestamp(date.getTime());
    Timestamp p_registration = time;

    String sql = "SELECT * FROM user WHERE user_id = " + name + " ;";
    ResultSet rs;
    rs = do_query(connection, sql);
    try {
      while (rs.next()) {
        p_registration = Timestamp.valueOf((rs.getString("p_registration")));
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    close_resultset(rs);
    long temp = (time.getTime() - p_registration.getTime()) / 1000;
    if (temp > 5) {
      sql = "UPDATE user SET program=" + my_plan + " WHERE user_id=" + name + " ;";
      do_update(connection, sql);
      sql = "UPDATE user SET p_registration=CURRENT_TIMESTAMP " + "WHERE user_id=" + name + " ;";
      do_update(connection, sql);
      System.out.println("Program changed to program " + my_plan);
    } else System.out.println("Program cannot be changed");
  }
Beispiel #9
0
  private static BlockStatus createInstanceFromResultSet(ResultSet rs) throws SQLException {
    BlockStatus blockStatus = new BlockStatus();

    Integer col1 = rs.getInt("id");
    blockStatus.setId(rs.wasNull() ? null : col1);

    Integer col2 = rs.getInt("id2");
    blockStatus.setId2(rs.wasNull() ? null : col2);

    Integer col3 = rs.getInt("shipment_id");
    blockStatus.setShipmentId(rs.wasNull() ? null : col3);

    String col4 = rs.getString("declaration_no");
    blockStatus.setDeclarationNo(rs.wasNull() ? null : col4);

    String col5 = rs.getString("status");
    blockStatus.setStatus(rs.wasNull() ? null : col5);

    String col6 = rs.getString("remark");
    blockStatus.setRemark(rs.wasNull() ? null : col6);

    java.sql.Timestamp col7 = rs.getTimestamp("block_date_time");
    blockStatus.setBlockDateTime(rs.wasNull() ? null : new java.util.Date(col7.getTime()));

    java.sql.Timestamp col8 = rs.getTimestamp("unblock_date_time");
    blockStatus.setUnblockDateTime(rs.wasNull() ? null : new java.util.Date(col8.getTime()));

    String col9 = rs.getString("company_code");
    blockStatus.setCompanyCode(rs.wasNull() ? null : col9);

    String col10 = rs.getString("company_type");
    blockStatus.setCompanyType(rs.wasNull() ? null : col10);

    String col11 = rs.getString("user_block");
    blockStatus.setUserBlock(rs.wasNull() ? null : col11);

    String col12 = rs.getString("mawb");
    blockStatus.setMawb(rs.wasNull() ? null : col12);

    String col13 = rs.getString("hawb");
    blockStatus.setHawb(rs.wasNull() ? null : col13);

    String col14 = rs.getString("flight_no");
    blockStatus.setFlightNo(rs.wasNull() ? null : col14);

    java.sql.Timestamp col15 = rs.getTimestamp("flight_date");
    blockStatus.setFlightDate(rs.wasNull() ? null : new java.util.Date(col15.getTime()));

    String col16 = rs.getString("user_unblock");
    blockStatus.setUserUnblock(rs.wasNull() ? null : col16);

    java.sql.Timestamp col17 = rs.getTimestamp("modified_date_time");
    blockStatus.setModifiedDateTime(rs.wasNull() ? null : new java.util.Date(col17.getTime()));

    Integer col18 = rs.getInt("auto_block_profile_id");
    blockStatus.setAutoBlockProfileId(rs.wasNull() ? null : col18);

    return blockStatus;
  }
Beispiel #10
0
  /**
   * 时间1-时间2的毫秒
   *
   * @param t1
   * @param t2
   * @return
   */
  public static long between(Timestamp t1, Timestamp t2) {

    if ((t1 != null) && (t2 != null)) {
      return t1.getTime() - t2.getTime();
    }

    return 0;
  }
Beispiel #11
0
  /**
   * @param value Value
   * @return Timestamp
   */
  public static TimestampValue from(final Timestamp value) {
    if (value == null) {
      return new TimestampValue(value, TypeTimestamp.get());
    }

    // java does wired things with time zones (so we must correct this here)
    final long offset = TimeZone.getDefault().getOffset(value.getTime());
    final Timestamp timestamp = new Timestamp(value.getTime() - offset);
    timestamp.setNanos(value.getNanos());
    return new TimestampValue(timestamp, TypeTimestamp.get());
  }
Beispiel #12
0
  /**
   * Returns string representation of this class instance.
   *
   * @return string representation of this class instance.
   */
  public String toString() {
    String[] items =
        new String[] {
          m_hostname,
          Boolean.toString(m_mmode),
          m_mstart == null ? "" : Long.toString(m_mstart.getTime()),
          m_mstop == null ? "" : Long.toString(m_mstop.getTime())
        };

    return StringSet.join(items, ",");
  }
Beispiel #13
0
 public boolean validateServiceAvailiablity() {
   if (System.currentTimeMillis() >= maturityDate.getTime()) {
     arrearage = true;
     rotate();
     return false;
   } else {
     arrearage = false;
     serviceDaysLeft = (int) ((maturityDate.getTime() - System.currentTimeMillis()) / DAY_MILLIS);
     return true;
   }
 }
Beispiel #14
0
 /*!
  * 计算两个时间点之间的小时数
  */
 public static long countDay(String date1, String date2) throws Exception {
   if (f.empty(date1)) {
     date1 = f.today();
   }
   if (f.empty(date2)) {
     date2 = f.today();
   }
   Timestamp ts1 = f.time(date1);
   Timestamp ts2 = f.time(date2);
   long d = ts2.getTime() - ts1.getTime();
   return (d / (3600 * 1000) + 1);
 }
 private boolean isWebserviceInvocationAllowed(Calltype callType, Timestamp lastInvocation) {
   boolean oldEnough;
   if (lastInvocation == null) {
     oldEnough = true;
   } else if (lastInvocation.getTime() >> 32 == Integer.MAX_VALUE) {
     // checks if invocation_time is close enough to 'infinity'.
     oldEnough = false;
   } else {
     DateTime lastInvocationDateTime = new DateTime(lastInvocation.getTime());
     Days daysBetween = Days.daysBetween(lastInvocationDateTime, new DateTime());
     oldEnough = daysBetween.getDays() > callType.getDaysToCache();
   }
   return oldEnough;
 }
  /**
   * Execute this call to fill in heartbeat data on the slave. This call must be invoked after a
   * heartbeat event is applied.
   */
  public void completeHeartbeat(Database database, long seqno, String eventId) throws SQLException {
    if (logger.isDebugEnabled()) logger.debug("Processing slave heartbeat update");

    Statement st = null;
    ResultSet rs = null;
    Timestamp sts = new Timestamp(0);
    Timestamp now = new Timestamp(System.currentTimeMillis());
    ArrayList<Column> whereClause = new ArrayList<Column>();
    ArrayList<Column> values = new ArrayList<Column>();

    if (logger.isDebugEnabled()) logger.debug("Processing slave heartbeat update: " + now);

    // Get the source timestamp.
    try {
      st = database.createStatement();
      rs = st.executeQuery(sourceTsQuery);
      if (rs.next()) sts = rs.getTimestamp(1);
    } finally {
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException e) {
        }
      }
      if (st != null) {
        try {
          st.close();
        } catch (SQLException e) {
        }
      }
    }

    // Compute the difference between source and target.
    long lag_millis = now.getTime() - sts.getTime();

    // Update the heartbeat record with target time and difference.
    hbId.setValue(KEY);
    whereClause.add(hbId);

    hbSeqno.setValue(seqno);
    hbEventId.setValue(eventId);
    hbTargetTstamp.setValue(now);
    hbLagMillis.setValue(lag_millis);
    values.add(hbSeqno);
    values.add(hbEventId);
    values.add(hbTargetTstamp);
    values.add(hbLagMillis);

    database.update(hbTable, whereClause, values);
  }
  @Override
  public DateTime fromNonNullValue(Timestamp value) {

    DateTimeZone currentDatabaseZone =
        databaseZone == null ? ZoneHelper.getDefault() : databaseZone;
    DateTimeZone currentJavaZone = javaZone == null ? ZoneHelper.getDefault() : javaZone;

    int adjustment =
        TimeZone.getDefault().getOffset(value.getTime()) - currentDatabaseZone.getOffset(null);

    DateTime dateTime = new DateTime(value.getTime() + adjustment);
    DateTime dateTimeWithZone = dateTime.withZone(currentJavaZone);

    return dateTimeWithZone;
  }
 private Timestamp getScaledCurrentTimestamp(Timestamp time) {
   assert (this.clientStartTime != null);
   tmp_now.setTime(System.currentTimeMillis());
   time.setTime(
       AuctionMarkUtil.getScaledTimestamp(this.loaderStartTime, this.clientStartTime, tmp_now));
   if (LOG.isTraceEnabled())
     LOG.trace(
         String.format(
             "Scaled:%d / Now:%d / BenchmarkStart:%d / ClientStart:%d",
             time.getTime(),
             tmp_now.getTime(),
             this.loaderStartTime.getTime(),
             this.clientStartTime.getTime()));
   return (time);
 }
Beispiel #19
0
 private static DateTime toDateTime(Timestamp timestamp) {
   if (timestamp != null) {
     return new DateTime(timestamp.getTime(), DateTimeZone.UTC);
   } else {
     return null;
   }
 }
  @Override
  protected void writeImpl(AionConnection con) {
    PacketLoggerService.getInstance().logPacketSM(this.getPacketName());
    writeS(legion.getLegionName());
    writeC(legion.getLegionLevel());
    writeD(legion.getLegionRank());
    writeH(legion.getDeputyPermission());
    writeH(legion.getCenturionPermission());
    writeH(legion.getLegionaryPermission());
    writeH(legion.getVolunteerPermission());
    writeQ(legion.getContributionPoints());
    writeD(0x00);
    writeD(0x00);
    writeD(0x00); // unk 3.0

    /** Get Announcements List From DB By Legion * */
    Map<Timestamp, String> announcementList = legion.getAnnouncementList().descendingMap();

    /** Show max 7 announcements * */
    int i = 0;
    for (Timestamp unixTime : announcementList.keySet()) {
      writeS(announcementList.get(unixTime));
      writeD((int) (unixTime.getTime() / 1000));
      i++;
      if (i >= 7) {
        break;
      }
    }

    writeB(new byte[26]); // something like a spacer
  }
Beispiel #21
0
 public static java.util.Date addMonths(Comparable<?> param1, Comparable<?> param2, Calendar cal)
     throws ParseException {
   if (param1 == null && param2 == null) {
     return null;
   }
   try {
     int months = getInteger(param2);
     if (param1 instanceof Timestamp) {
       Timestamp d = (Timestamp) param1;
       cal.setTimeInMillis(d.getTime());
       cal.add(Calendar.MONTH, months);
       return new Timestamp(cal.getTimeInMillis());
     } else if (param1 instanceof java.sql.Date) {
       java.util.Date d = (java.util.Date) param1;
       cal.setTimeInMillis(d.getTime());
       cal.add(Calendar.MONTH, months);
       return new java.util.Date(cal.getTimeInMillis());
     } else {
       throw new ParseException();
     }
   } catch (ParseException e) {
     throw new ParseException(
         WRONG_TYPE + "  month_between(" + param1.getClass() + "," + param2.getClass() + ")");
   }
 }
  public ModelAndView executaBrowserIphone(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession();
    Usuario usuario = (Usuario) session.getAttribute("usuario");

    if (usuario != null) {
      if (validaMenu.validaMenu(idMenu, usuario.getUsuarioMenu().split(","))) {

        List<Demandas> demandas = administracaoFacade.adiquirirDemandas();

        for (Iterator<Demandas> iterator = demandas.iterator(); iterator.hasNext(); ) {
          Demandas demandas2 = (Demandas) iterator.next();
          demandas2.setCliente(demandas2.getUsuarioSolicitante().getUsuarioNome());
          demandas2.setResponsavel(
              demandas2.getUsuarioResponsavel() != null
                  ? demandas2.getUsuarioResponsavel().getUsuarioNome()
                  : "");
          demandas2.setTecnicoAbriu(demandas2.getUsuarioAbriu().getUsuarioNome());
          SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
          Timestamp time = demandas2.getDemandasDataAbertura();
          demandas2.setDataAbertura(sdf.format(new Date(time.getTime())));
          demandas2.setFechar("Aberta");
        }
        session.setAttribute("demandas", demandas);
        return new ModelAndView("iphone/demandas_FinalizarDemanda");
      } else {
        return new ModelAndView("index2");
      }
    } else {
      return new ModelAndView("index2");
    }
  }
Beispiel #23
0
  public static Date getLastCalendarModifiedDate(long calendarId)
      throws PortalException, SystemException {

    ClassLoader classLoader = ClassLoaderPool.getClassLoader("calendar-portlet");

    DynamicQuery dynamicQuery =
        DynamicQueryFactoryUtil.forClass(CalendarBooking.class, classLoader);

    dynamicQuery.add(RestrictionsFactoryUtil.eq("calendarId", calendarId));

    dynamicQuery.setProjection(ProjectionFactoryUtil.property("modifiedDate"));

    dynamicQuery.setLimit(0, 1);

    dynamicQuery.addOrder(OrderFactoryUtil.desc("modifiedDate"));

    List<Object> lastModifiedDate = CalendarBookingLocalServiceUtil.dynamicQuery(dynamicQuery);

    if ((lastModifiedDate != null) && !lastModifiedDate.isEmpty()) {
      Timestamp ts = (Timestamp) lastModifiedDate.get(0);
      return new Date(ts.getTime());
    }

    return new Date();
  }
Beispiel #24
0
 static Timestamp bucketByHour(Timestamp t) {
   Timestamp result = new Timestamp(t.getTime());
   result.setSeconds(0);
   result.setMinutes(0);
   result.setNanos(0);
   return result;
 }
 private boolean timestampIsActual(Timestamp timestamp) {
   long actualTime = actualityMinutes * 60;
   long current = System.currentTimeMillis() / 1000;
   long fromTrafInfo = timestamp.getTime();
   long sub = current - fromTrafInfo;
   return sub < actualTime;
 }
Beispiel #26
0
    public static IRubyObject prepareRubyDateTimeFromSqlTimestamp(Ruby runtime,Timestamp stamp){

       if (stamp.getTime() == 0) {
           return runtime.getNil();
       }

       gregCalendar.setTime(stamp);
       int month = gregCalendar.get(Calendar.MONTH);
       month++; // In Calendar January == 0, etc...

       int zoneOffset = gregCalendar.get(Calendar.ZONE_OFFSET)/3600000;
       RubyClass klazz = runtime.fastGetClass("DateTime");

       IRubyObject rbOffset = runtime.fastGetClass("Rational")
                .callMethod(runtime.getCurrentContext(), "new",new IRubyObject[]{
            runtime.newFixnum(zoneOffset),runtime.newFixnum(24)
        });

       return klazz.callMethod(runtime.getCurrentContext() , "civil",
                 new IRubyObject []{runtime.newFixnum(gregCalendar.get(Calendar.YEAR)),
                 runtime.newFixnum(month),
                 runtime.newFixnum(gregCalendar.get(Calendar.DAY_OF_MONTH)),
                 runtime.newFixnum(gregCalendar.get(Calendar.HOUR_OF_DAY)),
                 runtime.newFixnum(gregCalendar.get(Calendar.MINUTE)),
                 runtime.newFixnum(gregCalendar.get(Calendar.SECOND)),
                 rbOffset});
    }
  /**
   * **************************************************************
   *
   * <p>Test should be exactly n calender days before reference
   *
   * @param test - the date to test
   * @param reference - reference date
   * @param days - how many days
   * @return - is it on that day
   */
  public static boolean daysBefore(Timestamp test, Timestamp reference, int days) {

    reference = getDay(new Timestamp(reference.getTime() - 24 * 3600 * 1000 * days));
    test = getDay(test);

    return test.equals(reference);
  }
  protected void prepareTestData() throws java.lang.Exception {
    long currentTime = TimeUtil.getCurrentLocalTimeMillis();
    long oneHour = 3600000;
    long positive = 8 * oneHour + currentTime;
    long negative = -5 * oneHour + currentTime;

    _times =
        new long[][] {
          {positive, currentTime},
          {currentTime, currentTime},
          {negative, currentTime},
        };

    Calendar cal = GregorianCalendar.getInstance();
    cal.set(2002, 9, 19, 5, 5, 29);
    _testDate = new Timestamp(cal.getTime().getTime());

    Logger.debug("Test date (ts)= " + _testDate);
    Logger.debug("Test date (ms)= " + _testDate.getTime());

    _timeServer = UtcTimeServer.getInstance();

    TimeUtil.setTimeServer(_timeServer);

    _event = new GetUtcTimeEvent();

    //    createSessions(1);
    //    createStateMachines(1);

  }
 static String getBanDurationBreakdown(final Timestamp stamp) {
   if (stamp == null) return "Banned Forever";
   final long millis = stamp.getTime() - System.currentTimeMillis();
   if (millis < 0) return "Ban time left: 1 Minute";
   long seconds = Math.max(1, TimeUnit.MILLISECONDS.toSeconds(millis));
   final int minutesInSeconds = 60;
   final int hoursInSeconds = 60 * 60;
   final int daysInSeconds = 60 * 60 * 24;
   final long days = seconds / daysInSeconds;
   seconds -= days * daysInSeconds;
   final long hours = seconds / hoursInSeconds;
   seconds -= hours * hoursInSeconds;
   final long minutes = Math.max(1, seconds / minutesInSeconds);
   /*
   final long days = TimeUnit.MILLISECONDS.toDays(millis);
   millis -= TimeUnit.DAYS.toMillis(days);
   final long hours = TimeUnit.MILLISECONDS.toHours(millis);
   millis -= TimeUnit.HOURS.toMillis(hours);
   final long minutes = TimeUnit.MILLISECONDS.toMinutes(millis) + 1;*/
   final StringBuilder sb = new StringBuilder(64);
   sb.append("Ban time left: ");
   if (days > 0) {
     sb.append(days);
     sb.append(" Days ");
   }
   if (hours > 0) {
     sb.append(hours);
     sb.append(" Hours ");
   }
   if (minutes > 0) {
     sb.append(minutes);
     sb.append(" Minutes ");
   }
   return (sb.toString());
 }
    @Override
    public Pay mapRow(ResultSet rs, int rowNum) throws SQLException {
      Pay pay = new Pay();
      pay.setId(rs.getInt("id"));
      Timestamp timestamp = rs.getTimestamp("time");
      if (timestamp != null) {
        pay.setTime(new java.util.Date(timestamp.getTime()));
      }
      pay.setDemand_id(rs.getString("demand_id"));
      Manufacturer manufacturer =
          new Manufacturer(rs.getInt("manufacturer_id"), rs.getString("manufacturer_name"), null);
      pay.setManufacturer(manufacturer);
      User user =
          new User(
              rs.getInt("user_id"),
              rs.getString("user_name"),
              rs.getString("user_email"),
              rs.getString("user_login"));
      pay.setUser(user);
      pay.setStorno((rs.getInt("storno") == 0 ? false : true));
      pay.setSumm(rs.getDouble("summ"));
      pay.setNumDoc(rs.getString("numDoc"));
      pay.setClient(
          new Client(
              rs.getInt("client_id"),
              rs.getString("client_name"),
              rs.getString("client_email"),
              rs.getString("client_address"),
              null));

      return pay;
    }