org.joda.time.DateTimeZone Java Examples

The following examples show how to use org.joda.time.DateTimeZone. 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 check out the related API usage on the sidebar.
Example #1
Source File: jMutRepair_0051_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Decodes a built DateTimeZone from the given stream, as encoded by
 * writeTo.
 *
 * @param in input stream to read encoded DateTimeZone from.
 * @param id time zone id to assign
 */
public static DateTimeZone readFrom(DataInput in, String id) throws IOException {
    switch (in.readUnsignedByte()) {
    case 'F':
        DateTimeZone fixed = new FixedDateTimeZone
            (id, in.readUTF(), (int)readMillis(in), (int)readMillis(in));
        if (fixed.equals(DateTimeZone.UTC)) {
            fixed = DateTimeZone.UTC;
        }
        return fixed;
    case 'C':
        return CachedDateTimeZone.forZone(PrecalculatedZone.readFrom(in, id));
    case 'P':
        return PrecalculatedZone.readFrom(in, id);
    default:
        throw new IOException("Invalid encoding");
    }
}
 
Example #2
Source File: DateTimePeriodTest.java    From cloudhopper-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void toDays() throws Exception {
    // 1 day
    DateTimePeriod period0 = DateTimePeriod.createDay(2009, 1, 1, DateTimeZone.UTC);
    List<DateTimePeriod> periods = period0.toDays();
    Assert.assertArrayEquals(new DateTimePeriod[] {
            DateTimePeriod.createDay(2009, 1, 1, DateTimeZone.UTC)
        }, periods.toArray(new DateTimePeriod[0]));

    // multiple days (a little more than a day)
    period0 = new DateTimeDay(new DateTime(2009,1,1,0,0,0,0,DateTimeZone.UTC), new DateTime(2009,1,3,1,0,0,0,DateTimeZone.UTC));
    periods = period0.toPeriods(DateTimeDuration.DAY);
    Assert.assertArrayEquals(new DateTimePeriod[] {
            DateTimePeriod.createDay(2009, 1, 1, DateTimeZone.UTC),
            DateTimePeriod.createDay(2009, 1, 2, DateTimeZone.UTC)
        }, periods.toArray(new DateTimePeriod[0]));

    // no days (partial day such as a hour)
    period0 = DateTimePeriod.createHour(2009, 1, 1, 0, DateTimeZone.UTC);
    periods = period0.toDays();
    Assert.assertArrayEquals(new DateTimePeriod[] {}, periods.toArray(new DateTimePeriod[0]));
}
 
Example #3
Source File: ServerTimeZoneBackend.java    From unitime with Apache License 2.0 6 votes vote down vote up
@Override
public ServerTimeZoneResponse execute(ServerTimeZoneRequest request, SessionContext context) {
	Date first = null, last = null;
	for (Session session: SessionDAO.getInstance().findAll()) {
		if (first == null || first.after(session.getEventBeginDate()))
			first = session.getEventBeginDate();
		if (last == null || last.before(session.getEventEndDate()))
			last = session.getEventEndDate();
	}
	DateTimeZone zone = DateTimeZone.getDefault();
	int offsetInMinutes = zone.getOffset(first.getTime()) / 60000;
	ServerTimeZoneResponse ret = new ServerTimeZoneResponse();
	ret.setId(zone.getID());
	ret.addName(zone.getName(new Date().getTime()));
	ret.setTimeZoneOffsetInMinutes(offsetInMinutes);
	long time = first.getTime();
	long transition;
	while (time != (transition = zone.nextTransition(time)) && time < last.getTime()) {
		int adjustment = (zone.getOffset(transition) / 60000) - offsetInMinutes;
		ret.addTransition((int)(transition / 3600000), adjustment);
		time = transition;
	}
	return ret;
}
 
Example #4
Source File: JGenProg2017_0076_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Encodes a built DateTimeZone to the given stream. Call readFrom to
 * decode the data into a DateTimeZone object.
 *
 * @param out  the output stream to receive the encoded DateTimeZone
 * @since 1.5 (parameter added)
 */
