Skip to content

Commit

Permalink
Revert "[GEOS-11050] Refactor Resources and Paths API"
Browse files Browse the repository at this point in the history
This reverts commit e0f0a05.
  • Loading branch information
jodygarnett committed Feb 29, 2024
1 parent e0f0a05 commit 6fec0cf
Show file tree
Hide file tree
Showing 23 changed files with 363 additions and 544 deletions.
113 changes: 31 additions & 82 deletions doc/en/developer/source/programming-guide/config/resource.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,51 +17,21 @@ Reference:
* `GSIP-136 - Resource Notification Dispatcher <https://github.com/geoserver/geoserver/wiki/GSIP-136>`__
* `GSIP-132 - GSIP 132 - Resource Store changes <https://github.com/geoserver/geoserver/wiki/GSIP-132>`__

Parameter Naming Convention
---------------------------
.. note::

The methods in the Resource API use String parameter names consistently:
The methods in the Resource API use String parameter names consistently:

* ``resource path`` parameter is a path to a resource in the resource store.

In the case of the default FileSystemResourceStore, this is file path that is relative with respect to the data directory. To preserve generic behaviour compatible with any resource store, developers should not assume this to be the case.

Resource paths do not support the `.` and `..` relative directory names. Resource paths use forward slashes, similar to URL's and unix style file paths, and are OS-independent.

* ``file path`` parameter is an absolute path to a file in the file system.

While these are OS dependent (with regard to the root of the absolute path) but they must always use forward slashes, as supported by all operating systems and compatible with resource paths as well as file URL's. Note that ``Resource.path()`` for resources obtained by ``Files.asResource(file)`` will return a file path rather than a resource path.

* ``file`` parameter is a java File reference.

* ``url`` a location resolved with respect to the resource store.

A number of special cases developed over time distilled into ``Resources.fromUrl(base,url)`` method.

General Guidelines
------------------

All geoserver developers should be wary of the following general principles when contributing or reviewing:

* Avoid as much as possible using the file system directly.
* ``path`` relative location of resource within the data directory.

.. note:: The only acceptable exception is when third party libraries require use of a File. Even in this case use Resources API as much as possible.

* Use Avoid the usage of ``Resource.file()`` and ``Resource.directory()``.
Paths are represented similar to a File URL, ``file://`` prefix used internally and
by the resource REST API.

* ``file`` a java File reference.

These methods are only necessary for third party libraries that require usage of the file system, when the third party library accepts a file input.
* ``url`` a location resolved with respect to the data directory.

.. note:: The ``file()`` and ``directory()`` methods are never be used for permanent storage. Since there are alternative implementations of the ResourceStore that do not use the file system as underlying storage device, modifying a file on disk does not necessarily have a lasting effect.

* For custom configuration files with a fixed location, always use ``ResourceStore``.
A large number of special cases developed over time distilled into ``Resources.fromUrl(base,url)`` and ``Files.url(base,url)`` methods.

``GeoServerResourceLoader`` and ``GeoServerDataDirectory`` from GeoServer 1.0 have been rewritten internally to use Resource API , and should not be used in new code.

* For URL's provided by user configuration (such as templates, style sheets, etc), use ``Resources.fromURL``.

* For input/output, always use ``Resource.in()`` and ``Resource.out()``.
x
This approach is compatible with java try-with-resource making for easy to follow code.

ResourceStore
-------------
Expand All @@ -72,10 +42,10 @@ InputStream used to access configuration information:

.. code-block:: java
Properties properties = new Properties();
try (InputStream in = resourceStore.get("module/configuration.properties").in() ){
properties.load(in);
}
Properties properties = new Properties();
try (InputStream in = resourceStore.get("module/configuration.properties").in() ){
properties.load(in);
}
An OutputStream is provided for storage (a Resource will be created as needed):

Expand Down Expand Up @@ -113,19 +83,17 @@ Resource contents are streamed using ``out()`` and ``in()`` methods. The entire
Resource ``path()`` provides the complete path relative to the ``ResourceStore`` base directory. Use ``name()`` to retrieve the resource name (as the last component in the path name sequence).

Resource creation is handled in a lazy fashion, use ``out()`` and the resource will be created as required, including any required parent directories are created to produce the completed path.
Resource creation is handled in a lazy fashion, use ``file()`` or ``out()`` and the resource will be created as required.

Directory resources have the ability to ``list()`` their contents:
Use ``dir()`` to create a empty directory. Directories have the ability to ``list()`` their contents:

