use of org.restlet.representation.InputRepresentation 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.InputRepresentation in project xwiki-platform by xwiki.
the class ExtensionVersionFileRESTResource method downloadLocalExtension.
private ResponseBuilder downloadLocalExtension(String extensionId, String extensionVersion) throws ResolveException, IOException, QueryException, XWikiException {
XWikiDocument extensionDocument = getExistingExtensionDocumentById(extensionId);
checkRights(extensionDocument);
ResourceReference resourceReference = repositoryManager.getDownloadReference(extensionDocument, extensionVersion);
ResponseBuilder response = null;
if (ResourceType.ATTACHMENT.equals(resourceReference.getType())) {
// It's an attachment
AttachmentReference attachmentReference = this.attachmentResolver.resolve(resourceReference.getReference(), extensionDocument.getDocumentReference());
XWikiContext xcontext = getXWikiContext();
XWikiDocument document = xcontext.getWiki().getDocument(attachmentReference.getDocumentReference(), xcontext);
checkRights(document);
XWikiAttachment xwikiAttachment = document.getAttachment(attachmentReference.getName());
response = getAttachmentResponse(xwikiAttachment);
} else if (ResourceType.URL.equals(resourceReference.getType())) {
// It's an URL
URL url = new URL(resourceReference.getReference());
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "XWikiExtensionRepository");
httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
httpClient.setRoutePlanner(routePlanner);
HttpGet getMethod = new HttpGet(url.toString());
HttpResponse subResponse;
try {
subResponse = httpClient.execute(getMethod);
} catch (Exception e) {
throw new IOException("Failed to request [" + getMethod.getURI() + "]", e);
}
response = Response.status(subResponse.getStatusLine().getStatusCode());
// TODO: find a proper way to do a perfect proxy of the URL without directly using Restlet classes.
// Should probably use javax.ws.rs.ext.MessageBodyWriter
HttpEntity entity = subResponse.getEntity();
InputRepresentation content = new InputRepresentation(entity.getContent(), entity.getContentType() != null ? new MediaType(entity.getContentType().getValue()) : MediaType.APPLICATION_OCTET_STREAM, entity.getContentLength());
BaseObject extensionObject = getExtensionObject(extensionDocument);
String type = getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_TYPE);
Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT);
disposition.setFilename(extensionId + '-' + extensionVersion + '.' + type);
content.setDisposition(disposition);
response.entity(content);
} else if (ExtensionResourceReference.TYPE.equals(resourceReference.getType())) {
ExtensionResourceReference extensionResource;
if (resourceReference instanceof ExtensionResourceReference) {
extensionResource = (ExtensionResourceReference) resourceReference;
} else {
extensionResource = new ExtensionResourceReference(resourceReference.getReference());
}
response = downloadRemoteExtension(extensionResource);
} else {
throw new WebApplicationException(Status.NOT_FOUND);
}
return response;
}
use of org.restlet.representation.InputRepresentation in project xwiki-platform by xwiki.
the class FormUrlEncodedTagsReader method readFrom.
@Override
public Tags readFrom(Class<Tags> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
ObjectFactory objectFactory = new ObjectFactory();
Tags tags = objectFactory.createTags();
Representation representation = new InputRepresentation(entityStream, org.restlet.data.MediaType.APPLICATION_WWW_FORM);
Form form = new Form(representation);
/*
* If the form is empty then it might have happened that some filter has invalidated the entity stream. Try to
* read data using getParameter()
*/
if (form.getNames().isEmpty()) {
HttpServletRequest httpServletRequest = ServletUtils.getRequest(Request.getCurrent());
String text = httpServletRequest.getParameter(TAGS_FIELD_NAME);
if (text != null) {
String[] tagNames = text.split(" |,|\\|");
for (String tagName : tagNames) {
Tag tag = objectFactory.createTag();
tag.setName(tagName);
tags.getTags().add(tag);
}
}
String[] tagNames = httpServletRequest.getParameterValues(TAG_FIELD_NAME);
if (tagNames != null) {
for (String tagName : tagNames) {
Tag tag = objectFactory.createTag();
tag.setName(tagName);
tags.getTags().add(tag);
}
}
} else {
String text = form.getFirstValue(TAGS_FIELD_NAME);
if (text != null) {
String[] tagNames = text.split(" |,|\\|");
for (String tagName : tagNames) {
Tag tag = objectFactory.createTag();
tag.setName(tagName);
tags.getTags().add(tag);
}
}
for (String tagName : form.getValuesArray(TAG_FIELD_NAME)) {
Tag tag = objectFactory.createTag();
tag.setName(tagName);
tags.getTags().add(tag);
}
}
return tags;
}
use of org.restlet.representation.InputRepresentation in project xwiki-platform by xwiki.
the class FormUrlEncodedObjectReader method readFrom.
@Override
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
ObjectFactory objectFactory = new ObjectFactory();
Object object = objectFactory.createObject();
Representation representation = new InputRepresentation(entityStream, org.restlet.data.MediaType.APPLICATION_WWW_FORM);
Form form = new Form(representation);
/*
* If the form is empty then it might have happened that some filter has invalidated the entity stream. Try to
* read data using getParameter()
*/
if (form.getNames().isEmpty()) {
HttpServletRequest httpServletRequest = ServletUtils.getRequest(Request.getCurrent());
object.setClassName(httpServletRequest.getParameter(CLASSNAME_FIELD_NAME));
Enumeration<String> enumeration = httpServletRequest.getParameterNames();
while (enumeration.hasMoreElements()) {
String name = enumeration.nextElement();
if (name.startsWith(PROPERTY_PREFIX)) {
Property property = objectFactory.createProperty();
property.setName(name.replace(PROPERTY_PREFIX, ""));
property.setValue(httpServletRequest.getParameter(name));
object.getProperties().add(property);
}
}
} else {
object.setClassName(form.getFirstValue(CLASSNAME_FIELD_NAME));
for (String name : form.getNames()) {
if (name.startsWith(PROPERTY_PREFIX)) {
Property property = objectFactory.createProperty();
property.setName(name.replace(PROPERTY_PREFIX, ""));
property.setValue(form.getFirstValue(name));
object.getProperties().add(property);
}
}
}
return object;
}
use of org.restlet.representation.InputRepresentation 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();
}
}
Aggregations