public void writeTo(String zoneID, DataOutput out) throws IOException {
    // pass false so zone id is not written out
    DateTimeZone zone = toDateTimeZone(zoneID, false);

    if (zone instanceof FixedDateTimeZone) {
        out.writeByte('F'); // 'F' for fixed
        out.writeUTF(zone.getNameKey(0));
        writeMillis(out, zone.getOffset(0));
        writeMillis(out, zone.getStandardOffset(0));
    } else {
        if (zone instanceof CachedDateTimeZone) {
            out.writeByte('C'); // 'C' for cached, precalculated
            zone = ((CachedDateTimeZone)zone).getUncachedZone();
        } else {
            out.writeByte('P'); // 'P' for precalculated, uncached
        }
        ((PrecalculatedZone)zone).writeTo(out);
    }
}
 
Example #5
Source File: TimeZoneInfo.java    From es6draft with MIT License 6 votes vote down vote up
private int getOffset(DateTimeZone timeZone, long date) {
    if (IGNORE_LOCAL_BEFORE_EPOCH) {
        if (date < EPOCH) {
            date = toFirstDateWithNormalizedTime(timeZone, date);
        }
    } else if (IGNORE_LOCAL) {
        if (date <= LAST_LOCAL_TRANSITION) {
            date = toFirstDateWithNormalizedTime(timeZone, date);
        }
    } else if (IGNORE_LMT) {
        if (date <= LAST_LMT_TRANSITION) {
            date = toFirstDateAfterLocalMeanTime(timeZone, date);
        }
    }
    return timeZone.getOffset(date);
}
 
Example #6
Source File: WindowedTSCIteratorTest.java    From monsoon with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Before
public void setup() {
    final DateTime ts = new DateTime(1970, 1, 1, 0, 0, DateTimeZone.UTC);

    collections = new ArrayList<>();
    expected = new ArrayList<>();
    for (int i = 0; i < 4; ++i)
        collections.add(new EmptyTimeSeriesCollection(ts.plus(Duration.standardHours(i))));

    for (int i = 0; i < collections.size(); ++i) {
        TimeSeriesCollection c = collections.get(i);
        List<TimeSeriesCollection> past = collections.stream()
                .filter(elem -> !elem.getTimestamp().isBefore(c.getTimestamp().minus(lookBack)))
                .filter(elem -> elem.getTimestamp().isBefore(c.getTimestamp()))
                .collect(Collectors.toList());
        reverse(past);
        List<TimeSeriesCollection> future = collections.stream()
                .filter(elem -> !elem.getTimestamp().isAfter(c.getTimestamp().plus(lookForward)))
                .filter(elem -> elem.getTimestamp().isAfter(c.getTimestamp()))
                .collect(Collectors.toList());
        expected.add(new InterpolatedTSC(c, past, future));
    }
}
 
Example #7
Source File: Time_16_DateTimeFormatter_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Constructor.
 */
private DateTimeFormatter(
        DateTimePrinter printer, DateTimeParser parser,
        Locale locale, boolean offsetParsed,
        Chronology chrono, DateTimeZone zone,
        Integer pivotYear, int defaultYear) {
    super();
    iPrinter = printer;
    iParser = parser;
    iLocale = locale;
    iOffsetParsed = offsetParsed;
    iChrono = chrono;
    iZone = zone;
    iPivotYear = pivotYear;
    iDefaultYear = defaultYear;
}
 
