use of java.time.DateTimeException in project jdk8u_jdk by JetBrains.
the class TestUmmAlQuraChronology method test_hijrahDateLimits.
// Check the date limits
@Test
public void test_hijrahDateLimits() {
HijrahChronology chrono = HijrahChronology.INSTANCE;
ValueRange yearRange = chrono.range(YEAR);
ValueRange monthRange = chrono.range(MONTH_OF_YEAR);
ValueRange dayRange = chrono.range(DAY_OF_MONTH);
HijrahDate xx = chrono.date(1434, 1, 1);
HijrahDate minDate = chrono.date((int) yearRange.getLargestMinimum(), (int) monthRange.getMinimum(), (int) dayRange.getMinimum());
try {
HijrahDate before = minDate.minus(1, ChronoUnit.DAYS);
fail("Exception did not occur, minDate: " + minDate + ".minus(1, DAYS) = " + before);
} catch (DateTimeException ex) {
// ignore, this exception was expected
}
HijrahDate maxDate = chrono.date((int) yearRange.getSmallestMaximum(), (int) monthRange.getMaximum(), 1);
int monthLen = maxDate.lengthOfMonth();
maxDate = maxDate.with(DAY_OF_MONTH, monthLen);
try {
HijrahDate after = maxDate.plus(1, ChronoUnit.DAYS);
fail("Exception did not occur, maxDate: " + maxDate + ".plus(1, DAYS) = " + after);
} catch (DateTimeException ex) {
// ignore, this exception was expected
}
}
use of java.time.DateTimeException in project jdk8u_jdk by JetBrains.
the class TestDateTimeBuilderCombinations method test_normalized.
@Test(dataProvider = "normalized")
public void test_normalized(final TemporalField field1, final Number value1, TemporalField expectedField, Number expectedVal) {
// mock for testing that does not fully comply with TemporalAccessor contract
TemporalAccessor test = new TemporalAccessor() {
@Override
public boolean isSupported(TemporalField field) {
return field == field1;
}
@Override
public long getLong(TemporalField field) {
if (field == field1) {
return value1.longValue();
}
throw new DateTimeException("Unsupported");
}
};
DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(field1).toFormatter();
String str = value1.toString();
TemporalAccessor temporal = f.parse(str);
if (expectedVal != null) {
assertEquals(temporal.getLong(expectedField), expectedVal.longValue());
} else {
assertEquals(temporal.isSupported(expectedField), false);
}
}
use of java.time.DateTimeException in project jdk8u_jdk by JetBrains.
the class HijrahChronology method loadCalendarData.
/**
* Loads and processes the Hijrah calendar properties file for this calendarType.
* The starting Hijrah date and the corresponding ISO date are
* extracted and used to calculate the epochDate offset.
* The version number is identified and ignored.
* Everything else is the data for a year with containing the length of each
* of 12 months.
*
* @throws DateTimeException if initialization of the calendar data from the
* resource fails
*/
private void loadCalendarData() {
try {
String resourceName = calendarProperties.getProperty(PROP_PREFIX + typeId);
Objects.requireNonNull(resourceName, "Resource missing for calendar: " + PROP_PREFIX + typeId);
Properties props = readConfigProperties(resourceName);
Map<Integer, int[]> years = new HashMap<>();
int minYear = Integer.MAX_VALUE;
int maxYear = Integer.MIN_VALUE;
String id = null;
String type = null;
String version = null;
int isoStart = 0;
for (Map.Entry<Object, Object> entry : props.entrySet()) {
String key = (String) entry.getKey();
switch(key) {
case KEY_ID:
id = (String) entry.getValue();
break;
case KEY_TYPE:
type = (String) entry.getValue();
break;
case KEY_VERSION:
version = (String) entry.getValue();
break;
case KEY_ISO_START:
{
int[] ymd = parseYMD((String) entry.getValue());
isoStart = (int) LocalDate.of(ymd[0], ymd[1], ymd[2]).toEpochDay();
break;
}
default:
try {
// Everything else is either a year or invalid
int year = Integer.valueOf(key);
int[] months = parseMonths((String) entry.getValue());
years.put(year, months);
maxYear = Math.max(maxYear, year);
minYear = Math.min(minYear, year);
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("bad key: " + key);
}
}
}
if (!getId().equals(id)) {
throw new IllegalArgumentException("Configuration is for a different calendar: " + id);
}
if (!getCalendarType().equals(type)) {
throw new IllegalArgumentException("Configuration is for a different calendar type: " + type);
}
if (version == null || version.isEmpty()) {
throw new IllegalArgumentException("Configuration does not contain a version");
}
if (isoStart == 0) {
throw new IllegalArgumentException("Configuration does not contain a ISO start date");
}
// Now create and validate the array of epochDays indexed by epochMonth
hijrahStartEpochMonth = minYear * 12;
minEpochDay = isoStart;
hijrahEpochMonthStartDays = createEpochMonths(minEpochDay, minYear, maxYear, years);
maxEpochDay = hijrahEpochMonthStartDays[hijrahEpochMonthStartDays.length - 1];
// Compute the min and max year length in days.
for (int year = minYear; year < maxYear; year++) {
int length = getYearLength(year);
minYearLength = Math.min(minYearLength, length);
maxYearLength = Math.max(maxYearLength, length);
}
} catch (Exception ex) {
// Log error and throw a DateTimeException
PlatformLogger logger = PlatformLogger.getLogger("java.time.chrono");
logger.severe("Unable to initialize Hijrah calendar proxy: " + typeId, ex);
throw new DateTimeException("Unable to initialize HijrahCalendar: " + typeId, ex);
}
}
use of java.time.DateTimeException in project jdk8u_jdk by JetBrains.
the class DateTimeFormatter method parseBest.
/**
* Fully parses the text producing an object of one of the specified types.
* <p>
* This parse method is convenient for use when the parser can handle optional elements.
* For example, a pattern of 'uuuu-MM-dd HH.mm[ VV]' can be fully parsed to a {@code ZonedDateTime},
* or partially parsed to a {@code LocalDateTime}.
* The queries must be specified in order, starting from the best matching full-parse option
* and ending with the worst matching minimal parse option.
* The query is typically a method reference to a {@code from(TemporalAccessor)} method.
* <p>
* The result is associated with the first type that successfully parses.
* Normally, applications will use {@code instanceof} to check the result.
* For example:
* <pre>
* TemporalAccessor dt = parser.parseBest(str, ZonedDateTime::from, LocalDateTime::from);
* if (dt instanceof ZonedDateTime) {
* ...
* } else {
* ...
* }
* </pre>
* If the parse completes without reading the entire length of the text,
* or a problem occurs during parsing or merging, then an exception is thrown.
*
* @param text the text to parse, not null
* @param queries the queries defining the types to attempt to parse to,
* must implement {@code TemporalAccessor}, not null
* @return the parsed date-time, not null
* @throws IllegalArgumentException if less than 2 types are specified
* @throws DateTimeParseException if unable to parse the requested result
*/
public TemporalAccessor parseBest(CharSequence text, TemporalQuery<?>... queries) {
Objects.requireNonNull(text, "text");
Objects.requireNonNull(queries, "queries");
if (queries.length < 2) {
throw new IllegalArgumentException("At least two queries must be specified");
}
try {
TemporalAccessor resolved = parseResolved0(text, null);
for (TemporalQuery<?> query : queries) {
try {
return (TemporalAccessor) resolved.query(query);
} catch (RuntimeException ex) {
// continue
}
}
throw new DateTimeException("Unable to convert parsed text using any of the specified queries");
} catch (DateTimeParseException ex) {
throw ex;
} catch (RuntimeException ex) {
throw createError(text, ex);
}
}
use of java.time.DateTimeException in project jgnash by ccavanaugh.
the class YahooEventParser method retrieveNew.
public static Set<SecurityHistoryEvent> retrieveNew(final SecurityNode securityNode, final LocalDate endDate) {
final Set<SecurityHistoryEvent> events = new HashSet<>();
LocalDate startDate = LocalDate.now().minusDays(1);
final List<SecurityHistoryNode> historyNodeList = securityNode.getHistoryNodes();
if (historyNodeList.size() > 0) {
startDate = historyNodeList.get(0).getLocalDate();
}
/*final List<SecurityHistoryEvent> historyEvents = new ArrayList<>(securityNode.getHistoryEvents());
if (historyEvents.size() > 0) {
Collections.sort(historyEvents);
startDate = historyEvents.get(historyEvents.size() - 1).getDate().plusDays(1);
}*/
// s = symbol
// a = start month -1
// b = start day
// c = start year
// d = end month -1
// e = end day
// f = end year
// g=v&y=0&z=30000 dividends only
// http://ichart.finance.yahoo.com/x?s=IBM&a=00&b=2&c=1962&d=04&e=25&f=2011&g=v&y=0&z=30000
/*
Date,Dividends
DIVIDEND, 20110506,0.750000
DIVIDEND, 20110208,0.650000
DIVIDEND, 20101108,0.650000
DIVIDEND, 19971106,0.100000
DIVIDEND, 19970807,0.100000
SPLIT, 19970528,2:1
DIVIDEND, 19970206,0.087500
DIVIDEND, 19961106,0.087500
STARTDATE, 19620102
ENDDATE, 20110525
TOTALSIZE, 195
STATUS, 0
*/
final String s = securityNode.getSymbol();
final String a = Integer.toString(startDate.getMonthValue());
final String b = Integer.toString(startDate.getDayOfMonth());
final String c = Integer.toString(startDate.getYear());
final String d = Integer.toString(endDate.getMonthValue());
final String e = Integer.toString(endDate.getDayOfMonth());
final String f = Integer.toString(endDate.getYear());
//http://ichart.finance.yahoo.com/x?s=IBM&a=00&b=2&c=1962&d=04&e=25&f=2011&g=v&y=0&z=30000
final StringBuilder url = new StringBuilder("https://ichart.finance.yahoo.com/x?s=").append(s);
url.append("&a=").append(a).append("&b=").append(b).append("&c=").append(c);
url.append("&d=").append(d).append("&e=").append(e);
url.append("&f=").append(f);
url.append("&g=v&y=0&z=30000");
URLConnection connection = null;
try {
connection = ConnectionFactory.openConnection(url.toString());
if (connection != null) {
try (final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
String line = in.readLine();
if (RESPONSE_HEADER.equals(line)) {
// prime the first read
line = in.readLine();
while (line != null) {
if (Thread.currentThread().isInterrupted()) {
Thread.currentThread().interrupt();
}
final String[] fields = COMMA_DELIMITER_PATTERN.split(line);
if (fields.length == 3) {
try {
final LocalDate date = LocalDate.of(Integer.parseInt(fields[1].trim().substring(0, 4)), Integer.parseInt(fields[1].trim().substring(4, 6)), Integer.parseInt(fields[1].trim().substring(6, 8)));
switch(fields[0]) {
case "DIVIDEND":
final BigDecimal dividend = new BigDecimal(fields[2]);
events.add(new SecurityHistoryEvent(SecurityHistoryEventType.DIVIDEND, date, dividend));
break;
case "SPLIT":
final String[] fraction = fields[2].split(":");
final BigDecimal value = new BigDecimal(fraction[0]).divide(new BigDecimal(fraction[1]), MathContext.DECIMAL32);
events.add(new SecurityHistoryEvent(SecurityHistoryEventType.SPLIT, date, value));
break;
default:
Logger.getLogger(YahooEventParser.class.getName()).log(Level.SEVERE, "Unknown event: " + fields[0]);
break;
}
} catch (final DateTimeException | NumberFormatException ex) {
Logger.getLogger(YahooEventParser.class.getName()).log(Level.INFO, line);
Logger.getLogger(YahooEventParser.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
}
}
line = in.readLine();
}
}
}
}
} catch (final NullPointerException | IOException ex) {
Logger.getLogger(YahooEventParser.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
} finally {
if (connection != null) {
if (connection instanceof HttpURLConnection) {
((HttpURLConnection) connection).disconnect();
}
}
}
return events;
}
Aggregations