Search in sources :

Example 1 with Attachments

use of org.xwiki.rest.model.jaxb.Attachments 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 2 with Attachments

use of org.xwiki.rest.model.jaxb.Attachments in project xwiki-platform by xwiki.

the class BaseAttachmentsResource method getAttachmentsForDocument.

protected Attachments getAttachmentsForDocument(Document doc, int start, int number, Boolean withPrettyNames) {
    Attachments attachments = objectFactory.createAttachments();
    List<com.xpn.xwiki.api.Attachment> xwikiAttachments = doc.getAttachmentList();
    RangeIterable<com.xpn.xwiki.api.Attachment> ri = new RangeIterable<com.xpn.xwiki.api.Attachment>(xwikiAttachments, start, number);
    for (com.xpn.xwiki.api.Attachment xwikiAttachment : ri) {
        URL url = Utils.getXWikiContext(componentManager).getURLFactory().createAttachmentURL(xwikiAttachment.getFilename(), doc.getSpace(), doc.getName(), "download", null, doc.getWiki(), Utils.getXWikiContext(componentManager));
        String attachmentXWikiAbsoluteUrl = url.toString();
        String attachmentXWikiRelativeUrl = Utils.getXWikiContext(componentManager).getURLFactory().getURL(url, Utils.getXWikiContext(componentManager));
        attachments.getAttachments().add(DomainObjectFactory.createAttachment(objectFactory, uriInfo.getBaseUri(), xwikiAttachment, attachmentXWikiRelativeUrl, attachmentXWikiAbsoluteUrl, Utils.getXWikiApi(componentManager), withPrettyNames));
    }
    return attachments;
}
Also used : RangeIterable(org.xwiki.rest.internal.RangeIterable) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) Attachment(org.xwiki.rest.model.jaxb.Attachment) Attachments(org.xwiki.rest.model.jaxb.Attachments) URL(java.net.URL)

Example 3 with Attachments

use of org.xwiki.rest.model.jaxb.Attachments in project xwiki-platform by xwiki.

the class AttachmentsResourceTest method testPUTGETAttachments.

@Test
public void testPUTGETAttachments() throws Exception {
    /* Test normal random UUID method */
    String randomStr = String.format("%s.txt", UUID.randomUUID());
    /* Test filenames requiring url encoding */
    putAttachmentFilename(randomStr, "random");
    putAttachmentFilename("my attach.txt", "space");
    putAttachmentFilename("^caret.txt", "caret");
    putAttachmentFilename("#pound.txt", "pound");
    putAttachmentFilename("%percent.txt", "percent");
    putAttachmentFilename("{brace}.txt", "braces");
    putAttachmentFilename("[bracket].txt", "brackets");
    /**
     * Causes XWIKI-7874 *
     */
    putAttachmentFilename("plus+plus.txt", "plus");
    // Now get all the attachments.
    String attachmentsUri = buildURIForThisPage(AttachmentsResource.class);
    GetMethod getMethod = executeGet(attachmentsUri);
    Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode());
    Attachments attachments = (Attachments) this.unmarshaller.unmarshal(getMethod.getResponseBodyAsStream());
    Assert.assertEquals(8, attachments.getAttachments().size());
}
Also used : GetMethod(org.apache.commons.httpclient.methods.GetMethod) Attachments(org.xwiki.rest.model.jaxb.Attachments) AbstractHttpTest(org.xwiki.test.rest.framework.AbstractHttpTest) Test(org.junit.Test)

Example 4 with Attachments

use of org.xwiki.rest.model.jaxb.Attachments in project xwiki-platform by xwiki.

the class AttachmentsResourceTest method testGETAttachmentVersions.

@Test
public void testGETAttachmentVersions() throws Exception {
    final int NUMBER_OF_VERSIONS = 4;
    String attachmentName = String.format("%s.txt", UUID.randomUUID().toString());
    Map<String, String> versionToContentMap = new HashMap<String, String>();
    /* Create NUMBER_OF_ATTACHMENTS attachments */
    for (int i = 0; i < NUMBER_OF_VERSIONS; i++) {
        String attachmentURI = buildURIForThisPage(AttachmentResource.class, attachmentName);
        String content = String.format("CONTENT %d", i);
        PutMethod putMethod = executePut(attachmentURI, content, MediaType.TEXT_PLAIN, TestUtils.SUPER_ADMIN_CREDENTIALS.getUserName(), TestUtils.SUPER_ADMIN_CREDENTIALS.getPassword());
        if (i == 0) {
            Assert.assertEquals(getHttpMethodInfo(putMethod), HttpStatus.SC_CREATED, putMethod.getStatusCode());
        } else {
            Assert.assertEquals(getHttpMethodInfo(putMethod), HttpStatus.SC_ACCEPTED, putMethod.getStatusCode());
        }
        Attachment attachment = (Attachment) this.unmarshaller.unmarshal(putMethod.getResponseBodyAsStream());
        versionToContentMap.put(attachment.getVersion(), content);
    }
    String attachmentsUri = buildURIForThisPage(AttachmentHistoryResource.class, attachmentName);
    GetMethod getMethod = executeGet(attachmentsUri);
    Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode());
    Attachments attachments = (Attachments) this.unmarshaller.unmarshal(getMethod.getResponseBodyAsStream());
    Assert.assertEquals(NUMBER_OF_VERSIONS, attachments.getAttachments().size());
    for (Attachment attachment : attachments.getAttachments()) {
        getMethod = executeGet(getFirstLinkByRelation(attachment, Relations.ATTACHMENT_DATA).getHref());
        Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode());
        Assert.assertEquals(versionToContentMap.get(attachment.getVersion()), getMethod.getResponseBodyAsString());
    }
}
Also used : HashMap(java.util.HashMap) GetMethod(org.apache.commons.httpclient.methods.GetMethod) PutMethod(org.apache.commons.httpclient.methods.PutMethod) Attachment(org.xwiki.rest.model.jaxb.Attachment) Attachments(org.xwiki.rest.model.jaxb.Attachments) AbstractHttpTest(org.xwiki.test.rest.framework.AbstractHttpTest) Test(org.junit.Test)

