Example usage for java.util GregorianCalendar getTime

List of usage examples for java.util GregorianCalendar getTime

Introduction

In this page you can find the example usage for java.util GregorianCalendar getTime.

Prototype

public final Date getTime() 

Source Link

Document

Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").

Usage

From source file:org.jfree.data.time.DayTest.java

/**
 * Problem for date parsing./*w w w.  ja  v  a  2 s .c o  m*/
 * <p>
 * This test works only correct if the short pattern of the date
 * format is "dd/MM/yyyy". If not, this test will result in a
 * false negative.
 *
 * @throws ParseException on parsing errors.
 */
@Test
public void testParseDay() throws ParseException {
    GregorianCalendar gc = new GregorianCalendar(2001, 12, 31);
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    Date reference = format.parse("31/12/2001");
    if (reference.equals(gc.getTime())) {
        // test 1...
        Day d = Day.parseDay("31/12/2001");
        assertEquals(37256, d.getSerialDate().toSerial());
    }

    // test 2...
    Day d = Day.parseDay("2001-12-31");
    assertEquals(37256, d.getSerialDate().toSerial());
}

From source file:com.edduarte.vokter.job.JobManager.java

public boolean createJob(final SubscribeRequest request) {

    String documentUrl = request.getDocumentUrl();
    String clientUrl = request.getClientUrl();

    try {/*w w w  .  j  av  a  2s . c o  m*/
        // attempt creating a new DiffDetectorJob
        JobDetail detectionJob = JobBuilder.newJob(DetectionJob.class)
                .withIdentity(documentUrl, "detection" + documentUrl)
                .usingJobData(DetectionJob.PARENT_JOB_MANAGER, managerName)
                .usingJobData(DetectionJob.FAULT_COUNTER, 0).build();

        Trigger detectionTrigger = TriggerBuilder.newTrigger()
                .withIdentity(documentUrl, "detection" + documentUrl).withSchedule(SimpleScheduleBuilder
                        .simpleSchedule().withIntervalInSeconds(detectionInterval).repeatForever())
                .build();

        try {
            scheduler.scheduleJob(detectionJob, detectionTrigger);
            logger.info("Started detection job for '{}'.", documentUrl);
        } catch (ObjectAlreadyExistsException ignored) {
            // there is already a job monitoring the request url, so ignore this
        }

        ObjectMapper mapper = new ObjectMapper();
        String keywordJson = mapper.writeValueAsString(request.getKeywords());

        JobDetail matchingJob = JobBuilder.newJob(MatchingJob.class)
                .withIdentity(clientUrl, "matching" + documentUrl)
                .usingJobData(MatchingJob.PARENT_JOB_MANAGER, managerName)
                .usingJobData(MatchingJob.REQUEST_URL, documentUrl)
                .usingJobData(MatchingJob.KEYWORDS, keywordJson)
                .usingJobData(MatchingJob.IGNORE_ADDED, request.getIgnoreAdded())
                .usingJobData(MatchingJob.IGNORE_REMOVED, request.getIgnoreRemoved())
                .usingJobData(MatchingJob.HAS_NEW_DIFFS, false).build();

        GregorianCalendar cal = new GregorianCalendar();
        cal.add(Calendar.SECOND, request.getInterval());

        Trigger matchingTrigger = TriggerBuilder.newTrigger().withIdentity(clientUrl, "matching" + documentUrl)
                .startAt(cal.getTime()).withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(request.getInterval()).repeatForever())
                .build();

        try {
            scheduler.scheduleJob(matchingJob, matchingTrigger);
        } catch (ObjectAlreadyExistsException ex) {
            return false;
        }

    } catch (SchedulerException | JsonProcessingException ex) {
        logger.error(ex.getMessage(), ex);
    }

    return true;
}

From source file:org.springframework.integration.x.rollover.file.RolloverFileOutputStream.java

/**
 * @param filename/* w  w  w  .  j  a v  a2s  .  c o  m*/
 *            The filename must include the string "yyyy_mm_dd", which is replaced with the actual date when
 *            creating and rolling over the file.
 * @param append
 *            If true, existing files will be appended to.
 * @param zone
 *            the timezone for the output
 * @param dateFormat
 *            The format for the date file substitution. The default is "yyyy_MM_dd".
 * @param rolloverStartTimeMs
 *            Defines the time in [ms] of the first file roll over process to start.
 * @param rolloverPeriodMs
 *            Defines the frequency (in ms) of the file roll over processes.
 * @throws IOException
 *             if unable to create output
 */
