Example usage for java.util Calendar setTimeZone

List of usage examples for java.util Calendar setTimeZone

Introduction

In this page you can find the example usage for java.util Calendar setTimeZone.

Prototype

public void setTimeZone(TimeZone value) 

Source Link

Document

Sets the time zone with the given time zone value.

Usage

From source file:org.codehaus.mojo.mrm.impl.maven.ArtifactStoreFileSystem.java

/**
 * {@inheritDoc}//from  w  ww . j a v  a 2s .  c  om
 */
protected Entry get(DirectoryEntry parent, String name) {

    String path = parent.toPath() + "/" + name;

    if ("favicon.ico".equals(name)) {
        return null;
    }
    if (METADATA.matcher(path).matches()) {
        MetadataFileEntry entry = new MetadataFileEntry(this, parent, parent.toPath(), store);
        try {
            entry.getLastModified();
            return entry;
        } catch (IOException e) {
            return null;
        }
    } else {
        Matcher snapshotArtifact = SNAPSHOT_ARTIFACT.matcher(path);
        if (snapshotArtifact.matches()) {
            String groupId = StringUtils.stripEnd(snapshotArtifact.group(1), "/").replace('/', '.');
            String artifactId = snapshotArtifact.group(2);
            String version = snapshotArtifact.group(3) + "-SNAPSHOT";
            Pattern rule = Pattern.compile("\\Q" + artifactId + "\\E-(?:\\Q"
                    + StringUtils.removeEnd(version, "-SNAPSHOT")
                    + "\\E-(SNAPSHOT|(\\d{4})(\\d{2})(\\d{2})\\.(\\d{2})(\\d{2})(\\d{2})-(\\d+)))(?:-([^.]+))?\\.([^/]*)");
            Matcher matcher = rule.matcher(name);
            if (!matcher.matches()) {
                String classifier = snapshotArtifact.group(5);
                String type = snapshotArtifact.group(6);
                if (classifier != null) {
                    classifier = classifier.substring(1);
                }
                if (StringUtils.isEmpty(classifier)) {
                    classifier = null;
                }
                return new ArtifactFileEntry(this, parent,
                        new Artifact(groupId, artifactId, version, classifier, type), store);
            }
            if (matcher.group(1).equals("SNAPSHOT")) {
                Artifact artifact = new Artifact(groupId, artifactId, version, matcher.group(9),
                        matcher.group(10));
                try {
                    store.get(artifact);
                    return new ArtifactFileEntry(this, parent, artifact, store);
                } catch (IOException e) {
                    return null;
                } catch (ArtifactNotFoundException e) {
                    return null;
                }
            }
            try {
                Calendar cal = new GregorianCalendar();
                cal.setTimeZone(TimeZone.getTimeZone("GMT"));
                cal.set(Calendar.YEAR, Integer.parseInt(matcher.group(2)));
                cal.set(Calendar.MONTH, Integer.parseInt(matcher.group(3)) - 1);
                cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(matcher.group(4)));
                cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(matcher.group(5)));
                cal.set(Calendar.MINUTE, Integer.parseInt(matcher.group(6)));
                cal.set(Calendar.SECOND, Integer.parseInt(matcher.group(7)));
                long timestamp = cal.getTimeInMillis();
                int buildNumber = Integer.parseInt(matcher.group(8));

                Artifact artifact = new Artifact(groupId, artifactId, version, matcher.group(9),
                        matcher.group(10), timestamp, buildNumber);
                try {
                    store.get(artifact);
                    return new ArtifactFileEntry(this, parent, artifact, store);
                } catch (IOException e) {
                    return null;
                } catch (ArtifactNotFoundException e) {
                    return null;
                }
            } catch (NullPointerException e) {
                return new DefaultDirectoryEntry(this, parent, name);
            }
        } else {
            Matcher matcher = ARTIFACT.matcher(path);
            if (matcher.matches()) {
                String groupId = StringUtils.stripEnd(matcher.group(1), "/").replace('/', '.');
                String artifactId = matcher.group(2);
                String version = matcher.group(3);
                String classifier = matcher.group(5);
                String type = matcher.group(6);
                if (classifier != null) {
                    classifier = classifier.substring(1);
                }
                if (StringUtils.isEmpty(classifier)) {
                    classifier = null;
                }

                Artifact artifact = new Artifact(groupId, artifactId, version, classifier, type);
                try {
                    store.get(artifact);
                    return new ArtifactFileEntry(this, parent, artifact, store);
                } catch (ArtifactNotFoundException e) {
                    return null;
                } catch (IOException e) {
                    return null;
                }
            } else {
                return new DefaultDirectoryEntry(this, parent, name);
            }
        }
    }
}