.. code-block:: java
for( Resource child : resource.list()) {
...
}
The method ``isInternal()`` returns whether the resource is part of the resource store or rather a wrapped file obtained by ``File.asResource``. If this method returns `false` then ``path()`` returns a file path rather than a resource path.

The methods ``file()`` and ``dir()`` may be used to obtain a file system representation of the resource. Depending on the resource store implementation, this may be the underlying storage entity (in the case of the default FileSystemResourceStore), or merely a cached entity. Changes to these should not be assumed to be permanent. These methods should only be used for input when a third library requires a file and does not support passing on streams.
When creating a resource with ``file()``, ``out()`` or ``dir()`` any required parent directories are created to produce the completed path).

Once created resources can be managed with ``delete()``, ``renameTo(resource)`` methods.

Expand All @@ -136,7 +104,7 @@ Resource ``lock()`` is also supported.
Paths
-----

The ``Paths`` facade provides methods for working with resource paths used by ResourceStore.
The ``Paths`` facade provides methods for working with the relative paths used by ResourceStore.

Helpful methods are provided for working with paths and names:

Expand All @@ -146,21 +114,14 @@ Helpful methods are provided for working with paths and names:
* ``sidecar(path, extension)``
* ``names(path)`` processes the path into a list of names as discussed below.

The definition of a path has been expanded to work with the external locations (with ``Paths.isAbsolute(path)`` and ``Paths.names(path)``).

Paths are broken down into a sequence of names, as listed by ``Paths.names(path)``:

* ``Path.names("data/tasmania/roads.shp")`` is represented as a list of ``data``, ``tasmania``, ``roads.shp``.
* On linux ``Path.names("/src/gis/cadaster/district.geopkg")`` starts with a marker to indicate an absolute path, resulting in ``/``, ``src``, ``gis``, ``cadaster``, ``district.geopkg``.
* On windows ``Path.names("D:/gis/cadaster/district.geopkg")`` starts with a marker to indicate an absolute path, resulting in ``D:/``, ``gis``, ``cadaster``, ``district.geopkg``.

For file paths that are OS dependent, use ``FilePaths.names(file_path)`` instead.

FilePaths
---------

The ``FilePaths`` facade provides methods for working with file paths.

Paths are broken down into a sequence of names, as listed by ``Paths.names(path)``:

* On linux ``FilePath.names("/src/gis/cadaster/district.geopkg")`` starts with a marker to indicate an absolute path, resulting in ``/``, ``src``, ``gis``, ``cadaster``, ``district.geopkg``.
* On windows ``FilePath.names("D:/gis/cadaster/district.geopkg")`` starts with a marker to indicate an absolute path, resulting in ``D:/``, ``gis``, ``cadaster``, ``district.geopkg``.


Paths.convert
Expand Down Expand Up @@ -206,45 +167,33 @@ There are also method for working with directories recursively and filtering con
Resources.fromUrl
^^^^^^^^^^^^^^^^^

The interpretation of the URLs is as follows:

* ``resource:`` prefix - interpreted as a resource path, returns resource from the resource store.
* ``file:`` prefix with absolute path - interpreted as file path, returns resource created by Files.asResource that refers to file in the file system.
* ``file:`` prefix with relative path (deprecated) - interpreted as a resource path, returns resource from the resource store.
There is an important method ``Resources.fromURL( baseDirectory, url)`` that is used by a lot of code trying to understand data references:

Examples:

* ``Resources.fromURL( baseDirectory, "resource:images/image.png")`` - resource path
* ``Resources.fromURL( baseDirectory, "file:images/image.png")`` - resource path (deprecated)
* ``Resources.fromURL( null, "/src/gis/cadaster/district.geopgk")`` - absolute file path (linux)
* ``Resources.fromURL( baseDirectory, "D:\\gis\\cadaster\\district.geopkg")`` - absolute file path (windows)
* ``Resources.fromURL( baseDirectory, "file:///D:/gis/cadaster/district.geopkg")`` - absolute file url (windows)
* ``Resources.fromURL( baseDirectory, "ftp://veftp.gsfc.nasa.gov/bluemarble/")`` - null (external reference)

For the absolute file references above, see the next section on ``Files.url``.

Files
-----

The ``Files`` facade provides methods for working with file objects, and one method of critical importace to the Resource API.

Files.asResource
^^^^^^^^^^^^^^^^

