Search in sources :

Example 1 with XWikiRestException

use of org.xwiki.rest.XWikiRestException in project xwiki-platform by xwiki.

the class ModelFactory method toRestMapEntry.

public MapEntry toRestMapEntry(String key, java.lang.Object value) throws XWikiRestException {
    MapEntry restMapEntry = this.objectFactory.createMapEntry();
    restMapEntry.setKey(key);
    try {
        restMapEntry.setValue(this.jaxbConverter.serializeAny(value));
    } catch (ParserConfigurationException e) {
        throw new XWikiRestException("Failed to serialize property [" + key + "] with value [" + value + "]", e);
    }
    return restMapEntry;
}
Also used : MapEntry(org.xwiki.rest.model.jaxb.MapEntry) XWikiRestException(org.xwiki.rest.XWikiRestException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 2 with XWikiRestException

use of org.xwiki.rest.XWikiRestException in project xwiki-platform by xwiki.

the class BaseAttachmentsResource method getAttachments.

/**
 * Retrieves the attachments by filtering them.
 *
 * @param wikiName The virtual wiki.
 * @param name Name filter (include only attachments that matches this name)
 * @param page Page filter (include only attachments are attached to a page matches this string)
 * @param space Space filter (include only attachments are attached to a page in a space matching this string)
 * @param author Author filter (include only attachments from an author who matches this string)
 * @param types A comma separated list of string that will be matched against the actual mime type of the
 *            attachments.
 * @return The list of the retrieved attachments.
 */
public Attachments getAttachments(String wikiName, String name, String page, String space, String author, String types, Integer start, Integer number, Boolean withPrettyNames) throws XWikiRestException {
    String database = Utils.getXWikiContext(componentManager).getWikiId();
    Attachments attachments = objectFactory.createAttachments();
    /* This try is just needed for executing the finally clause. */
    try {
        Utils.getXWikiContext(componentManager).setWikiId(wikiName);
        Map<String, String> filters = new HashMap<String, String>();
        if (!name.equals("")) {
            filters.put("name", name);
        }
        if (!page.equals("")) {
            filters.put("page", name);
        }
        if (!space.equals("")) {
            filters.put("space", Utils.getLocalSpaceId(parseSpaceSegments(space)));
        }
        if (!author.equals("")) {
            filters.put("author", author);
        }
        /* Build the query */
        Formatter f = new Formatter();
        f.format("select doc.space, doc.name, doc.version, attachment from XWikiDocument as doc," + " XWikiAttachment as attachment where (attachment.docId=doc.id ");
        if (filters.keySet().size() > 0) {
            for (String param : filters.keySet()) {
                if (param.equals("name")) {
                    f.format(" and upper(attachment.filename) like :name ");
                }
                if (param.equals("page")) {
                    f.format(" and upper(doc.fullName) like :page ");
                }
                if (param.equals("space")) {
                    f.format(" and upper(doc.space) like :space ");
                }
                if (param.equals("author")) {
                    f.format(" and upper(attachment.author) like :author ");
                }
            }
        }
        f.format(")");
        String queryString = f.toString();
        /* Execute the query by filling the parameters */
        List<Object> queryResult = null;
        try {
            Query query = queryManager.createQuery(queryString, Query.XWQL).setLimit(number).setOffset(start);
            for (String param : filters.keySet()) {
                query.bindValue(param, String.format("%%%s%%", filters.get(param).toUpperCase()));
            }
            queryResult = query.execute();
        } catch (QueryException e) {
            throw new XWikiRestException(e);
        }
        Set<String> acceptedMimeTypes = new HashSet<String>();
        if (!types.equals("")) {
            String[] acceptedMimetypesArray = types.split(",");
            for (String type : acceptedMimetypesArray) {
                acceptedMimeTypes.add(type);
            }
        }
        for (Object object : queryResult) {
            Object[] fields = (Object[]) object;
            String pageSpaceId = (String) fields[0];
            List<String> pageSpaces = Utils.getSpacesFromSpaceId(pageSpaceId);
            String pageName = (String) fields[1];
            String pageId = Utils.getPageId(wikiName, pageSpaces, pageName);
            String pageVersion = (String) fields[2];
            XWikiAttachment xwikiAttachment = (XWikiAttachment) fields[3];
            String mimeType = xwikiAttachment.getMimeType(Utils.getXWikiContext(componentManager));
            boolean add = true;
            /* Check the mime type filter */
            if (acceptedMimeTypes.size() > 0) {
                add = false;
                for (String type : acceptedMimeTypes) {
                    if (mimeType.toUpperCase().contains(type.toUpperCase())) {
                        add = true;
                        break;
                    }
                }
            }
            if (add) {
                /*
                     * We manufacture attachments in place because we don't have all the data for calling the
                     * DomainObjectFactory method (doing so would require to retrieve an actual Document)
                     */
                Attachment attachment = objectFactory.createAttachment();
                attachment.setId(String.format("%s@%s", pageId, xwikiAttachment.getFilename()));
                attachment.setName(xwikiAttachment.getFilename());
                attachment.setLongSize(xwikiAttachment.getLongSize());
                // Retro compatibility
                attachment.setSize((int) xwikiAttachment.getLongSize());
                attachment.setMimeType(mimeType);
                attachment.setAuthor(xwikiAttachment.getAuthor());
                if (withPrettyNames) {
                    attachment.setAuthorName(Utils.getAuthorName(xwikiAttachment.getAuthorReference(), componentManager));
                }
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(xwikiAttachment.getDate());
                attachment.setDate(calendar);
                attachment.setPageId(pageId);
                attachment.setPageVersion(pageVersion);
                attachment.setVersion(xwikiAttachment.getVersion());
                URL absoluteUrl = Utils.getXWikiContext(componentManager).getURLFactory().createAttachmentURL(xwikiAttachment.getFilename(), pageSpaceId, pageName, "download", null, wikiName, Utils.getXWikiContext(componentManager));
                attachment.setXwikiAbsoluteUrl(absoluteUrl.toString());
                attachment.setXwikiRelativeUrl(Utils.getXWikiContext(componentManager).getURLFactory().getURL(absoluteUrl, Utils.getXWikiContext(componentManager)));
                URI pageUri = Utils.createURI(uriInfo.getBaseUri(), PageResource.class, wikiName, pageSpaces, pageName);
                Link pageLink = objectFactory.createLink();
                pageLink.setHref(pageUri.toString());
                pageLink.setRel(Relations.PAGE);
                attachment.getLinks().add(pageLink);
                URI attachmentUri = Utils.createURI(uriInfo.getBaseUri(), AttachmentResource.class, wikiName, pageSpaces, pageName, xwikiAttachment.getFilename());
                Link attachmentLink = objectFactory.createLink();
                attachmentLink.setHref(attachmentUri.toString());
                attachmentLink.setRel(Relations.ATTACHMENT_DATA);
                attachment.getLinks().add(attachmentLink);
                attachments.getAttachments().add(attachment);
            }
        }
    } finally {
        Utils.getXWikiContext(componentManager).setWikiId(database);
    }
    return attachments;
}
Also used : Query(org.xwiki.query.Query) HashMap(java.util.HashMap) Formatter(java.util.Formatter) XWikiRestException(org.xwiki.rest.XWikiRestException) Calendar(java.util.Calendar) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) Attachment(org.xwiki.rest.model.jaxb.Attachment) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) Attachments(org.xwiki.rest.model.jaxb.Attachments) URI(java.net.URI) URL(java.net.URL) QueryException(org.xwiki.query.QueryException) Link(org.xwiki.rest.model.jaxb.Link) HashSet(java.util.HashSet)

