Skip to content
This repository was archived by the owner on Jun 18, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of

package microsoft.exchange.webservices.data;

import microsoft.exchange.webservices.data.util.DateTimeParser;

import java.util.Date;
import java.util.EnumSet;

Expand Down Expand Up @@ -71,12 +73,11 @@ protected DateTimePropertyDefinition(String xmlElementName, String uri,
* @param propertyBag the property bag
* @throws Exception the exception
*/
protected void loadPropertyValueFromXml(EwsServiceXmlReader reader,
PropertyBag propertyBag) throws Exception {
String value = reader.readElementValue(XmlNamespace.Types,
getXmlElement());
propertyBag.setObjectFromPropertyDefinition(this, reader.getService()
.convertUniversalDateTimeStringToDate(value));
protected void loadPropertyValueFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag)
throws Exception {
String value = reader.readElementValue(XmlNamespace.Types, getXmlElement());
propertyBag.setObjectFromPropertyDefinition(this, new DateTimeParser()
.convertDateTimeStringToDate(value));
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of

package microsoft.exchange.webservices.data;

import microsoft.exchange.webservices.data.util.DateTimeParser;

import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
Expand All @@ -24,6 +26,8 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
*/
class EwsServiceXmlReader extends EwsXmlReader {

private DateTimeParser dateTimeParser = new DateTimeParser();

/**
* The service.
*/
Expand All @@ -42,38 +46,14 @@ protected EwsServiceXmlReader(InputStream stream, ExchangeService service)
this.service = service;
}

/**
* Converts the specified string into a DateTime objects.
*
* @param dateTimeString The date time string to convert.
* @return A DateTime representing the converted string.
*/
private Date convertStringToDateTime(String dateTimeString) {
return this.service
.convertUniversalDateTimeStringToDate(dateTimeString);
}

/**
* Converts the specified string into a
* unspecified Date object, ignoring offset.
*
* @param dateTimeString The date time string to convert.
* @return A DateTime representing the converted string.
* @throws java.text.ParseException
*/
private Date convertStringToUnspecifiedDate(String dateTimeString) throws ParseException {
return this.getService().
convertStartDateToUnspecifiedDateTime(dateTimeString);
}

/**
* Reads the element value as date time.
*
* @return Element value
* @throws Exception the exception
*/
public Date readElementValueAsDateTime() throws Exception {
return this.convertStringToDateTime(this.readElementValue());
return dateTimeParser.convertDateTimeStringToDate(readElementValue());
}

/**
Expand All @@ -83,7 +63,7 @@ public Date readElementValueAsDateTime() throws Exception {
* @throws Exception
*/
public Date readElementValueAsUnspecifiedDate() throws Exception {
return this.convertStringToUnspecifiedDate(this.readElementValue());
return dateTimeParser.convertDateStringToDate(readElementValue());
}

/**
Expand Down Expand Up @@ -144,10 +124,8 @@ public Date readElementValueAsUnbiasedDateTimeScopedToServiceTimeZone()
* @return the date
* @throws Exception the exception
*/
public Date readElementValueAsDateTime(XmlNamespace xmlNamespace,
String localName) throws Exception {
return this.convertStringToDateTime(this.readElementValue(xmlNamespace,
localName));
public Date readElementValueAsDateTime(XmlNamespace xmlNamespace, String localName) throws Exception {
return dateTimeParser.convertDateTimeStringToDate(readElementValue(xmlNamespace, localName));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -396,127 +396,6 @@ private void traceHttpResponseHeaders(TraceFlags traceType, HttpWebRequest reque
}
}

/**
* Converts the universal date time string to local date time.
*
* @param dateString The value.
* @return DateTime Returned date is always in UTC date.
*/
protected Date convertUniversalDateTimeStringToDate(String dateString) {
String localTimeRegex = "^(.*)([+-]{1}\\d\\d:\\d\\d)$";
Pattern localTimePattern = Pattern.compile(localTimeRegex);
String utcPattern = "yyyy-MM-dd'T'HH:mm:ss'Z'";
String utcPattern1 = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'";
String localPattern = "yyyy-MM-dd'T'HH:mm:ssz";
String localPattern1 = "yyyy-MM-dd'Z'";
String pattern = "yyyy-MM-ddz";
String localPattern2 = "yyyy-MM-dd'T'HH:mm:ss";
DateFormat utcFormatter = null;
Date dt = null;
String errMsg = String.format(
"Date String %s not in valid UTC/local format", dateString);
if (dateString == null || dateString.isEmpty()) {
return null;
} else {
if (dateString.endsWith("Z")) {
// String in UTC format yyyy-MM-ddTHH:mm:ssZ
utcFormatter = new SimpleDateFormat(utcPattern);
utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
dt = utcFormatter.parse(dateString);
} catch (ParseException e) {
utcFormatter = new SimpleDateFormat(pattern);
utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
// dateString = dateString.substring(0, 10)+"T12:00:00Z";
try {
dt = utcFormatter.parse(dateString);
} catch (ParseException e1) {
utcFormatter = new SimpleDateFormat(localPattern1);
utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));

try {
dt = utcFormatter.parse(dateString);
} catch (ParseException ex) {

utcFormatter = new SimpleDateFormat(utcPattern1);
utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
}
try {
dt = utcFormatter.parse(dateString);
} catch (ParseException e2) {
throw new IllegalArgumentException(errMsg, e);
}

}
// throw new IllegalArgumentException(errMsg,e);
}
} else if (dateString.endsWith("z")) {
// String in UTC format yyyy-MM-ddTHH:mm:ssZ
utcFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'z'");
utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
dt = utcFormatter.parse(dateString);
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
} else {
// dateString is not ending with Z.
// Check for yyyy-MM-ddTHH:mm:ss+/-HH:mm pattern
Matcher localTimeMatcher = localTimePattern.matcher(dateString);
if (localTimeMatcher.find()) {
System.out.println("Pattern matched");
String date = localTimeMatcher.group(1);
String zone = localTimeMatcher.group(2);
// Add the string GMT between DateTime and TimeZone
// since 'z' in yyyy-MM-dd'T'HH:mm:ssz matches
// either format GMT+/-HH:mm or +/-HHmm
dateString = String.format("%sGMT%s", date, zone);
try {
utcFormatter = new SimpleDateFormat(localPattern);
utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
dt = utcFormatter.parse(dateString);
} catch (ParseException e) {
try {
utcFormatter = new SimpleDateFormat(pattern);
utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
dt = utcFormatter.parse(dateString);
} catch (ParseException ex) {
throw new IllegalArgumentException(ex);
}
}
} else {
// Invalid format
utcFormatter = new SimpleDateFormat(localPattern2);
utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
dt = utcFormatter.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
throw new IllegalArgumentException(errMsg);
}
}
}
return dt;
}
}

