Created
March 9, 2012 18:25
-
-
Save electrum/2007885 to your computer and use it in GitHub Desktop.
Jersey AbstractParam
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.proofpoint.anomalytics.mailfetcher; | |
import javax.ws.rs.WebApplicationException; | |
import javax.ws.rs.core.Response; | |
import static javax.ws.rs.core.Response.Status; | |
/** | |
* Abstract parameter class for Jersey parameters | |
* | |
* @param <T> parameter value type | |
* @see <a href="http://codahale.com/what-makes-jersey-interesting-parameter-classes/"> | |
* http://codahale.com/what-makes-jersey-interesting-parameter-classes/</a> | |
*/ | |
public abstract class AbstractParam<T> | |
{ | |
private final T value; | |
private final String originalParam; | |
public AbstractParam(String param) | |
throws WebApplicationException | |
{ | |
this.originalParam = param; | |
try { | |
this.value = parse(param); | |
} | |
catch (Throwable e) { | |
throw new WebApplicationException(onError(param, e)); | |
} | |
} | |
public T getValue() | |
{ | |
return value; | |
} | |
public String getOriginalParam() | |
{ | |
return originalParam; | |
} | |
@Override | |
public String toString() | |
{ | |
return value.toString(); | |
} | |
protected abstract T parse(String param) | |
throws Throwable; | |
protected Response onError(String param, Throwable e) | |
{ | |
return Response | |
.status(Status.BAD_REQUEST) | |
.entity(getErrorMessage(param, e)) | |
.build(); | |
} | |
protected String getErrorMessage(String param, Throwable e) | |
{ | |
return "Invalid parameter: " + param + " (" + e.getMessage() + ")"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment