Java Code Examples for java.util.Date#getTime()

The following examples show how to use java.util.Date#getTime() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Eagle   File: AbstractHBaseLogReader.java    License: Apache License 2.0 6 votes vote down vote up
private static byte[] buildRowKey(String prefix, List<String> partitions, Date t){
	final int length = (partitions == null) ? (4 + 8) : (4 + 8 + partitions.size() * 4);
	final byte[] key = new byte[length];
	int offset = 0;
	ByteUtil.intToBytes(prefix.hashCode(), key, offset);
	offset += 4;
	if (partitions != null) {
		for (String partition : partitions) {
			ByteUtil.intToBytes(partition.hashCode(), key, offset);
			offset += 4;
		}
	}
	// reverse timestamp
	long ts = Long.MAX_VALUE - t.getTime();
	ByteUtil.longToBytes(ts, key, offset);
	return key;
}
 
Example 2
Source Project: steady   File: SecurityToken.java    License: Apache License 2.0 6 votes vote down vote up
public SecurityToken(String id,
             Element tokenElem,
             Date created,
             Date expires) {
    this.id = id;
    if (this.id != null && this.id.length() > 0 && this.id.charAt(0) == '#') {
        this.id = this.id.substring(1);
    }
    this.token = cloneElement(tokenElem);
    if (created != null) {
        this.created = new Date(created.getTime());
    }
    if (expires != null) {
        this.expires = new Date(expires.getTime());
    }
}
 
Example 3
private void checkTimeout(AlarmIncident incident) {
   if(incident == null || incident.isCleared()) {
      return;
   }
   
   List<TrackerEvent> tracker = incident.getTracker();
   Date lastActivity = null;
   if(tracker != null && !tracker.isEmpty()) {
      lastActivity = tracker.get(tracker.size() - 1).getTime();
   }
   if(lastActivity == null) {
      lastActivity = incident.getStartTime();
   }
   Date expirationDate = new Date(lastActivity.getTime() + TimeUnit.SECONDS.toMillis(dispatchTimeoutSeconds));
   if(new Date().after(expirationDate)) {
      updateMonitoringState(incident, AlarmIncidentCapability.MONITORINGSTATE_FAILED);
   }
}
 
Example 4
Source Project: bboxdb   File: TestTupleBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test the yellow taxi range tuple builder
 * @throws ParseException
 */
@Test
public void testYellowTaxiRangeTupleBuilder() throws ParseException {
	final TupleBuilder tupleBuilder = TupleBuilderFactory.getBuilderForFormat(
			TupleBuilderFactory.Name.YELLOWTAXI_RANGE);

	final Tuple tuple = tupleBuilder.buildTuple(TAXI_TEST_LINE, "1");

	Assert.assertNotNull(tuple);
	Assert.assertEquals(Integer.toString(1), tuple.getKey());

	final SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
	final Date dateLow = dateParser.parse("2016-01-01 00:00:00");
	final Date dateHigh = dateParser.parse("2016-01-01 00:00:00");

	final Hyperrectangle exptectedBox = new Hyperrectangle(-73.990371704101563, -73.981842041015625,
			40.732406616210937, 40.734695434570313,
			(double) dateLow.getTime(), (double) dateHigh.getTime());

	Assert.assertEquals(exptectedBox, tuple.getBoundingBox());
}
 