From source file:TVA.Hadoop.MapReduce.Historian.File.StandardPointFile.java

/**
 * Get this point's Date in milliseconds based off of the standard DatAware reference Date.
 * @return A Calendar object representing this point's Date/Time.
 *//*from w w  w  . j  a  v  a 2  s  . c om*/
public Calendar GetCalendar() {

    long time = this.iTimeTag;
    long lTimeTag = (long) (1000 * time);

    // now get ms from flag
    int iFlag = this.Flags;
    int iMS = (iFlag >> 5);
    long lFlagMS = (long) (iMS);

    Calendar cResult = Calendar.getInstance();
    cResult.setTimeZone(TimeZone.getTimeZone("UTC"));
    cResult.setTimeInMillis(StandardPointFile.cBaseDateTime.getTimeInMillis() + lTimeTag + lFlagMS);

    return cResult;

}

From source file:it.geosolutions.geobatch.imagemosaic.GranuleRemoverOnlineTest.java

@Test
public void removeGranules() throws Exception {
    removeStore();//from  w w w  .j  a  va 2  s.  c om

    File imcFile;

    //=== Add first set of granules
    LOGGER.info(" ***** CREATING FIRST BATCH OF GRANULES");
    {
        ImageMosaicCommand imc = recreateIMC("20121004", "20121005", "20121006", "20121007", "20121008");
        // serialize
        imcFile = new File(getTempDir(), "ImageMosaicCommand0.xml");
        LOGGER.info("Creating  " + imcFile);
        ImageMosaicCommand.serialize(imc, imcFile.toString());
    }

    {
        Queue<EventObject> inputQ = new LinkedList<EventObject>();
        inputQ.add(new FileSystemEvent(imcFile, FileSystemEventType.FILE_ADDED));
        ImageMosaicAction action = createMosaicAction(createMosaicConfig());
        Queue<EventObject> outputQ = action.execute(inputQ);
    }

    DataStore dataStore = createDatastore();
    assertEquals(5, dataStore.getFeatureSource(STORENAME).getCount(Query.ALL));

    //=== Add another granule
    LOGGER.info(" ***** ADD ONE MORE GRANULE");
    {
        ImageMosaicCommand imc = recreateIMC("20121009");
        // serialize
        imcFile = new File(getTempDir(), "ImageMosaicCommand1.xml");
        LOGGER.info("Creating  " + imcFile);
        ImageMosaicCommand.serialize(imc, imcFile.toString());
    }

    {
        Queue<EventObject> inputQ = new LinkedList<EventObject>();
        inputQ.add(new FileSystemEvent(imcFile, FileSystemEventType.FILE_ADDED));
        ImageMosaicAction action = createMosaicAction(createMosaicConfig());
        Queue<EventObject> outputQ = action.execute(inputQ);
    }

    assertEquals(6, dataStore.getFeatureSource(STORENAME).getCount(Query.ALL));

    //== performs some tests on delete list
    LOGGER.info(" ***** REMOVE OLD GRANULE");
    {
        ImageMosaicCommand imc = recreateIMC("nothing");
        GranuleRemover remover = new GranuleRemover();

        Calendar cal = new GregorianCalendar(2012, 9, 7);
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));

        remover.setBaseDate(cal);
        remover.setDaysAgo(2);
        remover.enrich(imc);
        LOGGER.info("remove " + imc.getDelFiles());
        assertEquals(2, imc.getDelFiles().size());

        imc.setDelFiles(null);
        remover.setDaysAgo(1);
        remover.enrich(imc);
        LOGGER.info("remove " + imc.getDelFiles());
        assertEquals(3, imc.getDelFiles().size());
        assertNotNull(imc.getAddFiles());

        // serialize
        imcFile = new File(getTempDir(), "ImageMosaicCommand2.xml");
        LOGGER.info("Creating  " + imcFile);
        ImageMosaicCommand.serialize(imc, imcFile.toString());
    }

    //== run the action with latest IMC
    {
        Queue<EventObject> inputQ = new LinkedList<EventObject>();
        inputQ.add(new FileSystemEvent(imcFile, FileSystemEventType.FILE_ADDED));
        ImageMosaicConfiguration conf = createMosaicConfig();
        //            conf.setFailIgnored(true);
        ImageMosaicAction action = createMosaicAction(conf);
        Queue<EventObject> outputQ = action.execute(inputQ);
    }

    assertEquals(3, dataStore.getFeatureSource(STORENAME).getCount(Query.ALL));

    //== Cleanup
    removeStore();
}

