Issue 695: Converted parsing of Tasks to JAXB, removed SAX handlers. Not verified by live test yet

This commit is contained in:
Jason King 2011-11-14 12:17:10 +00:00
parent dc1b74cc90
commit ea349810ef
10 changed files with 131 additions and 283 deletions

View File

@ -0,0 +1,46 @@
/**
* 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.trmk.enterprisecloud.domain;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Wraps individual Task elements.
* Needed because parsing is done with JAXB and it does not handle Generic collections
* @author Jason King
*/
@XmlRootElement(name = "Tasks")
public class Tasks {
private LinkedHashSet<Task> tasks = new LinkedHashSet<Task>();
@XmlElement(name = "Task")
void setTask(Task task) {
tasks.add(task);
}
public Set<Task> getTasks() {
return Collections.unmodifiableSet(tasks);
}
}

View File

@ -24,14 +24,13 @@ 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 org.jclouds.trmk.enterprisecloud.domain.Tasks;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import java.net.URI;
import java.util.Set;
/**
* Provides asynchronous access to Task via their REST API.
@ -53,9 +52,9 @@ public interface TaskAsyncClient {
@GET
@Path("/tasks/environments/{environmentId}")
@Consumes("application/vnd.tmrk.cloud.task; type=collection")
@XMLResponseParser(TasksHandler.class)
@JAXBResponseParser
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<Task>> getTasksInEnvironment(@PathParam("environmentId") long environmentId);
ListenableFuture<Tasks> getTasksInEnvironment(@PathParam("environmentId") long environmentId);
/**
* @see TaskClient#getTask

View File

@ -18,12 +18,12 @@
*/
package org.jclouds.trmk.enterprisecloud.features;
import java.net.URI;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.concurrent.Timeout;
import org.jclouds.trmk.enterprisecloud.domain.Task;
import org.jclouds.trmk.enterprisecloud.domain.Tasks;
import java.net.URI;
import java.util.concurrent.TimeUnit;
/**
* Provides synchronous access to Task.
@ -44,7 +44,7 @@ public interface TaskClient {
*
* @return a history of changes to the environment.
*/
Set<Task> getTasksInEnvironment(long environmentId);
Tasks getTasksInEnvironment(long environmentId);
/**
* The Get Tasks by ID call returns information regarding a specified task in

View File

@ -1,100 +0,0 @@
/**
* 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.trmk.enterprisecloud.xml;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.util.SaxUtils.currentOrNull;
import static org.jclouds.util.SaxUtils.equalsOrSuffix;
import java.util.Map;
import javax.inject.Inject;
import org.jclouds.date.DateService;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.trmk.enterprisecloud.domain.NamedResource;
import org.jclouds.trmk.enterprisecloud.domain.Task;
import org.jclouds.util.SaxUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
* @author Adrian Cole
*/
public class TaskHandler extends ParseSax.HandlerWithResult<Task> {
protected final DateService dateService;
protected StringBuilder currentText = new StringBuilder();
protected Task.Builder builder = Task.builder();
@Inject
public TaskHandler(DateService dateService) {
this.dateService = checkNotNull(dateService, "dateService");
}
public Task getResult() {
try {
return builder.build();
} finally {
builder = Task.builder();
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs);
if (equalsOrSuffix(qName, "Task")) {
builder.fromAttributes(attributes);
} else if (equalsOrSuffix(qName, "ImpactedItem")) {
builder.impactedItem(NamedResource.builder().fromAttributes(attributes).build());
} else if (equalsOrSuffix(qName, "InitiatedBy")) {
builder.initiatedBy(NamedResource.builder().fromAttributes(attributes).build());
}
}
@Override
public void endElement(String uri, String localName, String qName) {
if (equalsOrSuffix(qName, "Operation")) {
builder.operation(currentOrNull(currentText));
} else if (equalsOrSuffix(qName, "Status")) {
String status = currentOrNull(currentText);
if (status != null)
builder.status(Task.Status.fromValue(status));
} else if (equalsOrSuffix(qName, "StartTime")) {
String date = currentOrNull(currentText);
if (date != null)
builder.startTime(dateService.iso8601DateParse(date));
} else if (equalsOrSuffix(qName, "CompletedTime")) {
String date = currentOrNull(currentText);
if (date != null)
builder.completedTime(dateService.iso8601DateParse(date));
} else if (equalsOrSuffix(qName, "Notes")) {
builder.notes(currentOrNull(currentText));
} else if (equalsOrSuffix(qName, "ErrorMessage")) {
builder.errorMessage(currentOrNull(currentText));
}
currentText = new StringBuilder();
}
public void characters(char ch[], int start, int length) {
currentText.append(ch, start, length);
}
}

View File

