use of org.restlet.representation.ByteArrayRepresentation in project camel by apache.
the class DefaultRestletBinding method populateRestletResponseFromExchange.
public void populateRestletResponseFromExchange(Exchange exchange, Response response) throws Exception {
Message out;
if (exchange.isFailed()) {
// 500 for internal server error which can be overridden by response code in header
response.setStatus(Status.valueOf(500));
Message msg = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
if (msg.isFault()) {
out = msg;
} else {
// print exception as message and stacktrace
Exception t = exchange.getException();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
response.setEntity(sw.toString(), MediaType.TEXT_PLAIN);
return;
}
} else {
out = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
}
// get content type
MediaType mediaType = out.getHeader(Exchange.CONTENT_TYPE, MediaType.class);
if (mediaType == null) {
Object body = out.getBody();
mediaType = MediaType.TEXT_PLAIN;
if (body instanceof String) {
mediaType = MediaType.TEXT_PLAIN;
} else if (body instanceof StringSource || body instanceof DOMSource) {
mediaType = MediaType.TEXT_XML;
}
}
// get response code
Integer responseCode = out.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
if (responseCode != null) {
response.setStatus(Status.valueOf(responseCode));
}
// set response body according to the message body
Object body = out.getBody();
if (body instanceof WrappedFile) {
// grab body from generic file holder
GenericFile<?> gf = (GenericFile<?>) body;
body = gf.getBody();
}
if (body == null) {
// empty response
response.setEntity("", MediaType.TEXT_PLAIN);
} else if (body instanceof Response) {
// its already a restlet response, so dont do anything
LOG.debug("Using existing Restlet Response from exchange body: {}", body);
} else if (body instanceof Representation) {
response.setEntity(out.getBody(Representation.class));
} else if (body instanceof InputStream) {
response.setEntity(new InputRepresentation(out.getBody(InputStream.class), mediaType));
} else if (body instanceof File) {
response.setEntity(new FileRepresentation(out.getBody(File.class), mediaType));
} else if (body instanceof byte[]) {
byte[] bytes = out.getBody(byte[].class);
response.setEntity(new ByteArrayRepresentation(bytes, mediaType, bytes.length));
} else {
// fallback and use string
String text = out.getBody(String.class);
response.setEntity(text, mediaType);
}
LOG.debug("Populate Restlet response from exchange body: {}", body);
if (exchange.getProperty(Exchange.CHARSET_NAME) != null) {
CharacterSet cs = CharacterSet.valueOf(exchange.getProperty(Exchange.CHARSET_NAME, String.class));
response.getEntity().setCharacterSet(cs);
}
// set headers at the end, as the entity must be set first
// NOTE: setting HTTP headers on restlet is cumbersome and its API is "weird" and has some flaws
// so we need to headers two times, and the 2nd time we add the non-internal headers once more
Series<Header> series = new Series<Header>(Header.class);
for (Map.Entry<String, Object> entry : out.getHeaders().entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (!headerFilterStrategy.applyFilterToCamelHeaders(key, value, exchange)) {
boolean added = setResponseHeader(exchange, response, key, value);
if (!added) {
// we only want non internal headers
if (!key.startsWith("Camel") && !key.startsWith("org.restlet")) {
String text = exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange, value);
if (text != null) {
series.add(key, text);
}
}
}
}
}
// set HTTP headers so we return these in the response
if (!series.isEmpty()) {
response.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, series);
}
}
use of org.restlet.representation.ByteArrayRepresentation in project camel by apache.
the class DefaultRestletBinding method createRepresentationFromBody.
protected Representation createRepresentationFromBody(Exchange exchange, MediaType mediaType) {
Object body = exchange.getIn().getBody();
if (body == null) {
return new EmptyRepresentation();
}
// unwrap file
if (body instanceof WrappedFile) {
body = ((WrappedFile) body).getFile();
}
if (body instanceof InputStream) {
return new InputRepresentation((InputStream) body, mediaType);
} else if (body instanceof File) {
return new FileRepresentation((File) body, mediaType);
} else if (body instanceof byte[]) {
return new ByteArrayRepresentation((byte[]) body, mediaType);
} else if (body instanceof String) {
return new StringRepresentation((CharSequence) body, mediaType);
}
// fallback as string
body = exchange.getIn().getBody(String.class);
if (body != null) {
return new StringRepresentation((CharSequence) body, mediaType);
} else {
return new EmptyRepresentation();
}
}
use of org.restlet.representation.ByteArrayRepresentation in project vcell by virtualcell.
the class RpcRestlet method handle.
@Override
public void handle(Request req, Response response) {
if (req.getMethod().equals(Method.GET)) {
try {
User authuser = null;
HttpRequest request = (HttpRequest) req;
// Use "WWW-Authenticate - Basic" authentication scheme
// Browser takes care of asking user for credentials and sending them
// Must be used with https connection to hide credentials
Header authHeader = request.getHeaders().getFirst("Authorization");
if (authHeader != null) {
// caller included a user and password
String typeAndCredential = authHeader.getValue();
// System.out.println("--"+up);
java.util.StringTokenizer st = new java.util.StringTokenizer(typeAndCredential, " ");
String type = st.nextToken();
String userAndPasswordB64 = st.nextToken();
String s = new String(Base64.getDecoder().decode(userAndPasswordB64));
// System.out.println("type="+type+" decoded="+s);
if (type.equals("Basic")) {
java.util.StringTokenizer st2 = new java.util.StringTokenizer(s, ":");
if (st2.countTokens() == 2) {
String usr = st2.nextToken();
String pw = st2.nextToken();
// System.out.println("user="+usr+" password="+pw);
UserLoginInfo.DigestedPassword dpw = new UserLoginInfo.DigestedPassword(pw);
// System.out.println(dpw);
VCellApiApplication application = ((VCellApiApplication) getApplication());
authuser = application.getUserVerifier().authenticateUser(usr, dpw.getString().toCharArray());
// System.out.println(authuser);
}
}
}
if (authuser == null) {
// Response headers container might be null so add one if necessary
if (((HttpResponse) response).getHeaders() == null) {
((HttpResponse) response).getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, new Series(Header.class));
}
// Tell whoever called us we want a user and password that we will check against admin vcell users
HttpResponse.addHeader(response, "WWW-Authenticate", "Basic");
response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
return;
}
Form form = request.getResourceRef().getQueryAsForm();
if (form.getFirst("stats") != null) {
// get .../rpc?stats=value 'value'
String requestTypeString = form.getFirstValue("stats", true);
if ((authuser.getName().equals("frm") || authuser.getName().equals("les") || authuser.getName().equals("ion") || authuser.getName().equals("danv") || authuser.getName().equals("mblinov") || authuser.getName().equals("ACowan"))) {
String result = restDatabaseService.getBasicStatistics();
response.setStatus(Status.SUCCESS_OK);
response.setEntity(result, MediaType.TEXT_HTML);
return;
}
}
} catch (Exception e) {
String errMesg = "<html><body>Error RpcRestlet.handle(...) req='" + req.toString() + "' <br>err='" + e.getMessage() + "'</br>" + "</body></html>";
getLogger().severe(errMesg);
e.printStackTrace();
response.setStatus(Status.SERVER_ERROR_INTERNAL);
response.setEntity(errMesg, MediaType.TEXT_HTML);
}
} else if (req.getMethod().equals(Method.POST)) {
String destination = null;
String method = null;
try {
VCellApiApplication application = ((VCellApiApplication) getApplication());
User vcellUser = application.getVCellUser(req.getChallengeResponse(), AuthenticationPolicy.prohibitInvalidCredentials);
HttpRequest request = (HttpRequest) req;
String username = vcellUser.getName();
String userkey = vcellUser.getID().toString();
destination = request.getHeaders().getFirstValue("Destination");
method = request.getHeaders().getFirstValue("Method");
String returnRequired = request.getHeaders().getFirstValue("ReturnRequired");
String timeoutMS = request.getHeaders().getFirstValue("TimeoutMS");
String compressed = request.getHeaders().getFirstValue("Compressed");
String klass = request.getHeaders().getFirstValue("Class");
if (lg.isTraceEnabled()) {
lg.trace("username=" + username + ", userkey=" + userkey + ", destination=" + destination + ", method=" + method + ", returnRequired=" + returnRequired + ", timeoutMS=" + timeoutMS + ", compressed=" + compressed + ", class=" + klass);
}
req.bufferEntity();
Serializable rpcRequestBodyObject = VCellApiClient.fromCompressedSerialized(req.getEntity().getStream());
if (!(rpcRequestBodyObject instanceof VCellApiRpcBody)) {
throw new RuntimeException("expecting post content of type VCellApiRpcBody");
}
VCellApiRpcBody rpcBody = (VCellApiRpcBody) rpcRequestBodyObject;
if (rpcBody.rpcRequest.methodName == null || (User.isGuest(username) && !vcellguestAllowed.contains(rpcBody.rpcRequest.methodName))) {
throw new IllegalArgumentException(User.createGuestErrorMessage(rpcBody.rpcRequest.methodName));
}
RpcServiceType st = null;
VCellQueue queue = null;
switch(rpcBody.rpcRequest.rpcDestination) {
case DataRequestQueue:
{
st = RpcServiceType.DATA;
queue = VCellQueue.DataRequestQueue;
break;
}
case DbRequestQueue:
{
st = RpcServiceType.DB;
queue = VCellQueue.DbRequestQueue;
break;
}
case SimReqQueue:
{
st = RpcServiceType.DISPATCH;
queue = VCellQueue.SimReqQueue;
break;
}
default:
{
throw new RuntimeException("unsupported RPC Destination: " + rpcBody.rpcDestination);
}
}
VCellApiRpcRequest vcellapiRpcRequest = rpcBody.rpcRequest;
Serializable serializableResultObject = null;
/*if(vcellapiRpcRequest.methodName != null && vcellapiRpcRequest.methodName.equals("getVCInfoContainer")) {
serializableResultObject = restDatabaseService.getVCInfoContainer(vcellUser);
}else if(vcellapiRpcRequest.methodName != null && vcellapiRpcRequest.methodName.equals("getBioModelXML")) {
serializableResultObject = restDatabaseService.getBioModelXML((KeyValue)vcellapiRpcRequest.args[1], vcellUser);
}else if(vcellapiRpcRequest.methodName != null && vcellapiRpcRequest.methodName.equals("getMathModelXML")) {
serializableResultObject = restDatabaseService.getMathModelXML((KeyValue)vcellapiRpcRequest.args[1], vcellUser);
}else */
if (vcellapiRpcRequest.methodName != null && vcellapiRpcRequest.methodName.equals("getSimulationStatus")) {
if (vcellapiRpcRequest.args[1] instanceof KeyValue[]) {
serializableResultObject = restDatabaseService.getSimulationStatus((KeyValue[]) vcellapiRpcRequest.args[1], vcellUser);
} else if (vcellapiRpcRequest.args[1] instanceof KeyValue) {
serializableResultObject = restDatabaseService.getSimulationStatus((KeyValue) vcellapiRpcRequest.args[1], vcellUser);
}
} else if (vcellapiRpcRequest.methodName != null && vcellapiRpcRequest.methodName.equals("getSpecialUsers")) {
serializableResultObject = restDatabaseService.getSpecialUsers(vcellUser);
} else {
Object[] arglist = vcellapiRpcRequest.args;
String[] specialProperties = rpcBody.specialProperties;
Object[] specialValues = rpcBody.specialValues;
VCRpcRequest vcRpcRequest = new VCRpcRequest(vcellUser, st, method, arglist);
VCellApiApplication vcellApiApplication = (VCellApiApplication) getApplication();
RpcService rpcService = vcellApiApplication.getRpcService();
serializableResultObject = rpcService.sendRpcMessage(queue, vcRpcRequest, new Boolean(rpcBody.returnedRequired), specialProperties, specialValues, new UserLoginInfo(username, null));
}
byte[] serializedResultObject = VCellApiClient.toCompressedSerialized(serializableResultObject);
response.setStatus(Status.SUCCESS_OK, "rpc method=" + method + " succeeded");
response.setEntity(new ByteArrayRepresentation(serializedResultObject));
} catch (Exception e) {
getLogger().severe("internal error invoking " + destination + ":" + method + "(): " + e.getMessage());
e.printStackTrace();
response.setStatus(Status.SERVER_ERROR_INTERNAL);
if (e.getCause() instanceof ServerRejectedSaveException) {
// send back actual exception, client needs specific cause
try {
byte[] serializedResultObject = VCellApiClient.toCompressedSerialized(e.getCause());
response.setEntity(new ByteArrayRepresentation(serializedResultObject));
return;
} catch (Exception e1) {
e1.printStackTrace();
// continue and send error message
}
}
response.setEntity("internal error invoking " + destination + ":" + method + "(): " + e.getMessage(), MediaType.TEXT_PLAIN);
}
}
}
use of org.restlet.representation.ByteArrayRepresentation in project vcell by virtualcell.
the class BiomodelDiagramServerResource method get_png.
@Override
@Get("image/png")
public ByteArrayRepresentation get_png() {
VCellApiApplication application = ((VCellApiApplication) getApplication());
User vcellUser = application.getVCellUser(getChallengeResponse(), AuthenticationPolicy.ignoreInvalidCredentials);
String vcml = getBiomodelVCML(vcellUser);
if (vcml == null) {
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "BioModel not found");
}
try {
BioModel bioModel = XmlHelper.XMLToBioModel(new XMLSource(vcml));
Integer imageWidthInPixels = 1000;
BufferedImage bufferedImage = ITextWriter.generateDocReactionsImage(bioModel.getModel(), imageWidthInPixels);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", outputStream);
byte[] imageBytes = outputStream.toByteArray();
return new ByteArrayRepresentation(imageBytes, MediaType.IMAGE_PNG, imageBytes.length);
} catch (Exception e) {
e.printStackTrace();
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e.getMessage());
}
}
Aggregations