Example #8
Source File: EventActivityBuilder.java    From BotServiceStressToolkit with MIT License 6 votes vote down vote up
public static Event build(JsonObject channeldata, String name, Member from,
		Member recipient, String channelId, String serviceUrl, String conversationId) {
	Event event = new Event();
	event.setType(Event.EVENT_TYPE);
	event.setChanneldata(channeldata);
	event.setName(name);
	event.setFrom(from);

	event.setTimestamp(
			ISODateTimeFormat.dateHourMinuteSecondMillis().withZoneUTC().print(System.currentTimeMillis()));
	event.setTimestamp(ISODateTimeFormat.dateHourMinuteSecondMillis().withZone(DateTimeZone.forOffsetHours(-3))
			.print(System.currentTimeMillis()));

	event.setRecipient(recipient);
	event.setConversation(new Conversation(conversationId));
	event.setServiceUrl(serviceUrl);
	event.setChannelId(channelId);
	
	setActivityProperties(event);
	
	return event;
}
 
Example #9
Source File: jMutRepair_0045_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Decodes a built DateTimeZone from the given stream, as encoded by
 * writeTo.
 *
 * @param in input stream to read encoded DateTimeZone from.
 * @param id time zone id to assign
 */
public static DateTimeZone readFrom(DataInput in, String id) throws IOException {
    switch (in.readUnsignedByte()) {
    case 'F':
        DateTimeZone fixed = new FixedDateTimeZone
            (id, in.readUTF(), (int)readMillis(in), (int)readMillis(in));
        if (fixed.equals(DateTimeZone.UTC)) {
            fixed = DateTimeZone.UTC;
        }
        return fixed;
    case 'C':
        return CachedDateTimeZone.forZone(PrecalculatedZone.readFrom(in, id));
    case 'P':
        return PrecalculatedZone.readFrom(in, id);
    default:
        throw new IOException("Invalid encoding");
    }
}
 
Example #10
Source File: Time_7_DateTimeFormatter_s.java    From coming with MIT License 6 votes vote down vote up
private void printTo(Writer buf, long instant, Chronology chrono) throws IOException {
    DateTimePrinter printer = requirePrinter();
    chrono = selectChronology(chrono);
    // Shift instant into local time (UTC) to avoid excessive offset
    // calculations when printing multiple fields in a composite printer.
    DateTimeZone zone = chrono.getZone();
    int offset = zone.getOffset(instant);
    long adjustedInstant = instant + offset;
    if ((instant ^ adjustedInstant) < 0 && (instant ^ offset) >= 0) {
        // Time zone offset overflow, so revert to UTC.
        zone = DateTimeZone.UTC;
        offset = 0;
        adjustedInstant = instant;
    }
    printer.printTo(buf, adjustedInstant, chrono.withUTC(), offset, zone, iLocale);
}
 
Example #11
Source File: JGenProg2017_0042_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Encodes a built DateTimeZone to the given stream. Call readFrom to
 * decode the data into a DateTimeZone object.
 *
 * @param out  the output stream to receive the encoded DateTimeZone
 * @since 1.5 (parameter added)
 */
public void writeTo(String zoneID, DataOutput out) throws IOException {
    // pass false so zone id is not written out
    DateTimeZone zone = toDateTimeZone(zoneID, false);

    if (zone instanceof FixedDateTimeZone) {
        out.writeByte('F'); // 'F' for fixed
        out.writeUTF(zone.getNameKey(0));
        writeMillis(out, zone.getOffset(0));
        writeMillis(out, zone.getStandardOffset(0));
    } else {
        if (zone instanceof CachedDateTimeZone) {
            out.writeByte('C'); // 'C' for cached, precalculated
            zone = ((CachedDateTimeZone)zone).getUncachedZone();
        } else {
            out.writeByte('P'); // 'P' for precalculated, uncached
        }
        ((PrecalculatedZone)zone).writeTo(out);
    }
}
 
Example #12
Source File: TransportCreatePartitionsAction.java    From crate with Apache License 2.0 6 votes vote down vote up
private Settings createIndexSettings(ClusterState currentState, List<IndexTemplateMetaData> templates) {
    Settings.Builder indexSettingsBuilder = Settings.builder();
    // apply templates, here, in reverse order, since first ones are better matching
    for (int i = templates.size() - 1; i >= 0; i--) {
        indexSettingsBuilder.put(templates.get(i).settings());
    }
    if (indexSettingsBuilder.get(IndexMetaData.SETTING_VERSION_CREATED) == null) {
        DiscoveryNodes nodes = currentState.nodes();
        final Version createdVersion = Version.min(Version.CURRENT, nodes.getSmallestNonClientNodeVersion());
        indexSettingsBuilder.put(IndexMetaData.SETTING_VERSION_CREATED, createdVersion);
    }
    if (indexSettingsBuilder.get(IndexMetaData.SETTING_CREATION_DATE) == null) {
        indexSettingsBuilder.put(IndexMetaData.SETTING_CREATION_DATE, new DateTime(DateTimeZone.UTC).getMillis());
    }
    indexSettingsBuilder.put(IndexMetaData.SETTING_INDEX_UUID, UUIDs.randomBase64UUID());

    return indexSettingsBuilder.build();
}
 
Example #13
Source File: jMutRepair_0037_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Encodes a built DateTimeZone to the given stream. Call readFrom to
 * decode the data into a DateTimeZone object.
 *
 * @param out  the output stream to receive the encoded DateTimeZone
 * @since 1.5 (parameter added)
 */
public void writeTo(String zoneID, DataOutput out) throws IOException {
    // pass false so zone id is not written out
    DateTimeZone zone = toDateTimeZone(zoneID, false);

    if (zone instanceof FixedDateTimeZone) {
        out.writeByte('F'); // 'F' for fixed
        out.writeUTF(zone.getNameKey(0));
        writeMillis(out, zone.getOffset(0));
        writeMillis(out, zone.getStandardOffset(0));
    } else {
        if (zone instanceof CachedDateTimeZone) {
            out.writeByte('C'); // 'C' for cached, precalculated
            zone = ((CachedDateTimeZone)zone).getUncachedZone();
        } else {
            out.writeByte('P'); // 'P' for precalculated, uncached
        }
        ((PrecalculatedZone)zone).writeTo(out);
    }
}
 
Example #14
Source File: CalendarDate.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static CalendarDate withDoy(Calendar cal, int year, int doy, int hourOfDay, int minuteOfHour,
    int secondOfMinute) {
  Chronology base = Calendar.getChronology(cal);
  /*
   * if (base == null)
   * base = ISOChronology.getInstanceUTC(); // already in UTC
   * else
   * base = ZonedChronology.getInstance( base, DateTimeZone.UTC); // otherwise wrap it to be in UTC
   */

  DateTime dt = new DateTime(year, 1, 1, hourOfDay, minuteOfHour, secondOfMinute, base);
  dt = dt.withZone(DateTimeZone.UTC);
  dt = dt.withDayOfYear(doy);
  if (!Calendar.isDefaultChronology(cal))
    dt = dt.withChronology(Calendar.getChronology(cal));

  return new CalendarDate(cal, dt);
}
 
Example #15
Source File: ZonedChronology.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
ZonedDateTimeField(DateTimeField field,
                   DateTimeZone zone,
                   DurationField durationField,
                   DurationField rangeDurationField,
                   DurationField leapDurationField) {
    super(field.getType());
    if (!field.isSupported()) {
        throw new IllegalArgumentException();
    }
    iField = field;
    iZone = zone;
    iDurationField = durationField;
    iTimeField = useTimeArithmetic(durationField);
    iRangeDurationField = rangeDurationField;
    iLeapDurationField = leapDurationField;
}
 
Example #16
Source File: HoltWintersDetector.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch data from metric
 *
 * @param metricEntity metric entity
 * @param start start timestamp
 * @param end end timestamp
 * @param datasetConfig the dataset config
 * @return Data Frame that has data from start to end
 */
private DataFrame fetchData(MetricEntity metricEntity, long start, long end, DatasetConfigDTO datasetConfig) {

  List<MetricSlice> slices = new ArrayList<>();
  MetricSlice sliceData = MetricSlice.from(metricEntity.getId(), start, end,
      metricEntity.getFilters(), timeGranularity);
  slices.add(sliceData);
  LOG.info("Getting data for" + sliceData.toString());
  InputData data = this.dataFetcher.fetchData(new InputDataSpec().withTimeseriesSlices(slices)
      .withMetricIdsForDataset(Collections.singletonList(metricEntity.getId()))
      .withMetricIds(Collections.singletonList(metricEntity.getId())));
  MetricConfigDTO metricConfig = data.getMetrics().get(metricEntity.getId());
  DataFrame df = data.getTimeseries().get(sliceData);

  // aggregate data to specified weekly granularity
  if (this.monitoringGranularity.endsWith(TimeGranularity.WEEKS)) {
    Period monitoringGranularityPeriod =
        DetectionUtils.getMonitoringGranularityPeriod(this.monitoringGranularity, datasetConfig);
    long latestDataTimeStamp = df.getLong(COL_TIME, df.size() - 1);
    df = DetectionUtils.aggregateByPeriod(df, new DateTime(start, DateTimeZone.forID(datasetConfig.getTimezone())),
        monitoringGranularityPeriod, metricConfig.getDefaultAggFunction());
    df = DetectionUtils.filterIncompleteAggregation(df, latestDataTimeStamp, datasetConfig.bucketTimeGranularity(),
        monitoringGranularityPeriod);
  }
  return df;
}
 
Example #17
Source File: ChronosController.java    From chronos with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public List<FutureRunInfo> getJobFuture(Long id, int limit) {
  List<FutureRunInfo> toRet = new ArrayList<>();
  List<JobSpec> iterJobs;
  if (id == null) {
    iterJobs = jobDao.getJobs();
  } else {
    iterJobs = Arrays.asList(new JobSpec[]{ jobDao.getJob(id) });
  }

  if (iterJobs.size() == 0) {
    return toRet;
  }

  DateTime from = new DateTime().withZone(DateTimeZone.UTC);
  while (toRet.size() < limit) {
    innerJobFuture(toRet, from, iterJobs);
    Collections.sort(toRet);
    from = toRet.get(toRet.size() - 1).getTime();
  }
  return toRet;
}
 
Example #18
Source File: 1_DateTimeFormatter.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parses only the local date-time from the given text, returning a new LocalDateTime.
 * <p>
 * This will parse the text fully according to the formatter, using the UTC zone.
 * Once parsed, only the local date-time will be used.
 * This means that any parsed time-zone or offset field is completely ignored.
 * It also means that the zone and offset-parsed settings are ignored.
 *
 * @param text  the text to parse, not null
 * @return the parsed date-time, never null
 * @throws UnsupportedOperationException if parsing is not supported
 * @throws IllegalArgumentException if the text to parse is invalid
 * @since 2.0
 */
public LocalDateTime parseLocalDateTime(String text) {
    DateTimeParser parser = requireParser();
    
    Chronology chrono = selectChronology(null).withUTC();  // always use UTC, avoiding DST gaps
    DateTimeParserBucket bucket = new DateTimeParserBucket(0, chrono, iLocale, iPivotYear, iDefaultYear);
    int newPos = parser.parseInto(bucket, text, 0);
    if (newPos >= 0) {
        if (newPos >= text.length()) {
            long millis = bucket.computeMillis(true, text);
            if (bucket.getOffsetInteger() != null) {  // treat withOffsetParsed() as being true
                int parsedOffset = bucket.getOffsetInteger();
                DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);
                chrono = chrono.withZone(parsedZone);
            } else if (bucket.getZone() != null) {
                chrono = chrono.withZone(bucket.getZone());
            }
            return new LocalDateTime(millis, chrono);
        }
    } else {
        newPos = ~newPos;
    }
    throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos));
}
 