public RolloverFileOutputStream(String filename, boolean append, TimeZone zone, String dateFormat,
        long rolloverStartTimeMs, long rolloverPeriodMs, long maxRolledFileSize, String archivePrefix,
        boolean compressArchive, int bufferSize, FileCompressor fileCompressor) throws IOException {

    super(null);

    this.bufferSize = bufferSize;
    this.compressArchive = compressArchive;
    this.archivePrefix = archivePrefix;
    this.maxRolledFileSize = maxRolledFileSize;

    if (dateFormat == null) {
        dateFormat = ROLLOVER_FILE_DATE_FORMAT;
    }

    fileDateFormat = new SimpleDateFormat(dateFormat);

    if (StringUtils.isEmpty(filename)) {
        throw new IllegalArgumentException("Invalid filename");
    }

    filePath = filename.trim();
    fileDir = new File(new File(filename).getAbsolutePath()).getParentFile();

    if (fileDir != null && (!fileDir.isDirectory() || !fileDir.canWrite())) {
        throw new IOException("Cannot write into directory: " + fileDir);
    }

    appendToFile = append;
    setFile(true);

    synchronized (RolloverFileOutputStream.class) {

        if (rolloverTimer == null) {
            rolloverTimer = new Timer(RolloverFileOutputStream.class.getName(), true);
        }

        rollTask = new RollTask();

        Date startTime = null;
        if (rolloverStartTimeMs <= 0) {
            Calendar now = Calendar.getInstance();
            now.setTimeZone(zone);

            GregorianCalendar midnight = new GregorianCalendar(now.get(Calendar.YEAR), now.get(Calendar.MONTH),
                    now.get(Calendar.DAY_OF_MONTH), 23, 0);
            midnight.setTimeZone(zone);
            midnight.add(Calendar.HOUR, 1);

            startTime = midnight.getTime();
        } else {
            startTime = new Date(rolloverStartTimeMs);
        }

        long period = (rolloverPeriodMs <= 0) ? 86400000 : rolloverPeriodMs;

        rolloverTimer.scheduleAtFixedRate(rollTask, startTime, period);
    }

    this.fileCompressor = fileCompressor;
}

From source file:de.fhbingen.wbs.wpOverview.tabs.AvailabilityGraph.java

/**
 * Set the view to YEAR.//from w  w  w .  jav  a2  s . c o  m
 */
private void setYearView() {

    actualStart = (GregorianCalendar) actualDay.clone();
    actualStart.set(Calendar.DAY_OF_YEAR, actualDay.getActualMinimum(Calendar.DAY_OF_YEAR));
    actualStart.set(Calendar.HOUR, 0);
    actualStart.set(Calendar.MINUTE, 0);
    actualStart.add(Calendar.DAY_OF_YEAR, -1);

    actualEnd = (GregorianCalendar) actualDay.clone();
    actualEnd.set(Calendar.DAY_OF_YEAR, actualDay.getActualMaximum(Calendar.DAY_OF_YEAR));
    actualEnd.set(Calendar.HOUR, 23);
    actualEnd.set(Calendar.MINUTE, 59);

    actualView = YEAR;

    GregorianCalendar helper = (GregorianCalendar) actualEnd.clone();
    helper.add(Calendar.DATE, -1);

    makeChart(new SimpleDateFormat("yyyy").format(helper.getTime()));
}

From source file:org.xdi.oxauth.client.TokenRequest.java

public String getClientAssertion() {
    Jwt clientAssertion = new Jwt();

    if (algorithm == null) {
        algorithm = SignatureAlgorithm.HS256;
    }//from   w  ww. j a va 2  s .  c o  m
    GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    Date issuedAt = calendar.getTime();
    calendar.add(Calendar.MINUTE, 5);
    Date expirationTime = calendar.getTime();

    // Header
    clientAssertion.getHeader().setType(JwtType.JWS);
    clientAssertion.getHeader().setAlgorithm(algorithm);
    if (StringUtils.isNotBlank(keyId)) {
        clientAssertion.getHeader().setKeyId(keyId);
    }

    // Claims
    clientAssertion.getClaims().setIssuer(getAuthUsername());
    clientAssertion.getClaims().setSubjectIdentifier(getAuthUsername());
    clientAssertion.getClaims().setAudience(audience);
    clientAssertion.getClaims().setJwtId(UUID.randomUUID());
    clientAssertion.getClaims().setExpirationTime(expirationTime);
    clientAssertion.getClaims().setIssuedAt(issuedAt);

    // Signature
    try {
        if (algorithm == SignatureAlgorithm.HS256 || algorithm == SignatureAlgorithm.HS384
                || algorithm == SignatureAlgorithm.HS512) {
            if (sharedKey == null) {
                sharedKey = getAuthPassword();
            }
            HMACSigner hmacSigner = new HMACSigner(algorithm, sharedKey);
            clientAssertion = hmacSigner.sign(clientAssertion);
        } else if (algorithm == SignatureAlgorithm.RS256 || algorithm == SignatureAlgorithm.RS384
                || algorithm == SignatureAlgorithm.RS512) {
            RSASigner rsaSigner = new RSASigner(algorithm, rsaPrivateKey);
            clientAssertion = rsaSigner.sign(clientAssertion);
        } else if (algorithm == SignatureAlgorithm.ES256 || algorithm == SignatureAlgorithm.ES384
                || algorithm == SignatureAlgorithm.ES512) {
            ECDSASigner ecdsaSigner = new ECDSASigner(algorithm, ecPrivateKey);
            clientAssertion = ecdsaSigner.sign(clientAssertion);
        }
    } catch (SignatureException e) {
        return null;
    } catch (InvalidJwtException e) {
        return null;
    }

    return clientAssertion.toString();
}

