From 80c1f47ae680e58001a2e67b7d74fcafde697808 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Wed, 2 Feb 2022 09:26:20 +0100 Subject: [PATCH 01/29] refactor AttachmentURLCommand to RessourceUrlService --- .../ressource_url/RessourceUrlService.java | 185 ++++++++++++ .../RessourceUrlServiceRole.java | 42 +++ .../UrlRessourceNotExistException.java | 29 ++ .../web/plugin/cmd/AttachmentURLCommand.java | 169 +++++++++-- src/main/resources/META-INF/components.txt | 1 + .../RessourceUrlServiceTest.java | 282 ++++++++++++++++++ .../plugin/cmd/AttachmentURLCommandTest.java | 150 +++++++--- 7 files changed, 796 insertions(+), 62 deletions(-) create mode 100644 src/main/java/com/celements/ressource_url/RessourceUrlService.java create mode 100644 src/main/java/com/celements/ressource_url/RessourceUrlServiceRole.java create mode 100644 src/main/java/com/celements/ressource_url/UrlRessourceNotExistException.java create mode 100644 src/test/java/com/celements/ressource_url/RessourceUrlServiceTest.java diff --git a/src/main/java/com/celements/ressource_url/RessourceUrlService.java b/src/main/java/com/celements/ressource_url/RessourceUrlService.java new file mode 100644 index 000000000..37eb29ed7 --- /dev/null +++ b/src/main/java/com/celements/ressource_url/RessourceUrlService.java @@ -0,0 +1,185 @@ +package com.celements.ressource_url; + +import java.net.MalformedURLException; +import java.util.Optional; +import java.util.function.Supplier; +import java.util.regex.Pattern; + +import javax.annotation.Nullable; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.xwiki.component.annotation.Requirement; +import org.xwiki.model.reference.DocumentReference; + +import com.celements.filebase.IAttachmentServiceRole; +import com.celements.model.access.IModelAccessFacade; +import com.celements.model.access.exception.AttachmentNotExistsException; +import com.celements.model.access.exception.DocumentNotExistsException; +import com.celements.model.context.ModelContext; +import com.celements.model.util.ModelUtils; +import com.celements.web.service.LastStartupTimeStampRole; +import com.google.common.base.Suppliers; +import com.xpn.xwiki.doc.XWikiAttachment; +import com.xpn.xwiki.doc.XWikiDocument; +import com.xpn.xwiki.web.XWikiURLFactory; + +public class RessourceUrlService implements RessourceUrlServiceRole { + + private static final String ATTACHMENT_LINK_REGEX = "([\\w\\-]*:)?([\\w\\-]*\\.[\\w\\-]*){1};.*"; + private static final Supplier ATTACHMENT_LINK_PATTERN = Suppliers + .memoize(() -> Pattern.compile(ATTACHMENT_LINK_REGEX)); + private static final String ON_DISK_LINK_REGEX = "^:[/\\w\\-\\.]*"; + private static final Supplier ON_DISK_LINK_PATTERN = Suppliers + .memoize(() -> Pattern.compile(ON_DISK_LINK_REGEX)); + + private static final Logger LOGGER = LoggerFactory.getLogger(RessourceUrlService.class); + + @Requirement + private ModelContext context; + + @Requirement + private IModelAccessFacade modelAccess; + + @Requirement + private ModelUtils modelUtils; + + @Requirement + private IAttachmentServiceRole attachmentSrv; + + @Requirement + private LastStartupTimeStampRole lastStartupTimeStamp; + + @Override + @NotNull + public String getAttachmentName(@NotNull String link) { + return link.split(";")[1]; + } + + @Override + @NotNull + public DocumentReference getPageDocRef(@NotNull String link) { + return modelUtils.resolveRef(link.split(";")[0], DocumentReference.class); + } + + @Override + public boolean isAttachmentLink(String link) { + if (link != null) { + return ATTACHMENT_LINK_PATTERN.get().matcher(link.trim()).matches(); + } + return false; + } + + @Override + public boolean isOnDiskLink(@Nullable String link) { + if (link != null) { + return ON_DISK_LINK_PATTERN.get().matcher(link.trim()).matches(); + } + return false; + } + + private String getAction(Optional action) { + if (action.isPresent()) { + return action.get(); + } + return getDefaultAction(); + } + + private String getDefaultAction() { + return context.getXWikiContext().getWiki().getXWikiPreference("celdefaultAttAction", + "celements.attachmenturl.defaultaction", "file", context.getXWikiContext()); + } + + @Override + @NotEmpty + public String getRessourceURLPrefix() { + return getRessourceURLPrefix(getDefaultAction()); + } + + @Override + @NotEmpty + public String getRessourceURLPrefix(@NotEmpty String action) { + XWikiURLFactory urlf = context.getXWikiContext().getURLFactory(); + return urlf.createResourceURL("", true, context.getXWikiContext()).toString().replace("/skin/", + "/" + action + "/"); + } + + @Override + @NotNull + public String getExternalRessourceURL(@NotNull String fileName, + @NotNull Optional action) { + try { + return context.getXWikiContext().getURLFactory().getServerURL(context.getXWikiContext()) + .toExternalForm() + createRessourceUrl(fileName, action); + } catch (MalformedURLException | UrlRessourceNotExistException exp) { + LOGGER.error("Failed to getServerURL.", exp); + } + return ""; + } + + @Override + @NotNull + public String createRessourceUrl(@NotNull String link, @NotNull Optional action, + @NotNull Optional queryString) throws UrlRessourceNotExistException { + final String baseUrl = createRessourceUrl(link, action); + if (queryString.isPresent()) { + if (baseUrl.indexOf("?") > -1) { + return baseUrl + "&" + queryString.get(); + } else { + return baseUrl + "?" + queryString.get(); + } + } + return baseUrl; + } + + @Override + public @NotEmpty String createRessourceUrl(@NotNull String link, @NotNull Optional action) + throws UrlRessourceNotExistException { + String url = link; + if (isAttachmentLink(link)) { + url = createAttachmentUrl(link, action); + } else if (isOnDiskLink(link)) { + url = createOnDiskUrl(link, action); + } + return addContextUrl(url); + } + + private String addContextUrl(String url) { + Optional currentDoc = context.getCurrentDoc().toJavaUtil(); + if (currentDoc.isPresent() && url.startsWith("?")) { + url = currentDoc.get().getURL("view", context.getXWikiContext()) + url; + } + return url; + } + + private String createAttachmentUrl(String link, Optional action) + throws UrlRessourceNotExistException { + String attName = getAttachmentName(link); + try { + XWikiDocument doc = modelAccess.getDocument(getPageDocRef(link)); + XWikiAttachment att = attachmentSrv.getAttachmentNameEqual(doc, attName); + return doc.getAttachmentURL(attName, getAction(action), context.getXWikiContext()) + + "?version=" + lastStartupTimeStamp.getLastChangedTimeStamp(att.getDate()); + } catch (DocumentNotExistsException exp) { + LOGGER.error("Error getting attachment URL for doc '{}' and file {}", getPageDocRef(link), + attName, exp); + throw new UrlRessourceNotExistException(link); + } catch (AttachmentNotExistsException anee) { + LOGGER.info("Attachment not found for link [{}] and action [{}]", link, action, anee); + throw new UrlRessourceNotExistException(link); + } + } + + private String createOnDiskUrl(String link, Optional action) { + String url; + String path = link.trim().substring(1); + url = context.getXWikiContext().getWiki().getSkinFile(path, true, context.getXWikiContext()) + .replace("/skin/", + "/" + getAction(action) + "/"); + url += "?version=" + lastStartupTimeStamp.getFileModificationDate(path); + return url; + } + +} diff --git a/src/main/java/com/celements/ressource_url/RessourceUrlServiceRole.java b/src/main/java/com/celements/ressource_url/RessourceUrlServiceRole.java new file mode 100644 index 000000000..a3c1b50ce --- /dev/null +++ b/src/main/java/com/celements/ressource_url/RessourceUrlServiceRole.java @@ -0,0 +1,42 @@ +package com.celements.ressource_url; + +import java.util.Optional; + +import javax.annotation.Nullable; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + +import org.xwiki.component.annotation.ComponentRole; +import org.xwiki.model.reference.DocumentReference; + +@ComponentRole +public interface RessourceUrlServiceRole { + + @NotNull + public String getAttachmentName(@NotNull String link); + + @NotNull + DocumentReference getPageDocRef(@NotNull String link); + + boolean isAttachmentLink(String link); + + boolean isOnDiskLink(@Nullable String link); + + @NotNull + String createRessourceUrl(@NotNull String jsFile, @NotNull Optional action, + @NotNull Optional queryString) throws UrlRessourceNotExistException; + + @NotEmpty + String createRessourceUrl(@NotNull String link, @NotNull Optional action) + throws UrlRessourceNotExistException; + + @NotEmpty + String getRessourceURLPrefix(@NotEmpty String action); + + @NotEmpty + String getRessourceURLPrefix(); + + @NotNull + String getExternalRessourceURL(@NotNull String fileName, @NotNull Optional action); + +} diff --git a/src/main/java/com/celements/ressource_url/UrlRessourceNotExistException.java b/src/main/java/com/celements/ressource_url/UrlRessourceNotExistException.java new file mode 100644 index 000000000..ef051540c --- /dev/null +++ b/src/main/java/com/celements/ressource_url/UrlRessourceNotExistException.java @@ -0,0 +1,29 @@ +package com.celements.ressource_url; + +import javax.validation.constraints.NotNull; + +public class UrlRessourceNotExistException extends Exception { + + private static final long serialVersionUID = 1L; + private final String ressource; + + public UrlRessourceNotExistException(@NotNull String ressource) { + super("Url ressource [" + ressource + "] does not exist."); + this.ressource = ressource; + } + + public UrlRessourceNotExistException(@NotNull String message, @NotNull String ressource) { + super(message); + this.ressource = ressource; + } + + public UrlRessourceNotExistException(@NotNull String message, @NotNull String ressource, + Exception wrapExp) { + super(message, wrapExp); + this.ressource = ressource; + } + + public String getRessource() { + return ressource; + } +} diff --git a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java index ebc3e9b31..0377a0ddd 100644 --- a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java +++ b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java @@ -20,85 +20,187 @@ package com.celements.web.plugin.cmd; import java.net.MalformedURLException; +import java.util.Optional; + +import javax.annotation.Nullable; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.xwiki.context.Execution; +import org.xwiki.model.reference.DocumentReference; import com.celements.filebase.IAttachmentServiceRole; +import com.celements.model.access.IModelAccessFacade; import com.celements.model.access.exception.AttachmentNotExistsException; +import com.celements.model.access.exception.DocumentNotExistsException; +import com.celements.model.context.ModelContext; +import com.celements.model.util.ModelUtils; +import com.celements.ressource_url.RessourceUrlServiceRole; +import com.celements.ressource_url.UrlRessourceNotExistException; import com.celements.web.service.LastStartupTimeStampRole; import com.xpn.xwiki.XWikiContext; -import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.web.Utils; import com.xpn.xwiki.web.XWikiURLFactory; +/** + * @deprecated since 5.4 instead use {@link RessourceUrlServiceRole} + */ +@Deprecated public class AttachmentURLCommand { private static final Logger LOGGER = LoggerFactory.getLogger(AttachmentURLCommand.class); + /** + * @deprecated since 5.4 instead use + * {@link RessourceUrlServiceRole#createRessourceUrl(String, Optional)} + */ + @Deprecated public String getAttachmentURL(String link, XWikiContext context) { return getAttachmentURL(link, getDefaultAction(), context); } - protected String getDefaultAction() { + private String getDefaultAction() { return getContext().getWiki().getXWikiPreference("celdefaultAttAction", "celements.attachmenturl.defaultaction", "file", getContext()); } + /** + * @deprecated since 5.4 instead use {@link RessourceUrlServiceRole#getRessourceURLPrefix()} + */ + @Deprecated public String getAttachmentURLPrefix() { return getAttachmentURLPrefix(getDefaultAction()); } + /** + * @deprecated since 5.4 instead use {@link RessourceUrlServiceRole#getRessourceURLPrefix(String)} + */ + @Deprecated public String getAttachmentURLPrefix(String action) { XWikiURLFactory urlf = getContext().getURLFactory(); return urlf.createResourceURL("", true, getContext()).toString().replace("/skin/", "/" + action + "/"); } + /** + * @deprecated since 5.4 instead use + * {@link RessourceUrlServiceRole#createRessourceUrl(String, Optional)} + */ + @Deprecated + @Nullable public String getAttachmentURL(String link, String action, XWikiContext context) { + try { + return getAttachmentURL(link, Optional.ofNullable(action)); + } catch (UrlRessourceNotExistException exp) { + return null; + } + } + + /** + * @deprecated since 5.4 instead use + * {@link RessourceUrlServiceRole#createRessourceUrl(String, Optional)} + */ + @Deprecated + @NotEmpty + public String getAttachmentURL(@NotNull String link, @NotNull Optional action) + throws UrlRessourceNotExistException { String url = link; if (isAttachmentLink(link)) { String attName = getAttachmentName(link); try { - XWikiDocument doc = context.getWiki().getDocument(getPageFullName(link), context); + XWikiDocument doc = getModelAccess().getDocument(getPageDocRef(link)); XWikiAttachment att = getAttachmentService().getAttachmentNameEqual(doc, attName); - url = doc.getAttachmentURL(attName, action, context); + url = doc.getAttachmentURL(attName, getAction(action), getContext()); url += "?version=" + getLastStartupTimeStamp().getLastChangedTimeStamp(att.getDate()); - } catch (XWikiException exp) { - LOGGER.error("Error getting attachment URL for doc " + getPageFullName(link) + " and file " - + attName, exp); - url = link; + } catch (DocumentNotExistsException exp) { + LOGGER.error("Error getting attachment URL for doc '{}' and file {}", getPageFullName(link), + attName, exp); + // 01.02.2022;F.Pichler; is this functionality used? No test available. Adding exception. + // url = link; + throw new UrlRessourceNotExistException(link); } catch (AttachmentNotExistsException anee) { LOGGER.info("Attachment not found for link [{}] and action [{}]", link, action, anee); - return null; + throw new UrlRessourceNotExistException(link); } } else if (isOnDiskLink(link)) { String path = link.trim().substring(1); - url = context.getWiki().getSkinFile(path, true, context).replace("/skin/", "/" + action - + "/"); + url = getContext().getWiki().getSkinFile(path, true, getContext()).replace("/skin/", + "/" + getAction(action) + "/"); url += "?version=" + getLastStartupTimeStamp().getFileModificationDate(path); } - if (url.startsWith("?")) { - url = context.getDoc().getURL("view", context) + url; + Optional currentDoc = getModelContext().getCurrentDoc().toJavaUtil(); + if (currentDoc.isPresent() && url.startsWith("?")) { + url = currentDoc.get().getURL("view", getContext()) + url; } return url; } + private String getAction(Optional action) { + if (action.isPresent()) { + return action.get(); + } + return getDefaultAction(); + } + + /** + * @deprecated since 5.4 instead use + * {@link RessourceUrlServiceRole#createRessourceUrl(String, Optional, + * Optional)} + */ + @Deprecated + @Nullable + public String getAttachmentURL(@NotNull String link, @NotNull Optional action, + @NotNull Optional queryString) throws UrlRessourceNotExistException { + String attUrl = getAttachmentURL(link, action); + if (queryString.isPresent()) { + if (attUrl.indexOf("?") > -1) { + attUrl += "&" + queryString.get(); + } else { + attUrl += "?" + queryString.get(); + } + } + return attUrl; + } + private LastStartupTimeStampRole getLastStartupTimeStamp() { return Utils.getComponent(LastStartupTimeStampRole.class); } + /** + * @deprecated since 5.4 instead use + * {@link RessourceUrlServiceRole#getAttachmentName(String)} + */ + @Deprecated public String getAttachmentName(String link) { return link.split(";")[1]; } + /** + * @deprecated since 5.4 instead use + * {@link RessourceUrlServiceRole#getPageDocRef(String)} + */ + @Deprecated public String getPageFullName(String link) { return link.split(";")[0]; } + /** + * @deprecated since 5.4 instead use + * {@link RessourceUrlServiceRole#getPageDocRef(String)} + */ + @Deprecated + public DocumentReference getPageDocRef(String link) { + return getModelUtils().resolveRef(getPageFullName(link), DocumentReference.class); + } + + /** + * @deprecated since 5.4 instead use + * {@link RessourceUrlServiceRole#isAttachmentLink(String)} + */ + @Deprecated public boolean isAttachmentLink(String link) { boolean isAttachmentLink = false; if (link != null) { @@ -108,6 +210,11 @@ public boolean isAttachmentLink(String link) { return isAttachmentLink; } + /** + * @deprecated since 5.4 instead use + * {@link RessourceUrlServiceRole#isOnDiskLink(String)} + */ + @Deprecated public boolean isOnDiskLink(String link) { boolean isAttachmentLink = false; if (link != null) { @@ -117,11 +224,25 @@ public boolean isOnDiskLink(String link) { return isAttachmentLink; } + /** + * @deprecated since 5.4 instead use {@link RessourceUrlServiceRole#createRessourceUrl(String, + * Optional)} + */ + @Deprecated public String getExternalAttachmentURL(String fileName, String action, XWikiContext context) { + return getExternalAttachmentURL(fileName, Optional.ofNullable(action)); + } + + /** + * @deprecated since 5.4 instead use + * {@link RessourceUrlServiceRole#getExternalRessourceURL(String, Optional)} + */ + @Deprecated + public String getExternalAttachmentURL(String fileName, Optional action) { try { - return context.getURLFactory().getServerURL(context).toExternalForm() + getAttachmentURL( - fileName, action, context); - } catch (MalformedURLException exp) { + return getContext().getURLFactory().getServerURL(getContext()).toExternalForm() + + getAttachmentURL(fileName, action); + } catch (MalformedURLException | UrlRessourceNotExistException exp) { LOGGER.error("Failed to getServerURL.", exp); } return ""; @@ -132,11 +253,19 @@ private IAttachmentServiceRole getAttachmentService() { } private XWikiContext getContext() { - return (XWikiContext) getExecution().getContext().getProperty("xwikicontext"); + return getModelContext().getXWikiContext(); + } + + private @NotNull ModelContext getModelContext() { + return Utils.getComponent(ModelContext.class); + } + + private @NotNull IModelAccessFacade getModelAccess() { + return Utils.getComponent(IModelAccessFacade.class); } - private Execution getExecution() { - return Utils.getComponent(Execution.class); + private @NotNull ModelUtils getModelUtils() { + return Utils.getComponent(ModelUtils.class); } } diff --git a/src/main/resources/META-INF/components.txt b/src/main/resources/META-INF/components.txt index 9f50ab5a3..f9303247a 100644 --- a/src/main/resources/META-INF/components.txt +++ b/src/main/resources/META-INF/components.txt @@ -160,3 +160,4 @@ com.celements.cells.classes.PageLayoutPropertiesClass com.celements.cells.classes.GroupCellClass com.celements.cells.classes.PageDepCellConfigClass com.celements.cells.classes.TranslationBoxCellConfigClass +com.celements.ressource_url.RessourceUrlService diff --git a/src/test/java/com/celements/ressource_url/RessourceUrlServiceTest.java b/src/test/java/com/celements/ressource_url/RessourceUrlServiceTest.java new file mode 100644 index 000000000..f87d0bed2 --- /dev/null +++ b/src/test/java/com/celements/ressource_url/RessourceUrlServiceTest.java @@ -0,0 +1,282 @@ +package com.celements.ressource_url; + +import static com.celements.common.test.CelementsTestUtils.*; +import static org.easymock.EasyMock.*; +import static org.junit.Assert.*; + +import java.net.URL; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Optional; + +import org.junit.Before; +import org.junit.Test; +import org.xwiki.model.reference.AttachmentReference; +import org.xwiki.model.reference.DocumentReference; + +import com.celements.common.test.AbstractComponentTest; +import com.celements.model.access.IModelAccessFacade; +import com.celements.model.access.exception.AttachmentNotExistsException; +import com.celements.model.reference.RefBuilder; +import com.xpn.xwiki.XWiki; +import com.xpn.xwiki.XWikiContext; +import com.xpn.xwiki.doc.XWikiAttachment; +import com.xpn.xwiki.doc.XWikiDocument; +import com.xpn.xwiki.web.Utils; +import com.xpn.xwiki.web.XWikiURLFactory; + +public class RessourceUrlServiceTest extends AbstractComponentTest { + + private IModelAccessFacade modelAccessMock; + private XWikiContext context; + private XWikiURLFactory mockURLFactory; + private RessourceUrlServiceRole resUrlServ; + private XWiki wiki; + + @Before + public void setUp_RessourceUrlServiceTest() throws Exception { + modelAccessMock = registerComponentMock(IModelAccessFacade.class); + context = getContext(); + wiki = getWikiMock(); + mockURLFactory = createMockAndAddToDefault(XWikiURLFactory.class); + context.setURLFactory(mockURLFactory); + resUrlServ = (RessourceUrlServiceRole) Utils.getComponent(RessourceUrlServiceRole.class); + } + + @Test + public void test_createRessourceUrl_fullURL() throws Exception { + assertEquals("http://www.bla.com/bla.txt", resUrlServ.createRessourceUrl( + "http://www.bla.com/bla.txt", Optional.empty())); + } + + @Test + public void test_createRessourceUrl_partURL() throws Exception { + assertEquals("/xwiki/bin/download/A/B/bla.txt", resUrlServ.createRessourceUrl( + "/xwiki/bin/download/A/B/bla.txt", Optional.empty())); + } + + @Test + public void test_createRessourceUrl_dynamicParamURL() throws Exception { + String mySpaceName = "mySpace"; + String myDocName = "myDoc"; + DocumentReference myDocRef = new DocumentReference(context.getDatabase(), mySpaceName, + myDocName); + XWikiDocument doc = new XWikiDocument(myDocRef); + context.setDoc(doc); + URL viewURL = new URL("http://localhost/mySpace/myDoc"); + expect(mockURLFactory.createURL(eq(mySpaceName), eq(myDocName), eq("view"), (String) isNull(), + (String) isNull(), eq(context.getDatabase()), same(context))).andReturn(viewURL); + expect(mockURLFactory.getURL(eq(viewURL), same(context))).andReturn(viewURL.getPath()); + replayDefault(); + assertEquals("/mySpace/myDoc?xpage=bla&bli=blu", resUrlServ.createRessourceUrl( + "?xpage=bla&bli=blu", Optional.empty())); + verifyDefault(); + } + + @Test + public void test_createRessourceUrl_fullInternalLink() throws Exception { + String resultURL = "http://celements2web.localhost/file/A/B/bla.txt"; + DocumentReference abDocRef = new RefBuilder().wiki("celements2web").space("A").doc("B") + .build(DocumentReference.class); + XWikiDocument abDoc = new XWikiDocument(abDocRef); + List attachList = new ArrayList<>(); + XWikiAttachment blaAtt = new XWikiAttachment(); + String attName = "bla.txt"; + blaAtt.setFilename(attName); + blaAtt.setDoc(abDoc); + attachList.add(blaAtt); + abDoc.setAttachmentList(attachList); + URL tstURL = new URL(resultURL); + expect(mockURLFactory.createAttachmentURL(eq("bla.txt"), eq("A"), eq("B"), eq("file"), + (String) eq(null), eq("celements2web"), same(context))).andReturn(tstURL); + expect(mockURLFactory.getURL(eq(tstURL), same(context))).andReturn(resultURL); + expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); + expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( + "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); + expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) + .atLeastOnce(); + replayDefault(); + String attachmentURL = resUrlServ.createRessourceUrl("celements2web:A.B;bla.txt", + Optional.empty()); + assertNotNull(attachmentURL); + assertTrue("expecting " + resultURL + " but got " + attachmentURL, + attachmentURL.matches(resultURL + "\\?version=\\d{14}")); + verifyDefault(); + } + + @Test + public void test_createRessourceUrl_partInternalLink() throws Exception { + String resultURL = "http://mydomain.ch/file/A/B/bla.txt"; + URL tstURL = new URL(resultURL); + expect(mockURLFactory.createAttachmentURL(eq("bla.txt"), eq("A"), eq("B"), eq("file"), + (String) eq(null), eq(context.getDatabase()), same(context))).andReturn(tstURL); + expect(mockURLFactory.getURL(eq(tstURL), same(context))).andReturn(resultURL); + DocumentReference abDocRef = new RefBuilder().wiki(getContext().getDatabase()).space("A") + .doc("B").build(DocumentReference.class); + XWikiDocument abDoc = new XWikiDocument(abDocRef); + List attachList = new ArrayList<>(); + XWikiAttachment blaAtt = new XWikiAttachment(); + String attName = "bla.txt"; + blaAtt.setFilename(attName); + blaAtt.setDoc(abDoc); + attachList.add(blaAtt); + abDoc.setAttachmentList(attachList); + expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); + expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( + "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); + expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) + .atLeastOnce(); + replayDefault(); + String attachmentURL = resUrlServ.createRessourceUrl("A.B;bla.txt", Optional.empty()); + assertNotNull(attachmentURL); + assertTrue("expecting " + resultURL + " but got " + attachmentURL, + attachmentURL.matches(resultURL + "\\?version=\\d{14}")); + verifyDefault(); + } + + @Test + public void test_createRessourceUrl_partInternalLink_notExists() throws Exception { + DocumentReference abDocRef = new RefBuilder().wiki(getContext().getDatabase()).space("A") + .doc("B").build(DocumentReference.class); + XWikiDocument abDoc = new XWikiDocument(abDocRef); + expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); + String attName = "bla.txt"; + AttachmentReference attRef = new RefBuilder().with(abDocRef).att(attName) + .build(AttachmentReference.class); + expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))) + .andThrow(new AttachmentNotExistsException(attRef)).atLeastOnce(); + replayDefault(); + assertThrows(UrlRessourceNotExistException.class, + () -> resUrlServ.createRessourceUrl("A.B;bla.txt", Optional.empty())); + verifyDefault(); + } + + @Test + public void test_createRessourceUrl_onDiskLink() throws Exception { + String resultURL = "/appname/skin/resources/celJS/bla.js"; + expect(wiki.getSkinFile(eq("celJS/bla.js"), eq(true), same(context))).andReturn(resultURL); + expect(wiki.getResourceLastModificationDate(eq("resources/celJS/bla.js"))).andReturn( + new Date()); + expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( + "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("download"); + replayDefault(); + String attachmentURL = resUrlServ.createRessourceUrl(" :celJS/bla.js", Optional.empty(), + Optional.empty()); + String expectedURL = "/appname/download/resources/celJS/bla.js"; + assertNotNull(attachmentURL); + assertTrue("expecting " + expectedURL + " but got " + attachmentURL, + attachmentURL.matches(expectedURL + "\\?version=\\d{14}")); + verifyDefault(); + } + + @Test + public void test_createRessourceUrl_Rubish() throws Exception { + assertEquals("http://A.B;bla.txt", + resUrlServ.createRessourceUrl("http://A.B;bla.txt", Optional.empty(), + Optional.empty()).toString()); + } + + @Test + public void test_isAttachmentLink_null() { + assertFalse(resUrlServ.isAttachmentLink(null)); + } + + @Test + public void test_isAttachmentLink_empty() { + assertFalse(resUrlServ.isAttachmentLink("")); + } + + @Test + public void test_isAttachmentLink_url() { + assertFalse(resUrlServ.isAttachmentLink("/download/Space/Page/attachment.jpg")); + } + + @Test + public void test_isAttachmentLink_is() { + assertTrue(resUrlServ.isAttachmentLink("Space.Page;attachment.jpg")); + } + + @Test + public void test_isAttachmentLink_isSpecialChars() { + assertTrue(resUrlServ.isAttachmentLink("Teilnehmer.f8Nx9vyPOX8O2;Hans-002-Bearbeitet-2.jpg")); + } + + @Test + public void test_isAttachmentLink_isWithDb() { + assertTrue(resUrlServ.isAttachmentLink("db:Space.Page;attachment.jpg")); + } + + @Test + public void test_isOnDiskLink_true() { + assertTrue(resUrlServ.isOnDiskLink(":bla.js")); + assertTrue(resUrlServ.isOnDiskLink(" :celJS/bla.js")); + } + + @Test + public void test_isOnDiskLink_false() { + assertFalse(resUrlServ.isOnDiskLink("bla.js")); + assertFalse(resUrlServ.isOnDiskLink("x:celJS/bla.js")); + assertFalse(resUrlServ.isOnDiskLink("x:A.B;bla.js")); + } + + @Test + public void test_getRessourceURLPrefix() throws Exception { + expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( + "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); + expect(mockURLFactory.createResourceURL(eq(""), eq(true), same(context))).andReturn(new URL( + "http://test.fabian.dev:10080/skin/resources/")); + replayDefault(); + assertEquals("http://test.fabian.dev:10080/file/resources/", + resUrlServ.getRessourceURLPrefix()); + verifyDefault(); + } + + @Test + public void test_getAttachmentURL_onDisk_queryString() throws Exception { + String resultURL = "/appname/skin/resources/celJS/bla.js"; + expect(wiki.getSkinFile(eq("celJS/bla.js"), eq(true), same(context))).andReturn(resultURL); + expect(wiki.getResourceLastModificationDate(eq("resources/celJS/bla.js"))).andReturn( + new Date()); + expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( + "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("download"); + String queryString = "asf=oiu"; + replayDefault(); + String attachmentURL = resUrlServ.createRessourceUrl(":celJS/bla.js", Optional.empty(), + Optional.of(queryString)); + String expectedURL = "/appname/download/resources/celJS/bla.js"; + assertTrue(attachmentURL, + attachmentURL.matches(expectedURL + "\\?version=\\d{14}\\&" + queryString)); + verifyDefault(); + } + + @Test + public void test_getAttachmentURL_partInternalLink_queryString() throws Exception { + String resultURL = "http://mydomain.ch/testAction/A/B/bla.txt"; + URL tstURL = new URL(resultURL); + expect(mockURLFactory.createAttachmentURL(eq("bla.txt"), eq("A"), eq("B"), eq("testAction"), + (String) eq(null), eq(context.getDatabase()), same(context))).andReturn(tstURL); + expect(mockURLFactory.getURL(eq(tstURL), same(context))).andReturn(resultURL); + DocumentReference abDocRef = new RefBuilder().wiki(getContext().getDatabase()).space("A") + .doc("B").build(DocumentReference.class); + XWikiDocument abDoc = new XWikiDocument(abDocRef); + List attachList = new ArrayList<>(); + XWikiAttachment blaAtt = new XWikiAttachment(); + String attName = "bla.txt"; + blaAtt.setFilename(attName); + blaAtt.setDoc(abDoc); + attachList.add(blaAtt); + abDoc.setAttachmentList(attachList); + expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); + expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) + .atLeastOnce(); + String queryString = "asf=oiu"; + replayDefault(); + String attachmentURL = resUrlServ.createRessourceUrl("A.B;bla.txt", Optional.of("testAction"), + Optional.of(queryString)); + assertTrue(attachmentURL, + attachmentURL.matches(resultURL + "\\?version=\\d{14}\\&" + queryString)); + verifyDefault(); + } + +} diff --git a/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java b/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java index ce622685d..2bb5fcc1a 100644 --- a/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java +++ b/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java @@ -19,36 +19,44 @@ */ package com.celements.web.plugin.cmd; +import static com.celements.common.test.CelementsTestUtils.*; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; -import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.Optional; import org.junit.Before; import org.junit.Test; +import org.xwiki.model.reference.AttachmentReference; import org.xwiki.model.reference.DocumentReference; -import com.celements.common.test.AbstractBridgedComponentTestCase; +import com.celements.common.test.AbstractComponentTest; +import com.celements.model.access.IModelAccessFacade; +import com.celements.model.access.exception.AttachmentNotExistsException; +import com.celements.model.reference.RefBuilder; +import com.celements.ressource_url.UrlRessourceNotExistException; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; -import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.web.XWikiURLFactory; -public class AttachmentURLCommandTest extends AbstractBridgedComponentTestCase { +@Deprecated +public class AttachmentURLCommandTest extends AbstractComponentTest { private XWikiContext context; private XWiki wiki; private AttachmentURLCommand attUrlCmd; private XWikiURLFactory mockURLFactory; + private IModelAccessFacade modelAccessMock; @Before public void setUp_AttachmentURLCommandTest() throws Exception { + modelAccessMock = registerComponentMock(IModelAccessFacade.class); context = getContext(); wiki = getWikiMock(); attUrlCmd = new AttachmentURLCommand(); @@ -57,19 +65,19 @@ public void setUp_AttachmentURLCommandTest() throws Exception { } @Test - public void testGetAttachmentURL_fullURL() { + public void test_getAttachmentURL_fullURL() throws Exception { assertEquals("http://www.bla.com/bla.txt", attUrlCmd.getAttachmentURL( "http://www.bla.com/bla.txt", context)); } @Test - public void testGetAttachmentURL_partURL() { + public void test_getAttachmentURL_partURL() throws Exception { assertEquals("/xwiki/bin/download/A/B/bla.txt", attUrlCmd.getAttachmentURL( - "/xwiki/bin/download/A/B/bla.txt", context)); + "/xwiki/bin/download/A/B/bla.txt", Optional.empty())); } @Test - public void testGetAttachmentURL_dynamicParamURL() throws MalformedURLException { + public void test_getAttachmentURL_dynamicParamURL() throws Exception { String mySpaceName = "mySpace"; String myDocName = "myDoc"; DocumentReference myDocRef = new DocumentReference(context.getDatabase(), mySpaceName, @@ -89,24 +97,27 @@ public void testGetAttachmentURL_dynamicParamURL() throws MalformedURLException } @Test - public void testGetAttachmentURL_fullInternalLink() throws XWikiException, MalformedURLException { + public void test_getAttachmentURL_fullInternalLink() throws Exception { String resultURL = "http://celements2web.localhost/file/A/B/bla.txt"; - XWikiDocument abdoc = new XWikiDocument(); - abdoc.setFullName("A.B"); - abdoc.setDatabase("celements2web"); + DocumentReference abDocRef = new RefBuilder().wiki("celements2web").space("A").doc("B") + .build(DocumentReference.class); + XWikiDocument abDoc = new XWikiDocument(abDocRef); List attachList = new ArrayList<>(); XWikiAttachment blaAtt = new XWikiAttachment(); - blaAtt.setFilename("bla.txt"); - blaAtt.setDoc(abdoc); + String attName = "bla.txt"; + blaAtt.setFilename(attName); + blaAtt.setDoc(abDoc); attachList.add(blaAtt); - abdoc.setAttachmentList(attachList); + abDoc.setAttachmentList(attachList); URL tstURL = new URL(resultURL); expect(mockURLFactory.createAttachmentURL(eq("bla.txt"), eq("A"), eq("B"), eq("file"), (String) eq(null), eq("celements2web"), same(context))).andReturn(tstURL); expect(mockURLFactory.getURL(eq(tstURL), same(context))).andReturn(resultURL); - expect(wiki.getDocument(eq("celements2web:A.B"), same(context))).andReturn(abdoc).anyTimes(); + expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); + expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) + .atLeastOnce(); replayDefault(); String attachmentURL = attUrlCmd.getAttachmentURL("celements2web:A.B;bla.txt", context); assertTrue(attachmentURL, attachmentURL.matches(resultURL + "\\?version=\\d{14}")); @@ -114,23 +125,27 @@ public void testGetAttachmentURL_fullInternalLink() throws XWikiException, Malfo } @Test - public void testGetAttachmentURL_partInternalLink() throws XWikiException, MalformedURLException { + public void test_getAttachmentURL_partInternalLink() throws Exception { String resultURL = "http://mydomain.ch/file/A/B/bla.txt"; URL tstURL = new URL(resultURL); expect(mockURLFactory.createAttachmentURL(eq("bla.txt"), eq("A"), eq("B"), eq("file"), (String) eq(null), eq(context.getDatabase()), same(context))).andReturn(tstURL); expect(mockURLFactory.getURL(eq(tstURL), same(context))).andReturn(resultURL); - XWikiDocument abdoc = new XWikiDocument(); - abdoc.setFullName("A.B"); + DocumentReference abDocRef = new RefBuilder().wiki(getContext().getDatabase()).space("A") + .doc("B").build(DocumentReference.class); + XWikiDocument abDoc = new XWikiDocument(abDocRef); List attachList = new ArrayList<>(); XWikiAttachment blaAtt = new XWikiAttachment(); - blaAtt.setFilename("bla.txt"); - blaAtt.setDoc(abdoc); + String attName = "bla.txt"; + blaAtt.setFilename(attName); + blaAtt.setDoc(abDoc); attachList.add(blaAtt); - abdoc.setAttachmentList(attachList); - expect(wiki.getDocument(eq("A.B"), same(context))).andReturn(abdoc).anyTimes(); + abDoc.setAttachmentList(attachList); + expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); + expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) + .atLeastOnce(); replayDefault(); String attachmentURL = attUrlCmd.getAttachmentURL("A.B;bla.txt", context); assertTrue(attachmentURL, attachmentURL.matches(resultURL + "\\?version=\\d{14}")); @@ -138,20 +153,24 @@ public void testGetAttachmentURL_partInternalLink() throws XWikiException, Malfo } @Test - public void testGetAttachmentURL_partInternalLink_notExists() throws XWikiException, - MalformedURLException { - XWikiDocument abdoc = new XWikiDocument(); - abdoc.setFullName("A.B"); - expect(wiki.getDocument(eq("A.B"), same(context))).andReturn(abdoc).anyTimes(); - expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( - "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); + public void test_getAttachmentURL_partInternalLink_notExists() throws Exception { + DocumentReference abDocRef = new RefBuilder().wiki(getContext().getDatabase()).space("A") + .doc("B").build(DocumentReference.class); + XWikiDocument abDoc = new XWikiDocument(abDocRef); + expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); + String attName = "bla.txt"; + AttachmentReference attRef = new RefBuilder().with(abDocRef).att(attName) + .build(AttachmentReference.class); + expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))) + .andThrow(new AttachmentNotExistsException(attRef)).atLeastOnce(); replayDefault(); - assertNull(attUrlCmd.getAttachmentURL("A.B;bla.txt", context)); + assertThrows(UrlRessourceNotExistException.class, + () -> attUrlCmd.getAttachmentURL("A.B;bla.txt", Optional.empty())); verifyDefault(); } @Test - public void testGetAttachmentURL_onDiskLink() throws XWikiException, MalformedURLException { + public void test_getAttachmentURL_onDiskLink() throws Exception { String resultURL = "/appname/skin/resources/celJS/bla.js"; expect(wiki.getSkinFile(eq("celJS/bla.js"), eq(true), same(context))).andReturn(resultURL); expect(wiki.getResourceLastModificationDate(eq("resources/celJS/bla.js"))).andReturn( @@ -166,55 +185,55 @@ public void testGetAttachmentURL_onDiskLink() throws XWikiException, MalformedUR } @Test - public void isAttachmentLink_null() { + public void test_isAttachmentLink_null() { assertFalse(attUrlCmd.isAttachmentLink(null)); } @Test - public void isAttachmentLink_empty() { + public void test_isAttachmentLink_empty() { assertFalse(attUrlCmd.isAttachmentLink("")); } @Test - public void isAttachmentLink_url() { + public void test_isAttachmentLink_url() { assertFalse(attUrlCmd.isAttachmentLink("/download/Space/Page/attachment.jpg")); } @Test - public void isAttachmentLink_is() { + public void test_isAttachmentLink_is() { assertTrue(attUrlCmd.isAttachmentLink("Space.Page;attachment.jpg")); } @Test - public void isAttachmentLink_isSpecialChars() { + public void test_isAttachmentLink_isSpecialChars() { assertTrue(attUrlCmd.isAttachmentLink("Teilnehmer.f8Nx9vyPOX8O2;Hans-002-Bearbeitet-2.jpg")); } @Test - public void isAttachmentLink_isWithDb() { + public void test_isAttachmentLink_isWithDb() { assertTrue(attUrlCmd.isAttachmentLink("db:Space.Page;attachment.jpg")); } @Test - public void testGetAttachmentURL_Rubish() { + public void test_getAttachmentURL_Rubish() throws Exception { assertEquals("http://A.B;bla.txt", attUrlCmd.getAttachmentURL("http://A.B;bla.txt", context)); } @Test - public void testIsOnDiskLink_true() { + public void test_isOnDiskLink_true() { assertTrue(attUrlCmd.isOnDiskLink(":bla.js")); assertTrue(attUrlCmd.isOnDiskLink(" :celJS/bla.js")); } @Test - public void testIsOnDiskLink_false() { + public void test_isOnDiskLink_false() { assertFalse(attUrlCmd.isOnDiskLink("bla.js")); assertFalse(attUrlCmd.isOnDiskLink("x:celJS/bla.js")); assertFalse(attUrlCmd.isOnDiskLink("x:A.B;bla.js")); } @Test - public void testGetAttachmentURLPrefix() throws Exception { + public void test_getAttachmentURLPrefix() throws Exception { expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); expect(mockURLFactory.createResourceURL(eq(""), eq(true), same(context))).andReturn(new URL( @@ -225,4 +244,51 @@ public void testGetAttachmentURLPrefix() throws Exception { verifyDefault(); } + @Test + public void test_getAttachmentURL_onDisk_queryString() throws Exception { + String resultURL = "/appname/skin/resources/celJS/bla.js"; + expect(wiki.getSkinFile(eq("celJS/bla.js"), eq(true), same(context))).andReturn(resultURL); + expect(wiki.getResourceLastModificationDate(eq("resources/celJS/bla.js"))).andReturn( + new Date()); + expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( + "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("download"); + String queryString = "asf=oiu"; + replayDefault(); + String attachmentURL = attUrlCmd.getAttachmentURL(":celJS/bla.js", Optional.empty(), + Optional.of(queryString)); + String expectedURL = "/appname/download/resources/celJS/bla.js"; + assertTrue(attachmentURL, + attachmentURL.matches(expectedURL + "\\?version=\\d{14}\\&" + queryString)); + verifyDefault(); + } + + @Test + public void test_getAttachmentURL_partInternalLink_queryString() throws Exception { + String resultURL = "http://mydomain.ch/testAction/A/B/bla.txt"; + URL tstURL = new URL(resultURL); + expect(mockURLFactory.createAttachmentURL(eq("bla.txt"), eq("A"), eq("B"), eq("testAction"), + (String) eq(null), eq(context.getDatabase()), same(context))).andReturn(tstURL); + expect(mockURLFactory.getURL(eq(tstURL), same(context))).andReturn(resultURL); + DocumentReference abDocRef = new RefBuilder().wiki(getContext().getDatabase()).space("A") + .doc("B").build(DocumentReference.class); + XWikiDocument abDoc = new XWikiDocument(abDocRef); + List attachList = new ArrayList<>(); + XWikiAttachment blaAtt = new XWikiAttachment(); + String attName = "bla.txt"; + blaAtt.setFilename(attName); + blaAtt.setDoc(abDoc); + attachList.add(blaAtt); + abDoc.setAttachmentList(attachList); + expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); + expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) + .atLeastOnce(); + String queryString = "asf=oiu"; + replayDefault(); + String attachmentURL = attUrlCmd.getAttachmentURL("A.B;bla.txt", Optional.of("testAction"), + Optional.of(queryString)); + assertTrue(attachmentURL, + attachmentURL.matches(resultURL + "\\?version=\\d{14}\\&" + queryString)); + verifyDefault(); + } + } From 1280d395f72f39810d1d314958cf05e6b3eb716c Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Thu, 3 Feb 2022 08:41:23 +0100 Subject: [PATCH 02/29] rename ressource_uri package to com.celements.filebase.uri --- .../{ressource_url => filebase/uri}/RessourceUrlService.java | 2 +- .../uri}/RessourceUrlServiceRole.java | 2 +- .../uri}/UrlRessourceNotExistException.java | 2 +- .../com/celements/web/plugin/cmd/AttachmentURLCommand.java | 4 ++-- .../uri}/RessourceUrlServiceTest.java | 4 ++-- .../celements/web/plugin/cmd/AttachmentURLCommandTest.java | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) rename src/main/java/com/celements/{ressource_url => filebase/uri}/RessourceUrlService.java (96%) rename src/main/java/com/celements/{ressource_url => filebase/uri}/RessourceUrlServiceRole.java (93%) rename src/main/java/com/celements/{ressource_url => filebase/uri}/UrlRessourceNotExistException.java (92%) rename src/test/java/com/celements/{ressource_url => filebase/uri}/RessourceUrlServiceTest.java (96%) diff --git a/src/main/java/com/celements/ressource_url/RessourceUrlService.java b/src/main/java/com/celements/filebase/uri/RessourceUrlService.java similarity index 96% rename from src/main/java/com/celements/ressource_url/RessourceUrlService.java rename to src/main/java/com/celements/filebase/uri/RessourceUrlService.java index 37eb29ed7..f4e829dd6 100644 --- a/src/main/java/com/celements/ressource_url/RessourceUrlService.java +++ b/src/main/java/com/celements/filebase/uri/RessourceUrlService.java @@ -1,4 +1,4 @@ -package com.celements.ressource_url; +package com.celements.filebase.uri; import java.net.MalformedURLException; import java.util.Optional; diff --git a/src/main/java/com/celements/ressource_url/RessourceUrlServiceRole.java b/src/main/java/com/celements/filebase/uri/RessourceUrlServiceRole.java similarity index 93% rename from src/main/java/com/celements/ressource_url/RessourceUrlServiceRole.java rename to src/main/java/com/celements/filebase/uri/RessourceUrlServiceRole.java index a3c1b50ce..84cd661b5 100644 --- a/src/main/java/com/celements/ressource_url/RessourceUrlServiceRole.java +++ b/src/main/java/com/celements/filebase/uri/RessourceUrlServiceRole.java @@ -1,4 +1,4 @@ -package com.celements.ressource_url; +package com.celements.filebase.uri; import java.util.Optional; diff --git a/src/main/java/com/celements/ressource_url/UrlRessourceNotExistException.java b/src/main/java/com/celements/filebase/uri/UrlRessourceNotExistException.java similarity index 92% rename from src/main/java/com/celements/ressource_url/UrlRessourceNotExistException.java rename to src/main/java/com/celements/filebase/uri/UrlRessourceNotExistException.java index ef051540c..d977b8dcf 100644 --- a/src/main/java/com/celements/ressource_url/UrlRessourceNotExistException.java +++ b/src/main/java/com/celements/filebase/uri/UrlRessourceNotExistException.java @@ -1,4 +1,4 @@ -package com.celements.ressource_url; +package com.celements.filebase.uri; import javax.validation.constraints.NotNull; diff --git a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java index 0377a0ddd..495da83ad 100644 --- a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java +++ b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java @@ -31,13 +31,13 @@ import org.xwiki.model.reference.DocumentReference; import com.celements.filebase.IAttachmentServiceRole; +import com.celements.filebase.uri.RessourceUrlServiceRole; +import com.celements.filebase.uri.UrlRessourceNotExistException; import com.celements.model.access.IModelAccessFacade; import com.celements.model.access.exception.AttachmentNotExistsException; import com.celements.model.access.exception.DocumentNotExistsException; import com.celements.model.context.ModelContext; import com.celements.model.util.ModelUtils; -import com.celements.ressource_url.RessourceUrlServiceRole; -import com.celements.ressource_url.UrlRessourceNotExistException; import com.celements.web.service.LastStartupTimeStampRole; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.doc.XWikiAttachment; diff --git a/src/test/java/com/celements/ressource_url/RessourceUrlServiceTest.java b/src/test/java/com/celements/filebase/uri/RessourceUrlServiceTest.java similarity index 96% rename from src/test/java/com/celements/ressource_url/RessourceUrlServiceTest.java rename to src/test/java/com/celements/filebase/uri/RessourceUrlServiceTest.java index f87d0bed2..db26c2c09 100644 --- a/src/test/java/com/celements/ressource_url/RessourceUrlServiceTest.java +++ b/src/test/java/com/celements/filebase/uri/RessourceUrlServiceTest.java @@ -1,4 +1,4 @@ -package com.celements.ressource_url; +package com.celements.filebase.uri; import static com.celements.common.test.CelementsTestUtils.*; import static org.easymock.EasyMock.*; @@ -41,7 +41,7 @@ public void setUp_RessourceUrlServiceTest() throws Exception { wiki = getWikiMock(); mockURLFactory = createMockAndAddToDefault(XWikiURLFactory.class); context.setURLFactory(mockURLFactory); - resUrlServ = (RessourceUrlServiceRole) Utils.getComponent(RessourceUrlServiceRole.class); + resUrlServ = Utils.getComponent(RessourceUrlServiceRole.class); } @Test diff --git a/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java b/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java index 2bb5fcc1a..0a8b78e81 100644 --- a/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java +++ b/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java @@ -35,10 +35,10 @@ import org.xwiki.model.reference.DocumentReference; import com.celements.common.test.AbstractComponentTest; +import com.celements.filebase.uri.UrlRessourceNotExistException; import com.celements.model.access.IModelAccessFacade; import com.celements.model.access.exception.AttachmentNotExistsException; import com.celements.model.reference.RefBuilder; -import com.celements.ressource_url.UrlRessourceNotExistException; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.doc.XWikiAttachment; From 80b0d1ae885b981e9fe2122382b8151b15d9e5d1 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Thu, 3 Feb 2022 08:46:14 +0100 Subject: [PATCH 03/29] rename RessourceUrlXXX to FileUriXXX --- ...eption.java => FileNotExistException.java} | 8 ++--- ...rceUrlService.java => FileUriService.java} | 16 ++++----- ...rviceRole.java => FileUriServiceRole.java} | 6 ++-- .../web/plugin/cmd/AttachmentURLCommand.java | 34 +++++++++---------- ...rviceTest.java => FileUriServiceTest.java} | 8 ++--- .../plugin/cmd/AttachmentURLCommandTest.java | 4 +-- 6 files changed, 38 insertions(+), 38 deletions(-) rename src/main/java/com/celements/filebase/uri/{UrlRessourceNotExistException.java => FileNotExistException.java} (58%) rename src/main/java/com/celements/filebase/uri/{RessourceUrlService.java => FileUriService.java} (89%) rename src/main/java/com/celements/filebase/uri/{RessourceUrlServiceRole.java => FileUriServiceRole.java} (81%) rename src/test/java/com/celements/filebase/uri/{RessourceUrlServiceTest.java => FileUriServiceTest.java} (95%) diff --git a/src/main/java/com/celements/filebase/uri/UrlRessourceNotExistException.java b/src/main/java/com/celements/filebase/uri/FileNotExistException.java similarity index 58% rename from src/main/java/com/celements/filebase/uri/UrlRessourceNotExistException.java rename to src/main/java/com/celements/filebase/uri/FileNotExistException.java index d977b8dcf..e51818823 100644 --- a/src/main/java/com/celements/filebase/uri/UrlRessourceNotExistException.java +++ b/src/main/java/com/celements/filebase/uri/FileNotExistException.java @@ -2,22 +2,22 @@ import javax.validation.constraints.NotNull; -public class UrlRessourceNotExistException extends Exception { +public class FileNotExistException extends Exception { private static final long serialVersionUID = 1L; private final String ressource; - public UrlRessourceNotExistException(@NotNull String ressource) { + public FileNotExistException(@NotNull String ressource) { super("Url ressource [" + ressource + "] does not exist."); this.ressource = ressource; } - public UrlRessourceNotExistException(@NotNull String message, @NotNull String ressource) { + public FileNotExistException(@NotNull String message, @NotNull String ressource) { super(message); this.ressource = ressource; } - public UrlRessourceNotExistException(@NotNull String message, @NotNull String ressource, + public FileNotExistException(@NotNull String message, @NotNull String ressource, Exception wrapExp) { super(message, wrapExp); this.ressource = ressource; diff --git a/src/main/java/com/celements/filebase/uri/RessourceUrlService.java b/src/main/java/com/celements/filebase/uri/FileUriService.java similarity index 89% rename from src/main/java/com/celements/filebase/uri/RessourceUrlService.java rename to src/main/java/com/celements/filebase/uri/FileUriService.java index f4e829dd6..7ce853a29 100644 --- a/src/main/java/com/celements/filebase/uri/RessourceUrlService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriService.java @@ -26,7 +26,7 @@ import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.web.XWikiURLFactory; -public class RessourceUrlService implements RessourceUrlServiceRole { +public class FileUriService implements FileUriServiceRole { private static final String ATTACHMENT_LINK_REGEX = "([\\w\\-]*:)?([\\w\\-]*\\.[\\w\\-]*){1};.*"; private static final Supplier ATTACHMENT_LINK_PATTERN = Suppliers @@ -35,7 +35,7 @@ public class RessourceUrlService implements RessourceUrlServiceRole { private static final Supplier ON_DISK_LINK_PATTERN = Suppliers .memoize(() -> Pattern.compile(ON_DISK_LINK_REGEX)); - private static final Logger LOGGER = LoggerFactory.getLogger(RessourceUrlService.class); + private static final Logger LOGGER = LoggerFactory.getLogger(FileUriService.class); @Requirement private ModelContext context; @@ -113,7 +113,7 @@ public String getExternalRessourceURL(@NotNull String fileName, try { return context.getXWikiContext().getURLFactory().getServerURL(context.getXWikiContext()) .toExternalForm() + createRessourceUrl(fileName, action); - } catch (MalformedURLException | UrlRessourceNotExistException exp) { + } catch (MalformedURLException | FileNotExistException exp) { LOGGER.error("Failed to getServerURL.", exp); } return ""; @@ -122,7 +122,7 @@ public String getExternalRessourceURL(@NotNull String fileName, @Override @NotNull public String createRessourceUrl(@NotNull String link, @NotNull Optional action, - @NotNull Optional queryString) throws UrlRessourceNotExistException { + @NotNull Optional queryString) throws FileNotExistException { final String baseUrl = createRessourceUrl(link, action); if (queryString.isPresent()) { if (baseUrl.indexOf("?") > -1) { @@ -136,7 +136,7 @@ public String createRessourceUrl(@NotNull String link, @NotNull Optional @Override public @NotEmpty String createRessourceUrl(@NotNull String link, @NotNull Optional action) - throws UrlRessourceNotExistException { + throws FileNotExistException { String url = link; if (isAttachmentLink(link)) { url = createAttachmentUrl(link, action); @@ -155,7 +155,7 @@ private String addContextUrl(String url) { } private String createAttachmentUrl(String link, Optional action) - throws UrlRessourceNotExistException { + throws FileNotExistException { String attName = getAttachmentName(link); try { XWikiDocument doc = modelAccess.getDocument(getPageDocRef(link)); @@ -165,10 +165,10 @@ private String createAttachmentUrl(String link, Optional action) } catch (DocumentNotExistsException exp) { LOGGER.error("Error getting attachment URL for doc '{}' and file {}", getPageDocRef(link), attName, exp); - throw new UrlRessourceNotExistException(link); + throw new FileNotExistException(link); } catch (AttachmentNotExistsException anee) { LOGGER.info("Attachment not found for link [{}] and action [{}]", link, action, anee); - throw new UrlRessourceNotExistException(link); + throw new FileNotExistException(link); } } diff --git a/src/main/java/com/celements/filebase/uri/RessourceUrlServiceRole.java b/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java similarity index 81% rename from src/main/java/com/celements/filebase/uri/RessourceUrlServiceRole.java rename to src/main/java/com/celements/filebase/uri/FileUriServiceRole.java index 84cd661b5..9946901f6 100644 --- a/src/main/java/com/celements/filebase/uri/RessourceUrlServiceRole.java +++ b/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java @@ -10,7 +10,7 @@ import org.xwiki.model.reference.DocumentReference; @ComponentRole -public interface RessourceUrlServiceRole { +public interface FileUriServiceRole { @NotNull public String getAttachmentName(@NotNull String link); @@ -24,11 +24,11 @@ public interface RessourceUrlServiceRole { @NotNull String createRessourceUrl(@NotNull String jsFile, @NotNull Optional action, - @NotNull Optional queryString) throws UrlRessourceNotExistException; + @NotNull Optional queryString) throws FileNotExistException; @NotEmpty String createRessourceUrl(@NotNull String link, @NotNull Optional action) - throws UrlRessourceNotExistException; + throws FileNotExistException; @NotEmpty String getRessourceURLPrefix(@NotEmpty String action); diff --git a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java index 495da83ad..39f7d5522 100644 --- a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java +++ b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java @@ -31,8 +31,8 @@ import org.xwiki.model.reference.DocumentReference; import com.celements.filebase.IAttachmentServiceRole; -import com.celements.filebase.uri.RessourceUrlServiceRole; -import com.celements.filebase.uri.UrlRessourceNotExistException; +import com.celements.filebase.uri.FileUriServiceRole; +import com.celements.filebase.uri.FileNotExistException; import com.celements.model.access.IModelAccessFacade; import com.celements.model.access.exception.AttachmentNotExistsException; import com.celements.model.access.exception.DocumentNotExistsException; @@ -46,7 +46,7 @@ import com.xpn.xwiki.web.XWikiURLFactory; /** - * @deprecated since 5.4 instead use {@link RessourceUrlServiceRole} + * @deprecated since 5.4 instead use {@link FileUriServiceRole} */ @Deprecated public class AttachmentURLCommand { @@ -55,7 +55,7 @@ public class AttachmentURLCommand { /** * @deprecated since 5.4 instead use - * {@link RessourceUrlServiceRole#createRessourceUrl(String, Optional)} + * {@link FileUriServiceRole#createRessourceUrl(String, Optional)} */ @Deprecated public String getAttachmentURL(String link, XWikiContext context) { @@ -68,7 +68,7 @@ private String getDefaultAction() { } /** - * @deprecated since 5.4 instead use {@link RessourceUrlServiceRole#getRessourceURLPrefix()} + * @deprecated since 5.4 instead use {@link FileUriServiceRole#getRessourceURLPrefix()} */ @Deprecated public String getAttachmentURLPrefix() { @@ -76,7 +76,7 @@ public String getAttachmentURLPrefix() { } /** - * @deprecated since 5.4 instead use {@link RessourceUrlServiceRole#getRessourceURLPrefix(String)} + * @deprecated since 5.4 instead use {@link FileUriServiceRole#getRessourceURLPrefix(String)} */ @Deprecated public String getAttachmentURLPrefix(String action) { @@ -94,7 +94,7 @@ public String getAttachmentURLPrefix(String action) { public String getAttachmentURL(String link, String action, XWikiContext context) { try { return getAttachmentURL(link, Optional.ofNullable(action)); - } catch (UrlRessourceNotExistException exp) { + } catch (FileNotExistException exp) { return null; } } @@ -106,7 +106,7 @@ public String getAttachmentURL(String link, String action, XWikiContext context) @Deprecated @NotEmpty public String getAttachmentURL(@NotNull String link, @NotNull Optional action) - throws UrlRessourceNotExistException { + throws FileNotExistException { String url = link; if (isAttachmentLink(link)) { String attName = getAttachmentName(link); @@ -120,10 +120,10 @@ public String getAttachmentURL(@NotNull String link, @NotNull Optional a attName, exp); // 01.02.2022;F.Pichler; is this functionality used? No test available. Adding exception. // url = link; - throw new UrlRessourceNotExistException(link); + throw new FileNotExistException(link); } catch (AttachmentNotExistsException anee) { LOGGER.info("Attachment not found for link [{}] and action [{}]", link, action, anee); - throw new UrlRessourceNotExistException(link); + throw new FileNotExistException(link); } } else if (isOnDiskLink(link)) { String path = link.trim().substring(1); @@ -153,7 +153,7 @@ private String getAction(Optional action) { @Deprecated @Nullable public String getAttachmentURL(@NotNull String link, @NotNull Optional action, - @NotNull Optional queryString) throws UrlRessourceNotExistException { + @NotNull Optional queryString) throws FileNotExistException { String attUrl = getAttachmentURL(link, action); if (queryString.isPresent()) { if (attUrl.indexOf("?") > -1) { @@ -171,7 +171,7 @@ private LastStartupTimeStampRole getLastStartupTimeStamp() { /** * @deprecated since 5.4 instead use - * {@link RessourceUrlServiceRole#getAttachmentName(String)} + * {@link FileUriServiceRole#getAttachmentName(String)} */ @Deprecated public String getAttachmentName(String link) { @@ -180,7 +180,7 @@ public String getAttachmentName(String link) { /** * @deprecated since 5.4 instead use - * {@link RessourceUrlServiceRole#getPageDocRef(String)} + * {@link FileUriServiceRole#getPageDocRef(String)} */ @Deprecated public String getPageFullName(String link) { @@ -189,7 +189,7 @@ public String getPageFullName(String link) { /** * @deprecated since 5.4 instead use - * {@link RessourceUrlServiceRole#getPageDocRef(String)} + * {@link FileUriServiceRole#getPageDocRef(String)} */ @Deprecated public DocumentReference getPageDocRef(String link) { @@ -198,7 +198,7 @@ public DocumentReference getPageDocRef(String link) { /** * @deprecated since 5.4 instead use - * {@link RessourceUrlServiceRole#isAttachmentLink(String)} + * {@link FileUriServiceRole#isAttachmentLink(String)} */ @Deprecated public boolean isAttachmentLink(String link) { @@ -212,7 +212,7 @@ public boolean isAttachmentLink(String link) { /** * @deprecated since 5.4 instead use - * {@link RessourceUrlServiceRole#isOnDiskLink(String)} + * {@link FileUriServiceRole#isOnDiskLink(String)} */ @Deprecated public boolean isOnDiskLink(String link) { @@ -242,7 +242,7 @@ public String getExternalAttachmentURL(String fileName, Optional action) try { return getContext().getURLFactory().getServerURL(getContext()).toExternalForm() + getAttachmentURL(fileName, action); - } catch (MalformedURLException | UrlRessourceNotExistException exp) { + } catch (MalformedURLException | FileNotExistException exp) { LOGGER.error("Failed to getServerURL.", exp); } return ""; diff --git a/src/test/java/com/celements/filebase/uri/RessourceUrlServiceTest.java b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java similarity index 95% rename from src/test/java/com/celements/filebase/uri/RessourceUrlServiceTest.java rename to src/test/java/com/celements/filebase/uri/FileUriServiceTest.java index db26c2c09..487036fc5 100644 --- a/src/test/java/com/celements/filebase/uri/RessourceUrlServiceTest.java +++ b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java @@ -26,12 +26,12 @@ import com.xpn.xwiki.web.Utils; import com.xpn.xwiki.web.XWikiURLFactory; -public class RessourceUrlServiceTest extends AbstractComponentTest { +public class FileUriServiceTest extends AbstractComponentTest { private IModelAccessFacade modelAccessMock; private XWikiContext context; private XWikiURLFactory mockURLFactory; - private RessourceUrlServiceRole resUrlServ; + private FileUriServiceRole resUrlServ; private XWiki wiki; @Before @@ -41,7 +41,7 @@ public void setUp_RessourceUrlServiceTest() throws Exception { wiki = getWikiMock(); mockURLFactory = createMockAndAddToDefault(XWikiURLFactory.class); context.setURLFactory(mockURLFactory); - resUrlServ = Utils.getComponent(RessourceUrlServiceRole.class); + resUrlServ = Utils.getComponent(FileUriServiceRole.class); } @Test @@ -147,7 +147,7 @@ public void test_createRessourceUrl_partInternalLink_notExists() throws Exceptio expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))) .andThrow(new AttachmentNotExistsException(attRef)).atLeastOnce(); replayDefault(); - assertThrows(UrlRessourceNotExistException.class, + assertThrows(FileNotExistException.class, () -> resUrlServ.createRessourceUrl("A.B;bla.txt", Optional.empty())); verifyDefault(); } diff --git a/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java b/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java index 0a8b78e81..8c87a3c30 100644 --- a/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java +++ b/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java @@ -35,7 +35,7 @@ import org.xwiki.model.reference.DocumentReference; import com.celements.common.test.AbstractComponentTest; -import com.celements.filebase.uri.UrlRessourceNotExistException; +import com.celements.filebase.uri.FileNotExistException; import com.celements.model.access.IModelAccessFacade; import com.celements.model.access.exception.AttachmentNotExistsException; import com.celements.model.reference.RefBuilder; @@ -164,7 +164,7 @@ public void test_getAttachmentURL_partInternalLink_notExists() throws Exception expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))) .andThrow(new AttachmentNotExistsException(attRef)).atLeastOnce(); replayDefault(); - assertThrows(UrlRessourceNotExistException.class, + assertThrows(FileNotExistException.class, () -> attUrlCmd.getAttachmentURL("A.B;bla.txt", Optional.empty())); verifyDefault(); } From 47750ab02d9bbc070aa5e096d4edc312164fd0e2 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Thu, 3 Feb 2022 08:47:34 +0100 Subject: [PATCH 04/29] update components.txt --- src/main/java/com/celements/filebase/uri/FileUriService.java | 2 ++ src/main/resources/META-INF/components.txt | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/celements/filebase/uri/FileUriService.java b/src/main/java/com/celements/filebase/uri/FileUriService.java index 7ce853a29..f82702848 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriService.java @@ -11,6 +11,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.xwiki.component.annotation.Component; import org.xwiki.component.annotation.Requirement; import org.xwiki.model.reference.DocumentReference; @@ -26,6 +27,7 @@ import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.web.XWikiURLFactory; +@Component public class FileUriService implements FileUriServiceRole { private static final String ATTACHMENT_LINK_REGEX = "([\\w\\-]*:)?([\\w\\-]*\\.[\\w\\-]*){1};.*"; diff --git a/src/main/resources/META-INF/components.txt b/src/main/resources/META-INF/components.txt index f9303247a..1761932ad 100644 --- a/src/main/resources/META-INF/components.txt +++ b/src/main/resources/META-INF/components.txt @@ -160,4 +160,4 @@ com.celements.cells.classes.PageLayoutPropertiesClass com.celements.cells.classes.GroupCellClass com.celements.cells.classes.PageDepCellConfigClass com.celements.cells.classes.TranslationBoxCellConfigClass -com.celements.ressource_url.RessourceUrlService +com.celements.filebase.uri.FileUriService From 588f03479ebbda00158e4a60b16d347edfab47c9 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Thu, 3 Feb 2022 08:49:38 +0100 Subject: [PATCH 05/29] inline getAction --- .../com/celements/filebase/uri/FileUriService.java | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/celements/filebase/uri/FileUriService.java b/src/main/java/com/celements/filebase/uri/FileUriService.java index f82702848..a834cd5f7 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriService.java @@ -82,13 +82,6 @@ public boolean isOnDiskLink(@Nullable String link) { return false; } - private String getAction(Optional action) { - if (action.isPresent()) { - return action.get(); - } - return getDefaultAction(); - } - private String getDefaultAction() { return context.getXWikiContext().getWiki().getXWikiPreference("celdefaultAttAction", "celements.attachmenturl.defaultaction", "file", context.getXWikiContext()); @@ -162,7 +155,7 @@ private String createAttachmentUrl(String link, Optional action) try { XWikiDocument doc = modelAccess.getDocument(getPageDocRef(link)); XWikiAttachment att = attachmentSrv.getAttachmentNameEqual(doc, attName); - return doc.getAttachmentURL(attName, getAction(action), context.getXWikiContext()) + return doc.getAttachmentURL(attName, action.orElse(getDefaultAction()), context.getXWikiContext()) + "?version=" + lastStartupTimeStamp.getLastChangedTimeStamp(att.getDate()); } catch (DocumentNotExistsException exp) { LOGGER.error("Error getting attachment URL for doc '{}' and file {}", getPageDocRef(link), @@ -179,7 +172,7 @@ private String createOnDiskUrl(String link, Optional action) { String path = link.trim().substring(1); url = context.getXWikiContext().getWiki().getSkinFile(path, true, context.getXWikiContext()) .replace("/skin/", - "/" + getAction(action) + "/"); + "/" + action.orElse(getDefaultAction()) + "/"); url += "?version=" + lastStartupTimeStamp.getFileModificationDate(path); return url; } From 150a7fc0628e2372b56e9c56b093f0a855a4e0f6 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Thu, 3 Feb 2022 08:51:17 +0100 Subject: [PATCH 06/29] inline getAction --- .../web/plugin/cmd/AttachmentURLCommand.java | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java index 39f7d5522..bfb27086f 100644 --- a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java +++ b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java @@ -31,8 +31,8 @@ import org.xwiki.model.reference.DocumentReference; import com.celements.filebase.IAttachmentServiceRole; -import com.celements.filebase.uri.FileUriServiceRole; import com.celements.filebase.uri.FileNotExistException; +import com.celements.filebase.uri.FileUriServiceRole; import com.celements.model.access.IModelAccessFacade; import com.celements.model.access.exception.AttachmentNotExistsException; import com.celements.model.access.exception.DocumentNotExistsException; @@ -113,7 +113,7 @@ public String getAttachmentURL(@NotNull String link, @NotNull Optional a try { XWikiDocument doc = getModelAccess().getDocument(getPageDocRef(link)); XWikiAttachment att = getAttachmentService().getAttachmentNameEqual(doc, attName); - url = doc.getAttachmentURL(attName, getAction(action), getContext()); + url = doc.getAttachmentURL(attName, action.orElse(getDefaultAction()), getContext()); url += "?version=" + getLastStartupTimeStamp().getLastChangedTimeStamp(att.getDate()); } catch (DocumentNotExistsException exp) { LOGGER.error("Error getting attachment URL for doc '{}' and file {}", getPageFullName(link), @@ -128,7 +128,7 @@ public String getAttachmentURL(@NotNull String link, @NotNull Optional a } else if (isOnDiskLink(link)) { String path = link.trim().substring(1); url = getContext().getWiki().getSkinFile(path, true, getContext()).replace("/skin/", - "/" + getAction(action) + "/"); + "/" + action.orElse(getDefaultAction()) + "/"); url += "?version=" + getLastStartupTimeStamp().getFileModificationDate(path); } Optional currentDoc = getModelContext().getCurrentDoc().toJavaUtil(); @@ -138,13 +138,6 @@ public String getAttachmentURL(@NotNull String link, @NotNull Optional a return url; } - private String getAction(Optional action) { - if (action.isPresent()) { - return action.get(); - } - return getDefaultAction(); - } - /** * @deprecated since 5.4 instead use * {@link RessourceUrlServiceRole#createRessourceUrl(String, Optional, From 3b0ec7406adf1294f4064708b404fd76f43ecefb Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Mon, 7 Feb 2022 06:43:16 +0100 Subject: [PATCH 07/29] reset refactorings before deprecation --- .../web/plugin/cmd/AttachmentURLCommand.java | 114 ++++-------------- 1 file changed, 22 insertions(+), 92 deletions(-) diff --git a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java index bfb27086f..86fff50b4 100644 --- a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java +++ b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java @@ -23,23 +23,17 @@ import java.util.Optional; import javax.annotation.Nullable; -import javax.validation.constraints.NotEmpty; -import javax.validation.constraints.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.xwiki.model.reference.DocumentReference; +import org.xwiki.context.Execution; import com.celements.filebase.IAttachmentServiceRole; -import com.celements.filebase.uri.FileNotExistException; import com.celements.filebase.uri.FileUriServiceRole; -import com.celements.model.access.IModelAccessFacade; import com.celements.model.access.exception.AttachmentNotExistsException; -import com.celements.model.access.exception.DocumentNotExistsException; -import com.celements.model.context.ModelContext; -import com.celements.model.util.ModelUtils; import com.celements.web.service.LastStartupTimeStampRole; import com.xpn.xwiki.XWikiContext; +import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.web.Utils; @@ -55,7 +49,7 @@ public class AttachmentURLCommand { /** * @deprecated since 5.4 instead use - * {@link FileUriServiceRole#createRessourceUrl(String, Optional)} + * {@link FileUriServiceRole#createFileUrl(String, Optional)} */ @Deprecated public String getAttachmentURL(String link, XWikiContext context) { @@ -68,7 +62,7 @@ private String getDefaultAction() { } /** - * @deprecated since 5.4 instead use {@link FileUriServiceRole#getRessourceURLPrefix()} + * @deprecated since 5.4 instead use {@link FileUriServiceRole#getFileURLPrefix()} */ @Deprecated public String getAttachmentURLPrefix() { @@ -76,7 +70,7 @@ public String getAttachmentURLPrefix() { } /** - * @deprecated since 5.4 instead use {@link FileUriServiceRole#getRessourceURLPrefix(String)} + * @deprecated since 5.4 instead use {@link FileUriServiceRole#getFileURLPrefix(String)} */ @Deprecated public String getAttachmentURLPrefix(String action) { @@ -92,72 +86,34 @@ public String getAttachmentURLPrefix(String action) { @Deprecated @Nullable public String getAttachmentURL(String link, String action, XWikiContext context) { - try { - return getAttachmentURL(link, Optional.ofNullable(action)); - } catch (FileNotExistException exp) { - return null; - } - } - - /** - * @deprecated since 5.4 instead use - * {@link RessourceUrlServiceRole#createRessourceUrl(String, Optional)} - */ - @Deprecated - @NotEmpty - public String getAttachmentURL(@NotNull String link, @NotNull Optional action) - throws FileNotExistException { String url = link; if (isAttachmentLink(link)) { String attName = getAttachmentName(link); try { - XWikiDocument doc = getModelAccess().getDocument(getPageDocRef(link)); + XWikiDocument doc = context.getWiki().getDocument(getPageFullName(link), context); XWikiAttachment att = getAttachmentService().getAttachmentNameEqual(doc, attName); - url = doc.getAttachmentURL(attName, action.orElse(getDefaultAction()), getContext()); + url = doc.getAttachmentURL(attName, action, context); url += "?version=" + getLastStartupTimeStamp().getLastChangedTimeStamp(att.getDate()); - } catch (DocumentNotExistsException exp) { - LOGGER.error("Error getting attachment URL for doc '{}' and file {}", getPageFullName(link), - attName, exp); - // 01.02.2022;F.Pichler; is this functionality used? No test available. Adding exception. - // url = link; - throw new FileNotExistException(link); + } catch (XWikiException exp) { + LOGGER.error("Error getting attachment URL for doc " + getPageFullName(link) + " and file " + + attName, exp); + url = link; } catch (AttachmentNotExistsException anee) { LOGGER.info("Attachment not found for link [{}] and action [{}]", link, action, anee); - throw new FileNotExistException(link); + return null; } } else if (isOnDiskLink(link)) { String path = link.trim().substring(1); - url = getContext().getWiki().getSkinFile(path, true, getContext()).replace("/skin/", - "/" + action.orElse(getDefaultAction()) + "/"); + url = context.getWiki().getSkinFile(path, true, context).replace("/skin/", "/" + action + + "/"); url += "?version=" + getLastStartupTimeStamp().getFileModificationDate(path); } - Optional currentDoc = getModelContext().getCurrentDoc().toJavaUtil(); - if (currentDoc.isPresent() && url.startsWith("?")) { - url = currentDoc.get().getURL("view", getContext()) + url; + if (url.startsWith("?")) { + url = context.getDoc().getURL("view", context) + url; } return url; } - /** - * @deprecated since 5.4 instead use - * {@link RessourceUrlServiceRole#createRessourceUrl(String, Optional, - * Optional)} - */ - @Deprecated - @Nullable - public String getAttachmentURL(@NotNull String link, @NotNull Optional action, - @NotNull Optional queryString) throws FileNotExistException { - String attUrl = getAttachmentURL(link, action); - if (queryString.isPresent()) { - if (attUrl.indexOf("?") > -1) { - attUrl += "&" + queryString.get(); - } else { - attUrl += "?" + queryString.get(); - } - } - return attUrl; - } - private LastStartupTimeStampRole getLastStartupTimeStamp() { return Utils.getComponent(LastStartupTimeStampRole.class); } @@ -180,15 +136,6 @@ public String getPageFullName(String link) { return link.split(";")[0]; } - /** - * @deprecated since 5.4 instead use - * {@link FileUriServiceRole#getPageDocRef(String)} - */ - @Deprecated - public DocumentReference getPageDocRef(String link) { - return getModelUtils().resolveRef(getPageFullName(link), DocumentReference.class); - } - /** * @deprecated since 5.4 instead use * {@link FileUriServiceRole#isAttachmentLink(String)} @@ -223,19 +170,10 @@ public boolean isOnDiskLink(String link) { */ @Deprecated public String getExternalAttachmentURL(String fileName, String action, XWikiContext context) { - return getExternalAttachmentURL(fileName, Optional.ofNullable(action)); - } - - /** - * @deprecated since 5.4 instead use - * {@link RessourceUrlServiceRole#getExternalRessourceURL(String, Optional)} - */ - @Deprecated - public String getExternalAttachmentURL(String fileName, Optional action) { try { - return getContext().getURLFactory().getServerURL(getContext()).toExternalForm() - + getAttachmentURL(fileName, action); - } catch (MalformedURLException | FileNotExistException exp) { + return context.getURLFactory().getServerURL(context).toExternalForm() + getAttachmentURL( + fileName, action, context); + } catch (MalformedURLException exp) { LOGGER.error("Failed to getServerURL.", exp); } return ""; @@ -246,19 +184,11 @@ private IAttachmentServiceRole getAttachmentService() { } private XWikiContext getContext() { - return getModelContext().getXWikiContext(); - } - - private @NotNull ModelContext getModelContext() { - return Utils.getComponent(ModelContext.class); - } - - private @NotNull IModelAccessFacade getModelAccess() { - return Utils.getComponent(IModelAccessFacade.class); + return (XWikiContext) getExecution().getContext().getProperty("xwikicontext"); } - private @NotNull ModelUtils getModelUtils() { - return Utils.getComponent(ModelUtils.class); + private Execution getExecution() { + return Utils.getComponent(Execution.class); } } From 9e3352c560ee160de32892a274804e7627da5585 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Mon, 7 Feb 2022 06:45:34 +0100 Subject: [PATCH 08/29] overwrite hashCode, equals and toString --- .../javascript/ExtJsFileParameter.java | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/celements/javascript/ExtJsFileParameter.java b/src/main/java/com/celements/javascript/ExtJsFileParameter.java index 1b40fbde8..5f7aa6eb6 100644 --- a/src/main/java/com/celements/javascript/ExtJsFileParameter.java +++ b/src/main/java/com/celements/javascript/ExtJsFileParameter.java @@ -2,6 +2,7 @@ import static com.google.common.base.Preconditions.*; +import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; @@ -125,10 +126,24 @@ public boolean isLazyLoad() { return lazyLoad; } + @Override + public int hashCode() { + return Objects.hash(jsFileEntry, queryString, lazyLoad, action); + } + + @Override + public boolean equals(@Nullable Object obj) { + return (obj instanceof ExtJsFileParameter) + && Objects.equals(((ExtJsFileParameter) obj).jsFileEntry, this.jsFileEntry) + && Objects.equals(((ExtJsFileParameter) obj).queryString, this.queryString) + && Objects.equals(((ExtJsFileParameter) obj).lazyLoad, this.lazyLoad) + && Objects.equals(((ExtJsFileParameter) obj).action, this.action); + } + @Override public String toString() { - return "ExtJsFileParameter [action=" + action + ", jsFileEntry=" + jsFileEntry - + ", queryString=" + queryString + ", lazyLoad=" + lazyLoad + "]"; + return "ExtJsFileParameter [action=" + action + ", queryString=" + queryString + ", lazyLoad=" + + lazyLoad + ", jsFileEntry=" + jsFileEntry + "]"; } } From b1c77ba41b899b545fb53473e5bf7eba409a9d20 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Mon, 7 Feb 2022 06:53:38 +0100 Subject: [PATCH 09/29] correct javadoc links --- .../web/plugin/cmd/AttachmentURLCommand.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java index 86fff50b4..99170e8a8 100644 --- a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java +++ b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java @@ -29,6 +29,7 @@ import org.xwiki.context.Execution; import com.celements.filebase.IAttachmentServiceRole; +import com.celements.filebase.references.FileReference; import com.celements.filebase.uri.FileUriServiceRole; import com.celements.model.access.exception.AttachmentNotExistsException; import com.celements.web.service.LastStartupTimeStampRole; @@ -120,7 +121,7 @@ private LastStartupTimeStampRole getLastStartupTimeStamp() { /** * @deprecated since 5.4 instead use - * {@link FileUriServiceRole#getAttachmentName(String)} + * {@link FileReference#getName()} */ @Deprecated public String getAttachmentName(String link) { @@ -129,7 +130,7 @@ public String getAttachmentName(String link) { /** * @deprecated since 5.4 instead use - * {@link FileUriServiceRole#getPageDocRef(String)} + * {@link FileReference#getDocRef()} */ @Deprecated public String getPageFullName(String link) { @@ -138,7 +139,7 @@ public String getPageFullName(String link) { /** * @deprecated since 5.4 instead use - * {@link FileUriServiceRole#isAttachmentLink(String)} + * {@link FileReference#isAttachmentReference()} */ @Deprecated public boolean isAttachmentLink(String link) { @@ -152,7 +153,7 @@ public boolean isAttachmentLink(String link) { /** * @deprecated since 5.4 instead use - * {@link FileUriServiceRole#isOnDiskLink(String)} + * {@link FileReference#isOnDiskReference()} */ @Deprecated public boolean isOnDiskLink(String link) { @@ -165,8 +166,8 @@ public boolean isOnDiskLink(String link) { } /** - * @deprecated since 5.4 instead use {@link RessourceUrlServiceRole#createRessourceUrl(String, - * Optional)} + * @deprecated since 5.4 instead use + * {@link FileUriServiceRole#getExternalFileURL(FileReference, Optional)} */ @Deprecated public String getExternalAttachmentURL(String fileName, String action, XWikiContext context) { From 37b613827d489134ed143a286937052ed9168619 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Mon, 7 Feb 2022 07:56:30 +0100 Subject: [PATCH 10/29] remove not used modelAccess mock --- .../plugin/cmd/AttachmentURLCommandTest.java | 108 ++++-------------- 1 file changed, 21 insertions(+), 87 deletions(-) diff --git a/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java b/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java index 8c87a3c30..00fb4ed6c 100644 --- a/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java +++ b/src/test/java/com/celements/web/plugin/cmd/AttachmentURLCommandTest.java @@ -27,18 +27,12 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.Optional; import org.junit.Before; import org.junit.Test; -import org.xwiki.model.reference.AttachmentReference; import org.xwiki.model.reference.DocumentReference; import com.celements.common.test.AbstractComponentTest; -import com.celements.filebase.uri.FileNotExistException; -import com.celements.model.access.IModelAccessFacade; -import com.celements.model.access.exception.AttachmentNotExistsException; -import com.celements.model.reference.RefBuilder; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.doc.XWikiAttachment; @@ -52,11 +46,9 @@ public class AttachmentURLCommandTest extends AbstractComponentTest { private XWiki wiki; private AttachmentURLCommand attUrlCmd; private XWikiURLFactory mockURLFactory; - private IModelAccessFacade modelAccessMock; @Before public void setUp_AttachmentURLCommandTest() throws Exception { - modelAccessMock = registerComponentMock(IModelAccessFacade.class); context = getContext(); wiki = getWikiMock(); attUrlCmd = new AttachmentURLCommand(); @@ -73,7 +65,7 @@ public void test_getAttachmentURL_fullURL() throws Exception { @Test public void test_getAttachmentURL_partURL() throws Exception { assertEquals("/xwiki/bin/download/A/B/bla.txt", attUrlCmd.getAttachmentURL( - "/xwiki/bin/download/A/B/bla.txt", Optional.empty())); + "/xwiki/bin/download/A/B/bla.txt", context)); } @Test @@ -99,25 +91,22 @@ public void test_getAttachmentURL_dynamicParamURL() throws Exception { @Test public void test_getAttachmentURL_fullInternalLink() throws Exception { String resultURL = "http://celements2web.localhost/file/A/B/bla.txt"; - DocumentReference abDocRef = new RefBuilder().wiki("celements2web").space("A").doc("B") - .build(DocumentReference.class); - XWikiDocument abDoc = new XWikiDocument(abDocRef); + XWikiDocument abdoc = new XWikiDocument(); + abdoc.setFullName("A.B"); + abdoc.setDatabase("celements2web"); List attachList = new ArrayList<>(); XWikiAttachment blaAtt = new XWikiAttachment(); - String attName = "bla.txt"; - blaAtt.setFilename(attName); - blaAtt.setDoc(abDoc); + blaAtt.setFilename("bla.txt"); + blaAtt.setDoc(abdoc); attachList.add(blaAtt); - abDoc.setAttachmentList(attachList); + abdoc.setAttachmentList(attachList); URL tstURL = new URL(resultURL); expect(mockURLFactory.createAttachmentURL(eq("bla.txt"), eq("A"), eq("B"), eq("file"), (String) eq(null), eq("celements2web"), same(context))).andReturn(tstURL); expect(mockURLFactory.getURL(eq(tstURL), same(context))).andReturn(resultURL); - expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); + expect(wiki.getDocument(eq("celements2web:A.B"), same(context))).andReturn(abdoc).anyTimes(); expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); - expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) - .atLeastOnce(); replayDefault(); String attachmentURL = attUrlCmd.getAttachmentURL("celements2web:A.B;bla.txt", context); assertTrue(attachmentURL, attachmentURL.matches(resultURL + "\\?version=\\d{14}")); @@ -131,21 +120,17 @@ public void test_getAttachmentURL_partInternalLink() throws Exception { expect(mockURLFactory.createAttachmentURL(eq("bla.txt"), eq("A"), eq("B"), eq("file"), (String) eq(null), eq(context.getDatabase()), same(context))).andReturn(tstURL); expect(mockURLFactory.getURL(eq(tstURL), same(context))).andReturn(resultURL); - DocumentReference abDocRef = new RefBuilder().wiki(getContext().getDatabase()).space("A") - .doc("B").build(DocumentReference.class); - XWikiDocument abDoc = new XWikiDocument(abDocRef); + XWikiDocument abdoc = new XWikiDocument(); + abdoc.setFullName("A.B"); List attachList = new ArrayList<>(); XWikiAttachment blaAtt = new XWikiAttachment(); - String attName = "bla.txt"; - blaAtt.setFilename(attName); - blaAtt.setDoc(abDoc); + blaAtt.setFilename("bla.txt"); + blaAtt.setDoc(abdoc); attachList.add(blaAtt); - abDoc.setAttachmentList(attachList); - expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); + abdoc.setAttachmentList(attachList); + expect(wiki.getDocument(eq("A.B"), same(context))).andReturn(abdoc).anyTimes(); expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); - expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) - .atLeastOnce(); replayDefault(); String attachmentURL = attUrlCmd.getAttachmentURL("A.B;bla.txt", context); assertTrue(attachmentURL, attachmentURL.matches(resultURL + "\\?version=\\d{14}")); @@ -154,19 +139,15 @@ public void test_getAttachmentURL_partInternalLink() throws Exception { @Test public void test_getAttachmentURL_partInternalLink_notExists() throws Exception { - DocumentReference abDocRef = new RefBuilder().wiki(getContext().getDatabase()).space("A") - .doc("B").build(DocumentReference.class); - XWikiDocument abDoc = new XWikiDocument(abDocRef); - expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); - String attName = "bla.txt"; - AttachmentReference attRef = new RefBuilder().with(abDocRef).att(attName) - .build(AttachmentReference.class); - expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))) - .andThrow(new AttachmentNotExistsException(attRef)).atLeastOnce(); + XWikiDocument abdoc = new XWikiDocument(); + abdoc.setFullName("A.B"); + expect(wiki.getDocument(eq("A.B"), same(context))).andReturn(abdoc).anyTimes(); + expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( + "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); replayDefault(); - assertThrows(FileNotExistException.class, - () -> attUrlCmd.getAttachmentURL("A.B;bla.txt", Optional.empty())); + assertNull(attUrlCmd.getAttachmentURL("A.B;bla.txt", context)); verifyDefault(); + } @Test @@ -244,51 +225,4 @@ public void test_getAttachmentURLPrefix() throws Exception { verifyDefault(); } - @Test - public void test_getAttachmentURL_onDisk_queryString() throws Exception { - String resultURL = "/appname/skin/resources/celJS/bla.js"; - expect(wiki.getSkinFile(eq("celJS/bla.js"), eq(true), same(context))).andReturn(resultURL); - expect(wiki.getResourceLastModificationDate(eq("resources/celJS/bla.js"))).andReturn( - new Date()); - expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( - "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("download"); - String queryString = "asf=oiu"; - replayDefault(); - String attachmentURL = attUrlCmd.getAttachmentURL(":celJS/bla.js", Optional.empty(), - Optional.of(queryString)); - String expectedURL = "/appname/download/resources/celJS/bla.js"; - assertTrue(attachmentURL, - attachmentURL.matches(expectedURL + "\\?version=\\d{14}\\&" + queryString)); - verifyDefault(); - } - - @Test - public void test_getAttachmentURL_partInternalLink_queryString() throws Exception { - String resultURL = "http://mydomain.ch/testAction/A/B/bla.txt"; - URL tstURL = new URL(resultURL); - expect(mockURLFactory.createAttachmentURL(eq("bla.txt"), eq("A"), eq("B"), eq("testAction"), - (String) eq(null), eq(context.getDatabase()), same(context))).andReturn(tstURL); - expect(mockURLFactory.getURL(eq(tstURL), same(context))).andReturn(resultURL); - DocumentReference abDocRef = new RefBuilder().wiki(getContext().getDatabase()).space("A") - .doc("B").build(DocumentReference.class); - XWikiDocument abDoc = new XWikiDocument(abDocRef); - List attachList = new ArrayList<>(); - XWikiAttachment blaAtt = new XWikiAttachment(); - String attName = "bla.txt"; - blaAtt.setFilename(attName); - blaAtt.setDoc(abDoc); - attachList.add(blaAtt); - abDoc.setAttachmentList(attachList); - expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); - expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) - .atLeastOnce(); - String queryString = "asf=oiu"; - replayDefault(); - String attachmentURL = attUrlCmd.getAttachmentURL("A.B;bla.txt", Optional.of("testAction"), - Optional.of(queryString)); - assertTrue(attachmentURL, - attachmentURL.matches(resultURL + "\\?version=\\d{14}\\&" + queryString)); - verifyDefault(); - } - } From ab8fd7cbc8c1cd1be3378b9661a1695df558c07a Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Mon, 7 Feb 2022 08:04:38 +0100 Subject: [PATCH 11/29] add FileReference --- .../filebase/references/FileReference.java | 181 ++++++++++++++++++ .../references/FileReferenceType.java | 7 + .../references/FileReferenceTest.java | 60 ++++++ 3 files changed, 248 insertions(+) create mode 100644 src/main/java/com/celements/filebase/references/FileReference.java create mode 100644 src/main/java/com/celements/filebase/references/FileReferenceType.java create mode 100644 src/test/java/com/celements/filebase/references/FileReferenceTest.java diff --git a/src/main/java/com/celements/filebase/references/FileReference.java b/src/main/java/com/celements/filebase/references/FileReference.java new file mode 100644 index 000000000..d726ac669 --- /dev/null +++ b/src/main/java/com/celements/filebase/references/FileReference.java @@ -0,0 +1,181 @@ +package com.celements.filebase.references; + +import static com.google.common.base.Preconditions.*; + +import java.io.Serializable; +import java.util.Objects; +import java.util.function.Supplier; +import java.util.regex.Pattern; + +import javax.annotation.Nullable; +import javax.annotation.concurrent.NotThreadSafe; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + +import org.xwiki.model.reference.DocumentReference; + +import com.celements.model.util.ModelUtils; +import com.google.common.base.Strings; +import com.google.common.base.Suppliers; +import com.google.errorprone.annotations.Immutable; +import com.xpn.xwiki.web.Utils; + +@Immutable +public class FileReference implements Serializable { + + private static final long serialVersionUID = 1L; + + @NotThreadSafe + public static final class Builder { + + private static final String ATTACHMENT_LINK_REGEX = "([\\w\\-]*:)?([\\w\\-]*\\.[\\w\\-]*){1};.*"; + private static final Supplier ATTACHMENT_LINK_PATTERN = Suppliers + .memoize(() -> Pattern.compile(ATTACHMENT_LINK_REGEX)); + private static final String ON_DISK_LINK_REGEX = "^:[/\\w\\-\\.]*"; + private static final Supplier ON_DISK_LINK_PATTERN = Suppliers + .memoize(() -> Pattern.compile(ON_DISK_LINK_REGEX)); + + private String name; + private FileReferenceType type; + private DocumentReference docRef; + + private String fullPath; + + @NotNull + private static String getAttachmentName(@NotEmpty String link) { + return link.split(";")[1]; + } + + @NotNull + private static String getPathFileName(@NotEmpty String link) { + String[] linkParts = link.split("/"); + return linkParts[linkParts.length - 1]; + } + + private static boolean isAttachmentLink(@Nullable String link) { + if (link != null) { + return ATTACHMENT_LINK_PATTERN.get().matcher(link.trim()).matches(); + } + return false; + } + + private static boolean isOnDiskLink(@Nullable String link) { + if (link != null) { + return ON_DISK_LINK_PATTERN.get().matcher(link.trim()).matches(); + } + return false; + } + + @NotNull + private static DocumentReference getPageDocRef(@NotNull String link) { + return Utils.getComponent(ModelUtils.class).resolveRef(link.split(";")[0], + DocumentReference.class); + } + + private static FileReferenceType getTypeOfLink(@NotEmpty String link) { + if (isOnDiskLink(link)) { + return FileReferenceType.ON_DISK; + } else if (isAttachmentLink(link)) { + return FileReferenceType.ATTACHMENT; + } + return FileReferenceType.EXTERNAL; + } + + public Builder setFileName(@NotEmpty String fileName) { + checkArgument(!Strings.isNullOrEmpty(fileName), "fileName may not be empty"); + this.name = fileName; + return this; + } + + public Builder setType(@NotNull FileReferenceType type) { + checkNotNull(type); + this.type = type; + return this; + } + + public void setDocRef(@NotNull DocumentReference docRef) { + checkNotNull(docRef); + this.docRef = docRef; + } + + public void setFullPath(@NotEmpty String fullPath) { + checkArgument(!Strings.isNullOrEmpty(fullPath), "fileName may not be empty"); + this.fullPath = fullPath; + } + + public FileReference build() { + return new FileReference(this); + } + } + + private final String name; + private final FileReferenceType type; + private final DocumentReference docRef; + private final String fullPath; + + public FileReference(Builder builder) { + this.name = builder.name; + this.type = builder.type; + this.fullPath = builder.fullPath; + this.docRef = builder.docRef; + } + + public String getName() { + return name; + } + + public FileReferenceType getType() { + return type; + } + + public DocumentReference getDocRef() { + return docRef; + } + + public String getFullPath() { + return fullPath; + } + + public boolean isAttachmentReference() { + return type == FileReferenceType.ATTACHMENT; + } + + public boolean isOnDiskReference() { + return type == FileReferenceType.ON_DISK; + } + + @Override + public int hashCode() { + return Objects.hash(name, type, docRef, fullPath); + } + + @Override + public boolean equals(@Nullable Object obj) { + return (obj instanceof FileReference) + && Objects.equals(((FileReference) obj).name, this.name) + && Objects.equals(((FileReference) obj).type, this.type) + && Objects.equals(((FileReference) obj).docRef, this.docRef) + && Objects.equals(((FileReference) obj).fullPath, this.fullPath); + } + + @Override + public String toString() { + return "FileReference [name=" + name + ", type=" + type + ", docRef=" + docRef + ", fullPath=" + + fullPath + "]"; + } + + public static Builder of(@NotEmpty String link) { + checkArgument(!Strings.isNullOrEmpty(link), "fileName may not be empty"); + Builder builder = new Builder(); + builder.setType(Builder.getTypeOfLink(link)); + if (builder.type == FileReferenceType.ATTACHMENT) { + builder.setFileName(Builder.getAttachmentName(link)); + builder.setDocRef(Builder.getPageDocRef(link)); + } else { + builder.setFileName(Builder.getPathFileName(link)); + builder.setFullPath(link); + } + return builder; + } + +} diff --git a/src/main/java/com/celements/filebase/references/FileReferenceType.java b/src/main/java/com/celements/filebase/references/FileReferenceType.java new file mode 100644 index 000000000..c04a221d2 --- /dev/null +++ b/src/main/java/com/celements/filebase/references/FileReferenceType.java @@ -0,0 +1,7 @@ +package com.celements.filebase.references; + +public enum FileReferenceType { + + ON_DISK, ATTACHMENT, EXTERNAL; + +} diff --git a/src/test/java/com/celements/filebase/references/FileReferenceTest.java b/src/test/java/com/celements/filebase/references/FileReferenceTest.java new file mode 100644 index 000000000..7d8396d46 --- /dev/null +++ b/src/test/java/com/celements/filebase/references/FileReferenceTest.java @@ -0,0 +1,60 @@ +package com.celements.filebase.references; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + +import com.celements.common.test.AbstractComponentTest; + +public class FileReferenceTest extends AbstractComponentTest { + + @Before + public void setUp_FileReferenceTest() throws Exception {} + + @Test + public void test_isAttachmentLink_null() { + assertThrows(IllegalArgumentException.class, () -> FileReference.of(null)); + } + + @Test + public void test_isAttachmentLink_empty() { + assertThrows(IllegalArgumentException.class, () -> FileReference.of("")); + } + + @Test + public void test_isAttachmentLink_url() { + assertFalse( + FileReference.of("/download/Space/Page/attachment.jpg").build().isAttachmentReference()); + } + + @Test + public void test_isAttachmentLink_is() { + assertTrue(FileReference.of("Space.Page;attachment.jpg").build().isAttachmentReference()); + } + + @Test + public void test_isAttachmentLink_isSpecialChars() { + assertTrue(FileReference.of("Teilnehmer.f8Nx9vyPOX8O2;Hans-002-Bearbeitet-2.jpg").build() + .isAttachmentReference()); + } + + @Test + public void test_isAttachmentLink_isWithDb() { + assertTrue(FileReference.of("db:Space.Page;attachment.jpg").build().isAttachmentReference()); + } + + @Test + public void test_isOnDiskLink_true() { + assertTrue(FileReference.of(":bla.js").build().isOnDiskReference()); + assertTrue(FileReference.of(" :celJS/bla.js").build().isOnDiskReference()); + } + + @Test + public void test_isOnDiskLink_false() { + assertFalse(FileReference.of("bla.js").build().isOnDiskReference()); + assertFalse(FileReference.of("x:celJS/bla.js").build().isOnDiskReference()); + assertFalse(FileReference.of("x:A.B;bla.js").build().isOnDiskReference()); + } + +} From 504b79cdc39ad70d4780a22e47f37525280b28c3 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Mon, 7 Feb 2022 12:04:52 +0100 Subject: [PATCH 12/29] refactor FileUriService to use FileReference --- .../filebase/uri/FileNotExistException.java | 23 ++-- .../filebase/uri/FileUriService.java | 91 +++++---------- .../filebase/uri/FileUriServiceRole.java | 24 ++-- .../filebase/uri/FileUriServiceTest.java | 109 ++++++------------ 4 files changed, 85 insertions(+), 162 deletions(-) diff --git a/src/main/java/com/celements/filebase/uri/FileNotExistException.java b/src/main/java/com/celements/filebase/uri/FileNotExistException.java index e51818823..c30041b3f 100644 --- a/src/main/java/com/celements/filebase/uri/FileNotExistException.java +++ b/src/main/java/com/celements/filebase/uri/FileNotExistException.java @@ -2,28 +2,31 @@ import javax.validation.constraints.NotNull; +import com.celements.filebase.references.FileReference; + public class FileNotExistException extends Exception { private static final long serialVersionUID = 1L; - private final String ressource; - public FileNotExistException(@NotNull String ressource) { - super("Url ressource [" + ressource + "] does not exist."); - this.ressource = ressource; + private final FileReference fileReference; + + public FileNotExistException(@NotNull FileReference fileRef) { + super("Url fileRef [" + fileRef + "] does not exist."); + this.fileReference = fileRef; } - public FileNotExistException(@NotNull String message, @NotNull String ressource) { + public FileNotExistException(@NotNull String message, @NotNull FileReference fileRef) { super(message); - this.ressource = ressource; + this.fileReference = fileRef; } - public FileNotExistException(@NotNull String message, @NotNull String ressource, + public FileNotExistException(@NotNull String message, @NotNull FileReference fileRef, Exception wrapExp) { super(message, wrapExp); - this.ressource = ressource; + this.fileReference = fileRef; } - public String getRessource() { - return ressource; + public FileReference getFileReference() { + return fileReference; } } diff --git a/src/main/java/com/celements/filebase/uri/FileUriService.java b/src/main/java/com/celements/filebase/uri/FileUriService.java index a834cd5f7..1c3d461f8 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriService.java @@ -2,10 +2,7 @@ import java.net.MalformedURLException; import java.util.Optional; -import java.util.function.Supplier; -import java.util.regex.Pattern; -import javax.annotation.Nullable; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; @@ -13,16 +10,15 @@ import org.slf4j.LoggerFactory; import org.xwiki.component.annotation.Component; import org.xwiki.component.annotation.Requirement; -import org.xwiki.model.reference.DocumentReference; import com.celements.filebase.IAttachmentServiceRole; +import com.celements.filebase.references.FileReference; import com.celements.model.access.IModelAccessFacade; import com.celements.model.access.exception.AttachmentNotExistsException; import com.celements.model.access.exception.DocumentNotExistsException; import com.celements.model.context.ModelContext; import com.celements.model.util.ModelUtils; import com.celements.web.service.LastStartupTimeStampRole; -import com.google.common.base.Suppliers; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.web.XWikiURLFactory; @@ -30,13 +26,6 @@ @Component public class FileUriService implements FileUriServiceRole { - private static final String ATTACHMENT_LINK_REGEX = "([\\w\\-]*:)?([\\w\\-]*\\.[\\w\\-]*){1};.*"; - private static final Supplier ATTACHMENT_LINK_PATTERN = Suppliers - .memoize(() -> Pattern.compile(ATTACHMENT_LINK_REGEX)); - private static final String ON_DISK_LINK_REGEX = "^:[/\\w\\-\\.]*"; - private static final Supplier ON_DISK_LINK_PATTERN = Suppliers - .memoize(() -> Pattern.compile(ON_DISK_LINK_REGEX)); - private static final Logger LOGGER = LoggerFactory.getLogger(FileUriService.class); @Requirement @@ -54,34 +43,6 @@ public class FileUriService implements FileUriServiceRole { @Requirement private LastStartupTimeStampRole lastStartupTimeStamp; - @Override - @NotNull - public String getAttachmentName(@NotNull String link) { - return link.split(";")[1]; - } - - @Override - @NotNull - public DocumentReference getPageDocRef(@NotNull String link) { - return modelUtils.resolveRef(link.split(";")[0], DocumentReference.class); - } - - @Override - public boolean isAttachmentLink(String link) { - if (link != null) { - return ATTACHMENT_LINK_PATTERN.get().matcher(link.trim()).matches(); - } - return false; - } - - @Override - public boolean isOnDiskLink(@Nullable String link) { - if (link != null) { - return ON_DISK_LINK_PATTERN.get().matcher(link.trim()).matches(); - } - return false; - } - private String getDefaultAction() { return context.getXWikiContext().getWiki().getXWikiPreference("celdefaultAttAction", "celements.attachmenturl.defaultaction", "file", context.getXWikiContext()); @@ -89,13 +50,13 @@ private String getDefaultAction() { @Override @NotEmpty - public String getRessourceURLPrefix() { - return getRessourceURLPrefix(getDefaultAction()); + public String getFileURLPrefix() { + return getFileURLPrefix(getDefaultAction()); } @Override @NotEmpty - public String getRessourceURLPrefix(@NotEmpty String action) { + public String getFileURLPrefix(@NotEmpty String action) { XWikiURLFactory urlf = context.getXWikiContext().getURLFactory(); return urlf.createResourceURL("", true, context.getXWikiContext()).toString().replace("/skin/", "/" + action + "/"); @@ -103,11 +64,11 @@ public String getRessourceURLPrefix(@NotEmpty String action) { @Override @NotNull - public String getExternalRessourceURL(@NotNull String fileName, + public String getExternalFileURL(@NotNull FileReference fileRef, @NotNull Optional action) { try { return context.getXWikiContext().getURLFactory().getServerURL(context.getXWikiContext()) - .toExternalForm() + createRessourceUrl(fileName, action); + .toExternalForm() + createFileUrl(fileRef, action); } catch (MalformedURLException | FileNotExistException exp) { LOGGER.error("Failed to getServerURL.", exp); } @@ -116,9 +77,9 @@ public String getExternalRessourceURL(@NotNull String fileName, @Override @NotNull - public String createRessourceUrl(@NotNull String link, @NotNull Optional action, + public String createFileUrl(@NotNull FileReference fileRef, @NotNull Optional action, @NotNull Optional queryString) throws FileNotExistException { - final String baseUrl = createRessourceUrl(link, action); + final String baseUrl = createFileUrl(fileRef, action); if (queryString.isPresent()) { if (baseUrl.indexOf("?") > -1) { return baseUrl + "&" + queryString.get(); @@ -130,13 +91,16 @@ public String createRessourceUrl(@NotNull String link, @NotNull Optional } @Override - public @NotEmpty String createRessourceUrl(@NotNull String link, @NotNull Optional action) + public @NotEmpty String createFileUrl(@NotNull FileReference fileRef, + @NotNull Optional action) throws FileNotExistException { - String url = link; - if (isAttachmentLink(link)) { - url = createAttachmentUrl(link, action); - } else if (isOnDiskLink(link)) { - url = createOnDiskUrl(link, action); + String url; + if (fileRef.isAttachmentReference()) { + url = createAttachmentUrl(fileRef, action); + } else if (fileRef.isOnDiskReference()) { + url = createOnDiskUrl(fileRef, action); + } else { + url = fileRef.getFullPath(); } return addContextUrl(url); } @@ -149,27 +113,28 @@ private String addContextUrl(String url) { return url; } - private String createAttachmentUrl(String link, Optional action) + private String createAttachmentUrl(@NotNull FileReference fileRef, Optional action) throws FileNotExistException { - String attName = getAttachmentName(link); + String attName = fileRef.getName(); try { - XWikiDocument doc = modelAccess.getDocument(getPageDocRef(link)); + XWikiDocument doc = modelAccess.getDocument(fileRef.getDocRef()); XWikiAttachment att = attachmentSrv.getAttachmentNameEqual(doc, attName); - return doc.getAttachmentURL(attName, action.orElse(getDefaultAction()), context.getXWikiContext()) + return doc.getAttachmentURL(attName, action.orElse(getDefaultAction()), + context.getXWikiContext()) + "?version=" + lastStartupTimeStamp.getLastChangedTimeStamp(att.getDate()); } catch (DocumentNotExistsException exp) { - LOGGER.error("Error getting attachment URL for doc '{}' and file {}", getPageDocRef(link), + LOGGER.error("Error getting attachment URL for doc '{}' and file {}", fileRef.getDocRef(), attName, exp); - throw new FileNotExistException(link); + throw new FileNotExistException(fileRef); } catch (AttachmentNotExistsException anee) { - LOGGER.info("Attachment not found for link [{}] and action [{}]", link, action, anee); - throw new FileNotExistException(link); + LOGGER.info("Attachment not found for link [{}] and action [{}]", fileRef, action, anee); + throw new FileNotExistException(fileRef); } } - private String createOnDiskUrl(String link, Optional action) { + private String createOnDiskUrl(@NotNull FileReference fileRef, Optional action) { String url; - String path = link.trim().substring(1); + String path = fileRef.getFullPath().trim().substring(1); url = context.getXWikiContext().getWiki().getSkinFile(path, true, context.getXWikiContext()) .replace("/skin/", "/" + action.orElse(getDefaultAction()) + "/"); diff --git a/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java b/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java index 9946901f6..1987027cc 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java +++ b/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java @@ -2,41 +2,31 @@ import java.util.Optional; -import javax.annotation.Nullable; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import org.xwiki.component.annotation.ComponentRole; -import org.xwiki.model.reference.DocumentReference; + +import com.celements.filebase.references.FileReference; @ComponentRole public interface FileUriServiceRole { @NotNull - public String getAttachmentName(@NotNull String link); - - @NotNull - DocumentReference getPageDocRef(@NotNull String link); - - boolean isAttachmentLink(String link); - - boolean isOnDiskLink(@Nullable String link); - - @NotNull - String createRessourceUrl(@NotNull String jsFile, @NotNull Optional action, + String createFileUrl(@NotNull FileReference fileRef, @NotNull Optional action, @NotNull Optional queryString) throws FileNotExistException; @NotEmpty - String createRessourceUrl(@NotNull String link, @NotNull Optional action) + String createFileUrl(@NotNull FileReference fileRef, @NotNull Optional action) throws FileNotExistException; @NotEmpty - String getRessourceURLPrefix(@NotEmpty String action); + String getFileURLPrefix(@NotEmpty String action); @NotEmpty - String getRessourceURLPrefix(); + String getFileURLPrefix(); @NotNull - String getExternalRessourceURL(@NotNull String fileName, @NotNull Optional action); + String getExternalFileURL(@NotNull FileReference fileRef, @NotNull Optional action); } diff --git a/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java index 487036fc5..3bcb4f34a 100644 --- a/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java +++ b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java @@ -16,6 +16,7 @@ import org.xwiki.model.reference.DocumentReference; import com.celements.common.test.AbstractComponentTest; +import com.celements.filebase.references.FileReference; import com.celements.model.access.IModelAccessFacade; import com.celements.model.access.exception.AttachmentNotExistsException; import com.celements.model.reference.RefBuilder; @@ -45,19 +46,20 @@ public void setUp_RessourceUrlServiceTest() throws Exception { } @Test - public void test_createRessourceUrl_fullURL() throws Exception { - assertEquals("http://www.bla.com/bla.txt", resUrlServ.createRessourceUrl( - "http://www.bla.com/bla.txt", Optional.empty())); + public void test_createFileUrl_fullURL() throws Exception { + FileReference fileRef = FileReference.of("http://www.bla.com/bla.txt").build(); + assertEquals("http://www.bla.com/bla.txt", resUrlServ.createFileUrl(fileRef, Optional.empty())); } @Test - public void test_createRessourceUrl_partURL() throws Exception { - assertEquals("/xwiki/bin/download/A/B/bla.txt", resUrlServ.createRessourceUrl( - "/xwiki/bin/download/A/B/bla.txt", Optional.empty())); + public void test_createFileUrl_partURL() throws Exception { + FileReference fileRef = FileReference.of("/xwiki/bin/download/A/B/bla.txt").build(); + assertEquals("/xwiki/bin/download/A/B/bla.txt", resUrlServ.createFileUrl(fileRef, + Optional.empty())); } @Test - public void test_createRessourceUrl_dynamicParamURL() throws Exception { + public void test_createFileUrl_dynamicParamURL() throws Exception { String mySpaceName = "mySpace"; String myDocName = "myDoc"; DocumentReference myDocRef = new DocumentReference(context.getDatabase(), mySpaceName, @@ -69,13 +71,14 @@ public void test_createRessourceUrl_dynamicParamURL() throws Exception { (String) isNull(), eq(context.getDatabase()), same(context))).andReturn(viewURL); expect(mockURLFactory.getURL(eq(viewURL), same(context))).andReturn(viewURL.getPath()); replayDefault(); - assertEquals("/mySpace/myDoc?xpage=bla&bli=blu", resUrlServ.createRessourceUrl( - "?xpage=bla&bli=blu", Optional.empty())); + FileReference fileRef = FileReference.of("?xpage=bla&bli=blu").build(); + assertEquals("/mySpace/myDoc?xpage=bla&bli=blu", resUrlServ.createFileUrl(fileRef, + Optional.empty())); verifyDefault(); } @Test - public void test_createRessourceUrl_fullInternalLink() throws Exception { + public void test_createFileUrl_fullInternalLink() throws Exception { String resultURL = "http://celements2web.localhost/file/A/B/bla.txt"; DocumentReference abDocRef = new RefBuilder().wiki("celements2web").space("A").doc("B") .build(DocumentReference.class); @@ -97,8 +100,8 @@ public void test_createRessourceUrl_fullInternalLink() throws Exception { expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) .atLeastOnce(); replayDefault(); - String attachmentURL = resUrlServ.createRessourceUrl("celements2web:A.B;bla.txt", - Optional.empty()); + FileReference fileRef = FileReference.of("celements2web:A.B;bla.txt").build(); + String attachmentURL = resUrlServ.createFileUrl(fileRef, Optional.empty()); assertNotNull(attachmentURL); assertTrue("expecting " + resultURL + " but got " + attachmentURL, attachmentURL.matches(resultURL + "\\?version=\\d{14}")); @@ -106,7 +109,7 @@ public void test_createRessourceUrl_fullInternalLink() throws Exception { } @Test - public void test_createRessourceUrl_partInternalLink() throws Exception { + public void test_createFileUrl_partInternalLink() throws Exception { String resultURL = "http://mydomain.ch/file/A/B/bla.txt"; URL tstURL = new URL(resultURL); expect(mockURLFactory.createAttachmentURL(eq("bla.txt"), eq("A"), eq("B"), eq("file"), @@ -128,7 +131,8 @@ public void test_createRessourceUrl_partInternalLink() throws Exception { expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) .atLeastOnce(); replayDefault(); - String attachmentURL = resUrlServ.createRessourceUrl("A.B;bla.txt", Optional.empty()); + FileReference fileRef = FileReference.of("A.B;bla.txt").build(); + String attachmentURL = resUrlServ.createFileUrl(fileRef, Optional.empty()); assertNotNull(attachmentURL); assertTrue("expecting " + resultURL + " but got " + attachmentURL, attachmentURL.matches(resultURL + "\\?version=\\d{14}")); @@ -136,7 +140,7 @@ public void test_createRessourceUrl_partInternalLink() throws Exception { } @Test - public void test_createRessourceUrl_partInternalLink_notExists() throws Exception { + public void test_createFileUrl_partInternalLink_notExists() throws Exception { DocumentReference abDocRef = new RefBuilder().wiki(getContext().getDatabase()).space("A") .doc("B").build(DocumentReference.class); XWikiDocument abDoc = new XWikiDocument(abDocRef); @@ -147,13 +151,14 @@ public void test_createRessourceUrl_partInternalLink_notExists() throws Exceptio expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))) .andThrow(new AttachmentNotExistsException(attRef)).atLeastOnce(); replayDefault(); + FileReference fileRef = FileReference.of("A.B;bla.txt").build(); assertThrows(FileNotExistException.class, - () -> resUrlServ.createRessourceUrl("A.B;bla.txt", Optional.empty())); + () -> resUrlServ.createFileUrl(fileRef, Optional.empty())); verifyDefault(); } @Test - public void test_createRessourceUrl_onDiskLink() throws Exception { + public void test_createFileUrl_onDiskLink() throws Exception { String resultURL = "/appname/skin/resources/celJS/bla.js"; expect(wiki.getSkinFile(eq("celJS/bla.js"), eq(true), same(context))).andReturn(resultURL); expect(wiki.getResourceLastModificationDate(eq("resources/celJS/bla.js"))).andReturn( @@ -161,8 +166,8 @@ public void test_createRessourceUrl_onDiskLink() throws Exception { expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("download"); replayDefault(); - String attachmentURL = resUrlServ.createRessourceUrl(" :celJS/bla.js", Optional.empty(), - Optional.empty()); + FileReference fileRef = FileReference.of(" :celJS/bla.js").build(); + String attachmentURL = resUrlServ.createFileUrl(fileRef, Optional.empty(), Optional.empty()); String expectedURL = "/appname/download/resources/celJS/bla.js"; assertNotNull(attachmentURL); assertTrue("expecting " + expectedURL + " but got " + attachmentURL, @@ -171,69 +176,25 @@ public void test_createRessourceUrl_onDiskLink() throws Exception { } @Test - public void test_createRessourceUrl_Rubish() throws Exception { + public void test_createFileUrl_Rubish() throws Exception { + FileReference fileRef = FileReference.of("http://A.B;bla.txt").build(); assertEquals("http://A.B;bla.txt", - resUrlServ.createRessourceUrl("http://A.B;bla.txt", Optional.empty(), - Optional.empty()).toString()); + resUrlServ.createFileUrl(fileRef, Optional.empty(), Optional.empty()).toString()); } @Test - public void test_isAttachmentLink_null() { - assertFalse(resUrlServ.isAttachmentLink(null)); - } - - @Test - public void test_isAttachmentLink_empty() { - assertFalse(resUrlServ.isAttachmentLink("")); - } - - @Test - public void test_isAttachmentLink_url() { - assertFalse(resUrlServ.isAttachmentLink("/download/Space/Page/attachment.jpg")); - } - - @Test - public void test_isAttachmentLink_is() { - assertTrue(resUrlServ.isAttachmentLink("Space.Page;attachment.jpg")); - } - - @Test - public void test_isAttachmentLink_isSpecialChars() { - assertTrue(resUrlServ.isAttachmentLink("Teilnehmer.f8Nx9vyPOX8O2;Hans-002-Bearbeitet-2.jpg")); - } - - @Test - public void test_isAttachmentLink_isWithDb() { - assertTrue(resUrlServ.isAttachmentLink("db:Space.Page;attachment.jpg")); - } - - @Test - public void test_isOnDiskLink_true() { - assertTrue(resUrlServ.isOnDiskLink(":bla.js")); - assertTrue(resUrlServ.isOnDiskLink(" :celJS/bla.js")); - } - - @Test - public void test_isOnDiskLink_false() { - assertFalse(resUrlServ.isOnDiskLink("bla.js")); - assertFalse(resUrlServ.isOnDiskLink("x:celJS/bla.js")); - assertFalse(resUrlServ.isOnDiskLink("x:A.B;bla.js")); - } - - @Test - public void test_getRessourceURLPrefix() throws Exception { + public void test_getFileURLPrefix() throws Exception { expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); expect(mockURLFactory.createResourceURL(eq(""), eq(true), same(context))).andReturn(new URL( "http://test.fabian.dev:10080/skin/resources/")); replayDefault(); - assertEquals("http://test.fabian.dev:10080/file/resources/", - resUrlServ.getRessourceURLPrefix()); + assertEquals("http://test.fabian.dev:10080/file/resources/", resUrlServ.getFileURLPrefix()); verifyDefault(); } @Test - public void test_getAttachmentURL_onDisk_queryString() throws Exception { + public void test_createFileUrl_onDisk_queryString() throws Exception { String resultURL = "/appname/skin/resources/celJS/bla.js"; expect(wiki.getSkinFile(eq("celJS/bla.js"), eq(true), same(context))).andReturn(resultURL); expect(wiki.getResourceLastModificationDate(eq("resources/celJS/bla.js"))).andReturn( @@ -242,7 +203,8 @@ public void test_getAttachmentURL_onDisk_queryString() throws Exception { "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("download"); String queryString = "asf=oiu"; replayDefault(); - String attachmentURL = resUrlServ.createRessourceUrl(":celJS/bla.js", Optional.empty(), + FileReference fileRef = FileReference.of(":celJS/bla.js").build(); + String attachmentURL = resUrlServ.createFileUrl(fileRef, Optional.empty(), Optional.of(queryString)); String expectedURL = "/appname/download/resources/celJS/bla.js"; assertTrue(attachmentURL, @@ -251,7 +213,7 @@ public void test_getAttachmentURL_onDisk_queryString() throws Exception { } @Test - public void test_getAttachmentURL_partInternalLink_queryString() throws Exception { + public void test_createFileUrl_partInternalLink_queryString() throws Exception { String resultURL = "http://mydomain.ch/testAction/A/B/bla.txt"; URL tstURL = new URL(resultURL); expect(mockURLFactory.createAttachmentURL(eq("bla.txt"), eq("A"), eq("B"), eq("testAction"), @@ -270,9 +232,12 @@ public void test_getAttachmentURL_partInternalLink_queryString() throws Exceptio expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) .atLeastOnce(); + expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( + "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); String queryString = "asf=oiu"; replayDefault(); - String attachmentURL = resUrlServ.createRessourceUrl("A.B;bla.txt", Optional.of("testAction"), + FileReference fileRef = FileReference.of("A.B;bla.txt").build(); + String attachmentURL = resUrlServ.createFileUrl(fileRef, Optional.of("testAction"), Optional.of(queryString)); assertTrue(attachmentURL, attachmentURL.matches(resultURL + "\\?version=\\d{14}\\&" + queryString)); From b9feaa7a750038051c6dfd52a02477452125e498 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Mon, 7 Feb 2022 15:15:38 +0100 Subject: [PATCH 13/29] change return types to UriBuilder --- .../filebase/references/FileReference.java | 43 +++++++--- .../filebase/uri/FileUriService.java | 55 +++++++------ .../filebase/uri/FileUriServiceRole.java | 7 +- .../filebase/uri/FileUriServiceTest.java | 81 +++++++++++++++---- 4 files changed, 129 insertions(+), 57 deletions(-) diff --git a/src/main/java/com/celements/filebase/references/FileReference.java b/src/main/java/com/celements/filebase/references/FileReference.java index d726ac669..8df84a266 100644 --- a/src/main/java/com/celements/filebase/references/FileReference.java +++ b/src/main/java/com/celements/filebase/references/FileReference.java @@ -11,6 +11,7 @@ import javax.annotation.concurrent.NotThreadSafe; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; +import javax.ws.rs.core.UriBuilder; import org.xwiki.model.reference.DocumentReference; @@ -38,8 +39,8 @@ public static final class Builder { private String name; private FileReferenceType type; private DocumentReference docRef; - private String fullPath; + private String queryString; @NotNull private static String getAttachmentName(@NotEmpty String link) { @@ -81,8 +82,8 @@ private static FileReferenceType getTypeOfLink(@NotEmpty String link) { return FileReferenceType.EXTERNAL; } - public Builder setFileName(@NotEmpty String fileName) { - checkArgument(!Strings.isNullOrEmpty(fileName), "fileName may not be empty"); + public Builder setFileName(@NotNull String fileName) { + checkNotNull(fileName); this.name = fileName; return this; } @@ -98,26 +99,34 @@ public void setDocRef(@NotNull DocumentReference docRef) { this.docRef = docRef; } - public void setFullPath(@NotEmpty String fullPath) { - checkArgument(!Strings.isNullOrEmpty(fullPath), "fileName may not be empty"); + public void setFullPath(@NotNull String fullPath) { + checkNotNull(fullPath); this.fullPath = fullPath; } + public void setQueryString(@NotNull String queryString) { + checkNotNull(queryString); + this.queryString = queryString; + } + public FileReference build() { return new FileReference(this); } + } private final String name; private final FileReferenceType type; private final DocumentReference docRef; private final String fullPath; + private final String queryString; public FileReference(Builder builder) { this.name = builder.name; this.type = builder.type; this.fullPath = builder.fullPath; this.docRef = builder.docRef; + this.queryString = builder.queryString; } public String getName() { @@ -136,6 +145,14 @@ public String getFullPath() { return fullPath; } + public String getQueryString() { + return queryString; + } + + public UriBuilder getUri() { + return UriBuilder.fromPath(fullPath).replaceQuery(queryString); + } + public boolean isAttachmentReference() { return type == FileReferenceType.ATTACHMENT; } @@ -165,15 +182,19 @@ public String toString() { } public static Builder of(@NotEmpty String link) { - checkArgument(!Strings.isNullOrEmpty(link), "fileName may not be empty"); + checkArgument(!Strings.isNullOrEmpty(link), "link may not be empty"); + final String[] linkParts = link.split("\\?"); Builder builder = new Builder(); - builder.setType(Builder.getTypeOfLink(link)); + builder.setType(Builder.getTypeOfLink(linkParts[0])); if (builder.type == FileReferenceType.ATTACHMENT) { - builder.setFileName(Builder.getAttachmentName(link)); - builder.setDocRef(Builder.getPageDocRef(link)); + builder.setFileName(Builder.getAttachmentName(linkParts[0])); + builder.setDocRef(Builder.getPageDocRef(linkParts[0])); } else { - builder.setFileName(Builder.getPathFileName(link)); - builder.setFullPath(link); + builder.setFileName(Builder.getPathFileName(linkParts[0])); + builder.setFullPath(linkParts[0]); + } + if (linkParts.length > 1) { + builder.setQueryString(linkParts[1]); } return builder; } diff --git a/src/main/java/com/celements/filebase/uri/FileUriService.java b/src/main/java/com/celements/filebase/uri/FileUriService.java index 1c3d461f8..c23c90bfd 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriService.java @@ -5,6 +5,7 @@ import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; +import javax.ws.rs.core.UriBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -77,51 +78,53 @@ public String getExternalFileURL(@NotNull FileReference fileRef, @Override @NotNull - public String createFileUrl(@NotNull FileReference fileRef, @NotNull Optional action, + public UriBuilder createFileUrl(@NotNull FileReference fileRef, @NotNull Optional action, @NotNull Optional queryString) throws FileNotExistException { - final String baseUrl = createFileUrl(fileRef, action); + final UriBuilder baseUrl = createFileUrl(fileRef, action); if (queryString.isPresent()) { - if (baseUrl.indexOf("?") > -1) { - return baseUrl + "&" + queryString.get(); + String[] baseQueryParts = baseUrl.toString().split("\\?", 2); + if (baseQueryParts.length > 1) { + return baseUrl.replaceQuery(baseQueryParts[1] + "&" + queryString.get()); } else { - return baseUrl + "?" + queryString.get(); + return baseUrl.replaceQuery(queryString.get()); } } return baseUrl; } @Override - public @NotEmpty String createFileUrl(@NotNull FileReference fileRef, + public @NotNull UriBuilder createFileUrl(@NotNull FileReference fileRef, @NotNull Optional action) throws FileNotExistException { - String url; + UriBuilder uriBuilder; if (fileRef.isAttachmentReference()) { - url = createAttachmentUrl(fileRef, action); + uriBuilder = createAttachmentUrl(fileRef, action); } else if (fileRef.isOnDiskReference()) { - url = createOnDiskUrl(fileRef, action); + uriBuilder = createOnDiskUrl(fileRef, action); } else { - url = fileRef.getFullPath(); + uriBuilder = fileRef.getUri(); } - return addContextUrl(url); + return addContextUrl(uriBuilder); } - private String addContextUrl(String url) { + UriBuilder addContextUrl(UriBuilder uriBuilder) { Optional currentDoc = context.getCurrentDoc().toJavaUtil(); - if (currentDoc.isPresent() && url.startsWith("?")) { - url = currentDoc.get().getURL("view", context.getXWikiContext()) + url; + if (currentDoc.isPresent() && uriBuilder.toString().startsWith("?")) { + uriBuilder.replacePath(currentDoc.get().getURL("view", context.getXWikiContext())); } - return url; + return uriBuilder; } - private String createAttachmentUrl(@NotNull FileReference fileRef, Optional action) + private UriBuilder createAttachmentUrl(@NotNull FileReference fileRef, Optional action) throws FileNotExistException { String attName = fileRef.getName(); try { XWikiDocument doc = modelAccess.getDocument(fileRef.getDocRef()); XWikiAttachment att = attachmentSrv.getAttachmentNameEqual(doc, attName); - return doc.getAttachmentURL(attName, action.orElse(getDefaultAction()), - context.getXWikiContext()) - + "?version=" + lastStartupTimeStamp.getLastChangedTimeStamp(att.getDate()); + + return UriBuilder.fromPath(doc.getAttachmentURL(attName, action.orElse(getDefaultAction()), + context.getXWikiContext())) + .replaceQuery("version=" + lastStartupTimeStamp.getLastChangedTimeStamp(att.getDate())); } catch (DocumentNotExistsException exp) { LOGGER.error("Error getting attachment URL for doc '{}' and file {}", fileRef.getDocRef(), attName, exp); @@ -132,14 +135,14 @@ private String createAttachmentUrl(@NotNull FileReference fileRef, Optional action) { - String url; + UriBuilder createOnDiskUrl(@NotNull FileReference fileRef, Optional action) { String path = fileRef.getFullPath().trim().substring(1); - url = context.getXWikiContext().getWiki().getSkinFile(path, true, context.getXWikiContext()) - .replace("/skin/", - "/" + action.orElse(getDefaultAction()) + "/"); - url += "?version=" + lastStartupTimeStamp.getFileModificationDate(path); - return url; + UriBuilder uri = UriBuilder.fromPath( + context.getXWikiContext().getWiki().getSkinFile(path, true, context.getXWikiContext()) + .replace("/skin/", + "/" + action.orElse(getDefaultAction()) + "/")); + uri.queryParam("version", lastStartupTimeStamp.getFileModificationDate(path)); + return uri; } } diff --git a/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java b/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java index 1987027cc..780333816 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java +++ b/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java @@ -4,6 +4,7 @@ import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; +import javax.ws.rs.core.UriBuilder; import org.xwiki.component.annotation.ComponentRole; @@ -13,11 +14,11 @@ public interface FileUriServiceRole { @NotNull - String createFileUrl(@NotNull FileReference fileRef, @NotNull Optional action, + UriBuilder createFileUrl(@NotNull FileReference fileRef, @NotNull Optional action, @NotNull Optional queryString) throws FileNotExistException; - @NotEmpty - String createFileUrl(@NotNull FileReference fileRef, @NotNull Optional action) + @NotNull + UriBuilder createFileUrl(@NotNull FileReference fileRef, @NotNull Optional action) throws FileNotExistException; @NotEmpty diff --git a/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java index 3bcb4f34a..670ec2777 100644 --- a/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java +++ b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java @@ -5,11 +5,14 @@ import static org.junit.Assert.*; import java.net.URL; +import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; +import javax.ws.rs.core.UriBuilder; + import org.junit.Before; import org.junit.Test; import org.xwiki.model.reference.AttachmentReference; @@ -32,7 +35,7 @@ public class FileUriServiceTest extends AbstractComponentTest { private IModelAccessFacade modelAccessMock; private XWikiContext context; private XWikiURLFactory mockURLFactory; - private FileUriServiceRole resUrlServ; + private FileUriService fileUriServ; private XWiki wiki; @Before @@ -42,20 +45,21 @@ public void setUp_RessourceUrlServiceTest() throws Exception { wiki = getWikiMock(); mockURLFactory = createMockAndAddToDefault(XWikiURLFactory.class); context.setURLFactory(mockURLFactory); - resUrlServ = Utils.getComponent(FileUriServiceRole.class); + fileUriServ = (FileUriService) Utils.getComponent(FileUriServiceRole.class); } @Test public void test_createFileUrl_fullURL() throws Exception { FileReference fileRef = FileReference.of("http://www.bla.com/bla.txt").build(); - assertEquals("http://www.bla.com/bla.txt", resUrlServ.createFileUrl(fileRef, Optional.empty())); + assertEquals("http://www.bla.com/bla.txt", + fileUriServ.createFileUrl(fileRef, Optional.empty()).build().toString()); } @Test public void test_createFileUrl_partURL() throws Exception { FileReference fileRef = FileReference.of("/xwiki/bin/download/A/B/bla.txt").build(); - assertEquals("/xwiki/bin/download/A/B/bla.txt", resUrlServ.createFileUrl(fileRef, - Optional.empty())); + assertEquals("/xwiki/bin/download/A/B/bla.txt", fileUriServ.createFileUrl(fileRef, + Optional.empty()).build().toString()); } @Test @@ -72,8 +76,8 @@ public void test_createFileUrl_dynamicParamURL() throws Exception { expect(mockURLFactory.getURL(eq(viewURL), same(context))).andReturn(viewURL.getPath()); replayDefault(); FileReference fileRef = FileReference.of("?xpage=bla&bli=blu").build(); - assertEquals("/mySpace/myDoc?xpage=bla&bli=blu", resUrlServ.createFileUrl(fileRef, - Optional.empty())); + assertEquals("/mySpace/myDoc?xpage=bla&bli=blu", fileUriServ.createFileUrl(fileRef, + Optional.empty()).build().toString()); verifyDefault(); } @@ -101,7 +105,7 @@ public void test_createFileUrl_fullInternalLink() throws Exception { .atLeastOnce(); replayDefault(); FileReference fileRef = FileReference.of("celements2web:A.B;bla.txt").build(); - String attachmentURL = resUrlServ.createFileUrl(fileRef, Optional.empty()); + String attachmentURL = fileUriServ.createFileUrl(fileRef, Optional.empty()).build().toString(); assertNotNull(attachmentURL); assertTrue("expecting " + resultURL + " but got " + attachmentURL, attachmentURL.matches(resultURL + "\\?version=\\d{14}")); @@ -132,7 +136,7 @@ public void test_createFileUrl_partInternalLink() throws Exception { .atLeastOnce(); replayDefault(); FileReference fileRef = FileReference.of("A.B;bla.txt").build(); - String attachmentURL = resUrlServ.createFileUrl(fileRef, Optional.empty()); + String attachmentURL = fileUriServ.createFileUrl(fileRef, Optional.empty()).build().toString(); assertNotNull(attachmentURL); assertTrue("expecting " + resultURL + " but got " + attachmentURL, attachmentURL.matches(resultURL + "\\?version=\\d{14}")); @@ -153,7 +157,7 @@ public void test_createFileUrl_partInternalLink_notExists() throws Exception { replayDefault(); FileReference fileRef = FileReference.of("A.B;bla.txt").build(); assertThrows(FileNotExistException.class, - () -> resUrlServ.createFileUrl(fileRef, Optional.empty())); + () -> fileUriServ.createFileUrl(fileRef, Optional.empty())); verifyDefault(); } @@ -167,7 +171,8 @@ public void test_createFileUrl_onDiskLink() throws Exception { "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("download"); replayDefault(); FileReference fileRef = FileReference.of(" :celJS/bla.js").build(); - String attachmentURL = resUrlServ.createFileUrl(fileRef, Optional.empty(), Optional.empty()); + String attachmentURL = fileUriServ.createFileUrl(fileRef, Optional.empty(), Optional.empty()) + .toString(); String expectedURL = "/appname/download/resources/celJS/bla.js"; assertNotNull(attachmentURL); assertTrue("expecting " + expectedURL + " but got " + attachmentURL, @@ -179,7 +184,7 @@ public void test_createFileUrl_onDiskLink() throws Exception { public void test_createFileUrl_Rubish() throws Exception { FileReference fileRef = FileReference.of("http://A.B;bla.txt").build(); assertEquals("http://A.B;bla.txt", - resUrlServ.createFileUrl(fileRef, Optional.empty(), Optional.empty()).toString()); + fileUriServ.createFileUrl(fileRef, Optional.empty(), Optional.empty()).toString()); } @Test @@ -189,7 +194,7 @@ public void test_getFileURLPrefix() throws Exception { expect(mockURLFactory.createResourceURL(eq(""), eq(true), same(context))).andReturn(new URL( "http://test.fabian.dev:10080/skin/resources/")); replayDefault(); - assertEquals("http://test.fabian.dev:10080/file/resources/", resUrlServ.getFileURLPrefix()); + assertEquals("http://test.fabian.dev:10080/file/resources/", fileUriServ.getFileURLPrefix()); verifyDefault(); } @@ -204,8 +209,8 @@ public void test_createFileUrl_onDisk_queryString() throws Exception { String queryString = "asf=oiu"; replayDefault(); FileReference fileRef = FileReference.of(":celJS/bla.js").build(); - String attachmentURL = resUrlServ.createFileUrl(fileRef, Optional.empty(), - Optional.of(queryString)); + String attachmentURL = fileUriServ.createFileUrl(fileRef, Optional.empty(), + Optional.of(queryString)).toString(); String expectedURL = "/appname/download/resources/celJS/bla.js"; assertTrue(attachmentURL, attachmentURL.matches(expectedURL + "\\?version=\\d{14}\\&" + queryString)); @@ -237,11 +242,53 @@ public void test_createFileUrl_partInternalLink_queryString() throws Exception { String queryString = "asf=oiu"; replayDefault(); FileReference fileRef = FileReference.of("A.B;bla.txt").build(); - String attachmentURL = resUrlServ.createFileUrl(fileRef, Optional.of("testAction"), - Optional.of(queryString)); + String attachmentURL = fileUriServ.createFileUrl(fileRef, Optional.of("testAction"), + Optional.of(queryString)).toString(); assertTrue(attachmentURL, attachmentURL.matches(resultURL + "\\?version=\\d{14}\\&" + queryString)); verifyDefault(); } + @Test + public void test_addContextUrl() throws Exception { + String mySpaceName = "mySpace"; + String myDocName = "myDoc"; + DocumentReference myDocRef = new DocumentReference(context.getDatabase(), mySpaceName, + myDocName); + XWikiDocument doc = new XWikiDocument(myDocRef); + context.setDoc(doc); + URL viewURL = new URL("http://localhost/mySpace/myDoc"); + expect(mockURLFactory.createURL(eq(mySpaceName), eq(myDocName), eq("view"), (String) isNull(), + (String) isNull(), eq(context.getDatabase()), same(context))).andReturn(viewURL); + expect(mockURLFactory.getURL(eq(viewURL), same(context))).andReturn(viewURL.getPath()); + UriBuilder uri = UriBuilder.fromPath("").replaceQuery("sdf=asdf"); + replayDefault(); + assertEquals("/mySpace/myDoc?sdf=asdf", fileUriServ.addContextUrl(uri).toString()); + verifyDefault(); + } + + @Test + public void test_createOnDiskUrl() throws Exception { + String mySpaceName = "mySpace"; + String myDocName = "myDoc"; + DocumentReference myDocRef = new DocumentReference(context.getDatabase(), mySpaceName, + myDocName); + XWikiDocument doc = new XWikiDocument(myDocRef); + context.setDoc(doc); + Date lastModificationDate = new SimpleDateFormat("YYYYmmddHHMMss").parse("20201123101535"); + expect(wiki.getResourceLastModificationDate(eq("resources/celRes/test/bla.css"))).andReturn( + lastModificationDate); + String resultURL = "http://celements2web.localhost/skin/celRes/test/bla.css"; + expect(wiki.getSkinFile(eq("celRes/test/bla.css"), eq(true), same(context))) + .andReturn(resultURL); + expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( + "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); + replayDefault(); + FileReference fileRef = FileReference.of(":celRes/test/bla.css").build(); + assertEquals( + "http://celements2web.localhost/createOnDiskUrl/celRes/test/bla.css?version=20191230101135", + fileUriServ.createOnDiskUrl(fileRef, Optional.of("createOnDiskUrl")).toString()); + verifyDefault(); + } + } From 8933716c88aea8abc937a63502a50ce806e657e2 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Mon, 7 Feb 2022 19:00:15 +0100 Subject: [PATCH 14/29] add FileUriScriptService --- .../filebase/uri/FileUriScriptService.java | 57 +++++++++++++++++++ .../filebase/uri/FileUriService.java | 36 ++++++------ .../filebase/uri/FileUriServiceRole.java | 10 +--- src/main/resources/META-INF/components.txt | 1 + .../filebase/uri/FileUriServiceTest.java | 7 ++- 5 files changed, 80 insertions(+), 31 deletions(-) create mode 100644 src/main/java/com/celements/filebase/uri/FileUriScriptService.java diff --git a/src/main/java/com/celements/filebase/uri/FileUriScriptService.java b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java new file mode 100644 index 000000000..51aff67c5 --- /dev/null +++ b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java @@ -0,0 +1,57 @@ +package com.celements.filebase.uri; + +import java.util.Optional; + +import javax.annotation.Nullable; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import javax.ws.rs.core.UriBuilder; + +import org.xwiki.component.annotation.Component; +import org.xwiki.component.annotation.Requirement; +import org.xwiki.script.service.ScriptService; + +import com.celements.filebase.references.FileReference; + +@Component("fileUri") +public class FileUriScriptService implements ScriptService { + + @Requirement + private FileUriServiceRole fileUriService; + + public FileReference createFileReference(@NotEmpty String link) { + return FileReference.of(link).build(); + } + + @NotNull + public UriBuilder createFileUrl(@NotNull FileReference fileRef) { + return createFileUrl(fileRef, null); + } + + @NotNull + public UriBuilder createFileUrl(@NotNull FileReference fileRef, @Nullable String action) { + return createFileUrl(fileRef, action, null); + } + + @NotNull + public UriBuilder createFileUrl(@NotNull FileReference fileRef, @Nullable String action, + @Nullable String queryString) { + try { + return fileUriService.createFileUrl(fileRef, Optional.ofNullable(action), + Optional.ofNullable(queryString)); + } catch (FileNotExistException exp) { + return UriBuilder.fromPath(""); + } + } + + @NotNull + public UriBuilder getFileURLPrefix(@Nullable String action) { + return fileUriService.getFileURLPrefix(Optional.ofNullable(action)); + } + + @NotNull + public String getExternalFileURL(@NotNull FileReference fileRef, String action) { + return fileUriService.getExternalFileURL(fileRef, Optional.ofNullable(action)); + } + +} diff --git a/src/main/java/com/celements/filebase/uri/FileUriService.java b/src/main/java/com/celements/filebase/uri/FileUriService.java index c23c90bfd..acae0da98 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriService.java @@ -1,9 +1,10 @@ package com.celements.filebase.uri; import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; import java.util.Optional; -import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.ws.rs.core.UriBuilder; @@ -50,17 +51,17 @@ private String getDefaultAction() { } @Override - @NotEmpty - public String getFileURLPrefix() { - return getFileURLPrefix(getDefaultAction()); - } - - @Override - @NotEmpty - public String getFileURLPrefix(@NotEmpty String action) { + public @NotNull UriBuilder getFileURLPrefix(@NotNull Optional action) { XWikiURLFactory urlf = context.getXWikiContext().getURLFactory(); - return urlf.createResourceURL("", true, context.getXWikiContext()).toString().replace("/skin/", - "/" + action + "/"); + URL baseUrl = urlf.createResourceURL("", false, context.getXWikiContext()); + try { + return UriBuilder.fromUri(baseUrl.toURI()) + .replacePath("/" + action.orElse(getDefaultAction()) + "/") + .path(baseUrl.getPath()); + } catch (URISyntaxException exp) { + LOGGER.error("Failed to get file url prefix.", exp); + return UriBuilder.fromPath(baseUrl.toString()); + } } @Override @@ -82,18 +83,15 @@ public UriBuilder createFileUrl(@NotNull FileReference fileRef, @NotNull Optiona @NotNull Optional queryString) throws FileNotExistException { final UriBuilder baseUrl = createFileUrl(fileRef, action); if (queryString.isPresent()) { - String[] baseQueryParts = baseUrl.toString().split("\\?", 2); - if (baseQueryParts.length > 1) { - return baseUrl.replaceQuery(baseQueryParts[1] + "&" + queryString.get()); - } else { - return baseUrl.replaceQuery(queryString.get()); - } + return baseUrl.replaceQuery(Optional.ofNullable(baseUrl.build().getQuery()) + .map(qS -> qS + "&" + queryString.get()) + .orElse(queryString.get())); } return baseUrl; } - @Override - public @NotNull UriBuilder createFileUrl(@NotNull FileReference fileRef, + @NotNull + UriBuilder createFileUrl(@NotNull FileReference fileRef, @NotNull Optional action) throws FileNotExistException { UriBuilder uriBuilder; diff --git a/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java b/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java index 780333816..c260376d8 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java +++ b/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java @@ -2,7 +2,6 @@ import java.util.Optional; -import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.ws.rs.core.UriBuilder; @@ -18,14 +17,7 @@ UriBuilder createFileUrl(@NotNull FileReference fileRef, @NotNull Optional queryString) throws FileNotExistException; @NotNull - UriBuilder createFileUrl(@NotNull FileReference fileRef, @NotNull Optional action) - throws FileNotExistException; - - @NotEmpty - String getFileURLPrefix(@NotEmpty String action); - - @NotEmpty - String getFileURLPrefix(); + UriBuilder getFileURLPrefix(@NotNull Optional action); @NotNull String getExternalFileURL(@NotNull FileReference fileRef, @NotNull Optional action); diff --git a/src/main/resources/META-INF/components.txt b/src/main/resources/META-INF/components.txt index 1761932ad..6b78f2c37 100644 --- a/src/main/resources/META-INF/components.txt +++ b/src/main/resources/META-INF/components.txt @@ -161,3 +161,4 @@ com.celements.cells.classes.GroupCellClass com.celements.cells.classes.PageDepCellConfigClass com.celements.cells.classes.TranslationBoxCellConfigClass com.celements.filebase.uri.FileUriService +com.celements.filebase.uri.FileUriScriptService diff --git a/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java index 670ec2777..b7c0f9a44 100644 --- a/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java +++ b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java @@ -191,10 +191,11 @@ public void test_createFileUrl_Rubish() throws Exception { public void test_getFileURLPrefix() throws Exception { expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); - expect(mockURLFactory.createResourceURL(eq(""), eq(true), same(context))).andReturn(new URL( - "http://test.fabian.dev:10080/skin/resources/")); + expect(mockURLFactory.createResourceURL(eq(""), eq(false), same(context))).andReturn(new URL( + "http://test.fabian.dev:10080/resources/")); replayDefault(); - assertEquals("http://test.fabian.dev:10080/file/resources/", fileUriServ.getFileURLPrefix()); + assertEquals("http://test.fabian.dev:10080/file/resources/", + fileUriServ.getFileURLPrefix(Optional.empty()).toString()); verifyDefault(); } From 69aed61db36e12e44fd3287d471e162d266cd0f7 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Mon, 7 Feb 2022 19:11:57 +0100 Subject: [PATCH 15/29] update scheduler plugin dependency --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index c62d9b04b..f131f4672 100644 --- a/pom.xml +++ b/pom.xml @@ -79,7 +79,7 @@ test - com.xpn.xwiki.platform.plugins + com.celements xwiki-plugin-scheduler provided From 0f4570c7f6b786f76fe42d12500c8dc66ec81a05 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Tue, 8 Feb 2022 06:28:50 +0100 Subject: [PATCH 16/29] refactorings --- .../filebase/uri/FileUriScriptService.java | 78 ++++++++++++++---- .../filebase/uri/FileUriService.java | 41 +++++----- .../filebase/uri/FileUriServiceRole.java | 7 +- .../web/plugin/cmd/AttachmentURLCommand.java | 4 +- .../uri/FileUriScriptServiceTest.java | 81 +++++++++++++++++++ .../filebase/uri/FileUriServiceTest.java | 51 +++++++++--- 6 files changed, 210 insertions(+), 52 deletions(-) create mode 100644 src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java diff --git a/src/main/java/com/celements/filebase/uri/FileUriScriptService.java b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java index 51aff67c5..72f66e335 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriScriptService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java @@ -1,21 +1,31 @@ package com.celements.filebase.uri; +import java.net.MalformedURLException; +import java.net.URL; import java.util.Optional; import javax.annotation.Nullable; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriBuilderException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.xwiki.component.annotation.Component; import org.xwiki.component.annotation.Requirement; import org.xwiki.script.service.ScriptService; import com.celements.filebase.references.FileReference; +import com.google.common.base.Strings; -@Component("fileUri") +@Component(FileUriScriptService.NAME) public class FileUriScriptService implements ScriptService { + public static final String NAME = "fileUri"; + + private static final Logger LOGGER = LoggerFactory.getLogger(FileUriScriptService.class); + @Requirement private FileUriServiceRole fileUriService; @@ -23,35 +33,73 @@ public FileReference createFileReference(@NotEmpty String link) { return FileReference.of(link).build(); } - @NotNull - public UriBuilder createFileUrl(@NotNull FileReference fileRef) { + @Nullable + public URL createFileUrl(@Nullable String fileRef) { return createFileUrl(fileRef, null); } - @NotNull - public UriBuilder createFileUrl(@NotNull FileReference fileRef, @Nullable String action) { + @Nullable + public URL createFileUrl(@Nullable String fileRef, @Nullable String action) { return createFileUrl(fileRef, action, null); } - @NotNull - public UriBuilder createFileUrl(@NotNull FileReference fileRef, @Nullable String action, + @Nullable + public URL createFileUrl(@Nullable String fileRef, @Nullable String action, @Nullable String queryString) { - try { - return fileUriService.createFileUrl(fileRef, Optional.ofNullable(action), - Optional.ofNullable(queryString)); - } catch (FileNotExistException exp) { - return UriBuilder.fromPath(""); + if (!Strings.isNullOrEmpty(fileRef)) { + return createFileUrl(createFileReference(fileRef), action, queryString); } + return null; + } + + @Nullable + public URL createFileUrl(@Nullable FileReference fileRef, @Nullable String action, + @Nullable String queryString) { + if (fileRef != null) { + try { + return fileUriService.createFileUri(fileRef, Optional.ofNullable(action), + Optional.ofNullable(queryString)).build().toURL(); + } catch (FileNotExistException | MalformedURLException | IllegalArgumentException + | UriBuilderException exp) { + LOGGER.info("createFileUrl for [{}] with action [{}] an queryString [{}] failed.", fileRef, + action, queryString, exp); + } + } + return null; } @NotNull public UriBuilder getFileURLPrefix(@Nullable String action) { - return fileUriService.getFileURLPrefix(Optional.ofNullable(action)); + return fileUriService.getFileUriPrefix(Optional.ofNullable(action)); } @NotNull - public String getExternalFileURL(@NotNull FileReference fileRef, String action) { - return fileUriService.getExternalFileURL(fileRef, Optional.ofNullable(action)); + public String getExternalFileURL(@Nullable FileReference fileRef, @Nullable String action) { + return getExternalFileURL(fileRef, action, null); + } + + @NotNull + public String getExternalFileURL(@Nullable FileReference fileRef, @Nullable String action, + @Nullable String queryString) { + if (fileRef != null) { + try { + return fileUriService.createAbsoluteFileUri(fileRef, Optional.ofNullable(action), + Optional.ofNullable(queryString)).build().toURL().toExternalForm(); + } catch (MalformedURLException | IllegalArgumentException | UriBuilderException exp) { + LOGGER.info("getExternalFileURL for [{}] with action [{}] failed.", fileRef, action, exp); + } + } + return ""; + } + + @NotNull + public UriBuilder createAbsoluteFileUri(@Nullable FileReference fileRef, String action, + @Nullable String queryString) { + if (fileRef != null) { + return fileUriService.createAbsoluteFileUri(fileRef, Optional.ofNullable(action), + Optional.ofNullable(queryString)); + } + return UriBuilder.fromPath(""); } } diff --git a/src/main/java/com/celements/filebase/uri/FileUriService.java b/src/main/java/com/celements/filebase/uri/FileUriService.java index acae0da98..352a99bdf 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriService.java @@ -51,9 +51,8 @@ private String getDefaultAction() { } @Override - public @NotNull UriBuilder getFileURLPrefix(@NotNull Optional action) { - XWikiURLFactory urlf = context.getXWikiContext().getURLFactory(); - URL baseUrl = urlf.createResourceURL("", false, context.getXWikiContext()); + public @NotNull UriBuilder getFileUriPrefix(@NotNull Optional action) { + URL baseUrl = getUrlFactory().createResourceURL("", false, context.getXWikiContext()); try { return UriBuilder.fromUri(baseUrl.toURI()) .replacePath("/" + action.orElse(getDefaultAction()) + "/") @@ -66,22 +65,26 @@ private String getDefaultAction() { @Override @NotNull - public String getExternalFileURL(@NotNull FileReference fileRef, - @NotNull Optional action) { + public UriBuilder createAbsoluteFileUri(@NotNull FileReference fileRef, + @NotNull Optional action, Optional queryString) { try { - return context.getXWikiContext().getURLFactory().getServerURL(context.getXWikiContext()) - .toExternalForm() + createFileUrl(fileRef, action); - } catch (MalformedURLException | FileNotExistException exp) { - LOGGER.error("Failed to getServerURL.", exp); + return UriBuilder.fromUri(getUrlFactory().getServerURL(context.getXWikiContext()).toURI()) + .uri(createFileUri(fileRef, action, queryString).build()); + } catch (MalformedURLException | FileNotExistException | URISyntaxException exp) { + LOGGER.error("Failed to getServerURL for [{}].", fileRef, exp); + return UriBuilder.fromPath(""); } - return ""; + } + + private XWikiURLFactory getUrlFactory() { + return context.getXWikiContext().getURLFactory(); } @Override @NotNull - public UriBuilder createFileUrl(@NotNull FileReference fileRef, @NotNull Optional action, + public UriBuilder createFileUri(@NotNull FileReference fileRef, @NotNull Optional action, @NotNull Optional queryString) throws FileNotExistException { - final UriBuilder baseUrl = createFileUrl(fileRef, action); + final UriBuilder baseUrl = createFileUri(fileRef, action); if (queryString.isPresent()) { return baseUrl.replaceQuery(Optional.ofNullable(baseUrl.build().getQuery()) .map(qS -> qS + "&" + queryString.get()) @@ -91,21 +94,21 @@ public UriBuilder createFileUrl(@NotNull FileReference fileRef, @NotNull Optiona } @NotNull - UriBuilder createFileUrl(@NotNull FileReference fileRef, + UriBuilder createFileUri(@NotNull FileReference fileRef, @NotNull Optional action) throws FileNotExistException { UriBuilder uriBuilder; if (fileRef.isAttachmentReference()) { - uriBuilder = createAttachmentUrl(fileRef, action); + uriBuilder = createAttachmentUri(fileRef, action); } else if (fileRef.isOnDiskReference()) { - uriBuilder = createOnDiskUrl(fileRef, action); + uriBuilder = createOnDiskUri(fileRef, action); } else { uriBuilder = fileRef.getUri(); } - return addContextUrl(uriBuilder); + return addContextUri(uriBuilder); } - UriBuilder addContextUrl(UriBuilder uriBuilder) { + UriBuilder addContextUri(UriBuilder uriBuilder) { Optional currentDoc = context.getCurrentDoc().toJavaUtil(); if (currentDoc.isPresent() && uriBuilder.toString().startsWith("?")) { uriBuilder.replacePath(currentDoc.get().getURL("view", context.getXWikiContext())); @@ -113,7 +116,7 @@ UriBuilder addContextUrl(UriBuilder uriBuilder) { return uriBuilder; } - private UriBuilder createAttachmentUrl(@NotNull FileReference fileRef, Optional action) + private UriBuilder createAttachmentUri(@NotNull FileReference fileRef, Optional action) throws FileNotExistException { String attName = fileRef.getName(); try { @@ -133,7 +136,7 @@ private UriBuilder createAttachmentUrl(@NotNull FileReference fileRef, Optional< } } - UriBuilder createOnDiskUrl(@NotNull FileReference fileRef, Optional action) { + UriBuilder createOnDiskUri(@NotNull FileReference fileRef, Optional action) { String path = fileRef.getFullPath().trim().substring(1); UriBuilder uri = UriBuilder.fromPath( context.getXWikiContext().getWiki().getSkinFile(path, true, context.getXWikiContext()) diff --git a/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java b/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java index c260376d8..fafee8b98 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java +++ b/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java @@ -13,13 +13,14 @@ public interface FileUriServiceRole { @NotNull - UriBuilder createFileUrl(@NotNull FileReference fileRef, @NotNull Optional action, + UriBuilder createFileUri(@NotNull FileReference fileRef, @NotNull Optional action, @NotNull Optional queryString) throws FileNotExistException; @NotNull - UriBuilder getFileURLPrefix(@NotNull Optional action); + UriBuilder getFileUriPrefix(@NotNull Optional action); @NotNull - String getExternalFileURL(@NotNull FileReference fileRef, @NotNull Optional action); + UriBuilder createAbsoluteFileUri(@NotNull FileReference fileRef, @NotNull Optional action, + Optional queryString); } diff --git a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java index 99170e8a8..6f3cb08b9 100644 --- a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java +++ b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java @@ -50,7 +50,7 @@ public class AttachmentURLCommand { /** * @deprecated since 5.4 instead use - * {@link FileUriServiceRole#createFileUrl(String, Optional)} + * {@link FileUriServiceRole#createFileUri(String, Optional)} */ @Deprecated public String getAttachmentURL(String link, XWikiContext context) { @@ -71,7 +71,7 @@ public String getAttachmentURLPrefix() { } /** - * @deprecated since 5.4 instead use {@link FileUriServiceRole#getFileURLPrefix(String)} + * @deprecated since 5.4 instead use {@link FileUriServiceRole#getFileUriPrefix(String)} */ @Deprecated public String getAttachmentURLPrefix(String action) { diff --git a/src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java b/src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java new file mode 100644 index 000000000..b8a18d349 --- /dev/null +++ b/src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java @@ -0,0 +1,81 @@ +package com.celements.filebase.uri; + +import static com.celements.common.test.CelementsTestUtils.*; +import static org.easymock.EasyMock.*; +import static org.junit.Assert.*; + +import java.net.URL; + +import javax.ws.rs.core.UriBuilder; + +import org.junit.Before; +import org.junit.Test; +import org.xwiki.script.service.ScriptService; + +import com.celements.common.test.AbstractComponentTest; +import com.celements.filebase.references.FileReference; +import com.xpn.xwiki.XWikiContext; +import com.xpn.xwiki.web.Utils; +import com.xpn.xwiki.web.XWikiURLFactory; + +public class FileUriScriptServiceTest extends AbstractComponentTest { + + private FileUriScriptService fileUriSrv; + private XWikiContext context; + private XWikiURLFactory mockURLFactory; + + @Before + public void setUp_FileUriScriptServiceTest() throws Exception { + context = getContext(); + mockURLFactory = createMockAndAddToDefault(XWikiURLFactory.class); + context.setURLFactory(mockURLFactory); + fileUriSrv = (FileUriScriptService) Utils.getComponent(ScriptService.class, + FileUriScriptService.NAME); + } + + @Test + public void test_createFileUrl_null() throws Exception { + assertNull(fileUriSrv.createFileUrl((FileReference) null, null, null)); + assertNull(fileUriSrv.createFileUrl((String) null, null, null)); + assertNull(fileUriSrv.createFileUrl((String) null, null)); + assertNull(fileUriSrv.createFileUrl((String) null)); + } + + @Test + public void test_createAbsoluteFileUri_null() { + assertNotNull(fileUriSrv.createAbsoluteFileUri(null, null, null)); + } + + @Test + public void test_createAbsoluteFileUri() throws Exception { + String serverUrl = "http://localhost"; + URL viewURL = new URL(serverUrl); + expect(mockURLFactory.getServerURL(same(context))).andReturn(viewURL); + replayDefault(); + String filePath = "/a/b/c.txt"; + FileReference fileRef = fileUriSrv.createFileReference(filePath); + UriBuilder fileUri = fileUriSrv.createAbsoluteFileUri(fileRef, null, null); + assertNotNull(fileUri); + assertEquals(serverUrl + filePath, fileUri.build().toURL().toExternalForm()); + verifyDefault(); + } + + @Test + public void test_getExternalFileURL_null() { + assertNotNull(fileUriSrv.getExternalFileURL(null, null, null)); + assertEquals("", fileUriSrv.getExternalFileURL(null, null, null)); + assertNotNull(fileUriSrv.getExternalFileURL(null, null)); + assertEquals("", fileUriSrv.getExternalFileURL(null, null)); + } + + @Test + public void test_getExternalFileURL() throws Exception { + URL viewURL = new URL("http://localhost"); + expect(mockURLFactory.getServerURL(same(context))).andReturn(viewURL); + replayDefault(); + FileReference fileRef = fileUriSrv.createFileReference("/a/b/c.txt"); + assertNotNull(fileUriSrv.getExternalFileURL(fileRef, null, null)); + verifyDefault(); + } + +} diff --git a/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java index b7c0f9a44..fbefc6ec9 100644 --- a/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java +++ b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java @@ -52,16 +52,41 @@ public void setUp_RessourceUrlServiceTest() throws Exception { public void test_createFileUrl_fullURL() throws Exception { FileReference fileRef = FileReference.of("http://www.bla.com/bla.txt").build(); assertEquals("http://www.bla.com/bla.txt", - fileUriServ.createFileUrl(fileRef, Optional.empty()).build().toString()); + fileUriServ.createFileUri(fileRef, Optional.empty()).build().toString()); } @Test public void test_createFileUrl_partURL() throws Exception { FileReference fileRef = FileReference.of("/xwiki/bin/download/A/B/bla.txt").build(); - assertEquals("/xwiki/bin/download/A/B/bla.txt", fileUriServ.createFileUrl(fileRef, + assertEquals("/xwiki/bin/download/A/B/bla.txt", fileUriServ.createFileUri(fileRef, Optional.empty()).build().toString()); } + @Test + public void test_getExternalFileURL_partURL() throws Exception { + FileReference fileRef = FileReference.of("/xwiki/bin/download/A/B/bla.txt").build(); + URL viewURL = new URL("http://localhost"); + expect(mockURLFactory.getServerURL(same(context))).andReturn(viewURL); + replayDefault(); + assertEquals("http://localhost/xwiki/bin/download/A/B/bla.txt", + fileUriServ.createAbsoluteFileUri(fileRef, Optional.empty(), Optional.empty()).build() + .toURL().toExternalForm().toString()); + verifyDefault(); + } + + @Test + public void test_getExternalFileURL_partURL_external() throws Exception { + FileReference fileRef = FileReference.of("http://myTesthost.ch/xwiki/bin/download/A/B/bla.txt") + .build(); + URL viewURL = new URL("http://localhost"); + expect(mockURLFactory.getServerURL(same(context))).andReturn(viewURL); + replayDefault(); + assertEquals("http://myTesthost.ch/xwiki/bin/download/A/B/bla.txt", + fileUriServ.createAbsoluteFileUri(fileRef, Optional.empty(), Optional.empty()).build() + .toURL().toExternalForm().toString()); + verifyDefault(); + } + @Test public void test_createFileUrl_dynamicParamURL() throws Exception { String mySpaceName = "mySpace"; @@ -76,7 +101,7 @@ public void test_createFileUrl_dynamicParamURL() throws Exception { expect(mockURLFactory.getURL(eq(viewURL), same(context))).andReturn(viewURL.getPath()); replayDefault(); FileReference fileRef = FileReference.of("?xpage=bla&bli=blu").build(); - assertEquals("/mySpace/myDoc?xpage=bla&bli=blu", fileUriServ.createFileUrl(fileRef, + assertEquals("/mySpace/myDoc?xpage=bla&bli=blu", fileUriServ.createFileUri(fileRef, Optional.empty()).build().toString()); verifyDefault(); } @@ -105,7 +130,7 @@ public void test_createFileUrl_fullInternalLink() throws Exception { .atLeastOnce(); replayDefault(); FileReference fileRef = FileReference.of("celements2web:A.B;bla.txt").build(); - String attachmentURL = fileUriServ.createFileUrl(fileRef, Optional.empty()).build().toString(); + String attachmentURL = fileUriServ.createFileUri(fileRef, Optional.empty()).build().toString(); assertNotNull(attachmentURL); assertTrue("expecting " + resultURL + " but got " + attachmentURL, attachmentURL.matches(resultURL + "\\?version=\\d{14}")); @@ -136,7 +161,7 @@ public void test_createFileUrl_partInternalLink() throws Exception { .atLeastOnce(); replayDefault(); FileReference fileRef = FileReference.of("A.B;bla.txt").build(); - String attachmentURL = fileUriServ.createFileUrl(fileRef, Optional.empty()).build().toString(); + String attachmentURL = fileUriServ.createFileUri(fileRef, Optional.empty()).build().toString(); assertNotNull(attachmentURL); assertTrue("expecting " + resultURL + " but got " + attachmentURL, attachmentURL.matches(resultURL + "\\?version=\\d{14}")); @@ -157,7 +182,7 @@ public void test_createFileUrl_partInternalLink_notExists() throws Exception { replayDefault(); FileReference fileRef = FileReference.of("A.B;bla.txt").build(); assertThrows(FileNotExistException.class, - () -> fileUriServ.createFileUrl(fileRef, Optional.empty())); + () -> fileUriServ.createFileUri(fileRef, Optional.empty())); verifyDefault(); } @@ -171,7 +196,7 @@ public void test_createFileUrl_onDiskLink() throws Exception { "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("download"); replayDefault(); FileReference fileRef = FileReference.of(" :celJS/bla.js").build(); - String attachmentURL = fileUriServ.createFileUrl(fileRef, Optional.empty(), Optional.empty()) + String attachmentURL = fileUriServ.createFileUri(fileRef, Optional.empty(), Optional.empty()) .toString(); String expectedURL = "/appname/download/resources/celJS/bla.js"; assertNotNull(attachmentURL); @@ -184,7 +209,7 @@ public void test_createFileUrl_onDiskLink() throws Exception { public void test_createFileUrl_Rubish() throws Exception { FileReference fileRef = FileReference.of("http://A.B;bla.txt").build(); assertEquals("http://A.B;bla.txt", - fileUriServ.createFileUrl(fileRef, Optional.empty(), Optional.empty()).toString()); + fileUriServ.createFileUri(fileRef, Optional.empty(), Optional.empty()).toString()); } @Test @@ -195,7 +220,7 @@ public void test_getFileURLPrefix() throws Exception { "http://test.fabian.dev:10080/resources/")); replayDefault(); assertEquals("http://test.fabian.dev:10080/file/resources/", - fileUriServ.getFileURLPrefix(Optional.empty()).toString()); + fileUriServ.getFileUriPrefix(Optional.empty()).toString()); verifyDefault(); } @@ -210,7 +235,7 @@ public void test_createFileUrl_onDisk_queryString() throws Exception { String queryString = "asf=oiu"; replayDefault(); FileReference fileRef = FileReference.of(":celJS/bla.js").build(); - String attachmentURL = fileUriServ.createFileUrl(fileRef, Optional.empty(), + String attachmentURL = fileUriServ.createFileUri(fileRef, Optional.empty(), Optional.of(queryString)).toString(); String expectedURL = "/appname/download/resources/celJS/bla.js"; assertTrue(attachmentURL, @@ -243,7 +268,7 @@ public void test_createFileUrl_partInternalLink_queryString() throws Exception { String queryString = "asf=oiu"; replayDefault(); FileReference fileRef = FileReference.of("A.B;bla.txt").build(); - String attachmentURL = fileUriServ.createFileUrl(fileRef, Optional.of("testAction"), + String attachmentURL = fileUriServ.createFileUri(fileRef, Optional.of("testAction"), Optional.of(queryString)).toString(); assertTrue(attachmentURL, attachmentURL.matches(resultURL + "\\?version=\\d{14}\\&" + queryString)); @@ -264,7 +289,7 @@ public void test_addContextUrl() throws Exception { expect(mockURLFactory.getURL(eq(viewURL), same(context))).andReturn(viewURL.getPath()); UriBuilder uri = UriBuilder.fromPath("").replaceQuery("sdf=asdf"); replayDefault(); - assertEquals("/mySpace/myDoc?sdf=asdf", fileUriServ.addContextUrl(uri).toString()); + assertEquals("/mySpace/myDoc?sdf=asdf", fileUriServ.addContextUri(uri).toString()); verifyDefault(); } @@ -288,7 +313,7 @@ public void test_createOnDiskUrl() throws Exception { FileReference fileRef = FileReference.of(":celRes/test/bla.css").build(); assertEquals( "http://celements2web.localhost/createOnDiskUrl/celRes/test/bla.css?version=20191230101135", - fileUriServ.createOnDiskUrl(fileRef, Optional.of("createOnDiskUrl")).toString()); + fileUriServ.createOnDiskUri(fileRef, Optional.of("createOnDiskUrl")).toString()); verifyDefault(); } From ee3a2bd0a3161c5c3dfbb52ba0b2b8f200434e7b Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Tue, 8 Feb 2022 07:08:13 +0100 Subject: [PATCH 17/29] change createFileUrl to return --- .../filebase/uri/FileUriScriptService.java | 38 +++++++-------- .../uri/FileUriScriptServiceTest.java | 48 ++++++++++++++++--- 2 files changed, 61 insertions(+), 25 deletions(-) diff --git a/src/main/java/com/celements/filebase/uri/FileUriScriptService.java b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java index 72f66e335..82e4f4b16 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriScriptService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java @@ -1,7 +1,6 @@ package com.celements.filebase.uri; import java.net.MalformedURLException; -import java.net.URL; import java.util.Optional; import javax.annotation.Nullable; @@ -29,43 +28,43 @@ public class FileUriScriptService implements ScriptService { @Requirement private FileUriServiceRole fileUriService; + @NotNull public FileReference createFileReference(@NotEmpty String link) { return FileReference.of(link).build(); } - @Nullable - public URL createFileUrl(@Nullable String fileRef) { + @NotNull + public UriBuilder createFileUrl(@Nullable String fileRef) { return createFileUrl(fileRef, null); } - @Nullable - public URL createFileUrl(@Nullable String fileRef, @Nullable String action) { + @NotNull + public UriBuilder createFileUrl(@Nullable String fileRef, @Nullable String action) { return createFileUrl(fileRef, action, null); } - @Nullable - public URL createFileUrl(@Nullable String fileRef, @Nullable String action, + @NotNull + public UriBuilder createFileUrl(@Nullable String fileRef, @Nullable String action, @Nullable String queryString) { if (!Strings.isNullOrEmpty(fileRef)) { return createFileUrl(createFileReference(fileRef), action, queryString); } - return null; + return UriBuilder.fromPath(""); } - @Nullable - public URL createFileUrl(@Nullable FileReference fileRef, @Nullable String action, + @NotNull + public UriBuilder createFileUrl(@Nullable FileReference fileRef, @Nullable String action, @Nullable String queryString) { if (fileRef != null) { try { return fileUriService.createFileUri(fileRef, Optional.ofNullable(action), - Optional.ofNullable(queryString)).build().toURL(); - } catch (FileNotExistException | MalformedURLException | IllegalArgumentException - | UriBuilderException exp) { + Optional.ofNullable(queryString)); + } catch (FileNotExistException exp) { LOGGER.info("createFileUrl for [{}] with action [{}] an queryString [{}] failed.", fileRef, action, queryString, exp); } } - return null; + return UriBuilder.fromPath(""); } @NotNull @@ -74,17 +73,18 @@ public UriBuilder getFileURLPrefix(@Nullable String action) { } @NotNull - public String getExternalFileURL(@Nullable FileReference fileRef, @Nullable String action) { + public String getExternalFileURL(@Nullable String fileRef, @Nullable String action) { return getExternalFileURL(fileRef, action, null); } @NotNull - public String getExternalFileURL(@Nullable FileReference fileRef, @Nullable String action, + public String getExternalFileURL(@Nullable String fileRef, @Nullable String action, @Nullable String queryString) { - if (fileRef != null) { + if (!Strings.isNullOrEmpty(fileRef)) { try { - return fileUriService.createAbsoluteFileUri(fileRef, Optional.ofNullable(action), - Optional.ofNullable(queryString)).build().toURL().toExternalForm(); + return fileUriService.createAbsoluteFileUri(FileReference.of(fileRef).build(), + Optional.ofNullable(action), Optional.ofNullable(queryString)) + .build().toURL().toExternalForm(); } catch (MalformedURLException | IllegalArgumentException | UriBuilderException exp) { LOGGER.info("getExternalFileURL for [{}] with action [{}] failed.", fileRef, action, exp); } diff --git a/src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java b/src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java index b8a18d349..f0bebf4c7 100644 --- a/src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java +++ b/src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java @@ -5,6 +5,8 @@ import static org.junit.Assert.*; import java.net.URL; +import java.text.SimpleDateFormat; +import java.util.Date; import javax.ws.rs.core.UriBuilder; @@ -14,6 +16,7 @@ import com.celements.common.test.AbstractComponentTest; import com.celements.filebase.references.FileReference; +import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.web.Utils; import com.xpn.xwiki.web.XWikiURLFactory; @@ -23,10 +26,12 @@ public class FileUriScriptServiceTest extends AbstractComponentTest { private FileUriScriptService fileUriSrv; private XWikiContext context; private XWikiURLFactory mockURLFactory; + private XWiki wiki; @Before public void setUp_FileUriScriptServiceTest() throws Exception { context = getContext(); + wiki = getWikiMock(); mockURLFactory = createMockAndAddToDefault(XWikiURLFactory.class); context.setURLFactory(mockURLFactory); fileUriSrv = (FileUriScriptService) Utils.getComponent(ScriptService.class, @@ -35,10 +40,42 @@ public void setUp_FileUriScriptServiceTest() throws Exception { @Test public void test_createFileUrl_null() throws Exception { - assertNull(fileUriSrv.createFileUrl((FileReference) null, null, null)); - assertNull(fileUriSrv.createFileUrl((String) null, null, null)); - assertNull(fileUriSrv.createFileUrl((String) null, null)); - assertNull(fileUriSrv.createFileUrl((String) null)); + assertEquals("", fileUriSrv.createFileUrl((FileReference) null, null, null).toString()); + assertEquals("", fileUriSrv.createFileUrl((String) null, null, null).toString()); + assertEquals("", fileUriSrv.createFileUrl((String) null, null).toString()); + assertEquals("", fileUriSrv.createFileUrl((String) null).toString()); + } + + @Test + public void test_createFileUrl_file_action() throws Exception { + String resultURL = "/skin/resources/celJS/prototype.js"; + expect(wiki.getSkinFile(eq("celJS/prototype.js"), eq(true), same(context))) + .andReturn(resultURL); + Date lastModificationDate = new SimpleDateFormat("YYYYmmddHHMMss").parse("20201123101535"); + expect(wiki.getResourceLastModificationDate(eq("resources/celJS/prototype.js"))).andReturn( + lastModificationDate); + expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( + "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("download"); + replayDefault(); + assertEquals("/file/resources/celJS/prototype.js?version=20191230101135", + fileUriSrv.createFileUrl(":celJS/prototype.js", "file").toString()); + verifyDefault(); + } + + @Test + public void test_createFileUrl_file_action_query() throws Exception { + String resultURL = "/skin/resources/celJS/prototype.js"; + expect(wiki.getSkinFile(eq("celJS/prototype.js"), eq(true), same(context))) + .andReturn(resultURL); + Date lastModificationDate = new SimpleDateFormat("YYYYmmddHHMMss").parse("20201123101535"); + expect(wiki.getResourceLastModificationDate(eq("resources/celJS/prototype.js"))).andReturn( + lastModificationDate); + expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( + "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("download"); + replayDefault(); + assertEquals("/file/resources/celJS/prototype.js?version=20191230101135&bla=asfd", + fileUriSrv.createFileUrl(":celJS/prototype.js", "file", "bla=asfd").toString()); + verifyDefault(); } @Test @@ -73,8 +110,7 @@ public void test_getExternalFileURL() throws Exception { URL viewURL = new URL("http://localhost"); expect(mockURLFactory.getServerURL(same(context))).andReturn(viewURL); replayDefault(); - FileReference fileRef = fileUriSrv.createFileReference("/a/b/c.txt"); - assertNotNull(fileUriSrv.getExternalFileURL(fileRef, null, null)); + assertNotNull(fileUriSrv.getExternalFileURL("/a/b/c.txt", null, null)); verifyDefault(); } From a74d3f986b2fa2466c469b624fceae280d121d59 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Tue, 8 Feb 2022 09:56:04 +0100 Subject: [PATCH 18/29] remove getExternalFileURL and instead use createAbsoluteFileUri --- .../filebase/uri/FileUriScriptService.java | 18 ++++-------- .../uri/FileUriScriptServiceTest.java | 28 ++++++++++--------- 2 files changed, 20 insertions(+), 26 deletions(-) diff --git a/src/main/java/com/celements/filebase/uri/FileUriScriptService.java b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java index 82e4f4b16..64cbc3b1b 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriScriptService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java @@ -1,13 +1,11 @@ package com.celements.filebase.uri; -import java.net.MalformedURLException; import java.util.Optional; import javax.annotation.Nullable; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.ws.rs.core.UriBuilder; -import javax.ws.rs.core.UriBuilderException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -73,23 +71,17 @@ public UriBuilder getFileURLPrefix(@Nullable String action) { } @NotNull - public String getExternalFileURL(@Nullable String fileRef, @Nullable String action) { - return getExternalFileURL(fileRef, action, null); + public UriBuilder createAbsoluteFileUri(@Nullable String fileRef, @Nullable String action) { + return createAbsoluteFileUri(fileRef, action, null); } @NotNull - public String getExternalFileURL(@Nullable String fileRef, @Nullable String action, + public UriBuilder createAbsoluteFileUri(@Nullable String fileRef, String action, @Nullable String queryString) { if (!Strings.isNullOrEmpty(fileRef)) { - try { - return fileUriService.createAbsoluteFileUri(FileReference.of(fileRef).build(), - Optional.ofNullable(action), Optional.ofNullable(queryString)) - .build().toURL().toExternalForm(); - } catch (MalformedURLException | IllegalArgumentException | UriBuilderException exp) { - LOGGER.info("getExternalFileURL for [{}] with action [{}] failed.", fileRef, action, exp); - } + return createAbsoluteFileUri(createFileReference(fileRef), action, queryString); } - return ""; + return UriBuilder.fromPath(""); } @NotNull diff --git a/src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java b/src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java index f0bebf4c7..14060bb32 100644 --- a/src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java +++ b/src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java @@ -80,11 +80,16 @@ public void test_createFileUrl_file_action_query() throws Exception { @Test public void test_createAbsoluteFileUri_null() { - assertNotNull(fileUriSrv.createAbsoluteFileUri(null, null, null)); + assertNotNull(fileUriSrv.createAbsoluteFileUri((FileReference) null, null, null)); + assertEquals("", fileUriSrv.createAbsoluteFileUri((FileReference) null, null, null).toString()); + assertNotNull(fileUriSrv.createAbsoluteFileUri((String) null, null, null)); + assertEquals("", fileUriSrv.createAbsoluteFileUri((String) null, null, null).toString()); + assertNotNull(fileUriSrv.createAbsoluteFileUri((String) null, null)); + assertEquals("", fileUriSrv.createAbsoluteFileUri((String) null, null).toString()); } @Test - public void test_createAbsoluteFileUri() throws Exception { + public void test_createAbsoluteFileUri_fileRef() throws Exception { String serverUrl = "http://localhost"; URL viewURL = new URL(serverUrl); expect(mockURLFactory.getServerURL(same(context))).andReturn(viewURL); @@ -98,19 +103,16 @@ public void test_createAbsoluteFileUri() throws Exception { } @Test - public void test_getExternalFileURL_null() { - assertNotNull(fileUriSrv.getExternalFileURL(null, null, null)); - assertEquals("", fileUriSrv.getExternalFileURL(null, null, null)); - assertNotNull(fileUriSrv.getExternalFileURL(null, null)); - assertEquals("", fileUriSrv.getExternalFileURL(null, null)); - } - - @Test - public void test_getExternalFileURL() throws Exception { - URL viewURL = new URL("http://localhost"); + public void test_getExternalFileURL_string() throws Exception { + String filePath = "/a/b/c.txt"; + String serverUrl = "http://localhost"; + URL viewURL = new URL(serverUrl); expect(mockURLFactory.getServerURL(same(context))).andReturn(viewURL); replayDefault(); - assertNotNull(fileUriSrv.getExternalFileURL("/a/b/c.txt", null, null)); + UriBuilder fileUri = fileUriSrv.createAbsoluteFileUri(filePath, null, null); + assertNotNull(fileUri); + assertEquals("Absolute file uri must enclose all information for externalForm.", + serverUrl + filePath, fileUri.build().toURL().toExternalForm()); verifyDefault(); } From c62b5f62292929e502d8ab91f3cdeecb7a194889 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Tue, 8 Feb 2022 10:10:09 +0100 Subject: [PATCH 19/29] mark deprecated --- .../filebase/uri/FileUriScriptService.java | 5 +++ .../service/CelementsWebScriptService.java | 44 ++++++++++++++----- 2 files changed, 38 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/celements/filebase/uri/FileUriScriptService.java b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java index 64cbc3b1b..1f34fa4c2 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriScriptService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java @@ -65,6 +65,11 @@ public UriBuilder createFileUrl(@Nullable FileReference fileRef, @Nullable Strin return UriBuilder.fromPath(""); } + @NotNull + public UriBuilder getFileURLPrefix() { + return fileUriService.getFileUriPrefix(Optional.empty()); + } + @NotNull public UriBuilder getFileURLPrefix(@Nullable String action) { return fileUriService.getFileUriPrefix(Optional.ofNullable(action)); diff --git a/src/main/java/com/celements/web/service/CelementsWebScriptService.java b/src/main/java/com/celements/web/service/CelementsWebScriptService.java index 74a0a4b01..089e0d730 100644 --- a/src/main/java/com/celements/web/service/CelementsWebScriptService.java +++ b/src/main/java/com/celements/web/service/CelementsWebScriptService.java @@ -54,6 +54,7 @@ import com.celements.appScript.IAppScriptService; import com.celements.common.classes.IClassesCompositorComponent; import com.celements.filebase.FileBaseScriptService; +import com.celements.filebase.uri.FileUriScriptService; import com.celements.lastChanged.ILastChangedRole; import com.celements.mandatory.IMandatoryDocumentCompositorRole; import com.celements.metatag.BaseObjectMetaTagProvider; @@ -99,6 +100,8 @@ @Component("celementsweb") public class CelementsWebScriptService implements ScriptService { + private static final String DELETED_ATTACHMENTS_HQL = "select datt.id from DeletedAttachment as datt order by datt.filename asc"; + private static final String CEL_GLOBALVAL_PREFIX = "celements.globalvalues."; private static final String IMAGE_MAP_COMMAND = "com.celements.web.ImageMapCommand"; @@ -373,22 +376,43 @@ public String displayImageMapConfigs() { return getImageMapCommand().displayAllImageMapConfigs(); } + /** + * @deprecated since 5.4 instead use {@link FileUriScriptService#createFileUrl(String)} + */ + @Deprecated public String getSkinFile(String fileName) { return new AttachmentURLCommand().getAttachmentURL(fileName, getContext()); } + /** + * @deprecated since 5.4 instead use {@link FileUriScriptService#createFileUrl(String, String)} + */ + @Deprecated public String getSkinFile(String fileName, String action) { return new AttachmentURLCommand().getAttachmentURL(fileName, action, getContext()); } + /** + * @deprecated since 5.4 instead use {@link FileUriScriptService#getFileURLPrefix()} + */ + @Deprecated public String getAttachmentURLPrefix() { return new AttachmentURLCommand().getAttachmentURLPrefix(); } + /** + * @deprecated since 5.4 instead use {@link FileUriScriptService#getFileURLPrefix(String)} + */ + @Deprecated public String getAttachmentURLPrefix(String action) { return new AttachmentURLCommand().getAttachmentURLPrefix(action); } + /** + * @deprecated since 5.4 instead use + * {@link FileUriScriptService#createAbsoluteFileUri(String, String)} + */ + @Deprecated public String getSkinFileExternal(String fileName, String action) { return new AttachmentURLCommand().getExternalAttachmentURL(fileName, action, getContext()); } @@ -485,8 +509,8 @@ public String renderDocument(DocumentReference docRef, String lang, boolean remo renderCommand.initRenderingEngine(rendererNameList); return renderCommand.renderDocument(docRef, lang); } catch (XWikiException exp) { - LOGGER.error("renderCelementsDocument: Failed to render [" + docRef + "] lang [" + lang - + "].", exp); + LOGGER.error("renderCelementsDocument: Failed to render [{}] in lang [{}].", docRef, lang, + exp); } return ""; } @@ -513,8 +537,9 @@ public String renderInheritableDocument(DocumentReference docRef, String lang) { try { return webUtilsService.renderInheritableDocument(docRef, lang); } catch (XWikiException exp) { - LOGGER.error("renderInheritableDocument: Failed to render inheritable [" + docRef - + "] in lang [" + lang + "]."); + LOGGER.error( + "renderInheritableDocument: Failed to render inheritable [{}] in lang [{}].", docRef, + lang, exp); } return ""; } @@ -563,7 +588,8 @@ public List getDeletedDocuments(String orderby, boolean hideOverwritten) } private String getDeletedDocsHql(String orderby, boolean hideOverwritten) { - String deletedDocsHql = "select distinct ddoc.fullName" + " from XWikiDeletedDocument as ddoc"; + String deletedDocsHql = "select distinct ddoc.fullName" + + " from XWikiDeletedDocument as ddoc"; if (hideOverwritten) { deletedDocsHql += " where ddoc.fullName not in (select doc.fullName from" + " XWikiDocument as doc)"; @@ -628,7 +654,7 @@ public Integer permanentlyEmptyTrash(int waitDays) { public List getDeletedAttachments() { List resultList = Collections.emptyList(); try { - Query query = queryManager.createQuery(getDeletedAttachmentsHql(), Query.HQL); + Query query = queryManager.createQuery(DELETED_ATTACHMENTS_HQL, Query.HQL); resultList = query.execute(); } catch (QueryException queryExp) { LOGGER.error("Failed to parse or execute deletedAttachments hql query.", queryExp); @@ -636,10 +662,6 @@ public List getDeletedAttachments() { return resultList; } - private String getDeletedAttachmentsHql() { - return "select datt.id from DeletedAttachment as datt order by datt.filename asc"; - } - /** * permanentlyEmptyAttachmentTrash delete all documents after waitDays and minWaitDays * @@ -724,7 +746,7 @@ public com.xpn.xwiki.api.Object getSkinConfigFieldInheritor(String fallbackClass String key) { BaseCollection skinConfigBaseColl = new SkinConfigObjCommand().getSkinConfigFieldInheritor( fallbackClassName).getObject(key); - if ((skinConfigBaseColl != null) && (skinConfigBaseColl instanceof BaseObject)) { + if (skinConfigBaseColl instanceof BaseObject) { BaseObject skinConfigObj = (BaseObject) skinConfigBaseColl; return skinConfigObj.newObjectApi(skinConfigObj, getContext()); } else { From 09a4c028078f311edb569ced07729af5c5b7a880 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Tue, 8 Feb 2022 11:43:07 +0100 Subject: [PATCH 20/29] add configsource --- .../filebase/uri/FileUriService.java | 12 +++++-- .../filebase/uri/FileUriServiceTest.java | 36 +++++++++++-------- 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/celements/filebase/uri/FileUriService.java b/src/main/java/com/celements/filebase/uri/FileUriService.java index 352a99bdf..9f765b079 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriService.java @@ -12,7 +12,9 @@ import org.slf4j.LoggerFactory; import org.xwiki.component.annotation.Component; import org.xwiki.component.annotation.Requirement; +import org.xwiki.configuration.ConfigurationSource; +import com.celements.configuration.CelementsFromWikiConfigurationSource; import com.celements.filebase.IAttachmentServiceRole; import com.celements.filebase.references.FileReference; import com.celements.model.access.IModelAccessFacade; @@ -21,6 +23,7 @@ import com.celements.model.context.ModelContext; import com.celements.model.util.ModelUtils; import com.celements.web.service.LastStartupTimeStampRole; +import com.google.common.base.Strings; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.web.XWikiURLFactory; @@ -45,9 +48,14 @@ public class FileUriService implements FileUriServiceRole { @Requirement private LastStartupTimeStampRole lastStartupTimeStamp; + @Requirement(CelementsFromWikiConfigurationSource.NAME) + private ConfigurationSource configSrc; + private String getDefaultAction() { - return context.getXWikiContext().getWiki().getXWikiPreference("celdefaultAttAction", - "celements.attachmenturl.defaultaction", "file", context.getXWikiContext()); + return Optional.ofNullable( + Strings.emptyToNull(configSrc.getProperty("celements.fileuri.defaultaction"))) + .orElse(context.getXWikiContext().getWiki().getXWikiPreference("celdefaultAttAction", + "celements.attachmenturl.defaultaction", "file", context.getXWikiContext())); } @Override diff --git a/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java index fbefc6ec9..30e830328 100644 --- a/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java +++ b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java @@ -15,10 +15,12 @@ import org.junit.Before; import org.junit.Test; +import org.xwiki.configuration.ConfigurationSource; import org.xwiki.model.reference.AttachmentReference; import org.xwiki.model.reference.DocumentReference; import com.celements.common.test.AbstractComponentTest; +import com.celements.configuration.CelementsFromWikiConfigurationSource; import com.celements.filebase.references.FileReference; import com.celements.model.access.IModelAccessFacade; import com.celements.model.access.exception.AttachmentNotExistsException; @@ -35,12 +37,15 @@ public class FileUriServiceTest extends AbstractComponentTest { private IModelAccessFacade modelAccessMock; private XWikiContext context; private XWikiURLFactory mockURLFactory; - private FileUriService fileUriServ; + private ConfigurationSource configSrcMock; private XWiki wiki; + private FileUriService fileUriServ; @Before public void setUp_RessourceUrlServiceTest() throws Exception { modelAccessMock = registerComponentMock(IModelAccessFacade.class); + configSrcMock = registerComponentMock(ConfigurationSource.class, + CelementsFromWikiConfigurationSource.NAME); context = getContext(); wiki = getWikiMock(); mockURLFactory = createMockAndAddToDefault(XWikiURLFactory.class); @@ -124,8 +129,7 @@ public void test_createFileUrl_fullInternalLink() throws Exception { (String) eq(null), eq("celements2web"), same(context))).andReturn(tstURL); expect(mockURLFactory.getURL(eq(tstURL), same(context))).andReturn(resultURL); expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); - expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( - "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); + expectDefaultAction(Optional.empty()); expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) .atLeastOnce(); replayDefault(); @@ -155,8 +159,7 @@ public void test_createFileUrl_partInternalLink() throws Exception { attachList.add(blaAtt); abDoc.setAttachmentList(attachList); expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); - expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( - "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); + expectDefaultAction(Optional.empty()); expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) .atLeastOnce(); replayDefault(); @@ -192,8 +195,7 @@ public void test_createFileUrl_onDiskLink() throws Exception { expect(wiki.getSkinFile(eq("celJS/bla.js"), eq(true), same(context))).andReturn(resultURL); expect(wiki.getResourceLastModificationDate(eq("resources/celJS/bla.js"))).andReturn( new Date()); - expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( - "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("download"); + expectDefaultAction(Optional.of("download")); replayDefault(); FileReference fileRef = FileReference.of(" :celJS/bla.js").build(); String attachmentURL = fileUriServ.createFileUri(fileRef, Optional.empty(), Optional.empty()) @@ -214,8 +216,7 @@ public void test_createFileUrl_Rubish() throws Exception { @Test public void test_getFileURLPrefix() throws Exception { - expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( - "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); + expectDefaultAction(Optional.empty()); expect(mockURLFactory.createResourceURL(eq(""), eq(false), same(context))).andReturn(new URL( "http://test.fabian.dev:10080/resources/")); replayDefault(); @@ -230,8 +231,7 @@ public void test_createFileUrl_onDisk_queryString() throws Exception { expect(wiki.getSkinFile(eq("celJS/bla.js"), eq(true), same(context))).andReturn(resultURL); expect(wiki.getResourceLastModificationDate(eq("resources/celJS/bla.js"))).andReturn( new Date()); - expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( - "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("download"); + expectDefaultAction(Optional.of("download")); String queryString = "asf=oiu"; replayDefault(); FileReference fileRef = FileReference.of(":celJS/bla.js").build(); @@ -263,8 +263,7 @@ public void test_createFileUrl_partInternalLink_queryString() throws Exception { expect(modelAccessMock.getDocument(eq(abDocRef))).andReturn(abDoc).atLeastOnce(); expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) .atLeastOnce(); - expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( - "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); + expectDefaultAction(Optional.empty()); String queryString = "asf=oiu"; replayDefault(); FileReference fileRef = FileReference.of("A.B;bla.txt").build(); @@ -307,8 +306,7 @@ public void test_createOnDiskUrl() throws Exception { String resultURL = "http://celements2web.localhost/skin/celRes/test/bla.css"; expect(wiki.getSkinFile(eq("celRes/test/bla.css"), eq(true), same(context))) .andReturn(resultURL); - expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( - "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("file"); + expectDefaultAction(Optional.empty()); replayDefault(); FileReference fileRef = FileReference.of(":celRes/test/bla.css").build(); assertEquals( @@ -317,4 +315,12 @@ public void test_createOnDiskUrl() throws Exception { verifyDefault(); } + private void expectDefaultAction(Optional action) { + expect(configSrcMock.getProperty(eq("celements.fileuri.defaultaction"))) + .andReturn(action.orElse("file")); + expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( + "celements.attachmenturl.defaultaction"), eq("file"), same(context))) + .andReturn(action.orElse("file")).atLeastOnce(); + } + } From c507cc8df442fc3aad1f22229a745619593023a7 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Tue, 8 Feb 2022 11:45:21 +0100 Subject: [PATCH 21/29] fix testing --- .../uri/FileUriScriptServiceTest.java | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java b/src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java index 14060bb32..6b9523603 100644 --- a/src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java +++ b/src/test/java/com/celements/filebase/uri/FileUriScriptServiceTest.java @@ -7,14 +7,17 @@ import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.Optional; import javax.ws.rs.core.UriBuilder; import org.junit.Before; import org.junit.Test; +import org.xwiki.configuration.ConfigurationSource; import org.xwiki.script.service.ScriptService; import com.celements.common.test.AbstractComponentTest; +import com.celements.configuration.CelementsFromWikiConfigurationSource; import com.celements.filebase.references.FileReference; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; @@ -27,9 +30,12 @@ public class FileUriScriptServiceTest extends AbstractComponentTest { private XWikiContext context; private XWikiURLFactory mockURLFactory; private XWiki wiki; + private ConfigurationSource configSrcMock; @Before public void setUp_FileUriScriptServiceTest() throws Exception { + configSrcMock = registerComponentMock(ConfigurationSource.class, + CelementsFromWikiConfigurationSource.NAME); context = getContext(); wiki = getWikiMock(); mockURLFactory = createMockAndAddToDefault(XWikiURLFactory.class); @@ -54,8 +60,7 @@ public void test_createFileUrl_file_action() throws Exception { Date lastModificationDate = new SimpleDateFormat("YYYYmmddHHMMss").parse("20201123101535"); expect(wiki.getResourceLastModificationDate(eq("resources/celJS/prototype.js"))).andReturn( lastModificationDate); - expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( - "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("download"); + expectDefaultAction(Optional.of("download")); replayDefault(); assertEquals("/file/resources/celJS/prototype.js?version=20191230101135", fileUriSrv.createFileUrl(":celJS/prototype.js", "file").toString()); @@ -70,8 +75,7 @@ public void test_createFileUrl_file_action_query() throws Exception { Date lastModificationDate = new SimpleDateFormat("YYYYmmddHHMMss").parse("20201123101535"); expect(wiki.getResourceLastModificationDate(eq("resources/celJS/prototype.js"))).andReturn( lastModificationDate); - expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( - "celements.attachmenturl.defaultaction"), eq("file"), same(context))).andReturn("download"); + expectDefaultAction(Optional.of("download")); replayDefault(); assertEquals("/file/resources/celJS/prototype.js?version=20191230101135&bla=asfd", fileUriSrv.createFileUrl(":celJS/prototype.js", "file", "bla=asfd").toString()); @@ -116,4 +120,11 @@ public void test_getExternalFileURL_string() throws Exception { verifyDefault(); } + private void expectDefaultAction(Optional action) { + expect(configSrcMock.getProperty(eq("celements.fileuri.defaultaction"))) + .andReturn(action.orElse("file")); + expect(wiki.getXWikiPreference(eq("celdefaultAttAction"), eq( + "celements.attachmenturl.defaultaction"), eq("file"), same(context))) + .andReturn(action.orElse("file")).atLeastOnce(); + } } From 6f4b91621dbd5be24b42b243174c6a4b7d1a58c8 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Tue, 8 Feb 2022 16:39:05 +0100 Subject: [PATCH 22/29] set FileReference to final. --- .../java/com/celements/filebase/references/FileReference.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/celements/filebase/references/FileReference.java b/src/main/java/com/celements/filebase/references/FileReference.java index 8df84a266..6b77fd40b 100644 --- a/src/main/java/com/celements/filebase/references/FileReference.java +++ b/src/main/java/com/celements/filebase/references/FileReference.java @@ -22,7 +22,7 @@ import com.xpn.xwiki.web.Utils; @Immutable -public class FileReference implements Serializable { +public final class FileReference implements Serializable { private static final long serialVersionUID = 1L; From 229455d556b7cfdad7ec3d9771f52b98d432035f Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Tue, 8 Feb 2022 16:50:19 +0100 Subject: [PATCH 23/29] adding Singleton annotations --- .../java/com/celements/filebase/uri/FileUriScriptService.java | 3 +++ src/main/java/com/celements/filebase/uri/FileUriService.java | 3 +++ 2 files changed, 6 insertions(+) diff --git a/src/main/java/com/celements/filebase/uri/FileUriScriptService.java b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java index 1f34fa4c2..af7f6190c 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriScriptService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java @@ -16,7 +16,10 @@ import com.celements.filebase.references.FileReference; import com.google.common.base.Strings; +import groovy.lang.Singleton; + @Component(FileUriScriptService.NAME) +@Singleton public class FileUriScriptService implements ScriptService { public static final String NAME = "fileUri"; diff --git a/src/main/java/com/celements/filebase/uri/FileUriService.java b/src/main/java/com/celements/filebase/uri/FileUriService.java index 9f765b079..2b000b973 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriService.java @@ -28,7 +28,10 @@ import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.web.XWikiURLFactory; +import groovy.lang.Singleton; + @Component +@Singleton public class FileUriService implements FileUriServiceRole { private static final Logger LOGGER = LoggerFactory.getLogger(FileUriService.class); From f2fa74cb0caf4a62102f9d6a2fc53b96029867fa Mon Sep 17 00:00:00 2001 From: Fabian Date: Wed, 9 Feb 2022 05:33:46 +0100 Subject: [PATCH 24/29] Update src/main/java/com/celements/filebase/references/FileReference.java Co-authored-by: Marc Sladek --- .../com/celements/filebase/references/FileReference.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/celements/filebase/references/FileReference.java b/src/main/java/com/celements/filebase/references/FileReference.java index 6b77fd40b..5bb99fbbf 100644 --- a/src/main/java/com/celements/filebase/references/FileReference.java +++ b/src/main/java/com/celements/filebase/references/FileReference.java @@ -29,12 +29,9 @@ public final class FileReference implements Serializable { @NotThreadSafe public static final class Builder { - private static final String ATTACHMENT_LINK_REGEX = "([\\w\\-]*:)?([\\w\\-]*\\.[\\w\\-]*){1};.*"; - private static final Supplier ATTACHMENT_LINK_PATTERN = Suppliers - .memoize(() -> Pattern.compile(ATTACHMENT_LINK_REGEX)); - private static final String ON_DISK_LINK_REGEX = "^:[/\\w\\-\\.]*"; - private static final Supplier ON_DISK_LINK_PATTERN = Suppliers - .memoize(() -> Pattern.compile(ON_DISK_LINK_REGEX)); + private static final Pattern ATTACHMENT_LINK_PATTERN = Pattern.compile( + "([\\w\\-]*:)?([\\w\\-]*\\.[\\w\\-]*){1};.*"); + private static final Pattern ON_DISK_LINK_PATTERN = Pattern.compile("^:[/\\w\\-\\.]*"); private String name; private FileReferenceType type; From 334d07e7405250c59328974fcdcad5f6b29fe113 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Wed, 9 Feb 2022 07:30:30 +0100 Subject: [PATCH 25/29] inline FileReferenceType --- .../filebase/references/FileReference.java | 20 ++++++---- .../references/FileReferenceType.java | 7 ---- .../filebase/uri/FileUriScriptService.java | 5 +-- .../references/FileReferenceTest.java | 18 ++++----- .../filebase/uri/FileUriServiceTest.java | 37 +++++++++---------- 5 files changed, 41 insertions(+), 46 deletions(-) delete mode 100644 src/main/java/com/celements/filebase/references/FileReferenceType.java diff --git a/src/main/java/com/celements/filebase/references/FileReference.java b/src/main/java/com/celements/filebase/references/FileReference.java index 6b77fd40b..e2626d0b2 100644 --- a/src/main/java/com/celements/filebase/references/FileReference.java +++ b/src/main/java/com/celements/filebase/references/FileReference.java @@ -4,6 +4,7 @@ import java.io.Serializable; import java.util.Objects; +import java.util.Optional; import java.util.function.Supplier; import java.util.regex.Pattern; @@ -26,6 +27,10 @@ public final class FileReference implements Serializable { private static final long serialVersionUID = 1L; + public enum FileReferenceType { + ON_DISK, ATTACHMENT, EXTERNAL; + } + @NotThreadSafe public static final class Builder { @@ -104,9 +109,8 @@ public void setFullPath(@NotNull String fullPath) { this.fullPath = fullPath; } - public void setQueryString(@NotNull String queryString) { - checkNotNull(queryString); - this.queryString = queryString; + public void setQueryString(@Nullable String queryString) { + this.queryString = Strings.emptyToNull(queryString); } public FileReference build() { @@ -121,7 +125,7 @@ public FileReference build() { private final String fullPath; private final String queryString; - public FileReference(Builder builder) { + private FileReference(Builder builder) { this.name = builder.name; this.type = builder.type; this.fullPath = builder.fullPath; @@ -145,8 +149,8 @@ public String getFullPath() { return fullPath; } - public String getQueryString() { - return queryString; + public Optional getQueryString() { + return Optional.ofNullable(queryString); } public UriBuilder getUri() { @@ -181,7 +185,7 @@ public String toString() { + fullPath + "]"; } - public static Builder of(@NotEmpty String link) { + public static FileReference of(@NotEmpty String link) { checkArgument(!Strings.isNullOrEmpty(link), "link may not be empty"); final String[] linkParts = link.split("\\?"); Builder builder = new Builder(); @@ -196,7 +200,7 @@ public static Builder of(@NotEmpty String link) { if (linkParts.length > 1) { builder.setQueryString(linkParts[1]); } - return builder; + return builder.build(); } } diff --git a/src/main/java/com/celements/filebase/references/FileReferenceType.java b/src/main/java/com/celements/filebase/references/FileReferenceType.java deleted file mode 100644 index c04a221d2..000000000 --- a/src/main/java/com/celements/filebase/references/FileReferenceType.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.celements.filebase.references; - -public enum FileReferenceType { - - ON_DISK, ATTACHMENT, EXTERNAL; - -} diff --git a/src/main/java/com/celements/filebase/uri/FileUriScriptService.java b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java index af7f6190c..a94b6438b 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriScriptService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java @@ -3,6 +3,7 @@ import java.util.Optional; import javax.annotation.Nullable; +import javax.inject.Singleton; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.ws.rs.core.UriBuilder; @@ -16,8 +17,6 @@ import com.celements.filebase.references.FileReference; import com.google.common.base.Strings; -import groovy.lang.Singleton; - @Component(FileUriScriptService.NAME) @Singleton public class FileUriScriptService implements ScriptService { @@ -31,7 +30,7 @@ public class FileUriScriptService implements ScriptService { @NotNull public FileReference createFileReference(@NotEmpty String link) { - return FileReference.of(link).build(); + return FileReference.of(link); } @NotNull diff --git a/src/test/java/com/celements/filebase/references/FileReferenceTest.java b/src/test/java/com/celements/filebase/references/FileReferenceTest.java index 7d8396d46..92fa1e1aa 100644 --- a/src/test/java/com/celements/filebase/references/FileReferenceTest.java +++ b/src/test/java/com/celements/filebase/references/FileReferenceTest.java @@ -25,36 +25,36 @@ public void test_isAttachmentLink_empty() { @Test public void test_isAttachmentLink_url() { assertFalse( - FileReference.of("/download/Space/Page/attachment.jpg").build().isAttachmentReference()); + FileReference.of("/download/Space/Page/attachment.jpg").isAttachmentReference()); } @Test public void test_isAttachmentLink_is() { - assertTrue(FileReference.of("Space.Page;attachment.jpg").build().isAttachmentReference()); + assertTrue(FileReference.of("Space.Page;attachment.jpg").isAttachmentReference()); } @Test public void test_isAttachmentLink_isSpecialChars() { - assertTrue(FileReference.of("Teilnehmer.f8Nx9vyPOX8O2;Hans-002-Bearbeitet-2.jpg").build() + assertTrue(FileReference.of("Teilnehmer.f8Nx9vyPOX8O2;Hans-002-Bearbeitet-2.jpg") .isAttachmentReference()); } @Test public void test_isAttachmentLink_isWithDb() { - assertTrue(FileReference.of("db:Space.Page;attachment.jpg").build().isAttachmentReference()); + assertTrue(FileReference.of("db:Space.Page;attachment.jpg").isAttachmentReference()); } @Test public void test_isOnDiskLink_true() { - assertTrue(FileReference.of(":bla.js").build().isOnDiskReference()); - assertTrue(FileReference.of(" :celJS/bla.js").build().isOnDiskReference()); + assertTrue(FileReference.of(":bla.js").isOnDiskReference()); + assertTrue(FileReference.of(" :celJS/bla.js").isOnDiskReference()); } @Test public void test_isOnDiskLink_false() { - assertFalse(FileReference.of("bla.js").build().isOnDiskReference()); - assertFalse(FileReference.of("x:celJS/bla.js").build().isOnDiskReference()); - assertFalse(FileReference.of("x:A.B;bla.js").build().isOnDiskReference()); + assertFalse(FileReference.of("bla.js").isOnDiskReference()); + assertFalse(FileReference.of("x:celJS/bla.js").isOnDiskReference()); + assertFalse(FileReference.of("x:A.B;bla.js").isOnDiskReference()); } } diff --git a/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java index 30e830328..f145be7ab 100644 --- a/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java +++ b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java @@ -55,21 +55,21 @@ public void setUp_RessourceUrlServiceTest() throws Exception { @Test public void test_createFileUrl_fullURL() throws Exception { - FileReference fileRef = FileReference.of("http://www.bla.com/bla.txt").build(); + FileReference fileRef = FileReference.of("http://www.bla.com/bla.txt"); assertEquals("http://www.bla.com/bla.txt", - fileUriServ.createFileUri(fileRef, Optional.empty()).build().toString()); + fileUriServ.createFileUri(fileRef, Optional.empty()).toString()); } @Test public void test_createFileUrl_partURL() throws Exception { - FileReference fileRef = FileReference.of("/xwiki/bin/download/A/B/bla.txt").build(); + FileReference fileRef = FileReference.of("/xwiki/bin/download/A/B/bla.txt"); assertEquals("/xwiki/bin/download/A/B/bla.txt", fileUriServ.createFileUri(fileRef, - Optional.empty()).build().toString()); + Optional.empty()).toString()); } @Test public void test_getExternalFileURL_partURL() throws Exception { - FileReference fileRef = FileReference.of("/xwiki/bin/download/A/B/bla.txt").build(); + FileReference fileRef = FileReference.of("/xwiki/bin/download/A/B/bla.txt"); URL viewURL = new URL("http://localhost"); expect(mockURLFactory.getServerURL(same(context))).andReturn(viewURL); replayDefault(); @@ -81,8 +81,7 @@ public void test_getExternalFileURL_partURL() throws Exception { @Test public void test_getExternalFileURL_partURL_external() throws Exception { - FileReference fileRef = FileReference.of("http://myTesthost.ch/xwiki/bin/download/A/B/bla.txt") - .build(); + FileReference fileRef = FileReference.of("http://myTesthost.ch/xwiki/bin/download/A/B/bla.txt"); URL viewURL = new URL("http://localhost"); expect(mockURLFactory.getServerURL(same(context))).andReturn(viewURL); replayDefault(); @@ -105,9 +104,9 @@ public void test_createFileUrl_dynamicParamURL() throws Exception { (String) isNull(), eq(context.getDatabase()), same(context))).andReturn(viewURL); expect(mockURLFactory.getURL(eq(viewURL), same(context))).andReturn(viewURL.getPath()); replayDefault(); - FileReference fileRef = FileReference.of("?xpage=bla&bli=blu").build(); + FileReference fileRef = FileReference.of("?xpage=bla&bli=blu"); assertEquals("/mySpace/myDoc?xpage=bla&bli=blu", fileUriServ.createFileUri(fileRef, - Optional.empty()).build().toString()); + Optional.empty()).toString()); verifyDefault(); } @@ -133,8 +132,8 @@ public void test_createFileUrl_fullInternalLink() throws Exception { expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) .atLeastOnce(); replayDefault(); - FileReference fileRef = FileReference.of("celements2web:A.B;bla.txt").build(); - String attachmentURL = fileUriServ.createFileUri(fileRef, Optional.empty()).build().toString(); + FileReference fileRef = FileReference.of("celements2web:A.B;bla.txt"); + String attachmentURL = fileUriServ.createFileUri(fileRef, Optional.empty()).toString(); assertNotNull(attachmentURL); assertTrue("expecting " + resultURL + " but got " + attachmentURL, attachmentURL.matches(resultURL + "\\?version=\\d{14}")); @@ -163,8 +162,8 @@ public void test_createFileUrl_partInternalLink() throws Exception { expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))).andReturn(blaAtt) .atLeastOnce(); replayDefault(); - FileReference fileRef = FileReference.of("A.B;bla.txt").build(); - String attachmentURL = fileUriServ.createFileUri(fileRef, Optional.empty()).build().toString(); + FileReference fileRef = FileReference.of("A.B;bla.txt"); + String attachmentURL = fileUriServ.createFileUri(fileRef, Optional.empty()).toString(); assertNotNull(attachmentURL); assertTrue("expecting " + resultURL + " but got " + attachmentURL, attachmentURL.matches(resultURL + "\\?version=\\d{14}")); @@ -183,7 +182,7 @@ public void test_createFileUrl_partInternalLink_notExists() throws Exception { expect(modelAccessMock.getAttachmentNameEqual(same(abDoc), eq(attName))) .andThrow(new AttachmentNotExistsException(attRef)).atLeastOnce(); replayDefault(); - FileReference fileRef = FileReference.of("A.B;bla.txt").build(); + FileReference fileRef = FileReference.of("A.B;bla.txt"); assertThrows(FileNotExistException.class, () -> fileUriServ.createFileUri(fileRef, Optional.empty())); verifyDefault(); @@ -197,7 +196,7 @@ public void test_createFileUrl_onDiskLink() throws Exception { new Date()); expectDefaultAction(Optional.of("download")); replayDefault(); - FileReference fileRef = FileReference.of(" :celJS/bla.js").build(); + FileReference fileRef = FileReference.of(" :celJS/bla.js"); String attachmentURL = fileUriServ.createFileUri(fileRef, Optional.empty(), Optional.empty()) .toString(); String expectedURL = "/appname/download/resources/celJS/bla.js"; @@ -209,7 +208,7 @@ public void test_createFileUrl_onDiskLink() throws Exception { @Test public void test_createFileUrl_Rubish() throws Exception { - FileReference fileRef = FileReference.of("http://A.B;bla.txt").build(); + FileReference fileRef = FileReference.of("http://A.B;bla.txt"); assertEquals("http://A.B;bla.txt", fileUriServ.createFileUri(fileRef, Optional.empty(), Optional.empty()).toString()); } @@ -234,7 +233,7 @@ public void test_createFileUrl_onDisk_queryString() throws Exception { expectDefaultAction(Optional.of("download")); String queryString = "asf=oiu"; replayDefault(); - FileReference fileRef = FileReference.of(":celJS/bla.js").build(); + FileReference fileRef = FileReference.of(":celJS/bla.js"); String attachmentURL = fileUriServ.createFileUri(fileRef, Optional.empty(), Optional.of(queryString)).toString(); String expectedURL = "/appname/download/resources/celJS/bla.js"; @@ -266,7 +265,7 @@ public void test_createFileUrl_partInternalLink_queryString() throws Exception { expectDefaultAction(Optional.empty()); String queryString = "asf=oiu"; replayDefault(); - FileReference fileRef = FileReference.of("A.B;bla.txt").build(); + FileReference fileRef = FileReference.of("A.B;bla.txt"); String attachmentURL = fileUriServ.createFileUri(fileRef, Optional.of("testAction"), Optional.of(queryString)).toString(); assertTrue(attachmentURL, @@ -308,7 +307,7 @@ public void test_createOnDiskUrl() throws Exception { .andReturn(resultURL); expectDefaultAction(Optional.empty()); replayDefault(); - FileReference fileRef = FileReference.of(":celRes/test/bla.css").build(); + FileReference fileRef = FileReference.of(":celRes/test/bla.css"); assertEquals( "http://celements2web.localhost/createOnDiskUrl/celRes/test/bla.css?version=20191230101135", fileUriServ.createOnDiskUri(fileRef, Optional.of("createOnDiskUrl")).toString()); From 094d2c04d0ba074f5280fa94f7b1af404ecdb759 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Wed, 9 Feb 2022 07:32:49 +0100 Subject: [PATCH 26/29] Merge branch 'CELDEV-1006' of git@github.com:celements/celements-core.git into CELDEV-1006 --- .../celements/filebase/references/FileReference.java | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/celements/filebase/references/FileReference.java b/src/main/java/com/celements/filebase/references/FileReference.java index d9a993ca5..209579bf4 100644 --- a/src/main/java/com/celements/filebase/references/FileReference.java +++ b/src/main/java/com/celements/filebase/references/FileReference.java @@ -5,7 +5,6 @@ import java.io.Serializable; import java.util.Objects; import java.util.Optional; -import java.util.function.Supplier; import java.util.regex.Pattern; import javax.annotation.Nullable; @@ -18,7 +17,6 @@ import com.celements.model.util.ModelUtils; import com.google.common.base.Strings; -import com.google.common.base.Suppliers; import com.google.errorprone.annotations.Immutable; import com.xpn.xwiki.web.Utils; @@ -34,9 +32,9 @@ public enum FileReferenceType { @NotThreadSafe public static final class Builder { - private static final Pattern ATTACHMENT_LINK_PATTERN = Pattern.compile( - "([\\w\\-]*:)?([\\w\\-]*\\.[\\w\\-]*){1};.*"); - private static final Pattern ON_DISK_LINK_PATTERN = Pattern.compile("^:[/\\w\\-\\.]*"); + private static final Pattern ATTACHMENT_LINK_PATTERN = Pattern.compile( + "([\\w\\-]*:)?([\\w\\-]*\\.[\\w\\-]*){1};.*"); + private static final Pattern ON_DISK_LINK_PATTERN = Pattern.compile("^:[/\\w\\-\\.]*"); private String name; private FileReferenceType type; @@ -57,14 +55,14 @@ private static String getPathFileName(@NotEmpty String link) { private static boolean isAttachmentLink(@Nullable String link) { if (link != null) { - return ATTACHMENT_LINK_PATTERN.get().matcher(link.trim()).matches(); + return ATTACHMENT_LINK_PATTERN.matcher(link.trim()).matches(); } return false; } private static boolean isOnDiskLink(@Nullable String link) { if (link != null) { - return ON_DISK_LINK_PATTERN.get().matcher(link.trim()).matches(); + return ON_DISK_LINK_PATTERN.matcher(link.trim()).matches(); } return false; } From 38fdb38dae313971fe72bc39707ad76b6558708d Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Wed, 9 Feb 2022 07:37:42 +0100 Subject: [PATCH 27/29] add NotNull/NotEmpty/Nullable annotations --- .../filebase/references/FileReference.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/celements/filebase/references/FileReference.java b/src/main/java/com/celements/filebase/references/FileReference.java index 209579bf4..b66e1ca8e 100644 --- a/src/main/java/com/celements/filebase/references/FileReference.java +++ b/src/main/java/com/celements/filebase/references/FileReference.java @@ -73,6 +73,7 @@ private static DocumentReference getPageDocRef(@NotNull String link) { DocumentReference.class); } + @NotNull private static FileReferenceType getTypeOfLink(@NotEmpty String link) { if (isOnDiskLink(link)) { return FileReferenceType.ON_DISK; @@ -82,12 +83,14 @@ private static FileReferenceType getTypeOfLink(@NotEmpty String link) { return FileReferenceType.EXTERNAL; } + @NotNull public Builder setFileName(@NotNull String fileName) { checkNotNull(fileName); this.name = fileName; return this; } + @NotNull public Builder setType(@NotNull FileReferenceType type) { checkNotNull(type); this.type = type; @@ -99,8 +102,8 @@ public void setDocRef(@NotNull DocumentReference docRef) { this.docRef = docRef; } - public void setFullPath(@NotNull String fullPath) { - checkNotNull(fullPath); + public void setFullPath(@NotEmpty String fullPath) { + checkArgument(!Strings.isNullOrEmpty(fullPath), "path may not be null or empty"); this.fullPath = fullPath; } @@ -108,6 +111,7 @@ public void setQueryString(@Nullable String queryString) { this.queryString = Strings.emptyToNull(queryString); } + @NotNull public FileReference build() { return new FileReference(this); } @@ -128,26 +132,32 @@ private FileReference(Builder builder) { this.queryString = builder.queryString; } + @NotNull public String getName() { return name; } + @NotNull public FileReferenceType getType() { return type; } + @Nullable public DocumentReference getDocRef() { return docRef; } + @NotEmpty public String getFullPath() { return fullPath; } + @NotNull public Optional getQueryString() { return Optional.ofNullable(queryString); } + @NotNull public UriBuilder getUri() { return UriBuilder.fromPath(fullPath).replaceQuery(queryString); } @@ -180,6 +190,7 @@ public String toString() { + fullPath + "]"; } + @NotNull public static FileReference of(@NotEmpty String link) { checkArgument(!Strings.isNullOrEmpty(link), "link may not be empty"); final String[] linkParts = link.split("\\?"); From 4c02d4f3b682b5b9665286bd958e1d1a3dabc183 Mon Sep 17 00:00:00 2001 From: Marc Sladek Date: Fri, 11 Feb 2022 19:02:27 +0100 Subject: [PATCH 28/29] remove ImmutableDocumentReference --- .../java/com/celements/docform/DocFormRequestKey.java | 6 ++---- .../celements/docform/DocFormRequestKeyParser.java | 11 ++++++----- .../celements/auth/user/CelementsUserServiceTest.java | 6 +++--- .../docform/DocFormRequestKeyParserTest.java | 4 ++-- .../com/celements/docform/DocFormRequestKeyTest.java | 4 ++-- .../celements/docform/DocFormScriptServiceTest.java | 5 +++-- ...PasswordRecoveryAndEmailValidationCommandTest.java | 6 +++--- 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/main/java/com/celements/docform/DocFormRequestKey.java b/src/main/java/com/celements/docform/DocFormRequestKey.java index 4f436fe2b..87bf66886 100644 --- a/src/main/java/com/celements/docform/DocFormRequestKey.java +++ b/src/main/java/com/celements/docform/DocFormRequestKey.java @@ -1,6 +1,5 @@ package com.celements.docform; -import static com.celements.model.util.References.*; import static com.google.common.base.Preconditions.*; import static com.google.common.base.Strings.*; @@ -11,7 +10,6 @@ import org.xwiki.model.reference.ClassReference; import org.xwiki.model.reference.DocumentReference; -import org.xwiki.model.reference.ImmutableDocumentReference; import com.google.common.collect.ComparisonChain; import com.google.common.collect.Ordering; @@ -25,7 +23,7 @@ public enum Type { private final String keyString; private final Type type; - private final ImmutableDocumentReference docRef; + private final DocumentReference docRef; private final ClassReference classRef; private final int objNb; private final boolean remove; @@ -59,7 +57,7 @@ private DocFormRequestKey(String key, Type type, DocumentReference docRef, ClassReference classRef, int objNb, boolean remove, String fieldName) { this.keyString = checkNotNull(emptyToNull(key)); this.type = checkNotNull(type); - this.docRef = cloneRef(docRef, ImmutableDocumentReference.class); + this.docRef = checkNotNull(docRef); this.classRef = classRef; this.objNb = objNb; this.remove = remove; diff --git a/src/main/java/com/celements/docform/DocFormRequestKeyParser.java b/src/main/java/com/celements/docform/DocFormRequestKeyParser.java index 771a15951..5c00e5840 100644 --- a/src/main/java/com/celements/docform/DocFormRequestKeyParser.java +++ b/src/main/java/com/celements/docform/DocFormRequestKeyParser.java @@ -1,8 +1,8 @@ package com.celements.docform; import static com.celements.docform.DocFormRequestKey.*; -import static com.celements.model.util.References.*; import static com.celements.web.classes.oldcore.XWikiDocumentClass.*; +import static com.google.common.base.Preconditions.*; import static com.google.common.base.Strings.*; import static com.google.common.collect.ImmutableList.*; import static com.google.common.collect.ImmutableSet.*; @@ -15,12 +15,13 @@ import java.util.function.Supplier; import java.util.regex.Pattern; +import javax.validation.constraints.NotNull; + import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xwiki.model.reference.ClassReference; import org.xwiki.model.reference.DocumentReference; -import org.xwiki.model.reference.ImmutableDocumentReference; import com.celements.model.classes.ClassDefinition; import com.celements.model.classes.fields.ClassField; @@ -46,10 +47,10 @@ public class DocFormRequestKeyParser { /** * used if no fullName is provided in the parsed string keys */ - private final ImmutableDocumentReference defaultDocRef; + private final DocumentReference defaultDocRef; - public DocFormRequestKeyParser(DocumentReference defaultDocRef) { - this.defaultDocRef = cloneRef(defaultDocRef, ImmutableDocumentReference.class); + public DocFormRequestKeyParser(@NotNull DocumentReference defaultDocRef) { + this.defaultDocRef = checkNotNull(defaultDocRef); } /** diff --git a/src/test/java/com/celements/auth/user/CelementsUserServiceTest.java b/src/test/java/com/celements/auth/user/CelementsUserServiceTest.java index 36b089eff..d0f0a64a6 100644 --- a/src/test/java/com/celements/auth/user/CelementsUserServiceTest.java +++ b/src/test/java/com/celements/auth/user/CelementsUserServiceTest.java @@ -16,7 +16,6 @@ import org.junit.Test; import org.xwiki.configuration.ConfigurationSource; import org.xwiki.model.reference.DocumentReference; -import org.xwiki.model.reference.ImmutableDocumentReference; import org.xwiki.model.reference.WikiReference; import org.xwiki.query.Query; import org.xwiki.query.QueryManager; @@ -31,6 +30,7 @@ import com.celements.model.classes.ClassDefinition; import com.celements.model.classes.fields.ClassField; import com.celements.model.object.xwiki.XWikiObjectFetcher; +import com.celements.model.reference.RefBuilder; import com.celements.query.IQueryExecutionServiceRole; import com.celements.rights.access.EAccessLevel; import com.celements.web.classes.oldcore.XWikiGroupsClass; @@ -51,8 +51,8 @@ public class CelementsUserServiceTest extends AbstractComponentTest { private CelementsUserService service; - private final DocumentReference userDocRef = new ImmutableDocumentReference("xwikidb", "XWiki", - "msladek"); + private final DocumentReference userDocRef = RefBuilder.create() + .wiki("XWiki").space("XWiki").doc("msladek").build(DocumentReference.class); @Before public void prepareTest() throws Exception { diff --git a/src/test/java/com/celements/docform/DocFormRequestKeyParserTest.java b/src/test/java/com/celements/docform/DocFormRequestKeyParserTest.java index 01aa467c6..6d666c0a1 100644 --- a/src/test/java/com/celements/docform/DocFormRequestKeyParserTest.java +++ b/src/test/java/com/celements/docform/DocFormRequestKeyParserTest.java @@ -13,7 +13,6 @@ import org.xwiki.model.reference.ClassReference; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.EntityReference; -import org.xwiki.model.reference.ImmutableDocumentReference; import com.celements.common.test.AbstractComponentTest; import com.celements.docform.DocFormRequestKeyParser.DocFormRequestParseException; @@ -31,7 +30,8 @@ public class DocFormRequestKeyParserTest extends AbstractComponentTest { @Before public void prepare() throws Exception { db = getContext().getDatabase(); - defaultDocRef = new ImmutableDocumentReference(db, "Space", "DefaultDoc"); + defaultDocRef = RefBuilder.create().wiki(db).space("space").doc("DefaultDoc") + .build(DocumentReference.class); parser = new DocFormRequestKeyParser(defaultDocRef); } diff --git a/src/test/java/com/celements/docform/DocFormRequestKeyTest.java b/src/test/java/com/celements/docform/DocFormRequestKeyTest.java index 3f6777728..524598ca0 100644 --- a/src/test/java/com/celements/docform/DocFormRequestKeyTest.java +++ b/src/test/java/com/celements/docform/DocFormRequestKeyTest.java @@ -13,8 +13,8 @@ import org.junit.Test; import org.xwiki.model.reference.ClassReference; import org.xwiki.model.reference.DocumentReference; -import org.xwiki.model.reference.ImmutableDocumentReference; +import com.celements.model.reference.RefBuilder; import com.google.common.collect.ImmutableList; public class DocFormRequestKeyTest { @@ -104,7 +104,7 @@ private List getSortedKeys() { } private DocumentReference getDocRef(String name) { - return new ImmutableDocumentReference("db", "space", name); + return RefBuilder.create().wiki("db").space("space").doc(name).build(DocumentReference.class); } private ClassReference getClassRef(String name) { diff --git a/src/test/java/com/celements/docform/DocFormScriptServiceTest.java b/src/test/java/com/celements/docform/DocFormScriptServiceTest.java index 2d0fec95a..fe9618272 100644 --- a/src/test/java/com/celements/docform/DocFormScriptServiceTest.java +++ b/src/test/java/com/celements/docform/DocFormScriptServiceTest.java @@ -13,13 +13,13 @@ import org.junit.Before; import org.junit.Test; import org.xwiki.model.reference.DocumentReference; -import org.xwiki.model.reference.ImmutableDocumentReference; import org.xwiki.script.service.ScriptService; import com.celements.common.test.AbstractComponentTest; import com.celements.docform.IDocForm.ResponseState; import com.celements.model.access.IModelAccessFacade; import com.celements.model.access.exception.DocumentSaveException; +import com.celements.model.reference.RefBuilder; import com.celements.rights.access.IRightsAccessFacadeRole; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -38,7 +38,8 @@ public class DocFormScriptServiceTest extends AbstractComponentTest { public void prepareTest() throws Exception { registerComponentMocks(IModelAccessFacade.class, IRightsAccessFacadeRole.class); docFormService = (DocFormScriptService) Utils.getComponent(ScriptService.class, "docform"); - docRef = new ImmutableDocumentReference("db", "space", "doc"); + docRef = RefBuilder.create().wiki("db").space("space").doc("doc") + .build(DocumentReference.class); getContext().setRequest(new XWikiServletRequestStub()); } diff --git a/src/test/java/com/celements/web/plugin/cmd/PasswordRecoveryAndEmailValidationCommandTest.java b/src/test/java/com/celements/web/plugin/cmd/PasswordRecoveryAndEmailValidationCommandTest.java index 7e5fe60bc..0f04d38a8 100644 --- a/src/test/java/com/celements/web/plugin/cmd/PasswordRecoveryAndEmailValidationCommandTest.java +++ b/src/test/java/com/celements/web/plugin/cmd/PasswordRecoveryAndEmailValidationCommandTest.java @@ -30,7 +30,6 @@ import org.junit.Before; import org.junit.Test; import org.xwiki.model.reference.DocumentReference; -import org.xwiki.model.reference.ImmutableDocumentReference; import org.xwiki.query.QueryException; import com.celements.auth.IAuthenticationServiceRole; @@ -42,6 +41,7 @@ import com.celements.common.test.TestMessageTool; import com.celements.model.access.IModelAccessFacade; import com.celements.model.access.exception.DocumentSaveException; +import com.celements.model.reference.RefBuilder; import com.celements.web.classes.oldcore.XWikiUsersClass; import com.celements.web.service.IWebUtilsService; import com.xpn.xwiki.api.Attachment; @@ -54,8 +54,8 @@ public class PasswordRecoveryAndEmailValidationCommandTest extends AbstractComponentTest { - private final DocumentReference userDocRef = new ImmutableDocumentReference("db", "XWiki", - "msladek"); + private final DocumentReference userDocRef = RefBuilder.create() + .wiki("db").space("XWiki").doc("msladek").build(DocumentReference.class); private PasswordRecoveryAndEmailValidationCommand cmd; From d05cae71a28193d1fb62e9cf2e53bee7502b96b1 Mon Sep 17 00:00:00 2001 From: Fabian Pichler Date: Wed, 20 Apr 2022 06:20:43 +0200 Subject: [PATCH 29/29] redefine FileUriServiceRole as FileUrlServiceRole --- .../filebase/uri/FileUriScriptService.java | 6 ++--- .../filebase/uri/FileUriService.java | 4 +-- .../filebase/uri/FileUriServiceRole.java | 26 ------------------- .../filebase/uri/FileUrlServiceRole.java | 26 +++++++++++++++++++ .../web/plugin/cmd/AttachmentURLCommand.java | 10 +++---- .../filebase/uri/FileUriServiceTest.java | 4 +-- 6 files changed, 38 insertions(+), 38 deletions(-) delete mode 100644 src/main/java/com/celements/filebase/uri/FileUriServiceRole.java create mode 100644 src/main/java/com/celements/filebase/uri/FileUrlServiceRole.java diff --git a/src/main/java/com/celements/filebase/uri/FileUriScriptService.java b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java index a94b6438b..878fc2f61 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriScriptService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriScriptService.java @@ -26,7 +26,7 @@ public class FileUriScriptService implements ScriptService { private static final Logger LOGGER = LoggerFactory.getLogger(FileUriScriptService.class); @Requirement - private FileUriServiceRole fileUriService; + private FileUrlServiceRole fileUriService; @NotNull public FileReference createFileReference(@NotEmpty String link) { @@ -69,12 +69,12 @@ public UriBuilder createFileUrl(@Nullable FileReference fileRef, @Nullable Strin @NotNull public UriBuilder getFileURLPrefix() { - return fileUriService.getFileUriPrefix(Optional.empty()); + return fileUriService.getFileUrlPrefix(Optional.empty()); } @NotNull public UriBuilder getFileURLPrefix(@Nullable String action) { - return fileUriService.getFileUriPrefix(Optional.ofNullable(action)); + return fileUriService.getFileUrlPrefix(Optional.ofNullable(action)); } @NotNull diff --git a/src/main/java/com/celements/filebase/uri/FileUriService.java b/src/main/java/com/celements/filebase/uri/FileUriService.java index 2b000b973..2a0587c31 100644 --- a/src/main/java/com/celements/filebase/uri/FileUriService.java +++ b/src/main/java/com/celements/filebase/uri/FileUriService.java @@ -32,7 +32,7 @@ @Component @Singleton -public class FileUriService implements FileUriServiceRole { +public class FileUriService implements FileUrlServiceRole { private static final Logger LOGGER = LoggerFactory.getLogger(FileUriService.class); @@ -62,7 +62,7 @@ private String getDefaultAction() { } @Override - public @NotNull UriBuilder getFileUriPrefix(@NotNull Optional action) { + public @NotNull UriBuilder getFileUrlPrefix(@NotNull Optional action) { URL baseUrl = getUrlFactory().createResourceURL("", false, context.getXWikiContext()); try { return UriBuilder.fromUri(baseUrl.toURI()) diff --git a/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java b/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java deleted file mode 100644 index fafee8b98..000000000 --- a/src/main/java/com/celements/filebase/uri/FileUriServiceRole.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.celements.filebase.uri; - -import java.util.Optional; - -import javax.validation.constraints.NotNull; -import javax.ws.rs.core.UriBuilder; - -import org.xwiki.component.annotation.ComponentRole; - -import com.celements.filebase.references.FileReference; - -@ComponentRole -public interface FileUriServiceRole { - - @NotNull - UriBuilder createFileUri(@NotNull FileReference fileRef, @NotNull Optional action, - @NotNull Optional queryString) throws FileNotExistException; - - @NotNull - UriBuilder getFileUriPrefix(@NotNull Optional action); - - @NotNull - UriBuilder createAbsoluteFileUri(@NotNull FileReference fileRef, @NotNull Optional action, - Optional queryString); - -} diff --git a/src/main/java/com/celements/filebase/uri/FileUrlServiceRole.java b/src/main/java/com/celements/filebase/uri/FileUrlServiceRole.java new file mode 100644 index 000000000..f43e7ba52 --- /dev/null +++ b/src/main/java/com/celements/filebase/uri/FileUrlServiceRole.java @@ -0,0 +1,26 @@ +package com.celements.filebase.uri; + +import java.net.URL; + +import javax.annotation.Nullable; +import javax.validation.constraints.NotNull; + +import org.xwiki.component.annotation.ComponentRole; + +import com.celements.filebase.references.FileReference; + +@ComponentRole +public interface FileUrlServiceRole { + + @NotNull + URL getFileUrl(@NotNull FileReference fileRef, @Nullable String action) + throws FileNotExistException; + + @NotNull + URL getFileUrl(@NotNull FileReference fileRef, @Nullable String action, + @Nullable String queryString) throws FileNotExistException; + + @NotNull + URL getFileUrlPrefix(@NotNull String action); + +} diff --git a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java index 6f3cb08b9..99b71547d 100644 --- a/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java +++ b/src/main/java/com/celements/web/plugin/cmd/AttachmentURLCommand.java @@ -30,7 +30,7 @@ import com.celements.filebase.IAttachmentServiceRole; import com.celements.filebase.references.FileReference; -import com.celements.filebase.uri.FileUriServiceRole; +import com.celements.filebase.uri.FileUrlServiceRole; import com.celements.model.access.exception.AttachmentNotExistsException; import com.celements.web.service.LastStartupTimeStampRole; import com.xpn.xwiki.XWikiContext; @@ -41,7 +41,7 @@ import com.xpn.xwiki.web.XWikiURLFactory; /** - * @deprecated since 5.4 instead use {@link FileUriServiceRole} + * @deprecated since 5.4 instead use {@link FileUrlServiceRole} */ @Deprecated public class AttachmentURLCommand { @@ -50,7 +50,7 @@ public class AttachmentURLCommand { /** * @deprecated since 5.4 instead use - * {@link FileUriServiceRole#createFileUri(String, Optional)} + * {@link FileUrlServiceRole#createFileUri(String, Optional)} */ @Deprecated public String getAttachmentURL(String link, XWikiContext context) { @@ -63,7 +63,7 @@ private String getDefaultAction() { } /** - * @deprecated since 5.4 instead use {@link FileUriServiceRole#getFileURLPrefix()} + * @deprecated since 5.4 instead use {@link FileUrlServiceRole#getFileURLPrefix()} */ @Deprecated public String getAttachmentURLPrefix() { @@ -71,7 +71,7 @@ public String getAttachmentURLPrefix() { } /** - * @deprecated since 5.4 instead use {@link FileUriServiceRole#getFileUriPrefix(String)} + * @deprecated since 5.4 instead use {@link FileUrlServiceRole#getFileUrlPrefix(String)} */ @Deprecated public String getAttachmentURLPrefix(String action) { diff --git a/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java index f145be7ab..4cf278607 100644 --- a/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java +++ b/src/test/java/com/celements/filebase/uri/FileUriServiceTest.java @@ -50,7 +50,7 @@ public void setUp_RessourceUrlServiceTest() throws Exception { wiki = getWikiMock(); mockURLFactory = createMockAndAddToDefault(XWikiURLFactory.class); context.setURLFactory(mockURLFactory); - fileUriServ = (FileUriService) Utils.getComponent(FileUriServiceRole.class); + fileUriServ = (FileUriService) Utils.getComponent(FileUrlServiceRole.class); } @Test @@ -220,7 +220,7 @@ public void test_getFileURLPrefix() throws Exception { "http://test.fabian.dev:10080/resources/")); replayDefault(); assertEquals("http://test.fabian.dev:10080/file/resources/", - fileUriServ.getFileUriPrefix(Optional.empty()).toString()); + fileUriServ.getFileUrlPrefix(Optional.empty()).toString()); verifyDefault(); }