From source file:edu.hawaii.soest.pacioos.text.FileTextSource.java

protected boolean execute() {
    log.debug("FileTextSource.execute() called.");
    boolean failed = false; // indicates overall success of execute()

    // do not execute the stream if there is no connection
    if (!isConnected())
        return false;

    try {//from  w  w w  .j  a  v  a2  s  . c  om

        // open the data file for monitoring
        FileReader reader = new FileReader(new File(getDataFilePath()));
        this.fileReader = new BufferedReader(reader);

        // add channels of data that will be pushed to the server.    
        // Each sample will be sent to the Data Turbine as an rbnb frame.    
        int channelIndex = 0;

        long lastSampleTimeAsSecondsSinceEpoch = getLastSampleTime();

        // poll the data file for new lines of data and insert them into the RBNB
        while (true) {
            String line = fileReader.readLine();

            if (line == null) {
                Thread.currentThread().sleep(this.pollInterval);

            } else {

                // test the line for the expected data pattern
                boolean valid = this.validateSample(line);

                // if the line matches the data pattern, insert it into the DataTurbine
                if (valid) {
                    log.debug("This line matches the data line pattern: " + line);

                    Date sampleDate = getSampleDate(line);

                    if (this.dateFormats == null || this.dateFields == null) {
                        log.warn("Using the default datetime format and field for sample data. "
                                + "Use the -f and -d options to explicitly set date time fields.");
                    }
                    log.debug("Sample date is: " + sampleDate.toString());

                    // convert the sample date to seconds since the epoch
                    long sampleTimeAsSecondsSinceEpoch = (sampleDate.getTime() / 1000L);

                    // only insert samples newer than the last sample seen at startup 
                    // and that are not in the future (> 1 hour since the CTD clock
                    // may have drifted)
                    Calendar currentCal = Calendar.getInstance();
                    this.tz = TimeZone.getTimeZone(this.timezone);
                    currentCal.setTimeZone(this.tz);
                    currentCal.add(Calendar.HOUR, 1);
                    Date currentDate = currentCal.getTime();

                    if (lastSampleTimeAsSecondsSinceEpoch < sampleTimeAsSecondsSinceEpoch
                            && sampleTimeAsSecondsSinceEpoch < currentDate.getTime() / 1000L) {

                        int numberOfChannelsFlushed = 0;
                        try {
                            //insert into the DataTurbine
                            numberOfChannelsFlushed = this.sendSample(line);

                        } catch (SAPIException sapie) {
                            // reconnect if an exception is thrown on Flush()
                            log.error("Error while flushing the source: " + sapie.getMessage());
                            failed = true;

                        }

                        // reset the last sample time to the sample just inserted
                        lastSampleTimeAsSecondsSinceEpoch = sampleTimeAsSecondsSinceEpoch;
                        log.debug("Last sample time is now: "
                                + (new Date(lastSampleTimeAsSecondsSinceEpoch * 1000L).toString()));
                        log.info(getRBNBClientName() + " Sample sent to the DataTurbine: " + line.trim());

                    } else {
                        log.info("The current line is earlier than the last entry "
                                + "in the Data Turbine or is a date in the future. "
                                + "Skipping it. The line was: " + line);

                    }

                } else {
                    log.info("The current line doesn't match an expected "
                            + "data line pattern. Skipping it.    The line was: " + line);

                }
            } // end if()
        } // end while

    } catch (ParseException pe) {
        log.info("There was a problem parsing the sample date string. The message was: " + pe.getMessage());
        failed = true;
        return !failed;

    } catch (SAPIException sapie) {
        log.info("There was a problem communicating with the DataTurbine. The message was: "
                + sapie.getMessage());
        failed = true;
        return !failed;

    } catch (InterruptedException ie) {
        log.info("There was a problem while polling the data file. The message was: " + ie.getMessage());
        failed = true;
        return !failed;

    } catch (IOException ioe) {
        log.info("There was a problem opening the data file. The message was: " + ioe.getMessage());
        failed = true;
        return !failed;

    } finally {
        try {
            this.fileReader.close();

        } catch (IOException ioe2) {
            log.error("There was a problem closing the data file. The message was: " + ioe2.getMessage());

        }

    }

}