@ -1,94 +0,0 @@
/**
* 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.trmk.enterprisecloud.xml;
import static org.jclouds.util.SaxUtils.equalsOrSuffix;
import java.util.Set;
import javax.inject.Inject;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.trmk.enterprisecloud.domain.Task;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import com.google.common.collect.ImmutableSet;
/**
* @author Adrian Cole
*/
public class TasksHandler extends ParseSax.HandlerWithResult<Set<Task>> {
public Set<Task> getResult() {
try {
return builder.build();
} finally {
builder = ImmutableSet.<Task> builder();
}
}
protected final TaskHandler taskHandler;
protected ImmutableSet.Builder<Task> builder = ImmutableSet.<Task> builder();
@Inject
public TasksHandler(TaskHandler taskHandler) {
this.taskHandler = taskHandler;
}
protected boolean inTask;
protected int depth = 0;
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
depth++;
if (depth == 2) {
if (equalsOrSuffix(qName, "Task")) {
inTask = true;
}
}
if (inTask) {
taskHandler.startElement(uri, localName, qName, attrs);
}
}
@Override
public void endElement(String uri, String localName, String qName) {
depth--;
if (depth == 1) {
if (equalsOrSuffix(qName, "Task")) {
inTask = false;
builder.add(taskHandler.getResult());
}
}
if (inTask) {
taskHandler.endElement(uri, localName, qName);
}
}
@Override
public void characters(char ch[], int start, int length) {
if (inTask) {
taskHandler.characters(ch, start, length);
}
}
}

View File

@ -20,12 +20,10 @@ package org.jclouds.trmk.enterprisecloud.features;
import com.google.inject.TypeLiteral;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ParseXMLWithJAXB;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.trmk.enterprisecloud.xml.TasksHandler;
import org.testng.annotations.Test;
import java.io.IOException;
@ -49,8 +47,7 @@ public class TaskAsyncClientTest extends BaseTerremarkEnterpriseCloudAsyncClient
"Accept: application/vnd.tmrk.cloud.task; type=collection\nx-trmk-version: 2011-07-01\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseSax.class);
assertSaxResponseParserClassEquals(method, TasksHandler.class);
assertResponseParserClassEquals(method, httpRequest, ParseXMLWithJAXB.class);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);

View File