Example 5
private Long durationTask(Business business, Date start, Date current, ActivityStub activityStub) throws Exception {
	EntityManager em = business.entityManagerContainer().get(Task.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Date> cq = cb.createQuery(Date.class);
	Root<Task> root = cq.from(Task.class);
	Predicate p = cb.greaterThan(root.get(Task_.startTime), start);
	p = cb.and(p, cb.equal(root.get(Task_.activity), activityStub.getValue()));
	cq.select(root.get(Task_.startTime)).where(p);
	List<Date> os = em.createQuery(cq).getResultList();
	long duration = 0;
	for (Date o : os) {
		duration += current.getTime() - o.getTime();
	}
	duration = duration / (1000L * 60L);
	return duration;
}
 
Example 6
Source Project: roncoo-pay   File: DateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 返回天数
 * @param date1
 * @param date2
 * @return
 */
public static long getDateDiff(Date date1, Date date2) {
	if (date1 == null || date2 == null) {
		return 0L;
	}
	long diff = (date1.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000) > 0 ? (date1.getTime() - date2
			.getTime()) / (24 * 60 * 60 * 1000) : (date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000);
	return diff;
}
 
Example 7
private void setCountdownTimer(String date) {
  SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  DecimalFormat countdownNumberFormat = new DecimalFormat("00");
  dateFormatter.setLenient(false);
  final long now = System.currentTimeMillis();
  long dateMillis = 0;
  Date endDate;
  try {
    endDate = dateFormatter.parse(date);
    dateMillis = endDate.getTime();
  } catch (ParseException e) {
    e.printStackTrace();
  }

  long timeToDisplay = dateMillis - now;

  poaCountdownHours.setText(countdownNumberFormat.format(0));
  poaCountdownMinutes.setText(countdownNumberFormat.format(0));
  poaCountdownSeconds.setText(countdownNumberFormat.format(0));

  if (timeToDisplay >= 0) {
    poaCountdownTimer = new CountDownTimer(timeToDisplay, 1000) {
      @Override public void onTick(long millisUntilFinished) {
        String hoursLeft = countdownNumberFormat.format(millisUntilFinished / 3600000);
        poaCountdownHours.setText(hoursLeft);
        String minutesLeft =
            countdownNumberFormat.format((millisUntilFinished % 3600000) / 60000);
        poaCountdownMinutes.setText(minutesLeft);
        String secondsLeft =
            countdownNumberFormat.format(((millisUntilFinished % 360000) % 60000) / 1000);
        poaCountdownSeconds.setText(secondsLeft);
      }

      @Override public void onFinish() {
      }
    }.start();
  }
}
 
Example 8
/**
 * Deserialize the {@code CertificateRevokedException} instance.
 */
private void readObject(ObjectInputStream ois)
    throws IOException, ClassNotFoundException {
    // Read in the non-transient fields
    // (revocationDate, reason, authority)
    ois.defaultReadObject();

    // Defensively copy the revocation date
    revocationDate = new Date(revocationDate.getTime());

    // Read in the size (number of mappings) of the extensions map
    // and create the extensions map
    int size = ois.readInt();
    if (size == 0) {
        extensions = Collections.emptyMap();
    } else {
        extensions = new HashMap<String, Extension>(size);
    }

    // Read in the extensions and put the mappings in the extensions map
    for (int i = 0; i < size; i++) {
        String oid = (String) ois.readObject();
        boolean critical = ois.readBoolean();
        int length = ois.readInt();
        byte[] extVal = new byte[length];
        ois.readFully(extVal);
        Extension ext = sun.security.x509.Extension.newExtension
            (new ObjectIdentifier(oid), critical, extVal);
        extensions.put(oid, ext);
    }
}
 
Example 9
@Test
public void testCascadeChangeToRecurringTimerAddToDuedate() {
  // given timer R2/PT30M
  BpmnModelInstance process = Bpmn.createExecutableProcess("process").startEvent().userTask("userTask").boundaryEvent().cancelActivity(false)
      .timerWithCycle("R2/PT30M").endEvent().moveToActivity("userTask").endEvent().done();
  testRule.deploy(process);
  runtimeService.startProcessInstanceByKey("process");

  // when

  // offset job1 due date by +15 minutes (=> due t0 + 45 minutes)
  Job job1 = managementService.createJobQuery().singleResult();
  job1 = modifyDueDate(job1, true, minutes(15));

  // currentTime = due date + 5 seconds
  Date t1 = new Date(t0.getTime() + minutes(45) + 5000);
  setTimeAndExecuteJobs(t1);

  // job2 should keep the offset of +15 minutes (=> due t1 + 30 minutes)
  Job job2 = managementService.createJobQuery().singleResult();

  // currentTime = due date + 5 seconds
  Date t2 = new Date(t1.getTime() + minutes(30));
  setTimeAndExecuteJobs(t2);

  // then
  assertThat(job1.getId()).isNotEqualTo(job2.getId());
  // job1 is due after 45 minutes (30 + 15 offset)
  assertThat(job1.getDuedate().getTime()).isEqualTo(t0.getTime() + minutes(45));
  // job2 is due 30 minutes after job1 (keeps offset due to cascade=true)
  assertThat(job2.getDuedate().getTime()).isEqualTo(job1.getDuedate().getTime() + minutes(30));
}
 
Example 10
public static Date forceDate(Date timestamp) {
	if (timestamp != null) {
		return new Date(timestamp.getTime());
	} else {
		return null;
	}
}
 
Example 11
protected void parseMaxAgeParameter(RoutingContext context) {
    // if user is already authenticated and if the last login date is greater than the max age parameter,
    // the OP MUST attempt to actively re-authenticate the End-User.
    User authenticatedUser = context.user();
    if (authenticatedUser == null || !(authenticatedUser.getDelegate() instanceof io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User)) {
        // user not authenticated, continue
        return;
    }

    String maxAge = context.request().getParam(Parameters.MAX_AGE);
    if (maxAge == null || !maxAge.matches("-?\\d+")) {
        // none or invalid max age, continue
        return;
    }

    io.gravitee.am.model.User endUser = ((io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User) authenticatedUser.getDelegate()).getUser();
    Date loggedAt = endUser.getLoggedAt();
    if (loggedAt == null) {
        // user has no last login date, continue
        return;
    }

    // check the elapsed user session duration
    long elapsedLoginTime = (System.currentTimeMillis() - loggedAt.getTime()) / 1000L;
    Long maxAgeValue = Long.valueOf(maxAge);
    if (maxAgeValue < elapsedLoginTime) {
        // check if the user doesn't come from the login page
        if (!returnFromLoginPage(context)) {
            // should we logout the user or just force it to go to the login page ?
            context.clearUser();

            // check prompt parameter in case the user set 'none' option
            parsePromptParameter(context);
        }
    }
}
 
Example 12
Source Project: Tomcat8-Source-Read   File: ExpiresFilter.java    License: MIT License 5 votes vote down vote up
/**
 * <p>
 * If no expiration header has been set by the servlet and an expiration has
 * been defined in the {@link ExpiresFilter} configuration, sets the
 * '{@code Expires}' header and the attribute '{@code max-age}' of the
 * '{@code Cache-Control}' header.
 * </p>
 * <p>
 * Must be called on the "Start Write Response Body" event.
 * </p>
 * <p>
 * Invocations to {@code Logger.debug(...)} are guarded by
 * {@link Log#isDebugEnabled()} because
 * {@link HttpServletRequest#getRequestURI()} and
 * {@link HttpServletResponse#getContentType()} costs {@code String}
 * objects instantiations (as of Tomcat 7).
 * </p>
 * @param request The Servlet request
 * @param response The Servlet response
 */
public void onBeforeWriteResponseBody(HttpServletRequest request,
        XHttpServletResponse response) {

    if (!isEligibleToExpirationHeaderGeneration(request, response)) {
        return;
    }

    Date expirationDate = getExpirationDate(request, response);
    if (expirationDate == null) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("expiresFilter.noExpirationConfigured",
                    request.getRequestURI(),
                    Integer.valueOf(response.getStatus()),
                    response.getContentType()));
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("expiresFilter.setExpirationDate",
                    request.getRequestURI(),
                    Integer.valueOf(response.getStatus()),
                    response.getContentType(), expirationDate));
        }

        String maxAgeDirective = "max-age=" +
                ((expirationDate.getTime() - System.currentTimeMillis()) / 1000);

        String cacheControlHeader = response.getCacheControlHeader();
        String newCacheControlHeader = (cacheControlHeader == null) ? maxAgeDirective
                : cacheControlHeader + ", " + maxAgeDirective;
        response.setHeader(HEADER_CACHE_CONTROL, newCacheControlHeader);
        response.setDateHeader(HEADER_EXPIRES, expirationDate.getTime());
    }

}
 
