Skip to content

Commit

Permalink
Merge branch 'master' into jersey-cache-client-with-apache-client
Browse files Browse the repository at this point in the history
  • Loading branch information
imyousuf committed Jan 31, 2011
2 parents 7d48717 + fb6bc63 commit 84045f3
Show file tree
Hide file tree
Showing 12 changed files with 372 additions and 70 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,15 @@
*/
package com.smartitengineering.util.rest.atom.server;

import com.smartitengineering.util.rest.server.ServerResourceInjectables;
import com.sun.jersey.api.core.HttpContext;
import com.sun.jersey.api.core.ResourceContext;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Date;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Entry;
Expand All @@ -30,28 +36,46 @@ public abstract class AbstractResource extends com.smartitengineering.util.rest.

private final Factory abderaFactory = Abdera.getNewFactory();

protected AbstractResource() {
}

protected AbstractResource(UriInfo info, HttpContext context, ResourceContext resourceContext) {
super(info, context, resourceContext);
}

protected AbstractResource(ServerResourceInjectables injectables) {
super(injectables);
}

protected Factory getAbderaFactory() {
return abderaFactory;
}

protected Feed getFeed() {
return getFeed(getUriInfo().getRequestUri().toString(), getUriInfo().getAbsolutePath().toString(), new Date());
return getFeed(getUriInfo().getRequestUri().toASCIIString(), getUriInfo().getAbsolutePath().toString(), new Date());
}

protected Feed getFeed(String title) {
return getFeed(getUriInfo().getRequestUri().toString(), title, new Date());
return getFeed(getUriInfo().getRequestUri().toASCIIString(), title, new Date());
}

protected Feed getFeed(String title,
Date updated) {
return getFeed(getUriInfo().getRequestUri().toString(), title, updated);
return getFeed(getUriInfo().getRequestUri().toASCIIString(), title, updated);
}