@ -18,15 +18,14 @@
*/
package org.jclouds.trmk.enterprisecloud.features;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.Set;
import org.jclouds.trmk.enterprisecloud.domain.Task;
import org.jclouds.trmk.enterprisecloud.domain.Tasks;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
/**
* Tests behavior of {@code TaskClient}
*
@ -47,11 +46,11 @@ public class TaskClientLiveTest extends BaseTerremarkEnterpriseCloudClientLiveTe
// TODO: don't hard-code id
// TODO: docs say don't parse the href, yet no xml includes "identifier",
// I suspect we may need to change to URI args as opposed to long
Set<Task> response = client.getTasksInEnvironment(77);
Tasks response = client.getTasksInEnvironment(77);
assert null != response;
assertTrue(response.size() >= 0);
for (Task task : response) {
assertTrue(response.getTasks().size() >= 0);
for (Task task : response.getTasks()) {
assertEquals(client.getTask(task.getHref()), task);
assert task.getStatus() != Task.Status.UNRECOGNIZED : response;
}

View File

@ -36,8 +36,10 @@ import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.jclouds.trmk.enterprisecloud.domain.NamedResource;
import org.jclouds.trmk.enterprisecloud.domain.Task;
import org.jclouds.trmk.enterprisecloud.domain.Tasks;
import org.jclouds.trmk.enterprisecloud.features.TaskAsyncClient;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.inject.Named;
@ -50,16 +52,23 @@ 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;
import static org.testng.Assert.assertTrue;
/**
* Tests behavior of {@code TaskHandler}
* Tests behavior of JAXB parsing for Task/Tasks
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "TaskHandlerTest")
public class TaskHandlerTest extends BaseRestClientTest {
static SimpleDateFormatDateService dateService = new SimpleDateFormatDateService();
static Task expected = Task
private SimpleDateFormatDateService dateService;
private Task expected1;
private Task expected2;
@BeforeMethod
public void setUp() {
dateService = new SimpleDateFormatDateService();
expected1 = Task
.builder()
.href(URI.create("/livespec/tasks/1002"))
.type("application/vnd.tmrk.cloud.task")
@ -76,6 +85,24 @@ public class TaskHandlerTest extends BaseRestClientTest {
NamedResource.builder().href(URI.create("/livespec/admin/users/1")).name("User 1")
.type("application/vnd.tmrk.cloud.admin.user").build()).build();
expected2 = Task
.builder()
.href(URI.create("/livespec/tasks/1003"))
.type("application/vnd.tmrk.cloud.task")
.operation("Add Node Service 2")
.status(Task.Status.SUCCESS)
.impactedItem(
NamedResource.builder().href(URI.create("/livespec/nodeservices/2")).name("sample node internet 2")
.type("application/vnd.tmrk.cloud.nodeService").build())
.startTime(dateService.iso8601DateParse("2011-11-11T11:19:13.38225Z"))
.completedTime(dateService.iso8601DateParse("2011-11-11T11:20:13.38225Z"))
.notes("Some notes about the operation.")
.errorMessage("sample success message 1 here")
.initiatedBy(
NamedResource.builder().href(URI.create("/livespec/admin/users/3")).name("User 3")
.type("application/vnd.tmrk.cloud.admin.user").build()).build();
}
@BeforeClass
void setupFactory() {
RestContextSpec<String, Integer> contextSpec = contextSpec("test", "http://localhost:9999", "1", "", "userfoo",
@ -111,6 +138,25 @@ public class TaskHandlerTest extends BaseRestClientTest {
InputStream is = getClass().getResourceAsStream("/task.xml");
Task task = parser.apply(new HttpResponse(200, "ok", newInputStreamPayload(is)));
assertEquals(task, expected);
assertEquals(task, expected1);
}
@Test
public void testParseTasksWithJAXB() throws Exception {
Method method = TaskAsyncClient.class.getMethod("getTasksInEnvironment",long.class);
HttpRequest request = factory(TaskAsyncClient.class).createRequest(method,1);
assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class);
Function<HttpResponse, Tasks> parser = (Function<HttpResponse, Tasks>) RestAnnotationProcessor
.createResponseParser(parserFactory, injector, method, request);
InputStream is = getClass().getResourceAsStream("/tasks.xml");
Tasks tasksResponse = parser.apply(new HttpResponse(200, "ok", newInputStreamPayload(is)));
Set<Task> tasks = tasksResponse.getTasks();
assertEquals(tasks.size(), 2);
assertTrue(tasks.contains(expected1));
assertTrue(tasks.contains(expected2));
}
}

View File

@ -1,55 +0,0 @@
/**
* 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.trmk.enterprisecloud.xml;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.util.Set;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ParseSax.Factory;
import org.jclouds.http.functions.config.SaxParserModule;
import org.jclouds.trmk.enterprisecloud.domain.Task;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code TasksHandler}
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "TasksHandlerTest")
public class TasksHandlerTest {
public void test() {
InputStream is = getClass().getResourceAsStream("/tasks.xml");
Injector injector = Guice.createInjector(new SaxParserModule());
Factory factory = injector.getInstance(ParseSax.Factory.class);
Set<Task> result = factory.create(injector.getInstance(TasksHandler.class)).parse(is);
Set<Task> expected = ImmutableSet.of(TaskHandlerTest.expected);
assertEquals(result.toString(), expected.toString());
}
}

View File

@ -1,12 +1,22 @@
<Tasks href="/livespec/tasks/environments/1" type="application/vnd.tmrk.cloud.task; type=collection">
<Task href="/livespec/tasks/1002" type="application/vnd.tmrk.cloud.task">
<Operation>Add Node Service</Operation>
<Status>Error</Status>
<ImpactedItem href="/livespec/nodeservices/1" name="sample node internet 1" type="application/vnd.tmrk.cloud.nodeService"/>
<StartTime>2011-11-07T11:19:13.38225Z</StartTime>
<CompletedTime>2011-11-07T11:20:13.38225Z</CompletedTime>
<Notes>Some notes about the operation.</Notes>
<ErrorMessage>sample error message 1 here</ErrorMessage>
<InitiatedBy href="/livespec/admin/users/1" name="User 1" type="application/vnd.tmrk.cloud.admin.user"/>
</Task>
<Operation>Add Node Service</Operation>
<Status>Error</Status>
<ImpactedItem href="/livespec/nodeservices/1" name="sample node internet 1" type="application/vnd.tmrk.cloud.nodeService"/>
<StartTime>2011-11-07T11:19:13.38225Z</StartTime>
<CompletedTime>2011-11-07T11:20:13.38225Z</CompletedTime>
<Notes>Some notes about the operation.</Notes>
<ErrorMessage>sample error message 1 here</ErrorMessage>
<InitiatedBy href="/livespec/admin/users/1" name="User 1" type="application/vnd.tmrk.cloud.admin.user"/>
</Task>
<Task href="/livespec/tasks/1003" type="application/vnd.tmrk.cloud.task">
<Operation>Add Node Service 2</Operation>
<Status>Success</Status>
<ImpactedItem href="/livespec/nodeservices/2" name="sample node internet 2" type="application/vnd.tmrk.cloud.nodeService"/>
<StartTime>2011-11-11T11:19:13.38225Z</StartTime>
<CompletedTime>2011-11-11T11:20:13.38225Z</CompletedTime>
<Notes>Some notes about the operation.</Notes>
<ErrorMessage>sample success message 1 here</ErrorMessage>
<InitiatedBy href="/livespec/admin/users/3" name="User 3" type="application/vnd.tmrk.cloud.admin.user"/>
</Task>
</Tasks>