/**
* Converts xs:dateTime string with either "Z", "-00:00" bias, or ""
* suffixes to unspecified StartDate value ignoring the suffix.Needs to fix
* E14:232996.
*
* @param value The string value to parse.
* @return The parsed DateTime value.
*/
protected Date convertStartDateToUnspecifiedDateTime(String value) throws ParseException {
if (value == null || value.isEmpty()) {
return null;
} else {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'Z'");
return df.parse(value);
}
}

/**
* Converts the date time to universal date time string.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of

package microsoft.exchange.webservices.data;

import microsoft.exchange.webservices.data.util.DateTimeParser;

import javax.xml.stream.XMLStreamException;
import java.lang.reflect.Array;
import java.util.*;
Expand Down Expand Up @@ -581,8 +583,7 @@ private Object constructObject(UserConfigurationDictionaryObjectType type,
} else if (type.equals(UserConfigurationDictionaryObjectType.ByteArray)) {
dictionaryObject = Base64EncoderStream.decode(value.get(0));
} else if (type.equals(UserConfigurationDictionaryObjectType.DateTime)) {
Date dateTime = reader.getService()
.convertUniversalDateTimeStringToDate(value.get(0));
Date dateTime = new DateTimeParser().convertDateTimeStringToDate(value.get(0));
if (dateTime != null) {
dictionaryObject = dateTime;
} else {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/**************************************************************************
Exchange Web Services Java API
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************/

