Search in sources :

Example 1 with Attachment

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

the class ModelFactory method toRestAttachment.

public Attachment toRestAttachment(URI baseUri, com.xpn.xwiki.api.Attachment xwikiAttachment, String xwikiRelativeUrl, String xwikiAbsoluteUrl, Boolean withPrettyNames, boolean versionURL) {
    Attachment attachment = this.objectFactory.createAttachment();
    Document doc = xwikiAttachment.getDocument();
    attachment.setId(String.format("%s@%s", doc.getPrefixedFullName(), xwikiAttachment.getFilename()));
    attachment.setName(xwikiAttachment.getFilename());
    attachment.setSize(xwikiAttachment.getFilesize());
    attachment.setVersion(xwikiAttachment.getVersion());
    attachment.setPageId(doc.getPrefixedFullName());
    attachment.setPageVersion(doc.getVersion());
    attachment.setMimeType(xwikiAttachment.getMimeType());
    attachment.setAuthor(xwikiAttachment.getAuthor());
    if (withPrettyNames) {
        XWikiContext xcontext = xcontextProvider.get();
        attachment.setAuthorName(xcontext.getWiki().getUserName(xwikiAttachment.getAuthor(), null, false, xcontext));
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(xwikiAttachment.getDate());
    attachment.setDate(calendar);
    attachment.setXwikiRelativeUrl(xwikiRelativeUrl);
    attachment.setXwikiAbsoluteUrl(xwikiAbsoluteUrl);
    String pageUri = Utils.createURI(baseUri, PageResource.class, doc.getWiki(), Utils.getSpacesFromSpaceId(doc.getSpace()), doc.getName()).toString();
    Link pageLink = objectFactory.createLink();
    pageLink.setHref(pageUri);
    pageLink.setRel(Relations.PAGE);
    attachment.getLinks().add(pageLink);
    String attachmentUri;
    if (versionURL) {
        attachmentUri = Utils.createURI(baseUri, AttachmentVersionResource.class, doc.getWiki(), Utils.getSpacesFromSpaceId(doc.getSpace()), doc.getName(), xwikiAttachment.getFilename(), xwikiAttachment.getVersion()).toString();
    } else {
        attachmentUri = Utils.createURI(baseUri, AttachmentResource.class, doc.getWiki(), Utils.getSpacesFromSpaceId(doc.getSpace()), doc.getName(), xwikiAttachment.getFilename()).toString();
    }
    Link attachmentLink = objectFactory.createLink();
    attachmentLink.setHref(attachmentUri);
    attachmentLink.setRel(Relations.ATTACHMENT_DATA);
    attachment.getLinks().add(attachmentLink);
    return attachment;
}
Also used : PageResource(org.xwiki.rest.resources.pages.PageResource) Calendar(java.util.Calendar) XWikiContext(com.xpn.xwiki.XWikiContext) Attachment(org.xwiki.rest.model.jaxb.Attachment) Document(com.xpn.xwiki.api.Document) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) Link(org.xwiki.rest.model.jaxb.Link)

Example 2 with Attachment

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

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

the class BaseAttachmentsResource method storeAttachment.

protected AttachmentInfo storeAttachment(Document doc, String attachmentName, byte[] content) throws XWikiException {
    XWikiContext xcontext = Utils.getXWikiContext(componentManager);
    XWikiDocument xwikiDocument = Utils.getXWiki(componentManager).getDocument(doc.getDocumentReference(), xcontext);
    boolean alreadyExisting = xwikiDocument.getAttachment(attachmentName) != null;
    XWikiAttachment xwikiAttachment;
    try {
        xwikiAttachment = xwikiDocument.setAttachment(attachmentName, new ByteArrayInputStream(content != null ? content : new byte[0]), xcontext);
    } catch (IOException e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_MISC, String.format("Failed to store the content of attachment [%s] in document [%s].", attachmentName, doc.getPrefixedFullName()), e);
    }
    Utils.getXWiki(componentManager).saveDocument(xwikiDocument, xcontext);
    URL url = Utils.getXWikiContext(componentManager).getURLFactory().createAttachmentURL(attachmentName, doc.getSpace(), doc.getName(), "download", null, doc.getWiki(), xcontext);
    String attachmentXWikiAbsoluteUrl = url.toString();
    String attachmentXWikiRelativeUrl = xcontext.getURLFactory().getURL(url, xcontext);
    Attachment attachment = DomainObjectFactory.createAttachment(objectFactory, uriInfo.getBaseUri(), new com.xpn.xwiki.api.Attachment(doc, xwikiAttachment, xcontext), attachmentXWikiRelativeUrl, attachmentXWikiAbsoluteUrl, Utils.getXWikiApi(componentManager), false);
    return new AttachmentInfo(attachment, alreadyExisting);
}
Also used : XWikiContext(com.xpn.xwiki.XWikiContext) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) Attachment(org.xwiki.rest.model.jaxb.Attachment) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) IOException(java.io.IOException) URL(java.net.URL) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) ByteArrayInputStream(java.io.ByteArrayInputStream) XWikiException(com.xpn.xwiki.XWikiException)

Example 4 with Attachment

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

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

Attachment (org.xwiki.rest.model.jaxb.Attachment)8 Attachments (org.xwiki.rest.model.jaxb.Attachments)5 GetMethod (org.apache.commons.httpclient.methods.GetMethod)4 Test (org.junit.Test)4 AbstractHttpTest (org.xwiki.test.rest.framework.AbstractHttpTest)4 XWikiContext (com.xpn.xwiki.XWikiContext)2 XWikiAttachment (com.xpn.xwiki.doc.XWikiAttachment)2 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)2 StringReader (java.io.StringReader)2 URL (java.net.URL)2 Calendar (java.util.Calendar)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 Link (org.xwiki.rest.model.jaxb.Link)2 XWikiException (com.xpn.xwiki.XWikiException)1 Document (com.xpn.xwiki.api.Document)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 IOException (java.io.IOException)1