From source file:de.fhbingen.wbs.wpOverview.tabs.AvailabilityGraph.java

/**
 * Set the view to MONTH.//from   www.j a v  a  2 s.co m
 */
private void setMonthView() {

    actualStart = (GregorianCalendar) actualDay.clone();
    actualStart.set(Calendar.DAY_OF_MONTH, 1);
    actualStart.set(Calendar.HOUR, 0);
    actualStart.set(Calendar.MINUTE, 0);

    actualEnd = (GregorianCalendar) actualDay.clone();
    actualEnd.set(Calendar.DAY_OF_MONTH, actualEnd.getActualMaximum(Calendar.DAY_OF_MONTH));
    actualEnd.set(Calendar.HOUR, 23);
    actualEnd.set(Calendar.MINUTE, 59);

    actualStart.add(Calendar.HOUR, -1);
    actualEnd.add(Calendar.HOUR, 1);

    actualView = MONTH;

    GregorianCalendar helper = (GregorianCalendar) actualEnd.clone();
    helper.add(Calendar.DATE, -1);

    makeChart(new SimpleDateFormat("MMMM yyyy").format(helper.getTime()));
}

From source file:org.geotools.gce.imagemosaic.ImageMosaicPostgisIndexTest.java

/**
 * Complex test for Postgis indexing on db.
 * /*from w  w w . ja v a 2s  .  c o  m*/
 * @throws Exception
 */
@Test
public void testSortingAndLimiting() throws Exception {
    final File workDir = new File(TestData.file(this, "."), "watertemp4");
    assertTrue(workDir.mkdir());
    FileUtils.copyFile(TestData.file(this, "watertemp.zip"), new File(workDir, "watertemp.zip"));
    TestData.unzipFile(this, "watertemp4/watertemp.zip");
    final URL timeElevURL = TestData.url(this, "watertemp4");

    //place datastore.properties file in the dir for the indexing
    FileWriter out = null;
    try {
        out = new FileWriter(new File(TestData.file(this, "."), "/watertemp4/datastore.properties"));

        final Set<Object> keyset = fixture.keySet();
        for (Object key : keyset) {
            final String key_ = (String) key;
            final String value = fixture.getProperty(key_);
            out.write(key_.replace(" ", "\\ ") + "=" + value.replace(" ", "\\ ") + "\n");
        }
        out.flush();
    } finally {
        if (out != null) {
            IOUtils.closeQuietly(out);
        }
    }

    // now start the test
    final AbstractGridFormat format = TestUtils.getFormat(timeElevURL);
    assertNotNull(format);
    ImageMosaicReader reader = TestUtils.getReader(timeElevURL, format);
    assertNotNull(reader);

    final String[] metadataNames = reader.getMetadataNames();
    assertNotNull(metadataNames);
    assertEquals(metadataNames.length, 10);

    assertEquals("true", reader.getMetadataValue("HAS_TIME_DOMAIN"));
    assertEquals("true", reader.getMetadataValue("HAS_ELEVATION_DOMAIN"));

    // dispose and create new reader
    reader.dispose();
    final MyImageMosaicReader reader1 = new MyImageMosaicReader(timeElevURL);
    final RasterManager rm = reader1.getRasterManager();

    // query
    final SimpleFeatureType type = rm.granuleCatalog.getType();
    Query query = null;
    if (type != null) {
        // creating query
        query = new Query(rm.granuleCatalog.getType().getTypeName());

        // sorting and limiting
        // max number of elements
        query.setMaxFeatures(1);

        // sorting
        final SortBy[] clauses = new SortBy[] {
                new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property("ingestion"),
                        SortOrder.DESCENDING),
                new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property("elevation"),
                        SortOrder.ASCENDING), };
        query.setSortBy(clauses);

    }

    // checking that we get a single feature and that feature is correct
    Collection<GranuleDescriptor> features = rm.getGranules(query);
    assertEquals(features.size(), 1);
    GranuleDescriptor granule = features.iterator().next();
    SimpleFeature sf = granule.getOriginator();
    assertNotNull(sf);
    Object ingestion = sf.getAttribute("ingestion");
    assertTrue(ingestion instanceof Timestamp);
    final GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    gc.setTimeInMillis(1225497600000l);
    assertEquals(0, (((Timestamp) ingestion).compareTo(gc.getTime())));
    Object elevation = sf.getAttribute("elevation");
    assertTrue(elevation instanceof Integer);
    assertEquals(((Integer) elevation).intValue(), 0);

    // Reverting order (the previous timestamp shouldn't match anymore)
    final SortBy[] clauses = new SortBy[] {
            new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property("ingestion"), SortOrder.ASCENDING),
            new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property("elevation"),
                    SortOrder.DESCENDING), };
    query.setSortBy(clauses);

    // checking that we get a single feature and that feature is correct
    features = rm.getGranules(query);
    assertEquals(features.size(), 1);
    granule = features.iterator().next();
    sf = granule.getOriginator();
    assertNotNull(sf);
    ingestion = sf.getAttribute("ingestion");
    assertTrue(ingestion instanceof Timestamp);
    assertNotSame(0, (((Timestamp) ingestion).compareTo(gc.getTime())));
    elevation = sf.getAttribute("elevation");
    assertTrue(elevation instanceof Integer);
    assertNotSame(((Integer) elevation).intValue(), 0);

}

