Merge pull request #139 from jsonking/master

Issue 695: Converted Task parsing to JAXB and fixed a bug with date parsing
This commit is contained in:
Adrian Cole 2011-11-11 09:55:17 -08:00
commit 56a7dec54a
12 changed files with 247 additions and 60 deletions

View File

@ -27,13 +27,15 @@ import java.util.regex.Pattern;
*/ */
public class DateUtils { public class DateUtils {
public static final Pattern NANOS_TO_MILLIS_PATTERN = Pattern.compile(".*[0-9][0-9][0-9][0-9][0-9][0-9]"); public static final Pattern MILLIS_PATTERN = Pattern.compile("(.*\\.[0-9][0-9][0-9])[0-9]*Z?");
public static final Pattern TZ_PATTERN = Pattern.compile("(.*)[+-][0-9][0-9]:?[0-9][0-9]Z?"); public static final Pattern TZ_PATTERN = Pattern.compile("(.*)[+-][0-9][0-9]:?[0-9][0-9]Z?");
public static String trimNanosToMillis(String toParse) { public static String trimToMillis(String toParse) {
if (NANOS_TO_MILLIS_PATTERN.matcher(toParse).matches()) Matcher matcher = MILLIS_PATTERN.matcher(toParse);
toParse = toParse.substring(0, toParse.length() - 3) + 'Z'; if (matcher.find()) {
toParse = matcher.group(1) + 'Z';
}
return toParse; return toParse;
} }

View File

@ -17,7 +17,7 @@
* under the License. * under the License.
*/ */
package org.jclouds.date.internal; package org.jclouds.date.internal;
import static org.jclouds.date.internal.DateUtils.trimNanosToMillis; import static org.jclouds.date.internal.DateUtils.trimToMillis;
import static org.jclouds.date.internal.DateUtils.trimTZ; import static org.jclouds.date.internal.DateUtils.trimTZ;
import java.text.ParseException; import java.text.ParseException;
@ -124,7 +124,7 @@ public class SimpleDateFormatDateService implements DateService {
public final Date iso8601DateParse(String toParse) { public final Date iso8601DateParse(String toParse) {
toParse = trimTZ(toParse); toParse = trimTZ(toParse);
toParse = trimNanosToMillis(toParse); toParse = trimToMillis(toParse);
synchronized (iso8601SimpleDateFormat) { synchronized (iso8601SimpleDateFormat) {
try { try {
return iso8601SimpleDateFormat.parse(toParse); return iso8601SimpleDateFormat.parse(toParse);

View File

@ -0,0 +1,55 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.date.internal;
import org.testng.annotations.Test;
import static org.testng.AssertJUnit.assertEquals;
@Test(groups = "unit", testName = "DateUtilsTest")
public class DateUtilsTest {
@Test
public void testTrimsToMillisWithTimezone() {
assertEquals("NO_MILLISZ",DateUtils.trimToMillis("NO_MILLISZ"));
assertEquals("NO_MILLIS.1Z",DateUtils.trimToMillis("NO_MILLIS.1Z"));
assertEquals("NO_MILLIS.12Z",DateUtils.trimToMillis("NO_MILLIS.12Z"));
assertEquals("NO_MILLIS.123Z",DateUtils.trimToMillis("NO_MILLIS.123Z"));
assertEquals("NO_MILLIS.123Z",DateUtils.trimToMillis("NO_MILLIS.1234Z"));
assertEquals("NO_MILLIS.123Z",DateUtils.trimToMillis("NO_MILLIS.12345Z"));
assertEquals("NO_MILLIS.123Z",DateUtils.trimToMillis("NO_MILLIS.123456Z"));
assertEquals("NO_MILLIS.123Z",DateUtils.trimToMillis("NO_MILLIS.1234567Z"));
assertEquals("NO_MILLIS.123Z",DateUtils.trimToMillis("NO_MILLIS.12345689Z"));
assertEquals("NO_MILLIS.123Z",DateUtils.trimToMillis("NO_MILLIS.12345690123345678Z"));
}
@Test
public void testTrimsToMillisNoTimezone() {
assertEquals("NO_MILLIS",DateUtils.trimToMillis("NO_MILLISZ"));
assertEquals("NO_MILLIS.1",DateUtils.trimToMillis("NO_MILLIS.1"));
assertEquals("NO_MILLIS.12",DateUtils.trimToMillis("NO_MILLIS.12"));
assertEquals("NO_MILLIS.123",DateUtils.trimToMillis("NO_MILLIS.123"));
assertEquals("NO_MILLIS.123",DateUtils.trimToMillis("NO_MILLIS.1234"));
assertEquals("NO_MILLIS.123",DateUtils.trimToMillis("NO_MILLIS.12345"));
assertEquals("NO_MILLIS.123",DateUtils.trimToMillis("NO_MILLIS.123456"));
assertEquals("NO_MILLIS.123",DateUtils.trimToMillis("NO_MILLIS.1234567"));
assertEquals("NO_MILLIS.123",DateUtils.trimToMillis("NO_MILLIS.12345689"));
assertEquals("NO_MILLIS.123",DateUtils.trimToMillis("NO_MILLIS.12345690123345678"));
}
}

View File

@ -0,0 +1,41 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.date.internal;
import org.testng.annotations.Test;
import java.util.Date;
import static org.testng.AssertJUnit.assertEquals;
@Test(groups = "unit", testName = "SimpleDateFormatDateServiceTest")
public class SimpleDateFormatDateServiceTest {
@Test
public void testCorrectHandlingOfMillis() {
Date date = new SimpleDateFormatDateService().iso8601DateParse("2011-11-07T11:19:13.38225Z");
assertEquals("Mon Nov 07 11:19:13 GMT 2011",date.toString());
}
@Test
public void testCorrectHandlingOfMillisWithNoTimezone() {
Date date = new SimpleDateFormatDateService().iso8601DateParse("2009-02-03T05:26:32.612278");
assertEquals("Tue Feb 03 05:26:32 GMT 2009",date.toString());
}
}

View File

@ -18,7 +18,7 @@
*/ */
package org.jclouds.date.joda; package org.jclouds.date.joda;
import static org.jclouds.date.internal.DateUtils.trimNanosToMillis; import static org.jclouds.date.internal.DateUtils.trimToMillis;
import static org.jclouds.date.internal.DateUtils.trimTZ; import static org.jclouds.date.internal.DateUtils.trimTZ;
import java.util.Date; import java.util.Date;
@ -98,7 +98,7 @@ public class JodaDateService implements DateService {
public final Date iso8601DateParse(String toParse) { public final Date iso8601DateParse(String toParse) {
toParse = trimTZ(toParse); toParse = trimTZ(toParse);
toParse = trimNanosToMillis(toParse); toParse = trimToMillis(toParse);
return iso8601DateFormatter.parseDateTime(toParse).toDate(); return iso8601DateFormatter.parseDateTime(toParse).toDate();
} }

View File

@ -107,4 +107,8 @@ public class NamedResource extends BaseNamedResource<NamedResource> {
public NamedResource(URI href, String type, String name) { public NamedResource(URI href, String type, String name) {
super(href, type, name); super(href, type, name);
} }
protected NamedResource() {
//For JAXB
}
} }

View File

@ -29,32 +29,44 @@ import java.util.Map;
import org.jclouds.javax.annotation.Nullable; import org.jclouds.javax.annotation.Nullable;
import org.jclouds.trmk.enterprisecloud.domain.internal.BaseResource; import org.jclouds.trmk.enterprisecloud.domain.internal.BaseResource;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlRootElement;
/** /**
* *
* @author Adrian Cole * @author Adrian Cole
* *
*/ */
@XmlRootElement(name = "Task")
public class Task extends BaseResource<Task> { public class Task extends BaseResource<Task> {
@XmlEnum
public static enum Status { public static enum Status {
/** /**
* the task is queued for execution. * the task is queued for execution.
*/ */
@XmlEnumValue("Queued")
QUEUED, QUEUED,
/** /**
* the task is running. * the task is running.
*/ */
@XmlEnumValue("Running")
RUNNING, RUNNING,
/** /**
* the task failed. * the task failed.
*/ */
@XmlEnumValue("Failed")
FAILED, FAILED,
/** /**
* the task completed successfully. * the task completed successfully.
*/ */
@XmlEnumValue("Success")
SUCCESS, SUCCESS,
/** /**
* the task failed with an error. * the task failed with an error.
*/ */
@XmlEnumValue("Error")
ERROR, ERROR,
/** /**
* Status was not parsed by jclouds. * Status was not parsed by jclouds.
@ -212,14 +224,29 @@ public class Task extends BaseResource<Task> {
} }
protected final String operation; @XmlElement(name = "Operation", required = true)
protected final Status status; protected String operation;
protected final NamedResource impactedItem;
protected final Date startTime; @XmlElement(name = "Status", required = true)
protected final Date completedTime; protected Status status;
protected final String notes;
protected final String errorMessage; @XmlElement(name = "ImpactedItem", required = true)
protected final NamedResource initiatedBy; protected NamedResource impactedItem;
@XmlElement(name = "StartTime", required = true)
protected Date startTime;
@XmlElement(name = "CompletedTime", required = false)
protected Date completedTime;
@XmlElement(name = "Notes", required = false)
protected String notes;
@XmlElement(name = "ErrorMessage", required = false)
protected String errorMessage;
@XmlElement(name = "InitiatedBy", required = true)
protected NamedResource initiatedBy;
public Task(URI href, String type, String operation, Status status, NamedResource impactedItem, Date startTime, public Task(URI href, String type, String operation, Status status, NamedResource impactedItem, Date startTime,
@Nullable Date completedTime, @Nullable String notes, @Nullable String errorMessage, NamedResource initiatedBy) { @Nullable Date completedTime, @Nullable String notes, @Nullable String errorMessage, NamedResource initiatedBy) {
@ -234,6 +261,10 @@ public class Task extends BaseResource<Task> {
this.initiatedBy = checkNotNull(initiatedBy, "initiatedBy"); this.initiatedBy = checkNotNull(initiatedBy, "initiatedBy");
} }
protected Task() {
//For JAXB
}
/** /**
* *
* *

View File

@ -18,6 +18,8 @@
*/ */
package org.jclouds.trmk.enterprisecloud.domain.internal; package org.jclouds.trmk.enterprisecloud.domain.internal;
import javax.xml.bind.annotation.XmlAttribute;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI; import java.net.URI;
@ -77,13 +79,18 @@ public class BaseNamedResource<T extends BaseNamedResource<T>> extends BaseResou
} }
} }
protected final String name; @XmlAttribute
protected String name;
public BaseNamedResource(URI href, String type, String name) { public BaseNamedResource(URI href, String type, String name) {
super(href, type); super(href, type);
this.name = checkNotNull(name, "name"); this.name = checkNotNull(name, "name");
} }
protected BaseNamedResource() {
//For JAXB
}
public String getName() { public String getName() {
return name; return name;
} }

View File

@ -18,6 +18,8 @@
*/ */
package org.jclouds.trmk.enterprisecloud.domain.internal; package org.jclouds.trmk.enterprisecloud.domain.internal;
import javax.xml.bind.annotation.XmlAttribute;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI; import java.net.URI;
@ -74,14 +76,21 @@ public class BaseResource<T extends BaseResource<T>> {
} }
protected final String type; @XmlAttribute
protected final URI href; protected String type;
@XmlAttribute
protected URI href;
public BaseResource(URI href, String type) { public BaseResource(URI href, String type) {
this.type = checkNotNull(type, "type"); this.type = checkNotNull(type, "type");
this.href = checkNotNull(href, "href"); this.href = checkNotNull(href, "href");
} }
protected BaseResource() {
//For JAXB
}
/** /**
* *
* @return type definition, type, expressed as an HTTP Content-Type * @return type definition, type, expressed as an HTTP Content-Type

View File

@ -18,27 +18,20 @@
*/ */
package org.jclouds.trmk.enterprisecloud.features; package org.jclouds.trmk.enterprisecloud.features;
import java.net.URI; import com.google.common.util.concurrent.ListenableFuture;
import java.util.Set; import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.rest.annotations.*;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.trmk.enterprisecloud.domain.Task;
import org.jclouds.trmk.enterprisecloud.xml.TasksHandler;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import java.net.URI;
import org.jclouds.http.filters.BasicAuthentication; import java.util.Set;
import org.jclouds.rest.annotations.EndpointParam;
import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.Headers;
import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.XMLResponseParser;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.trmk.enterprisecloud.domain.Task;
import org.jclouds.trmk.enterprisecloud.xml.TaskHandler;
import org.jclouds.trmk.enterprisecloud.xml.TasksHandler;
import com.google.common.util.concurrent.ListenableFuture;
/** /**
* Provides asynchronous access to Task via their REST API. * Provides asynchronous access to Task via their REST API.
@ -69,7 +62,7 @@ public interface TaskAsyncClient {
*/ */
@GET @GET
@Consumes("application/vnd.tmrk.cloud.task") @Consumes("application/vnd.tmrk.cloud.task")
@XMLResponseParser(TaskHandler.class) @JAXBResponseParser
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<Task> getTask(@EndpointParam URI taskId); ListenableFuture<Task> getTask(@EndpointParam URI taskId);

View File

@ -18,20 +18,19 @@
*/ */
package org.jclouds.trmk.enterprisecloud.features; package org.jclouds.trmk.enterprisecloud.features;
import java.io.IOException; import com.google.inject.TypeLiteral;
import java.lang.reflect.Method;
import java.net.URI;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ParseXMLWithJAXB;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.trmk.enterprisecloud.xml.TaskHandler;
import org.jclouds.trmk.enterprisecloud.xml.TasksHandler; import org.jclouds.trmk.enterprisecloud.xml.TasksHandler;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.inject.TypeLiteral; import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
/** /**
* Tests annotation parsing of {@code TaskAsyncClient} * Tests annotation parsing of {@code TaskAsyncClient}
@ -66,8 +65,7 @@ public class TaskAsyncClientTest extends BaseTerremarkEnterpriseCloudAsyncClient
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/vnd.tmrk.cloud.task\nx-trmk-version: 2011-07-01\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/vnd.tmrk.cloud.task\nx-trmk-version: 2011-07-01\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseSax.class); assertResponseParserClassEquals(method, httpRequest, ParseXMLWithJAXB.class);
assertSaxResponseParserClassEquals(method, TaskHandler.class);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
checkFilters(httpRequest); checkFilters(httpRequest);

View File

@ -18,21 +18,38 @@
*/ */
package org.jclouds.trmk.enterprisecloud.xml; package org.jclouds.trmk.enterprisecloud.xml;
import static org.testng.Assert.assertEquals; import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet;
import java.io.InputStream; import com.google.inject.AbstractModule;
import java.net.URI; import com.google.inject.Module;
import com.google.inject.Provides;
import org.jclouds.crypto.Crypto;
import org.jclouds.date.internal.SimpleDateFormatDateService; import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ParseSax.Factory; import org.jclouds.http.functions.ParseXMLWithJAXB;
import org.jclouds.http.functions.config.SaxParserModule; import org.jclouds.logging.config.NullLoggingModule;
import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.BaseRestClientTest;
import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.trmk.enterprisecloud.domain.NamedResource; import org.jclouds.trmk.enterprisecloud.domain.NamedResource;
import org.jclouds.trmk.enterprisecloud.domain.Task; import org.jclouds.trmk.enterprisecloud.domain.Task;
import org.jclouds.trmk.enterprisecloud.features.TaskAsyncClient;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.inject.Guice; import javax.inject.Named;
import com.google.inject.Injector; import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Set;
import static org.jclouds.io.Payloads.newInputStreamPayload;
import static org.jclouds.rest.RestContextFactory.contextSpec;
import static org.jclouds.rest.RestContextFactory.createContextBuilder;
import static org.testng.Assert.assertEquals;
/** /**
* Tests behavior of {@code TaskHandler} * Tests behavior of {@code TaskHandler}
@ -40,7 +57,7 @@ import com.google.inject.Injector;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "unit", testName = "TaskHandlerTest") @Test(groups = "unit", testName = "TaskHandlerTest")
public class TaskHandlerTest { public class TaskHandlerTest extends BaseRestClientTest {
static SimpleDateFormatDateService dateService = new SimpleDateFormatDateService(); static SimpleDateFormatDateService dateService = new SimpleDateFormatDateService();
static Task expected = Task static Task expected = Task
.builder() .builder()
@ -59,11 +76,41 @@ public class TaskHandlerTest {
NamedResource.builder().href(URI.create("/livespec/admin/users/1")).name("User 1") NamedResource.builder().href(URI.create("/livespec/admin/users/1")).name("User 1")
.type("application/vnd.tmrk.cloud.admin.user").build()).build(); .type("application/vnd.tmrk.cloud.admin.user").build()).build();
public void test() { @BeforeClass
void setupFactory() {
RestContextSpec<String, Integer> contextSpec = contextSpec("test", "http://localhost:9999", "1", "", "userfoo",
"credentialFoo", String.class, Integer.class,
ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(), new AbstractModule() {
@Override
protected void configure() {}
@SuppressWarnings("unused")
@Provides
@Named("exception")
Set<String> exception() {
throw new AuthorizationException();
}
}));
injector = createContextBuilder(contextSpec).buildInjector();
parserFactory = injector.getInstance(ParseSax.Factory.class);
crypto = injector.getInstance(Crypto.class);
}
@Test
public void testParseTaskWithJAXB() throws Exception {
Method method = TaskAsyncClient.class.getMethod("getTask",URI.class);
HttpRequest request = factory(TaskAsyncClient.class).createRequest(method);
assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class);
Function<HttpResponse, Task> parser = (Function<HttpResponse, Task>) RestAnnotationProcessor
.createResponseParser(parserFactory, injector, method, request);
InputStream is = getClass().getResourceAsStream("/task.xml"); InputStream is = getClass().getResourceAsStream("/task.xml");
Injector injector = Guice.createInjector(new SaxParserModule()); Task task = parser.apply(new HttpResponse(200, "ok", newInputStreamPayload(is)));
Factory factory = injector.getInstance(ParseSax.Factory.class); assertEquals(task, expected);
Task result = factory.create(injector.getInstance(TaskHandler.class)).parse(is);
assertEquals(result.toString(), expected.toString());
} }
} }