From source file:org.oscarehr.managers.ScheduleManager.java

public DayWorkSchedule getDayWorkSchedule(String providerNo, Calendar date) {
    // algorithm/*from w w w. j a va 2s.c  o  m*/
    //----------
    // select entries from scheduledate for the given day/provider where status = 'A' (for active?)
    // "hour" setting is the template to apply, i.e. template name
    // select entry from scheduletemplate to get the template to apply for the given day
    // timecode is a breakdown of the day into equal slots, where _ means nothing and some letter means a code in scheduletemplatecode
    // The only way to know the duration of the time code is to divide it up, i.e. minutes_per_day/timecode.length, i.e. 1440 minutes per second / 96 length = 15 minutes per slot.
    // For each time slot, then look up the scheduletemplatecode

    DayWorkSchedule dayWorkSchedule = new DayWorkSchedule();

    ScheduleHoliday scheduleHoliday = scheduleHolidayDao.find(date.getTime());
    dayWorkSchedule.setHoliday(scheduleHoliday != null);

    ScheduleDate scheduleDate = scheduleDateDao.findByProviderNoAndDate(providerNo, date.getTime());
    if (scheduleDate == null) {
        logger.debug(
                "No scheduledate for date requested. providerNo=" + providerNo + ", date=" + date.getTime());
        return (null);
    }
    String scheduleTemplateName = scheduleDate.getHour();

    // okay this is a mess, the ScheduleTemplate is messed up because no one links there via a PK, they only link there via the name column
    // and the name column isn't unique... so... we will have to do a search for the right template.
    // first we'll check under the providersId, if not we'll check under the public id.
    ScheduleTemplatePrimaryKey scheduleTemplatePrimaryKey = new ScheduleTemplatePrimaryKey(providerNo,
            scheduleTemplateName);
    ScheduleTemplate scheduleTemplate = scheduleTemplateDao.find(scheduleTemplatePrimaryKey);
    if (scheduleTemplate == null) {
        scheduleTemplatePrimaryKey = new ScheduleTemplatePrimaryKey(
                ScheduleTemplatePrimaryKey.DODGY_FAKE_PROVIDER_NO_USED_TO_HOLD_PUBLIC_TEMPLATES,
                scheduleTemplateName);
        scheduleTemplate = scheduleTemplateDao.find(scheduleTemplatePrimaryKey);
    }

    //  if it's still null, then ignore it as there's no schedule for the day.
    if (scheduleTemplate != null) {
        // time interval
        String timecode = scheduleTemplate.getTimecode();
        int timeSlotDuration = (60 * 24) / timecode.length();
        dayWorkSchedule.setTimeSlotDurationMin(timeSlotDuration);

        // sort out designated timeslots and their purpose
        Calendar timeSlot = (Calendar) date.clone();

        //make sure the appts returned are in local time. 
        timeSlot.setTimeZone(Calendar.getInstance().getTimeZone());
        timeSlot = DateUtils.truncate(timeSlot, Calendar.DAY_OF_MONTH);
        TreeMap<Calendar, Character> allTimeSlots = dayWorkSchedule.getTimeSlots();

        for (int i = 0; i < timecode.length(); i++) {
            // ignore _ because that's a blank place holder identifier... also not my fault, just processing what's been already written.
            if ('_' != timecode.charAt(i)) {
                allTimeSlots.put((Calendar) timeSlot.clone(), timecode.charAt(i));
            }

            timeSlot.add(GregorianCalendar.MINUTE, timeSlotDuration);
        }
    }

    // This method will not log access as the schedule is not private medical data.
    return (dayWorkSchedule);
}