Example #19
Source File: TestDateTimeZone.java    From joda-time-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsLocalDateTimeGap_NewYork() {
    DateTimeZone zone = DateTimeZone.forID("America/New_York");
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 1, 0)));
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 1, 59, 59, 99)));
    assertEquals(true, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 2, 0)));
    assertEquals(true, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 2, 30)));
    assertEquals(true, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 2, 59, 59, 99)));
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 3, 0)));
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 4, 0)));
    
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 11, 4, 0, 30)));  // before overlap
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 11, 4, 1, 30)));  // overlap
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 11, 4, 2, 30)));  // after overlap
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 12, 24, 12, 34)));
}
 
Example #20
Source File: JodaTime.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
private static String getVersion() {
    try {
        JarFile jf = Classes.jarFileOf(DateTimeZone.class);
        if (jf == null)
            return null;
        Manifest mf = jf.getManifest();
        Attributes attrs = mf.getMainAttributes();
        String name = attrs.getValue("Bundle-Name");
        String version = attrs.getValue("Bundle-Version");
        if ("Joda-Time".equals(name) && version != null) {
            return version;
        }
    } catch (Exception e) {
        InternalLogFactory.getLog(JodaTime.class).debug("FYI", e);
    }
    return null;
}
 
Example #21
Source File: SearchIndexServiceImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new search index statistics objects per specified parameters.
 *
 * @param settings the search index settings
 * @param docsStats the search index docs stats
 * @param indexCount the count of index
 *
 * @return the newly created search index statistics object
 */
protected SearchIndexStatistics createSearchIndexStatistics(Settings settings, DocsStats docsStats, long indexCount)
{
    SearchIndexStatistics searchIndexStatistics = new SearchIndexStatistics();

    Long creationDate = settings.getAsLong(IndexMetaData.SETTING_CREATION_DATE, -1L);
    if (creationDate.longValue() != -1L)
    {
        DateTime creationDateTime = new DateTime(creationDate, DateTimeZone.UTC);
        searchIndexStatistics.setIndexCreationDate(HerdDateUtils.getXMLGregorianCalendarValue(creationDateTime.toDate()));
    }

    searchIndexStatistics.setIndexNumberOfActiveDocuments(docsStats.getCount());
    searchIndexStatistics.setIndexNumberOfDeletedDocuments(docsStats.getDeleted());
    searchIndexStatistics.setIndexUuid(settings.get(IndexMetaData.SETTING_INDEX_UUID));
    searchIndexStatistics.setIndexCount(indexCount);

    return searchIndexStatistics;
}
 
Example #22
Source File: PersistentDateTimeAndZone.java    From jadira with Apache License 2.0 6 votes vote down vote up
@Override
protected DateTime fromConvertedColumns(Object[] convertedColumns) {

    LocalDateTime datePart = (LocalDateTime) convertedColumns[0];
    DateTimeZone zone = (DateTimeZone) convertedColumns[1];

    DateTime result;

    if (datePart == null) {
        result = null;
    } else {
        result = datePart.toDateTime(zone);
    }

    return result;
}
 
Example #23
Source File: AbelanaThings.java    From Abelana-Android with Apache License 2.0 6 votes vote down vote up
public static String getImage(String name) {
    final String Bucket = "abelana";
    DateTime soon = DateTime.now(DateTimeZone.UTC).plusMinutes(20);
    long expires = soon.getMillis()/1000;
    String stringToSign = "GET\n\n\n"
            + expires +"\n"
            + "/"+Bucket+"/"+name+".webp";

    String uri = "https://storage.googleapis.com/abelana/"+name+".webp"
            + "?GoogleAccessId="+credential.getServiceAccountId()
            +"&Expires="+expires
            +"&Signature="+Uri.encode(signData(stringToSign));

    return  uri;

}
 
Example #24
Source File: Arja_0087_s.java    From coming with MIT License 5 votes vote down vote up
private static DateTimeZone buildFixedZone(String id, String nameKey,
                                           int wallOffset, int standardOffset) {
    if ("UTC".equals(id) && id.equals(nameKey) &&
        wallOffset == 0 && standardOffset == 0) {
        return DateTimeZone.UTC;
    }
    return new FixedDateTimeZone(id, nameKey, wallOffset, standardOffset);
}
 