protected Feed getFeed(String id,
String title,
Date updated) {
Feed feed = getBaseFeed();
feed.setId(id);
String encodedId;
try {
encodedId = URLEncoder.encode(id, "UTF-8");
}
catch (UnsupportedEncodingException ex) {
encodedId = id;
}
feed.setId(encodedId);
feed.setTitle(title);
feed.setUpdated(updated);
return feed;
Expand All @@ -65,16 +89,20 @@ protected Feed getBaseFeed() {
}

protected Link getSelfLink() {
Link selfLink = abderaFactory.newLink();
selfLink.setHref(getUriInfo().getRequestUri().toString());
selfLink.setRel(Link.REL_SELF);
selfLink.setMimeType(MediaType.APPLICATION_ATOM_XML);
Link selfLink = getLink(getUriInfo().getRequestUri().toASCIIString(), Link.REL_SELF, MediaType.APPLICATION_ATOM_XML);
return selfLink;
}

protected Entry getEntry(final String id, final String name, final Date updated, Link... links) {
Entry entry = getAbderaFactory().newEntry();
entry.setId(id);
String entryId;
try {
entryId = URLEncoder.encode(id, "UTF-8");
}
catch (UnsupportedEncodingException ex) {
entryId = id;
}
entry.setId(entryId);
entry.setTitle(name);
entry.setUpdated(updated);
for (Link link : links) {
Expand All @@ -84,9 +112,13 @@ protected Entry getEntry(final String id, final String name, final Date updated,
}

protected Link getLink(URI uri, String rel, String mimeType) {
return getLink(uri.toASCIIString(), rel, mimeType);
}

protected Link getLink(String uri, String rel, String mimeType) {
Link link = getAbderaFactory().newLink();
link.setRel(rel);
link.setHref(uri.toString());
link.setHref(uri);
link.setMimeType(mimeType);
return link;
}
Expand Down
13 changes: 13 additions & 0 deletions rest/generic-client/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,19 @@
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jmock</groupId>
<artifactId>jmock-junit3</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,22 @@
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.config.ClientConfig;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* An abstract resource representation on client side for a client to a RESTful Web Service. It is designed to have one
Expand All @@ -50,10 +57,15 @@ public abstract class AbstractClientResource<T, P extends Resource> implements R

static {
CONNECTION_CONFIG = ConfigFactory.getInstance().getConnectionConfig();

BASE_URI = UriBuilder.fromUri(CONNECTION_CONFIG.getContextPath()).path(CONNECTION_CONFIG.getBasicUri()).host(
CONNECTION_CONFIG.getHost()).port(CONNECTION_CONFIG.getPort()).scheme("http").build();
if (CONNECTION_CONFIG != null) {
BASE_URI = UriBuilder.fromUri(CONNECTION_CONFIG.getContextPath()).path(CONNECTION_CONFIG.getBasicUri()).host(
CONNECTION_CONFIG.getHost()).port(CONNECTION_CONFIG.getPort()).scheme("http").build();
}
else {
BASE_URI = null;
}
}
protected Logger logger = LoggerFactory.getLogger(getClass());
private Resource referrer;
private URI thisResourceUri;
private URI absoluteThisResourceUri;
Expand All @@ -67,6 +79,12 @@ public abstract class AbstractClientResource<T, P extends Resource> implements R
private boolean followRedirectionEnabled;
private boolean invokeGet;
private final Map<String, Resource> nestedResources;
private final Map<String, Map<String, Object>> cachedHeaders;

protected AbstractClientResource(Resource referrer, ResourceLink resouceLink) throws
IllegalArgumentException, UniformInterfaceException {
this(referrer, resouceLink, null);
}

protected AbstractClientResource(Resource referrer, ResourceLink resouceLink, Class<? extends T> entityClass) throws
IllegalArgumentException, UniformInterfaceException {
Expand Down Expand Up @@ -127,7 +145,13 @@ protected AbstractClientResource(Resource referrer, URI thisResourceUri, String
throw new IllegalArgumentException("Accept header value can not be null!");
}
if (entityClass == null) {
throw new IllegalArgumentException("Entity class can not be null!");
entityClass = initializeEntityClassFromGenerics();
if (entityClass == null) {
throw new IllegalArgumentException("Entity class can not be null!");
}
}
if (clientUtil == null && entityClass != null) {
clientUtil = ClientUtilFactory.getInstance().getClientUtil(entityClass);
}
if (clientFactory == null) {
if (referrer == null) {
Expand All @@ -147,11 +171,32 @@ protected AbstractClientResource(Resource referrer, URI thisResourceUri, String
this.absoluteThisResourceUri = generateAbsoluteUri();
this.followRedirectionEnabled = followRedirection;
this.nestedResources = new HashMap<String, Resource>();
this.cachedHeaders = new HashMap<String, Map<String, Object>>();
if (invokeGet) {
get();
}
}

protected final Class<? extends T> initializeEntityClassFromGenerics() {
Class<? extends T> extractedEntityClass = null;
try {
Type paramType =
((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
if (paramType instanceof ParameterizedType) {
paramType = ((ParameterizedType) paramType).getRawType();
}
Class<T> pesistenceRegistryClass = paramType instanceof Class ? (Class<T>) paramType : null;
if (logger.isDebugEnabled()) {
logger.debug("Entity class predicted to: " + pesistenceRegistryClass.toString());
}
extractedEntityClass = pesistenceRegistryClass;
}
catch (Exception ex) {
logger.warn("Could not predict entity class ", ex);
}
return extractedEntityClass;
}

protected boolean isFollowRedirectionEnabled() {
return followRedirectionEnabled;
}
Expand Down Expand Up @@ -223,14 +268,17 @@ public String getResourceRepresentationType() {
}

@Override
public T get() {
public final T get() {
return get(getUri());
}

protected T get(URI uri) {
getInvocationCount++;
ClientResponse response = ClientUtil.readEntity(uri, getHttpClient(), getResourceRepresentationType(),
ClientResponse.class);
if (logger.isDebugEnabled()) {
logger.debug("Request Accept header: " + getResourceRepresentationType());
logger.debug("Response header: " + response.getType());
}
final int status = response.getStatus();
if (followRedirectionEnabled && status == ClientResponse.Status.MOVED_PERMANENTLY.getStatusCode()) {
final URI location = response.getLocation();
Expand All @@ -249,19 +297,35 @@ protected T get(URI uri) {
}
}
if (status < 300 ||
(status == ClientResponse.Status.NOT_MODIFIED.getStatusCode() && response.hasEntity())) {
lastReadStateOfEntity = response.getEntity(getEntityClass());
if (getClientUtil() != null) {
try {
getClientUtil().parseLinks(lastReadStateOfEntity, getRelatedResourceUris());
(status == ClientResponse.Status.NOT_MODIFIED.getStatusCode())) {
if (response.hasEntity() && response.getStatus() != ClientResponse.Status.NO_CONTENT.getStatusCode()) {
lastReadStateOfEntity = response.getEntity(getEntityClass());
if (getClientUtil() != null) {
try {
getClientUtil().parseLinks(lastReadStateOfEntity, getRelatedResourceUris());
}
catch (Exception ex) {
logger.warn(ex.getMessage(), ex);
}
}
catch (Exception ex) {
ex.printStackTrace();
if (invokeGet) {
invokeGETOnNestedResources();
}
}
if (invokeGet) {
invokeGETOnNestedResources();
else {
lastReadStateOfEntity = null;
}
getInvocationCount++;
Map<String, Object> headers = new HashMap<String, Object>();
EntityTag tag = response.getEntityTag();
if (tag != null) {
headers.put(HttpHeaders.ETAG, tag);
}
Date date = response.getLastModified();
if (date != null) {
headers.put(HttpHeaders.LAST_MODIFIED, date);
}
cachedHeaders.put(uri.toString(), headers);
return lastReadStateOfEntity;
}
throw new UniformInterfaceException(response);
Expand All @@ -288,15 +352,17 @@ public URI getUri() {
@Override
public ClientResponse delete(Status... status) {
WebResource webResource = getHttpClient().getWebResource(getUri());
final ClientResponse response = webResource.delete(ClientResponse.class);
Builder builder = addNecessaryHeaders(getUri(), webResource);
final ClientResponse response = builder.delete(ClientResponse.class);
checkStatus(response, status);
return response;
}

@Override
public <P> ClientResponse put(String contentType, P param, Status... status) {
WebResource webResource = getHttpClient().getWebResource(getUri());
Builder builder = webResource.type(contentType);
Builder builder = addNecessaryHeaders(getUri(), webResource);
builder.type(contentType);
final ClientResponse response = builder.put(ClientResponse.class, param);
checkStatus(response, status);
return response;
Expand All @@ -305,7 +371,8 @@ public <P> ClientResponse put(String contentType, P param, Status... status) {
@Override
public <P> ClientResponse post(String contentType, P param, Status... status) {
WebResource webResource = getHttpClient().getWebResource(getUri());
Builder builder = webResource.type(contentType);
Builder builder = addNecessaryHeaders(getUri(), webResource);
builder.type(contentType);
final ClientResponse response = builder.post(ClientResponse.class, param);
checkStatus(response, status);
return response;
Expand Down Expand Up @@ -404,4 +471,20 @@ protected void checkStatus(ClientResponse response, Status... status) {
}
throw new UniformInterfaceException(response);
}

protected Builder addNecessaryHeaders(URI uri, WebResource resource) {
Map<String, Object> headers = cachedHeaders.get(uri.toString());
Builder builder = resource.getRequestBuilder();
if (headers != null) {
final Object etag = headers.get(HttpHeaders.ETAG);
if (etag != null) {
builder.header(HttpHeaders.IF_MATCH, etag);
}
final Object lastModified = headers.get(HttpHeaders.LAST_MODIFIED);
if (lastModified != null) {
builder.header(HttpHeaders.IF_UNMODIFIED_SINCE, lastModified);
}
}
return builder;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
package com.smartitengineering.util.rest.client;

import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterface;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import java.net.URI;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.commons.lang.StringUtils;
Expand Down Expand Up @@ -48,11 +50,14 @@ public static ResourceLink createResourceLink(String rel, URI uri, String mimeTy
public static <T> T readEntity(final URI uri, HttpClient client, String acceptType, Class<? extends T> clazz) {
if (uri != null && client != null && clazz != null) {
try {
UniformInterface uniformInterface;
WebResource resource = client.getWebResource(uri);
uniformInterface = resource;
if (StringUtils.isNotBlank(acceptType)) {
resource.accept(acceptType);
Builder builder = resource.accept(acceptType);
uniformInterface = builder;
}
T newEntity = resource.get(clazz);
T newEntity = uniformInterface.get(clazz);
return newEntity;
}
catch (Exception ex) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ private ClientUtilFactory() {
}

public ClientUtil getClientUtil(Class clazz) {
if (clazz == null) {
return null;
}
return clientUtils.get(clazz);
}
}
Loading

0 comments on commit 84045f3

Please sign in to comment.