Example 13
Source Project: MaxKey   File: TimeBasedOTPTest.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  	 
  	 //byte[]byteseed=OPTSecret.generate();
  	 
  	
  	 byte[]byteseed= Base32Utils.decode("DCGAGPE2BCDBD6D3FG4NX2QGACVIHXP4");//HexUtils.hex2Bytes( "a1270caecf007f2303cc9db12597a9694ff541aa");
       String seed=Base32Utils.encode(byteseed);
       
       String hexString=Hex.encodeHexString(byteseed);
       //String hexString=HexUtils.bytes2HexString(byteseed);
       System.out.println(hexString);
       System.out.println(HexUtils.bytes2HexString(byteseed));

       
       DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       df.setTimeZone(TimeZone.getTimeZone("UTC"));
       String utcTime = df.format(new Date());
       Date curr=null;
       try {
      	 curr=df.parse(utcTime);
} catch (ParseException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
       long currentTimeSeconds = curr.getTime() / 1000;
       currentTimeSeconds =System.currentTimeMillis() / 1000;
       int INTERVAL = 30;
       
       System.out.println(utcTime);
       
       //google time based
  	 System.out.println(TimeBasedOTP.genOTP(hexString,Long.toHexString(currentTimeSeconds/INTERVAL).toUpperCase()+"","6"));
  	 //google counter based
  	 System.out.println(TimeBasedOTP.genOTP(hexString,3+"","6"));
  	
 
   }
 