The ``Files.asResource(file)`` method creates a ``ResourceAdapter`` wrapper around an absolute file location. Allows the use of Resource API when working with content outside of the data directory. This is primary useful for writing test cases.
The ``Files.asResource(file)`` method creates a ``ResourceAdapter`` wrapper around an absolute file location. Allows the use of Resource API when working with content outside of the data directory.

Files.url
^^^^^^^^^

.. warning:: This method is deprecated along with File use, recommend use of ``Resources.fromURL (baseDirectory, url )`` to obtain Resource.

The other key method is ``Files.url( baseDirectory, url)`` which is used to look up files based on a user provided URL (or path).


* ``Files.url( null, "resource:styles/logo.svg")`` - internal url format restricted to data directory content
* ``Files.url( null, "/src/gis/cadaster/district.geopgk")`` - absolute file path (linux)
* ``Files.url( baseDirectory, "D:\\gis\\cadaster\\district.geopkg")`` - absolute file path (windows)
* ``Files.url( baseDirectory, "file:///D:/gis/cadaster/district.geopkg")`` - absolute file url (windows)
* ``Files.url( baseDirectory, "ftp://veftp.gsfc.nasa.gov/bluemarble/")`` - null (external reference ignored as we cannot determine a file)
* ``Files.url( baseDirectory, "sde://user:pass@server:port")`` - null (custom strings are ignored as we cannot determine a file)
* ``Files.fromURL( null, "resource:styles/logo.svg")`` - internal url format restricted to data directory content
* ``Files.fromURL( null, "/src/gis/cadaster/district.geopgk")`` - absolute file path (linux)
* ``Files.fromURL( baseDirectory, "D:\\gis\\cadaster\\district.geopkg")`` - absolute file path (windows)
* ``Files.fromURL( baseDirectory, "file:///D:/gis/cadaster/district.geopkg")`` - absolute file url (windows)
* ``Files.fromURL( baseDirectory, "ftp://veftp.gsfc.nasa.gov/bluemarble/")`` - null (external reference ignored as we cannot determine a file)
* ``Files.fromURL( baseDirectory, "sde://user:pass@server:port")`` - null (custom strings are ignored as we cannot determine a file)