From source file:org.orekit.SolarInputs97to05.java

private void read(BufferedReader rFlux, BufferedReader rAp) throws IOException, OrekitException {

    rFlux.readLine();/*from   w  w  w  .  j a v  a  2  s .  c  o  m*/
    rFlux.readLine();
    rFlux.readLine();
    rFlux.readLine();
    rAp.readLine();
    String lineAp;
    String[] flux;
    String[] ap;
    Calendar cal = new GregorianCalendar();
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    cal.set(0, 0, 0, 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);

    AbsoluteDate date = null;
    boolean first = true;

    for (String lineFlux = rFlux.readLine(); lineFlux != null; lineFlux = rFlux.readLine()) {

        flux = lineFlux.trim().split("\\s+");

        lineAp = rAp.readLine();
        if (lineAp == null) {
            throw new OrekitException(
                    new DummyLocalizable("inconsistent JB2006 and geomagnetic indices files"));
        }
        ap = lineAp.trim().split("\\s+");

        int fluxYear = Integer.parseInt(flux[0]);
        int fluxDay = Integer.parseInt(flux[1]);
        int apYear = Integer.parseInt(ap[11]);

        if (fluxDay != Integer.parseInt(ap[0])) {
            throw new OrekitException(
                    new DummyLocalizable("inconsistent JB2006 and geomagnetic indices files"));
        }
        if (((fluxYear < 2000) && ((fluxYear - 1900) != apYear))
                || ((fluxYear >= 2000) && ((fluxYear - 2000) != apYear))) {
            throw new OrekitException(
                    new DummyLocalizable("inconsistent JB2006 and geomagnetic indices files"));
        }

        cal.set(Calendar.YEAR, fluxYear);
        cal.set(Calendar.DAY_OF_YEAR, fluxDay);

        date = new AbsoluteDate(cal.getTime(), TimeScalesFactory.getUTC());

        if (first) {
            first = false;
            firstDate = date;
        }

        data.add(new LineParameters(date,
                new double[] { Double.parseDouble(ap[3]), Double.parseDouble(ap[4]), Double.parseDouble(ap[5]),
                        Double.parseDouble(ap[6]), Double.parseDouble(ap[7]), Double.parseDouble(ap[8]),
                        Double.parseDouble(ap[9]), Double.parseDouble(ap[10]),

                }, Double.parseDouble(flux[3]), Double.parseDouble(flux[4]), Double.parseDouble(flux[5]),
                Double.parseDouble(flux[6]), Double.parseDouble(flux[7]), Double.parseDouble(flux[8])));

    }
    lastDate = date;

}