package microsoft.exchange.webservices.data.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class DateTimeParser {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to expose this for consumers of the library? Should we make it package internal?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I placed this class in a subpackage (yes, the first subpackage in this library), so we can't make it package private if we keep it there. This shouldn't be a problem though. All major libraries or frameworks expose internal utility classes like this. Otherwise package organisation wouldn't be possible.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So if we change a utility method interface, we will consider this a contract change? Hence, prefer to mark them as deprecated unless we are working on a major version? Or should we have SomeNameSpace.Internal.* to reflect that these are internal packages that shouldn't be used by client apps?


private final SimpleDateFormat[] dateTimeFormats = {
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"),
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"),
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"),
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"),
new SimpleDateFormat("yyyy-MM-ddX"),
new SimpleDateFormat("yyyy-MM-dd")
};

private final SimpleDateFormat[] dateFormats = {
new SimpleDateFormat("yyyy-MM-ddX"),
new SimpleDateFormat("yyyy-MM-dd")
};


public DateTimeParser() {
// Set default timezone of the formats to UTC, which will be used when the date string doesn't supply a
// timezone itself.

for (SimpleDateFormat format : dateTimeFormats) {
format.setTimeZone(TimeZone.getTimeZone("UTC"));
}

for (SimpleDateFormat format : dateFormats) {
format.setTimeZone(TimeZone.getTimeZone("UTC"));
}
}

/**
* Converts a date time string to local date time.
*
* Note: this method also allows dates without times, in which case the time will be 00:00:00 in the
* supplied timezone. UTC timezone will be assumed if no timezone is supplied.
*
* @param value The string value to parse.
* @return The parsed {@link Date}.
*
* @throws java.lang.IllegalArgumentException If string can not be parsed.
*/
public Date convertDateTimeStringToDate(String value) {
return parseInternal(value, false);
}

/**
* Converts a date string to local date time.
*
* UTC timezone will be assumed if no timezone is supplied.
*
* @param value The string value to parse.
* @return The parsed {@link Date}.
*
* @throws java.lang.IllegalArgumentException If string can not be parsed.
*/
public Date convertDateStringToDate(String value) {
return parseInternal(value, true);
}

private Date parseInternal(String value, boolean dateOnly) {
String originalValue = value;

if (value == null || value.isEmpty()) {
return null;
} else {
if (value.endsWith("z")) {
// This seems to be an edge case. Let's uppercase the Z to be sure.
value = value.substring(0, value.length() - 1) + "Z";
}

SimpleDateFormat[] formats = dateOnly ? dateFormats : dateTimeFormats;
for (SimpleDateFormat format : formats) {
try {
return format.parse(value);
} catch (ParseException e) {
// Ignore and try the next pattern.
}
}
}

throw new IllegalArgumentException(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason for throwing a different kind of exception here? IllegalArgumentException vs. ParseException? I generally prefer to use illegal argument kind of exceptions to reflect programming errors where exceptions based on runtime data would use ParseException (or FormatException in .NET). Thoughts?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The former method convertUniversalDateTimeStringToDate(...) already did so, so I kept this behaviour. Note that IllegalArgumentException is a runtime exception, where ParseException is a checked exception. I think that most important is that this behaviour is documented in the javadoc, like it is.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, I've just read about checked vs. runtime exceptions, I'm new to the concept of checked exceptions since it is unique to Java. However, I would have thought that parsing should be a checked exception to force the callers to handle the case where the string they are providing is not valid. This is not something that you want to bubble to the top of the stack. It is interesting however that SimpleDateFormat throws ParseException (checked) and long.ParseLong throws IllegalArgumentException (runtime). I would have thought there would be consistency there and both use checked, since I would expect parsing errors to be handled closest to where they are used.

String.format("Date String %s not in valid UTC/local format", originalValue));
}
}
Loading