Example #25
Source File: UtilTest.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void fixSequence() {
    List<TimeSeriesCollection> collection = Arrays.asList(
            new EmptyTimeSeriesCollection(new DateTime(600, DateTimeZone.UTC)),
            new EmptyTimeSeriesCollection(new DateTime(0, DateTimeZone.UTC)),
            new EmptyTimeSeriesCollection(new DateTime(600, DateTimeZone.UTC)));

    ObjectSequence<TimeSeriesCollection> fixed = Util.fixSequence(new ForwardSequence(0, collection.size()).map(collection::get, false, true, false));

    assertEquals(2, fixed.size());
    assertThat(fixed.toArray(new TimeSeriesCollection[0]),
            arrayContaining(
                    new EmptyTimeSeriesCollection(new DateTime(0, DateTimeZone.UTC)),
                    new EmptyTimeSeriesCollection(new DateTime(600, DateTimeZone.UTC))));
}
 
Example #26
Source File: DateTimeConverter.java    From atdl4j with MIT License 5 votes vote down vote up
@Override
public Object convertFixWireValueToParameterValue(String aFixWireValue)
{
	if ( aFixWireValue != null )
	{
		String str = (String) aFixWireValue;
		String format = getFormatString();
		DateTimeFormatter fmt = DateTimeFormat.forPattern( format );

		try
		{  
			if ( getParameter() == null || 
					getParameter() instanceof UTCTimeOnlyT || 
					getParameter() instanceof UTCTimestampT )
			{
				DateTime tempDateTime = fmt.withZone( DateTimeZone.UTC ).parseDateTime( str );
				return tempDateTime;
			}
			else
			{
				return fmt.parseDateTime( str );
			}
		}
		catch (IllegalArgumentException e)
		{
			throw new IllegalArgumentException( "Unable to parse \"" + str + "\" with format \"" + format + "\"  Execption: " + e.getMessage() );
		}
	}
	else
	{	
		return null;
	}	
}
 
Example #27
Source File: EthiopicChronology.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Serialization singleton.
 */
private Object readResolve() {
    Chronology base = getBase();
    return base == null ?
            getInstance(DateTimeZone.UTC, getMinimumDaysInFirstWeek()) :
                getInstance(base.getZone(), getMinimumDaysInFirstWeek());
}
 
Example #28
Source File: DeletedSasDefinitionItem.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
/**
 * Get the deletedDate value.
 *
 * @return the deletedDate value
 */
public DateTime deletedDate() {
    if (this.deletedDate == null) {
        return null;
    }
    return new DateTime(this.deletedDate * 1000L, DateTimeZone.UTC);
}
 
Example #29
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
/**
 * Stores the state value in each key-value pair in the project's datastore.
 *
 * @param sessionId Request from which to extract session.
 * @param varName   the name of the desired session variable
 * @param varValue  the value of the desired session variable
 */
protected void setSessionVariables(String sessionId, Map<String, String> setMap) {
  if (sessionId.equals("")) {
    return;
  }
  Key key = keyFactory.newKey(sessionId);
  Transaction transaction = datastore.newTransaction();
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  dt.toString(dtf);
  try {
    Entity stateEntity = transaction.get(key);
    Entity.Builder seBuilder;
    if (stateEntity == null) {
      seBuilder = Entity.newBuilder(key);
    } else {
      seBuilder = Entity.newBuilder(stateEntity);
    }
    for (String varName : setMap.keySet()) {
      seBuilder.set(varName, setMap.get(varName));
    }
    transaction.put(seBuilder.set("lastModified", dt.toString(dtf)).build());
    transaction.commit();
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}
 
Example #30
Source File: DeletedCertificateBundle.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
/**
 * Get the deletedDate value.
 *
 * @return the deletedDate value
 */
public DateTime deletedDate() {
    if (this.deletedDate == null) {
        return null;
    }
    return new DateTime(this.deletedDate * 1000L, DateTimeZone.UTC);
}