Example 3 with XWikiRestException

use of org.xwiki.rest.XWikiRestException in project xwiki-platform by xwiki.

the class AttachmentResourceImpl method getAttachment.

@Override
public Response getAttachment(String wikiName, String spaceName, String pageName, String attachmentName) throws XWikiRestException {
    try {
        DocumentInfo documentInfo = getDocumentInfo(wikiName, spaceName, pageName, null, null, true, false);
        Document doc = documentInfo.getDocument();
        final com.xpn.xwiki.api.Attachment xwikiAttachment = doc.getAttachment(attachmentName);
        if (xwikiAttachment == null) {
            throw new WebApplicationException(Status.NOT_FOUND);
        }
        return Response.ok().type(xwikiAttachment.getMimeType()).entity(xwikiAttachment.getContent()).build();
    } catch (XWikiException e) {
        throw new XWikiRestException(e);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) XWikiRestException(org.xwiki.rest.XWikiRestException) Document(com.xpn.xwiki.api.Document) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) XWikiException(com.xpn.xwiki.XWikiException)

Example 4 with XWikiRestException

use of org.xwiki.rest.XWikiRestException in project xwiki-platform by xwiki.

the class AttachmentsAtPageVersionResourceImpl method getAttachmentsAtPageVersion.

@Override
public Attachments getAttachmentsAtPageVersion(String wikiName, String spaceName, String pageName, String version, Integer start, Integer number, Boolean withPrettyNames) throws XWikiRestException {
    try {
        DocumentInfo documentInfo = getDocumentInfo(wikiName, spaceName, pageName, null, version, true, false);
        Document doc = documentInfo.getDocument();
        return getAttachmentsForDocument(doc, start, number, withPrettyNames);
    } catch (XWikiException e) {
        throw new XWikiRestException(e);
    }
}
Also used : XWikiRestException(org.xwiki.rest.XWikiRestException) Document(com.xpn.xwiki.api.Document) XWikiException(com.xpn.xwiki.XWikiException)