Example 5 with Attachments

use of org.xwiki.rest.model.jaxb.Attachments in project xwiki-platform by xwiki.

the class AttachmentsResourceTest method testGETAttachmentsAtPageVersion.

@Test
public void testGETAttachmentsAtPageVersion() throws Exception {
    final int NUMBER_OF_ATTACHMENTS = 4;
    String[] attachmentNames = new String[NUMBER_OF_ATTACHMENTS];
    String[] pageVersions = new String[NUMBER_OF_ATTACHMENTS];
    for (int i = 0; i < NUMBER_OF_ATTACHMENTS; i++) {
        attachmentNames[i] = String.format("%s.txt", UUID.randomUUID());
    }
    String content = "ATTACHMENT CONTENT";
    /* Create NUMBER_OF_ATTACHMENTS attachments */
    for (int i = 0; i < NUMBER_OF_ATTACHMENTS; i++) {
        String attachmentURI = buildURIForThisPage(AttachmentResource.class, attachmentNames[i]);
        PutMethod putMethod = executePut(attachmentURI, content, MediaType.TEXT_PLAIN, TestUtils.SUPER_ADMIN_CREDENTIALS.getUserName(), TestUtils.SUPER_ADMIN_CREDENTIALS.getPassword());
        Assert.assertEquals(getHttpMethodInfo(putMethod), HttpStatus.SC_CREATED, putMethod.getStatusCode());
        Attachment attachment = (Attachment) this.unmarshaller.unmarshal(putMethod.getResponseBodyAsStream());
        pageVersions[i] = attachment.getPageVersion();
    }
    // We do the following: at pageVersion[i] we check that all attachmentNames[0..i] are there.
    for (int i = 0; i < NUMBER_OF_ATTACHMENTS; i++) {
        String attachmentsUri = buildURIForThisPage(AttachmentsAtPageVersionResource.class, pageVersions[i]);
        GetMethod getMethod = executeGet(attachmentsUri);
        Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode());
        Attachments attachments = (Attachments) this.unmarshaller.unmarshal(getMethod.getResponseBodyAsStream());
        /*
             * Check that all attachmentNames[0..i] are present in the list of attachments of page at version
             * pageVersions[i]
             */
        for (int j = 0; j <= i; j++) {
            boolean found = false;
            for (Attachment attachment : attachments.getAttachments()) {
                if (attachment.getName().equals(attachmentNames[j])) {
                    if (attachment.getPageVersion().equals(pageVersions[i])) {
                        found = true;
                        break;
                    }
                }
            }
            Assert.assertTrue(String.format("%s is not present in attachments list of the page at version %s", attachmentNames[j], pageVersions[i]), found);
        }
        /* Check links */
        for (Attachment attachment : attachments.getAttachments()) {
            checkLinks(attachment);
        }
    }
}
Also used : GetMethod(org.apache.commons.httpclient.methods.GetMethod) PutMethod(org.apache.commons.httpclient.methods.PutMethod) Attachment(org.xwiki.rest.model.jaxb.Attachment) Attachments(org.xwiki.rest.model.jaxb.Attachments) AbstractHttpTest(org.xwiki.test.rest.framework.AbstractHttpTest) Test(org.junit.Test)

Aggregations

Attachments (org.xwiki.rest.model.jaxb.Attachments)8 Attachment (org.xwiki.rest.model.jaxb.Attachment)6 GetMethod (org.apache.commons.httpclient.methods.GetMethod)5 Test (org.junit.Test)5 AbstractHttpTest (org.xwiki.test.rest.framework.AbstractHttpTest)5 URL (java.net.URL)3 XWikiAttachment (com.xpn.xwiki.doc.XWikiAttachment)2 StringReader (java.io.StringReader)2 HashMap (java.util.HashMap)2 PutMethod (org.apache.commons.httpclient.methods.PutMethod)2 ReaderInputStream (org.restlet.engine.io.ReaderInputStream)2 AttachmentReference (org.xwiki.model.reference.AttachmentReference)2 XWikiRestException (org.xwiki.rest.XWikiRestException)2 RangeIterable (org.xwiki.rest.internal.RangeIterable)2 XWikiException (com.xpn.xwiki.XWikiException)1 Document (com.xpn.xwiki.api.Document)1 URI (java.net.URI)1 ArrayList (java.util.ArrayList)1 Calendar (java.util.Calendar)1 Formatter (java.util.Formatter)1