Example 14
Source Project: uavstack   File: DateTimeHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 判断二个日期相隔的天数,结束时间为null时,,取当前时间
 * 
 * @param startDate
 *            开始时间
 * @param endDate
 *            结束时间
 * @return
 */
public static int getBetweenTodaysStartDateAndEndDate(Date startDate, Date endDate) {

    int betweentoday = 0;
    if (startDate == null) {
        return betweentoday;
    }
    if (endDate == null) {
        Calendar calendar = Calendar.getInstance();
        String year = new Integer(calendar.get(Calendar.YEAR)).toString();
        String month = new Integer((calendar.get(Calendar.MONTH) + 1)).toString();
        String day = new Integer(calendar.get(Calendar.DAY_OF_MONTH)).toString();
        String strtodaytime = year + "-" + month + "-" + day;
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            endDate = formatter.parse(strtodaytime);
        }
        catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (endDate.after(startDate)) {
        betweentoday = (int) ((endDate.getTime() - startDate.getTime()) / 86400000);
    }
    else {
        betweentoday = (int) ((startDate.getTime() - endDate.getTime()) / 86400000);
    }
    return betweentoday;
}
 
Example 15
Source Project: org.openntf.domino   File: LogConfig.java    License: Apache License 2.0 5 votes vote down vote up
public void throwExpiredFCEs(final Date now) {
	for (int i = _logFCEList.size() - 1; i >= 0; i--) {
		L_LogFilterConfigEntry lfce = _logFCEList.get(i);
		if (lfce._validUntil != null && lfce._validUntil.getTime() <= now.getTime()) {
			System.out.println("HINT: Filter Config Entry expired due to ValidUntil=" + lfce._validUntilStr);
			_logFCEList.remove(i);
		}
	}
}
 
