use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.
the class ExportURLFactoryTest method createAttachmentURLWithWhitespacesInSpaceAndPageNames.
@Test
public void createAttachmentURLWithWhitespacesInSpaceAndPageNames() throws Exception {
// Prepare the exported document and attachment.
XWikiDocument doc = new XWikiDocument(new DocumentReference("Wiki", Arrays.asList(" Space1 ", "Space2"), "Pa ge"));
// Simulate the doc depth (there are 4 levels since the doc will be placed in
// pages/Wiki/Space1/Space2/Pa%20Page).
this.exportContext.setDocParentLevels(4);
XWikiAttachment attachment = new XWikiAttachment(doc, "img .jpg");
attachment.setContent(new ByteArrayInputStream("test".getBytes()));
doc.getAttachmentList().add(attachment);
this.oldcoreRule.getSpyXWiki().saveDocument(doc, this.oldcoreRule.getXWikiContext());
URL url = this.urlFactory.createAttachmentURL("img .jpg", " Space1 .Space2", "Pa ge", "view", "", "Wiki", this.oldcoreRule.getXWikiContext());
// Verify generated URL
assertEquals(new URL("file://../../../../attachment/Wiki/+Space1+/Space2/Pa+ge/img+.jpg"), url);
// Verify that the file on the FS exists and that the name is ok
File generatedFile = new File(this.tmpDir, "attachment/Wiki/+Space1+/Space2/Pa+ge/img+.jpg");
assertTrue(generatedFile.exists());
assertEquals("img+.jpg", generatedFile.getName());
}
use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.
the class MockitoDownloadActionTest method renderWhenZipExplorerPluginURL.
@Test
public void renderWhenZipExplorerPluginURL() throws Exception {
DownloadAction action = new DownloadAction();
XWikiContext xcontext = this.oldcore.getXWikiContext();
// Set the Request URL
XWikiServletRequestStub request = new XWikiServletRequestStub();
request.setRequestURI("http://localhost:8080/xwiki/bin/download/space/page/file.ext/some/path");
xcontext.setRequest(request);
// Set the current doc and current wiki
XWikiDocument document = mock(XWikiDocument.class);
when(document.getAttachment("path")).thenReturn(null);
xcontext.setDoc(document);
xcontext.setWikiId("wiki");
xcontext.setAction("download");
// Set the Response
XWikiResponse response = mock(XWikiResponse.class);
StubServletOutputStream ssos = new StubServletOutputStream();
when(response.getOutputStream()).thenReturn(ssos);
xcontext.setResponse(response);
// Set the Resource Reference Manager used to parse the URL and extract the attachment name
ResourceReferenceManager rrm = this.oldcore.getMocker().registerMockComponent(ResourceReferenceManager.class);
when(rrm.getResourceReference()).thenReturn(new EntityResourceReference(new AttachmentReference("path", new DocumentReference("wiki", Arrays.asList("space", "page", "file.ext"), "some")), EntityResourceAction.VIEW));
// Setup the returned attachment
XWikiAttachment attachment = mock(XWikiAttachment.class);
when(attachment.getContentSize(xcontext)).thenReturn(100);
Date now = new Date();
when(attachment.getDate()).thenReturn(now);
when(attachment.getFilename()).thenReturn("file.ext");
when(attachment.getContentInputStream(xcontext)).thenReturn(new ByteArrayInputStream("test".getBytes()));
when(attachment.getMimeType(xcontext)).thenReturn("mimetype");
when(attachment.clone()).thenReturn(attachment);
// Configure an existing doc in the store
XWiki xwiki = this.oldcore.getSpyXWiki();
XWikiDocument backwardCompatDocument = new XWikiDocument(new DocumentReference("wiki", "space", "page"));
backwardCompatDocument.addAttachment(attachment);
xwiki.saveDocument(backwardCompatDocument, xcontext);
// Make sure the user has permission to access the doc
doReturn(true).when(xwiki).checkAccess(eq("download"), any(XWikiDocument.class), any(XWikiContext.class));
// Setup ExecutionContextManager & VelocityManager using in the context backup
ExecutionContextManager ecm = this.oldcore.getMocker().registerMockComponent(ExecutionContextManager.class);
ExecutionContext ec = this.oldcore.getExecutionContext();
when(ecm.clone(ec)).thenReturn(ec);
VelocityManager vm = this.oldcore.getMocker().registerMockComponent(VelocityManager.class);
// Set the Plugin Manager
XWikiPluginManager pluginManager = mock(XWikiPluginManager.class);
when(pluginManager.downloadAttachment(attachment, xcontext)).thenReturn(attachment);
doReturn(pluginManager).when(this.oldcore.getSpyXWiki()).getPluginManager();
assertNull(action.render(xcontext));
// This is the test, we verify what is set in the response
verify(response).setContentType("mimetype");
verify(response).setHeader("Accept-Ranges", "bytes");
verify(response).addHeader("Content-disposition", "attachment; filename*=utf-8''file.ext");
verify(response).setDateHeader("Last-Modified", now.getTime());
verify(response).setContentLength(100);
assertEquals("test", ssos.baos.toString());
}
use of com.xpn.xwiki.doc.XWikiAttachment 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;
}
use of com.xpn.xwiki.doc.XWikiAttachment 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;
}
use of com.xpn.xwiki.doc.XWikiAttachment 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);
}
Aggregations