Search in sources :

Example 1 with InputRepresentation

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);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Message(org.apache.camel.Message) StringWriter(java.io.StringWriter) WrappedFile(org.apache.camel.WrappedFile) MediaType(org.restlet.data.MediaType) CharacterSet(org.restlet.data.CharacterSet) PrintWriter(java.io.PrintWriter) InputRepresentation(org.restlet.representation.InputRepresentation) InputStream(java.io.InputStream) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) StringRepresentation(org.restlet.representation.StringRepresentation) InputRepresentation(org.restlet.representation.InputRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) FileRepresentation(org.restlet.representation.FileRepresentation) StreamRepresentation(org.restlet.representation.StreamRepresentation) Representation(org.restlet.representation.Representation) DecodeRepresentation(org.restlet.engine.application.DecodeRepresentation) ParseException(java.text.ParseException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) ChallengeResponse(org.restlet.data.ChallengeResponse) Response(org.restlet.Response) Series(org.restlet.util.Series) Header(org.restlet.data.Header) FileRepresentation(org.restlet.representation.FileRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) StringSource(org.apache.camel.StringSource) WrappedFile(org.apache.camel.WrappedFile) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) Map(java.util.Map) GenericFile(org.apache.camel.component.file.GenericFile)

Example 2 with InputRepresentation

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;
}
Also used : AttachmentReference(org.xwiki.model.reference.AttachmentReference) HttpEntity(org.apache.http.HttpEntity) InputRepresentation(org.restlet.representation.InputRepresentation) WebApplicationException(javax.ws.rs.WebApplicationException) HttpGet(org.apache.http.client.methods.HttpGet) XWikiContext(com.xpn.xwiki.XWikiContext) HttpResponse(org.apache.http.HttpResponse) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) IOException(java.io.IOException) URL(java.net.URL) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) XWikiException(com.xpn.xwiki.XWikiException) URISyntaxException(java.net.URISyntaxException) WebApplicationException(javax.ws.rs.WebApplicationException) QueryException(org.xwiki.query.QueryException) IOException(java.io.IOException) ResolveException(org.xwiki.extension.ResolveException) BaseObject(com.xpn.xwiki.objects.BaseObject) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) ProxySelectorRoutePlanner(org.apache.http.impl.conn.ProxySelectorRoutePlanner) Disposition(org.restlet.data.Disposition) MediaType(org.restlet.data.MediaType) ResourceReference(org.xwiki.rendering.listener.reference.ResourceReference) ExtensionResourceReference(org.xwiki.repository.internal.reference.ExtensionResourceReference) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) ExtensionResourceReference(org.xwiki.repository.internal.reference.ExtensionResourceReference)

Example 3 with InputRepresentation

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;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ObjectFactory(org.xwiki.rest.model.jaxb.ObjectFactory) InputRepresentation(org.restlet.representation.InputRepresentation) Form(org.restlet.data.Form) InputRepresentation(org.restlet.representation.InputRepresentation) Representation(org.restlet.representation.Representation) Tag(org.xwiki.rest.model.jaxb.Tag) Tags(org.xwiki.rest.model.jaxb.Tags)

Example 4 with InputRepresentation

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;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ObjectFactory(org.xwiki.rest.model.jaxb.ObjectFactory) InputRepresentation(org.restlet.representation.InputRepresentation) Form(org.restlet.data.Form) Object(org.xwiki.rest.model.jaxb.Object) InputRepresentation(org.restlet.representation.InputRepresentation) Representation(org.restlet.representation.Representation) Property(org.xwiki.rest.model.jaxb.Property)

Example 5 with InputRepresentation

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();
    }
}
Also used : InputRepresentation(org.restlet.representation.InputRepresentation) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) WrappedFile(org.apache.camel.WrappedFile) StringRepresentation(org.restlet.representation.StringRepresentation) InputStream(java.io.InputStream) FileRepresentation(org.restlet.representation.FileRepresentation) ByteArrayRepresentation(org.restlet.representation.ByteArrayRepresentation) WrappedFile(org.apache.camel.WrappedFile) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File)

Aggregations

InputRepresentation (org.restlet.representation.InputRepresentation)12 Form (org.restlet.data.Form)7 Representation (org.restlet.representation.Representation)7 HttpServletRequest (javax.servlet.http.HttpServletRequest)6 ObjectFactory (org.xwiki.rest.model.jaxb.ObjectFactory)5 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 XWikiException (com.xpn.xwiki.XWikiException)2 File (java.io.File)2 PrintWriter (java.io.PrintWriter)2 URISyntaxException (java.net.URISyntaxException)2 Map (java.util.Map)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)2 WrappedFile (org.apache.camel.WrappedFile)2 GenericFile (org.apache.camel.component.file.GenericFile)2 Disposition (org.restlet.data.Disposition)2 MediaType (org.restlet.data.MediaType)2 ByteArrayRepresentation (org.restlet.representation.ByteArrayRepresentation)2 StringRepresentation (org.restlet.representation.StringRepresentation)2