Example 16
public static void waitForDocCount(Query query, long expectedNumFound, long waitMillis)
        throws Exception
{
    Date date = new Date();
    long timeout = date.getTime() + waitMillis;

    RefCounted<SolrIndexSearcher> ref = null;
    int totalHits = 0;
    while(new Date().getTime() < timeout)
    {
        try
        {
            ref = getCore().getSearcher();
            SolrIndexSearcher searcher = ref.get();
            TopDocs topDocs = searcher.search(query, 10);
            totalHits = topDocs.totalHits;
            if (topDocs.totalHits == expectedNumFound)
            {
                LOG.warn("Query \"" + query + "\" returned " + totalHits + " as expected");
                return;
            }
            else
            {
                LOG.warn("Query \"" + query + "\" returned " + totalHits + ", expected " + expectedNumFound);
                Thread.sleep(2000);
            }
        }
        finally
        {
            ref.decref();
        }
    }
    throw new Exception("Wait error expected "+expectedNumFound+" found "+totalHits+" : "+query.toString());
}
 
Example 17
/**
 * Creates a wait strategy that will wait until the given deadline and then timeout.
 *
 * @param deadline                  the time at which the wait strategy starts timing-out.
 * @param maximumPollDurationMillis maximum duration for each long-poll request to the server, in milliseconds
 */
public static WaitStrategy until(final Date deadline, final long maximumPollDurationMillis) {
    return new WaitStrategy() {
        @Override
        public String getWait() throws WaitStrategyExhaustedException {
            long remainingMillis = deadline.getTime() - System.currentTimeMillis();
            if (remainingMillis < 0)
                throw new WaitStrategyExhaustedException("Past deadline of " + deadline);
            return Math.min(remainingMillis, maximumPollDurationMillis) + "ms";
        }
    };
}
 
Example 18
public void setCloseDate(Date closeDate) {
    this.closeDate = closeDate.getTime();
}
 
Example 19
Source Project: coming   File: Time_12_LocalDateTime_s.java    License: MIT License 4 votes vote down vote up
/**
 * Constructs a LocalDateTime from a <code>java.util.Date</code>
 * using exactly the same field values.
 * <p>
 * Each field is queried from the Date and assigned to the LocalDateTime.
 * This is useful if you have been using the Date as a local date,
 * ignoring the zone.
 * <p>
 * One advantage of this method is that this method is unaffected if the
 * version of the time zone data differs between the JDK and Joda-Time.
 * That is because the local field values are transferred, calculated using
 * the JDK time zone data and without using the Joda-Time time zone data.
 * <p>
 * This factory method always creates a LocalDateTime with ISO chronology.
 *
 * @param date  the Date to extract fields from, not null
 * @return the created local date-time, not null
 * @throws IllegalArgumentException if the calendar is null
 * @throws IllegalArgumentException if the date is invalid for the ISO chronology
 */
@SuppressWarnings("deprecation")
public static LocalDateTime fromDateFields(Date date) {
    if (date == null) {
        throw new IllegalArgumentException("The date must not be null");
    }
        // handle years in era BC
    return new LocalDateTime(
        date.getYear() + 1900,
        date.getMonth() + 1,
        date.getDate(),
        date.getHours(),
        date.getMinutes(),
        date.getSeconds(),
        (((int) (date.getTime() % 1000)) + 1000) % 1000
    );
}
 
Example 20
Source Project: scelight   File: RelativeDate.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new {@link RelativeDate}.
 * 
 * See {@link #toString(boolean, int, boolean)} for details.
 * 
 * @param date absolute date to be represented relatively to the current time
 * @param longForm tells if long form is to be used for time units
 * @param tokens tells how many tokens to include
 * @param appendEra tells if era is to be appended; era is <code>"ago"</code> for past times and <code>"from now"</code> for future times
 * 
 * @see #toString(boolean, int, boolean)
 */
public RelativeDate( final Date date, final boolean longForm, final int tokens, final boolean appendEra ) {
	this( date.getTime(), longForm, tokens, appendEra );
}