Example 5 with XWikiRestException

use of org.xwiki.rest.XWikiRestException in project xwiki-platform by xwiki.

the class AttachmentsResourceImpl method addAttachment.

@Override
public Response addAttachment(String wikiName, String spaceName, String pageName, Multipart multipart) throws XWikiRestException {
    try {
        List<String> spaces = parseSpaceSegments(spaceName);
        DocumentInfo documentInfo = getDocumentInfo(wikiName, spaces, pageName, null, null, true, true);
        Document doc = documentInfo.getDocument();
        if (!doc.hasAccessLevel("edit", Utils.getXWikiUser(componentManager))) {
            throw new WebApplicationException(Status.UNAUTHORIZED);
        }
        /* The name to be used */
        String attachmentName = null;
        /* The actual filename of the sent file */
        String actualFileName = null;
        /* The specified file name using a form field */
        String overriddenFileName = null;
        String contentType = null;
        InputStream inputStream = null;
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            /* Get the content disposition headers */
            Enumeration e = bodyPart.getMatchingHeaders(new String[] { "Content-disposition" });
            while (e.hasMoreElements()) {
                Header h = (Header) e.nextElement();
                /* Parse header data. Normally headers are in the form form-data; key="value"; ... */
                if (h.getValue().startsWith("form-data")) {
                    String[] fieldData = h.getValue().split(";");
                    for (String s : fieldData) {
                        String[] pair = s.split("=");
                        if (pair.length == 2) {
                            String key = pair[0].trim();
                            String value = pair[1].replace("\"", "").trim();
                            if ("name".equals(key)) {
                                if (FORM_FILENAME_FIELD.equals(value)) {
                                    overriddenFileName = bodyPart.getContent().toString();
                                }
                            } else if ("filename".equals(key)) {
                                actualFileName = value;
                                contentType = bodyPart.getContentType();
                                inputStream = bodyPart.getInputStream();
                            }
                        }
                    }
                }
            }
        }
        if (overriddenFileName != null) {
            attachmentName = overriddenFileName;
        } else {
            attachmentName = actualFileName;
        }
        if (attachmentName == null) {
            throw new WebApplicationException(Status.BAD_REQUEST);
        }
        byte[] buffer = new byte[4096];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while (true) {
            int read = inputStream.read(buffer);
            if (read != 4096) {
                if (read != -1) {
                    baos.write(buffer, 0, read);
                }
                break;
            } else {
                baos.write(buffer);
            }
        }
        baos.flush();
        /* Attach the file */
        AttachmentInfo attachmentInfo = storeAttachment(doc, attachmentName, baos.toByteArray());
        if (attachmentInfo.isAlreadyExisting()) {
            return Response.status(Status.ACCEPTED).entity(attachmentInfo.getAttachment()).build();
        } else {
            return Response.created(Utils.createURI(uriInfo.getBaseUri(), AttachmentResource.class, wikiName, spaces, pageName, attachmentName)).entity(attachmentInfo.getAttachment()).build();
        }
    } catch (Exception e) {
        throw new XWikiRestException(e);
    }
}
Also used : BodyPart(javax.mail.BodyPart) AttachmentResource(org.xwiki.rest.resources.attachments.AttachmentResource) Enumeration(java.util.Enumeration) WebApplicationException(javax.ws.rs.WebApplicationException) InputStream(java.io.InputStream) XWikiRestException(org.xwiki.rest.XWikiRestException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(com.xpn.xwiki.api.Document) XWikiException(com.xpn.xwiki.XWikiException) XWikiRestException(org.xwiki.rest.XWikiRestException) WebApplicationException(javax.ws.rs.WebApplicationException) Header(javax.mail.Header)

Aggregations

XWikiRestException (org.xwiki.rest.XWikiRestException)71 XWikiException (com.xpn.xwiki.XWikiException)46 Document (com.xpn.xwiki.api.Document)40 WebApplicationException (javax.ws.rs.WebApplicationException)26 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)15 Link (org.xwiki.rest.model.jaxb.Link)12 QueryException (org.xwiki.query.QueryException)8 BaseObject (com.xpn.xwiki.objects.BaseObject)7 RangeIterable (org.xwiki.rest.internal.RangeIterable)7 XWikiContext (com.xpn.xwiki.XWikiContext)6 Object (org.xwiki.rest.model.jaxb.Object)5 Property (org.xwiki.rest.model.jaxb.Property)5 Date (java.util.Date)4 Test (org.junit.Test)4 ClassPropertyReference (org.xwiki.model.reference.ClassPropertyReference)4 Objects (org.xwiki.rest.model.jaxb.Objects)4 XWikiRCSNodeId (com.xpn.xwiki.doc.rcs.XWikiRCSNodeId)3 BaseClass (com.xpn.xwiki.objects.classes.BaseClass)3 URI (java.net.URI)3 URL (java.net.URL)3