From source file:org.infoscoop.web.KeywordRankingServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String uid = (String) request.getSession().getAttribute("Uid");

    if (log.isInfoEnabled()) {
        log.info("uid:[" + uid + "]: doPost");
    }/*from   w w w. j av a 2 s. c o m*/

    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");

    OutputStream out = null;

    int rankingPeriod;
    int rankingNum;
    String endDate;
    int offset = UserContext.instance().getUserInfo().getClientTimezoneOffset() / 60;
    String cacheName = "keywordRanking_UTC" + offset;

    try {
        String param_baseDate = request.getParameter("baseDate");

        // If baseDate is null, it is behavior of TODAY.
        endDate = (param_baseDate == null) ? TODAY : param_baseDate;

        Cache cache = CacheDAO.newInstance().getCacheById(cacheName);

        String rss;
        // We do cash only in case that appoined "TODAY".
        if (TODAY.equals(endDate) && cache != null && DateUtility.isToday(cache.getTimestamp())) {
            List<Header> headerList = cache.getHeaderList();
            for (Header header : headerList) {
                if (header.getName().equalsIgnoreCase("Last-Modified")) {
                    String lastModified = header.getValue();
                    if (lastModified != null && lastModified.equals(request.getHeader("If-Modified-Since"))) {
                        response.setStatus(304);
                        return;
                    }
                    response.addHeader("Last-Modified", lastModified);
                }
            }

            rss = new String(cache.getBodyBytes(), "UTF-8");
            log.info("get keywordRanking from cache.");
        } else {
            String param_period = request.getParameter("period");
            String param_rankingNum = request.getParameter("rankingNum");

            try {
                rankingPeriod = Integer.parseInt(param_period);
            } catch (NumberFormatException e) {
                log.warn("rankingPeriod [" + param_period + "] is not integer !");
                rankingPeriod = RANKING_PERIOD_DEFAULT;
            }
            try {
                rankingNum = Integer.parseInt(param_rankingNum);
            } catch (NumberFormatException e) {
                log.warn("rankingNum[" + param_rankingNum + "] is not integer !");
                rankingNum = RANKING_NUM_DEFAULT;
            }

            // check of the maximum
            rankingPeriod = (rankingPeriod > RANKING_PERIOD_MAX) ? RANKING_PERIOD_MAX : rankingPeriod;
            rankingNum = (rankingNum > RANKING_NUM_MAX) ? RANKING_NUM_MAX : rankingNum;

            boolean saveCache = true;
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

            if (TODAY.equals(endDate)) {
                Calendar yesterday = Calendar.getInstance();
                yesterday.setTimeZone(TimeZone.getTimeZone("UTC"));
                yesterday.set(Calendar.HOUR_OF_DAY, 0);
                endDate = sdf.format(yesterday.getTime());
            } else if (NOW.equals(endDate)) {
                endDate = sdf.format(new Date());
                saveCache = false; // When it is appointed "NOW", we don't do cash.
            }

            Map countMap = KeywordLogDAO.newInstance().getCountMap(getStartDate(endDate, rankingPeriod),
                    endDate, new Integer(0));
            if (countMap.size() == 0) {
                response.setStatus(204);
                return;
            }

            response.addDateHeader("Last-Modified", new Date().getTime());
            rss = makeRss(countMap, rankingPeriod, rankingNum);

            if (saveCache)
                insertRss(cacheName, rss);
        }

        boolean noProxy = false;
        Enumeration headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String headerName = (String) headers.nextElement();
            if (headerName.equalsIgnoreCase("X-IS-NOPROXY")) {
                noProxy = true;
                break;
            }
        }

        byte[] resByte;
        if (noProxy) {
            response.setContentType("text/plain; charset=UTF-8");
            String requestURL = request.getRequestURL() != null ? request.getRequestURL().toString() : "";
            ProxyRequest proxyRequest = new ProxyRequest(requestURL, "RSSReader");
            proxyRequest.setPortalUid((String) request.getSession().getAttribute("Uid"));

            resByte = RssFilter.process(proxyRequest, new ByteArrayInputStream(rss.getBytes("UTF-8")));
        } else {
            response.setContentType("text/xml; charset=UTF-8");
            resByte = rss.getBytes("UTF-8");
        }

        out = response.getOutputStream();
        out.write(resByte);
    } catch (Exception e) {
        log.error("--- unexpected error occurred.", e);
        response.sendError(500);
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:uk.bl.wa.annotation.AnnotatorTest.java

private void innerTestApplyAnnotations(String uriString, String sourceFile, int expected)
        throws URIException, URISyntaxException {
    ////w  ww.jav  a 2 s  .c  o  m
    URI uri = URI.create(uriString);
    //
    // Get the calendar instance.
    Calendar calendar = Calendar.getInstance();
    // Set the time for the notification to occur.
    calendar.set(Calendar.YEAR, 2013);
    calendar.set(Calendar.MONTH, 6);
    calendar.set(Calendar.DAY_OF_MONTH, 17);
    calendar.set(Calendar.HOUR_OF_DAY, 10);
    calendar.set(Calendar.MINUTE, 45);
    calendar.set(Calendar.SECOND, 0);
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    //
    SolrInputDocument solr = new SolrInputDocument();
    Date d = calendar.getTime();
    solr.setField(SolrFields.CRAWL_DATE, WARCIndexer.formatter.format(d));
    solr.setField(SolrFields.SOLR_URL, uri);
    solr.setField(SolrFields.SOURCE_FILE, sourceFile);
    //
    annotator.applyAnnotations(uri, solr);
    Annotator.prettyPrint(System.out, solr);
    int found = 0;
    //
    for (Object item : solr.getFieldValues(SolrFields.SOLR_COLLECTIONS)) {
        System.out.println("Contains... " + item);
        if ("Wikipedia".equals(item))
            found++;
        if ("Wikipedia|Main Site".equals(item))
            found++;
        if ("Wikipedia|Main Site|Mona Lisa".equals(item))
            found++;

    }
    if (solr.containsKey(SolrFields.ACCESS_TERMS)) {
        for (Object item : solr.getFieldValues(SolrFields.ACCESS_TERMS)) {
            if ("OA".equals(item))
                found++;

        }
    }
    assertTrue("Can't find the " + expected + " expected entries in 'collections for " + uriString + ", got "
            + found, found == expected);
}

From source file:com.boundary.sdk.event.EventCLI.java

protected Date parseDateTime(String s) throws java.text.ParseException {
    Date dt = null;//from ww  w  .j  av  a  2  s . c  o  m
    if (s != null) {
        Calendar c = DatatypeConverter.parseDateTime(s);
        c.setTimeZone(TimeZone.getTimeZone("GMT"));
        dt = c.getTime();
    }
    return dt;
}

From source file:org.osaf.cosmo.eim.eimml.EimmlTypeConverterTest.java

/** */
public void testToDateTime() throws Exception {
    String testString = "1996-12-19T16:39:57-08:00";

    Calendar resultCalendar = EimmlTypeConverter.toDateTime(testString);

    // since the test string's timezone is not actually parsed,
    // set the result calendar's timezone explicitly so that we
    // don't get variable numbers based on the system default
    // timezone//from w  w w  .  j a v  a  2s . c  o  m
    resultCalendar.setTimeZone(TimeZone.getTimeZone("GMT-8"));

    assertEquals("Result year does not match", 1996, resultCalendar.get(Calendar.YEAR));
    assertEquals("Result month does not match", 11, resultCalendar.get(Calendar.MONTH));
    assertEquals("Result day of week does not match", 19, resultCalendar.get(Calendar.DAY_OF_MONTH));
    assertEquals("Result hour of day does not match", 16, resultCalendar.get(Calendar.HOUR_OF_DAY));
    assertEquals("Result minute does not match", 39, resultCalendar.get(Calendar.MINUTE));
    assertEquals("Result second does not match", 57, resultCalendar.get(Calendar.SECOND));
}