GeoServerDataDirectory
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,25 @@ public void testResourceInfoAdditionalResourceWriter() throws IOException {
GeoServerDataDirectory td = new GeoServerDataDirectory(root);

Resource srcTemplatesDir = BackupUtils.dir(dd.get(Paths.BASE), "templates");
File srcTitleFtl = srcTemplatesDir.get("title.ftl").file();
File srcTitleFtl =
Resources.createNewFile(
Files.asResource(new File(srcTemplatesDir.dir(), "title.ftl")));
File srcHeaderFtl =
dd.get(Paths.BASE)
.get(Paths.path("workspaces", "gs", "foo", "t1", "header.ftl"))
.file();
Resources.createNewFile(
Files.asResource(
new File(
Paths.toFile(
dd.get(Paths.BASE).dir(),
Paths.path("workspaces", "gs", "foo", "t1")),
"header.ftl")));
File srcFakeFtl =
dd.get(Paths.BASE)
.get(Paths.path("workspaces", "gs", "foo", "t1", "fake.ftl"))
.file();
Resources.createNewFile(
Files.asResource(
new File(
Paths.toFile(
dd.get(Paths.BASE).dir(),
Paths.path("workspaces", "gs", "foo", "t1")),
"fake.ftl")));

assertTrue(Resources.exists(Files.asResource(srcTitleFtl)));
assertTrue(Resources.exists(Files.asResource(srcHeaderFtl)));
Expand All @@ -80,11 +90,21 @@ public void testResourceInfoAdditionalResourceWriter() throws IOException {

assertTrue(Resources.exists(trgTemplatesDir));

Resource trgTitleFtl = trgTemplatesDir.get("title.ftl");
Resource trgTitleFtl = Files.asResource(new File(trgTemplatesDir.dir(), "title.ftl"));
Resource trgHeaderFtl =
td.get(Paths.BASE).get(Paths.path("workspaces", "gs", "foo", "t1", "header.ftl"));
Files.asResource(
new File(
Paths.toFile(
td.get(Paths.BASE).dir(),
Paths.path("workspaces", "gs", "foo", "t1")),
"header.ftl"));
Resource trgFakeFtl =
td.get(Paths.BASE).get(Paths.path("workspaces", "gs", "foo", "t1", "fake.ftl"));
Files.asResource(
new File(
Paths.toFile(
td.get(Paths.BASE).dir(),
Paths.path("workspaces", "gs", "foo", "t1")),
"fake.ftl"));

assertTrue(Resources.exists(trgTitleFtl));
assertTrue(Resources.exists(trgHeaderFtl));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Set;
Expand All @@ -21,7 +19,7 @@
import org.geoserver.catalog.WorkspaceInfo;
import org.geoserver.importer.job.ProgressMonitor;
import org.geoserver.platform.GeoServerExtensions;
import org.geoserver.platform.resource.FilePaths;
import org.geoserver.platform.resource.Files;
import org.geoserver.platform.resource.Paths;
import org.geotools.api.data.DataStoreFactorySpi;
import org.geotools.api.data.FileDataStoreFactorySpi;
Expand Down Expand Up @@ -116,19 +114,9 @@ protected String relativeDataFileURL(String url, Catalog catalog) {
return url;
}
File baseDirectory = catalog.getResourceLoader().getBaseDirectory();
File f;
try {
f = new File(new URL(url).getFile());
} catch (MalformedURLException e) {
f = new File(url);
}
File f = Files.url(baseDirectory, url);

String relativePath = Paths.convert(baseDirectory, f);
if (!FilePaths.isAbsolute(relativePath)) {
return "file:" + relativePath;
} else {
return url;
}
return f == null ? url : "file:" + Paths.convert(baseDirectory, f);
}

public abstract String getName();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ protected Component getContents(String id) {
for (int i = 1; Resources.exists(store().get(dest)); i++) {
dest = getIthPath(i);
}
editPanel = new PanelEdit(id, store().get(dest), true, "");
editPanel = new PanelEdit(id, dest, true, "");
return editPanel;
}

Expand All @@ -380,7 +380,11 @@ private String getPath() {
protected boolean onSubmit(AjaxRequestTarget target, Component contents) {
editPanel.getFeedbackMessages().clear();
String resourcePath = editPanel.getResource();
if (!Paths.isValid(resourcePath)) {
if (Paths.isAbsolute(resourcePath)) {
// although ResourceStore.get(path) is limited to relative paths
// out of an abundance of caution we will reject
error(getLocalizer().getString("pathUnsupported", getPage()));
} else if (!Paths.isValid(resourcePath)) {
try {
Paths.valid(resourcePath);
} catch (IllegalArgumentException reason) {
Expand Down Expand Up @@ -461,7 +465,7 @@ public void onClick(AjaxRequestTarget target) {

@Override
protected Component getContents(String id) {
editPanel = new PanelEdit(id, resource, false, contents);
editPanel = new PanelEdit(id, resource.path(), false, contents);
return editPanel;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.geoserver.platform.resource.Resource;
import org.geoserver.platform.resource.Paths;

/**
* Panel for editing.
Expand All @@ -22,16 +22,16 @@ public class PanelEdit extends Panel {

private static final long serialVersionUID = -31594049414032328L;

public PanelEdit(String id, Resource resource, boolean isNew, String contents) {
public PanelEdit(String id, String resource, boolean isNew, String contents) {
super(id);
if (!resource.isInternal()) {
if (Paths.isAbsolute(resource)) {
// double check resource browser cannot be used to edit
// files outside of resource store
// absolute path locations
throw new IllegalStateException("Path location not supported by Resource Browser");
}
add(new FeedbackPanel("feedback").setOutputMarkupId(true));
add(
new TextField<String>("resource", new Model<>(resource.toString())) {
new TextField<String>("resource", new Model<>(resource)) {
private static final long serialVersionUID = 1019950718780805835L;

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import java.util.Set;
import java.util.TreeSet;
import org.apache.wicket.model.IModel;
import org.geoserver.platform.resource.Paths;
import org.geoserver.platform.resource.Resource;
import org.geoserver.platform.resource.Resources;
import org.geoserver.web.treeview.TreeNode;
Expand All @@ -29,9 +30,9 @@ public class ResourceNode implements TreeNode<Resource>, Comparable<ResourceNode
private String uniqueId;

public ResourceNode(Resource resource, ResourceExpandedStates expandedStates) {
if (!resource.isInternal()) {
if (Paths.isAbsolute(resource.path())) {
// double check resource browser cannot be used to edit
// files outside of resource store
// absolute path locations
throw new IllegalStateException("Path location not supported by Resource Browser");
}
this.resource = Resources.serializable(resource);
Expand Down
Loading

0 comments on commit 6fec0cf

Please sign in to comment.