From source file:org.jfree.data.time.junit.DayTest.java

/**
 * Problem for date parsing./*from   w w w.j  a  v a 2 s .c om*/
 * <p>
 * This test works only correct if the short pattern of the date
 * format is "dd/MM/yyyy". If not, this test will result in a
 * false negative.
 *
 * @throws ParseException on parsing errors.
 */
public void testParseDay() throws ParseException {
    GregorianCalendar gc = new GregorianCalendar(2001, 12, 31);
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    Date reference = format.parse("31/12/2001");
    if (reference.equals(gc.getTime())) {
        // test 1...
        Day d = Day.parseDay("31/12/2001");
        assertEquals(37256, d.getSerialDate().toSerial());
    }

    // test 2...
    Day d = Day.parseDay("2001-12-31");
    assertEquals(37256, d.getSerialDate().toSerial());
}

From source file:de.fhbingen.wbs.wpOverview.tabs.AvailabilityGraph.java

/**
 * Set the view to DAY./*w ww. j av  a  2 s .c o m*/
 */
private void setDayView() {

    actualStart = (GregorianCalendar) actualDay.clone();
    actualStart.set(Calendar.HOUR_OF_DAY, 0);
    actualStart.set(Calendar.MINUTE, 0);
    actualStart.add(Calendar.HOUR, -1);

    actualEnd = (GregorianCalendar) actualDay.clone();
    actualEnd.set(Calendar.HOUR_OF_DAY, 23);
    actualEnd.set(Calendar.MINUTE, 59);
    actualEnd.add(Calendar.HOUR, 1);

    actualView = DAY;

    GregorianCalendar helper = (GregorianCalendar) actualEnd.clone();
    helper.add(Calendar.DATE, -1);

    makeChart(new SimpleDateFormat("EEEE, dd.MM.yyyy").format(helper.getTime()));
}

From source file:com.workplacesystems.queuj.process.ProcessScheduler.java

synchronized void scheduleProcess(ProcessWrapper process, GregorianCalendar scheduled_time) {
    if (log.isDebugEnabled())
        log.debug("schedule process, scheduled_time: " + scheduled_time.getTime().toString()
                + ", process_scheduler: " + hashCode() + ", runner: " + process.runnerHashCode());

    if (!scheduled_time.after(new GregorianCalendar()))
        scheduled_time = null;//ww w.  j a  va 2  s.  c om

    // Firstly remove any previously scheduled instance of this Process
    unScheduleProcess(process);

    // Now lets schedule the Process
    processes.put(process, scheduled_time);

    if (scheduled_time != null) {
        FilterableArrayList list = (FilterableArrayList) process_times.get(scheduled_time);
        if (list == null) {
            list = new FilterableArrayList();
            process_times.put(scheduled_time, list);
        }
        list.add(process);

        // Wake the thread if the new time is the first
        if (process_times.firstKey().equals(scheduled_time)) {
            if (running)
                interrupt();
            else {
                running = true;
                start();
            }
        }
    }
}