[java-opensaml] branch main updated: OSJ-468 - Add file and resource backed StorageServices

Codeberg noreply at shibboleth.net
Tue Nov 17 18:11:01 UTC 2026


This is an automated email from the git hooks/post-receive script.

codeberg pushed a commit to branch main
in repository java-opensaml.

View the commit online:
https://codeberg.org/Shibboleth/java-opensaml/commit/9404eaa08d0a86728354d60d3e9f944068c804fb

The following commit(s) were added to refs/heads/main by this push:
     new 9404eaa08 OSJ-468 - Add file and resource backed StorageServices
9404eaa08 is described below

commit 9404eaa08d0a86728354d60d3e9f944068c804fb
Author: Scott Cantor <scott at restingparrotsoftware.com>
AuthorDate: Tue Nov 17 13:10:35 2026 -0500

    OSJ-468 - Add file and resource backed StorageServices
    
    https://shibboleth.atlassian.net/browse/OSJ-468
---
 .../storage/impl/FilesystemStorageService.java     | 321 ++++++++++++++++++++
 .../impl/ResourceBackedMemoryStorageService.java   | 324 +++++++++++++++++++++
 .../storage/impl/FilesystemStorageServiceTest.java | 239 +++++++++++++++
 .../ResourceBackedMemoryStorageServiceTest.java    | 110 +++++++
 .../memcached/MemcachedStorageServiceTest.java     |   1 -
 .../org/opensaml/storage/impl/invalid-storage1.txt |   1 +
 .../org/opensaml/storage/impl/invalid-storage2.txt |   1 +
 .../org/opensaml/storage/impl/valid-storage.txt    |   4 +
 8 files changed, 1000 insertions(+), 1 deletion(-)

diff --git a/opensaml-storage-impl/src/main/java/org/opensaml/storage/impl/FilesystemStorageService.java b/opensaml-storage-impl/src/main/java/org/opensaml/storage/impl/FilesystemStorageService.java
new file mode 100644
index 000000000..fffa1858a
--- /dev/null
+++ b/opensaml-storage-impl/src/main/java/org/opensaml/storage/impl/FilesystemStorageService.java
@@ -0,0 +1,321 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.opensaml.storage.impl;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.opensaml.storage.AbstractStorageService;
+import org.opensaml.storage.StorageRecord;
+import org.opensaml.storage.VersionMismatchException;
+
+import net.shibboleth.shared.annotation.constraint.NonnullAfterInit;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.annotation.constraint.Positive;
+import net.shibboleth.shared.codec.Base64Support;
+import net.shibboleth.shared.collection.Pair;
+import net.shibboleth.shared.component.ComponentInitializationException;
+import net.shibboleth.shared.logic.Constraint;
+import net.shibboleth.shared.primitive.StringSupport;
+
+/**
+ * Partial implementation of storage backed by filessystem.
+ * 
+ * <p>Updates are not supported, but creation/deletion are.</p>
+ * 
+ * @since 5.3.0
+ */
+public class FilesystemStorageService extends AbstractStorageService {
+
+    /** Tracks use of a shared file system for capability method. */
+    private boolean clustered;
+    
+    /** Whether service is read only. */
+    private boolean readOnly;
+    
+    /** Whether to treat data as binary, using base64 to encoder/decode across String boundary. */
+    private boolean encodeData;
+    
+    /** Base location of storage tree in filesystem. */
+    @NonnullAfterInit private String storageBase;
+    
+    /** Constructor. */
+    public FilesystemStorageService() {
+        readOnly = true;
+    }
+    
+    /**
+     * Sets whether the file system is clustered.
+     * 
+     * <p>Defaults to false.</p>
+     * 
+     * @param flag flag to set
+     */
+    public void setClustered(final boolean flag) {
+        checkSetterPreconditions();
+        
+        clustered = flag;
+    }
+    
+    /**
+     * Sets whether the service should operate read-only.
+     * 
+     * <p>Defaults to true.</p>
+     * 
+     * @param flag flag to set
+     */
+    public void setReadOnly(final boolean flag) {
+        checkSetterPreconditions();
+        
+        readOnly = flag;
+    }
+    
+    /**
+     * Sets whether the service should operate on binary data, encoding to base64 after reads
+     * and decoding from base64 on writes.
+     * 
+     * <p>Defaults to false.</p>
+     * 
+     * @param flag flag to set
+     */
+    public void setEncodeData(final boolean flag) {
+        checkSetterPreconditions();
+        
+        encodeData = flag;
+    }
+    
+    
+    /**
+     * Sets the base/root directory under which objects will be created and deleted.
+     * 
+     * <p>Must be an absolute path.</p>
+     * 
+     * @param base storage root location
+     */
+    public void setStorageBase(@Nonnull @NotEmpty final String base) {
+        checkSetterPreconditions();
+        
+        storageBase = Constraint.isNotNull(StringSupport.trimOrNull(base), "Storage base cannot be null or empty.");
+    }
+    
+    /** {@inheritDoc} */
+    @Override
+    protected void doInitialize() throws ComponentInitializationException {
+        if (storageBase == null) {
+            throw new ComponentInitializationException("Storage base location cannot be null.");
+        }
+        
+        try {
+            final Path storagePath = Path.of(storageBase);
+            if (!storagePath.isAbsolute()) {
+                throw new ComponentInitializationException("Storage base location must be absolute.");
+            }
+            
+            final File rootFile = storagePath.toFile();
+            if (!(rootFile.isDirectory() && rootFile.canRead())) {
+                throw new ComponentInitializationException("Storage root must be a readable directory.");
+            }
+            
+            if (!readOnly && !rootFile.canWrite()) {
+                throw new ComponentInitializationException("Storage root must be a writeable directory.");
+            }
+            
+        } catch (final Exception e) {
+            throw new ComponentInitializationException(e);
+        }
+    }
+    
+    /** {@inheritDoc} */
+    @Override
+    public boolean create(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String key,
+            @Nonnull @NotEmpty final String value, @Nullable @Positive final Long expiration) throws IOException {
+        if (expiration != null) {
+            throw new UnsupportedOperationException("Expiration is not supported by this StorageService implementation.");
+        }
+        
+        if (readOnly) {
+            throw new IOException("StorageService is read-only.");
+        }
+        
+        try {
+            final Path fullPath = Path.of(storageBase, context, key).normalize();
+            if (fullPath.toFile().exists()) {
+                return false;
+            }
+            
+            final Path parentFolder = fullPath.getParent();
+            Files.createDirectories(parentFolder);
+            
+            if (encodeData) {
+                final byte[] decoded = Base64Support.decode(value);
+                Files.write(fullPath, decoded, StandardOpenOption.CREATE_NEW);
+            } else {
+                Files.writeString(fullPath, value, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
+            }
+            
+            return true;
+        } catch (final Exception e) {
+            throw new IOException(e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    @Nullable public <T> StorageRecord<T> read(@Nonnull @NotEmpty final String context,
+            @Nonnull @NotEmpty final String key) throws IOException {
+        try {
+            final Path fullPath = Path.of(storageBase, context, key).normalize();
+            
+            if (!fullPath.toFile().exists()) {
+                return null;
+            }
+            
+            if (encodeData) {
+                final String encoded = Base64Support.encode(Files.readAllBytes(fullPath), false);
+                if (encoded != null) {
+                    return new StorageRecord<T>(encoded, null);
+                }
+            } else {
+                final String value = Files.readString(fullPath);
+                if (value != null) {
+                    return new StorageRecord<T>(value, null);
+                }
+            }
+            
+            return null;
+            
+        } catch (final Exception e) {
+            throw new IOException(e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    @Nonnull public <T> Pair<Long, StorageRecord<T>> read(@Nonnull @NotEmpty final String context,
+            @Nonnull @NotEmpty final String key, long version) throws IOException {
+        
+        // We don't handle versions, so the only possible version is 1, thus we either signal that, or
+        // return nothing since there will never be such a version.
+        
+        if (version == 1) {
+            return new Pair<>(1L, null);
+        }
+        
+        return new Pair<>(null, null);
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public boolean update(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String key,
+            @Nonnull @NotEmpty final String value, @Nullable @Positive final Long expiration) throws IOException {
+        throw new UnsupportedOperationException("Updates are not supported by this StorageService implementation.");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public Long updateWithVersion(long version, @Nonnull @NotEmpty final String context,
+            @Nonnull @NotEmpty final String key, @Nonnull @NotEmpty final String value,
+            @Nullable @Positive final Long expiration) throws IOException, VersionMismatchException {
+        throw new UnsupportedOperationException("Updates are not supported by this StorageService implementation.");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public boolean updateExpiration(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String key,
+            @Nullable @Positive final Long expiration) throws IOException {
+        throw new UnsupportedOperationException("Expiration is not supported by this StorageService implementation.");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public boolean delete(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String key)
+            throws IOException {
+        if (readOnly) {
+            throw new IOException("StorageService is read-only.");
+        }
+        
+        try {
+            final Path fullPath = Path.of(storageBase, context, key).normalize();
+            return Files.deleteIfExists(fullPath);
+            
+        } catch (final Exception e) {
+            throw new IOException(e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public boolean deleteWithVersion(long version, @Nonnull @NotEmpty final String context,
+            @Nonnull @NotEmpty final String key) throws IOException, VersionMismatchException {
+        if (readOnly) {
+            throw new IOException("StorageService is read-only.");
+        }
+        
+        if (version != 1) {
+            throw new VersionMismatchException("Versioning is not supported by this StorageService implementation.");
+        }
+        
+        try {
+            final Path fullPath = Path.of(storageBase, context, key).normalize();
+            return Files.deleteIfExists(fullPath);
+            
+        } catch (final Exception e) {
+            throw new IOException(e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public void reap(@Nonnull @NotEmpty final String context) throws IOException {
+        throw new UnsupportedOperationException("Expiration is not supported by this StorageService implementation.");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public void updateContextExpiration(@Nonnull @NotEmpty final String context,
+            @Nullable @Positive final Long expiration) throws IOException {
+        throw new UnsupportedOperationException("Expiration is not supported by this StorageService implementation.");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public void deleteContext(@Nonnull @NotEmpty final String context) throws IOException {
+        if (readOnly) {
+            throw new IOException("StorageService is read-only.");
+        }
+        
+        // We could do this. Should we? Probably not....
+        
+        throw new UnsupportedOperationException("Context deletion is not supported by this StorageService implementation.");
+    }
+
+    /** {@inheritDoc} */
+    public boolean isServerSide() {
+        return true;
+    }
+
+    /** {@inheritDoc} */
+    public boolean isClustered() {
+        return clustered;
+    }
+
+}
\ No newline at end of file
diff --git a/opensaml-storage-impl/src/main/java/org/opensaml/storage/impl/ResourceBackedMemoryStorageService.java b/opensaml-storage-impl/src/main/java/org/opensaml/storage/impl/ResourceBackedMemoryStorageService.java
new file mode 100644
index 000000000..42abdcabf
--- /dev/null
+++ b/opensaml-storage-impl/src/main/java/org/opensaml/storage/impl/ResourceBackedMemoryStorageService.java
@@ -0,0 +1,324 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.opensaml.storage.impl;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.TimerTask;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import net.shibboleth.shared.annotation.constraint.Live;
+import net.shibboleth.shared.annotation.constraint.NonnullAfterInit;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.annotation.constraint.NotLive;
+import net.shibboleth.shared.annotation.constraint.Unmodifiable;
+import net.shibboleth.shared.component.ComponentInitializationException;
+import net.shibboleth.shared.logic.Constraint;
+import net.shibboleth.shared.primitive.LoggerFactory;
+import net.shibboleth.shared.primitive.StringSupport;
+import net.shibboleth.shared.resource.Resource;
+import net.shibboleth.shared.security.DataSealer;
+import net.shibboleth.shared.security.DataSealerException;
+
+import org.opensaml.storage.AbstractMapBackedStorageService;
+import org.opensaml.storage.MutableStorageRecord;
+import org.opensaml.storage.StorageCapabilities;
+import org.opensaml.storage.VersionMismatchException;
+import org.slf4j.Logger;
+
+/**
+ * Implementation of {@link AbstractMapBackedStorageService} that stores data in-memory in a shared data structure 
+ * after loading it from a resource containing a simple one-line per record, delimited format.
+ * 
+ * <p>Records do not carry expirations.</p>
+ * 
+ * <p>The implementation is read-only and throws exceptions for any methods that would mutate the data. The "cleanup"
+ * task is instead used to periodically check the source file for updates and reloads the in-memory data under
+ * an exclusive lock.</p>
+ * 
+ * <p>Lines starting with a '#' character are ignored as comments.</p>
+ * 
+ * @since 5.3.0
+ */
+public class ResourceBackedMemoryStorageService extends AbstractMapBackedStorageService implements StorageCapabilities {
+
+    /** Class logger. */
+    @Nonnull private final Logger log = LoggerFactory.getLogger(ResourceBackedMemoryStorageService.class);
+
+    /** Map of contexts. */
+    @NonnullAfterInit private Map<String, Map<String, MutableStorageRecord<?>>> contextMap;
+    
+    /** A shared lock to synchronize access. */
+    @NonnullAfterInit private ReadWriteLock lock;
+
+    /** Optional encryption support. */
+    @Nullable private DataSealer dataSealer;
+    
+    /** Source of information. */
+    @Nullable private Resource storageResource;
+    
+    /** Field delimiter in resource. */
+    @Nonnull @NotEmpty private String delimiter;
+    
+    /** File timestamp. */
+    private long lastModified;
+    
+    /** Constructor. */
+    public ResourceBackedMemoryStorageService() {
+        lastModified = 0;
+        delimiter = ",";
+    }
+        
+    /** {@inheritDoc} */
+    public boolean isServerSide() {
+        return true;
+    }
+
+    /** {@inheritDoc} */
+    public boolean isClustered() {
+        return true;
+    }
+    
+    /**
+     * Sets the time between checks for changes to the resource and reload of the records.
+     * 
+     * <p>A value of 0 (the default) indicates that no reloading will be performed.</p>
+     * 
+     * <p>Non-file resources are detected and reload is skipped, though the task
+     * may still run and log warnings.</p>
+     * 
+     * @param interval time between reload checking
+     */
+    public void setReloadInterval(@Nonnull final Duration interval) {
+        setCleanupInterval(interval);
+    }
+    
+    /**
+     * Sets the {@link DataSealer} to use, which enables decryption of the
+     * record values (but not the rest).
+     * 
+     * @param sealer data sealer
+     */
+    public void setDataSealer(@Nullable final DataSealer sealer) {
+        checkSetterPreconditions();
+        dataSealer = sealer;
+    }
+    
+    /**
+     * Set the resource to use.
+     * 
+     * @param resource resource to use
+     */
+    public void setResource(@Nonnull final Resource resource) {
+        checkSetterPreconditions();
+        storageResource = Constraint.isNotNull(resource, "Resource cannot be null");
+    }
+    
+    /**
+     * Set the field delimiter to use to split the records.
+     * 
+     * <p>Defaults to "," (comma).</p>
+     * 
+     * @param delim delimiter string
+     */
+    public void setDelimiter(@Nonnull @NotEmpty final String delim) {
+        checkSetterPreconditions();
+        delimiter = Constraint.isNotNull(StringSupport.trimOrNull(delim), "Delimiter cannot be null or empty");
+    }
+    
+    /** {@inheritDoc} */
+    @Override
+    protected void doInitialize() throws ComponentInitializationException {
+        super.doInitialize();
+        lock = new ReentrantReadWriteLock(true);
+        
+        try {
+            final Resource resource = storageResource;
+            if (resource == null) {
+                throw new ComponentInitializationException("Resource cannot be null");
+            }
+            
+            try (final InputStream is = resource.getInputStream()) {
+                contextMap = load(is);
+            }
+
+            if (resource.isFile()) {
+                lastModified = resource.lastModified();
+            } else {
+                storageResource = null;
+            }
+            
+        } catch (final IOException e) {
+            throw new ComponentInitializationException("Error reading backing resource", e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    @Nonnull @Live protected Map<String, Map<String, MutableStorageRecord<?>>> getContextMap() {
+        checkComponentActive();
+        assert contextMap != null;
+        return contextMap;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    @Nonnull protected ReadWriteLock getLock() {
+        checkComponentActive();
+        assert lock != null;
+        return lock;
+    }
+    
+    
+    
+/** {@inheritDoc} */
+    @Override
+    public boolean create(String context, String key, String value, Long expiration) throws IOException {
+        throw new UnsupportedOperationException("Creates are not supported by this StorageService implementation.");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    protected Long updateImpl(Long version, String context, String key, String value, Long expiration)
+            throws IOException, VersionMismatchException {
+        throw new UnsupportedOperationException("Updates are not supported by this StorageService implementation.");
+    }
+    
+    /** {@inheritDoc} */
+    @Override
+    public void updateContextExpiration(@Nonnull @NotEmpty final String context, @Nullable final Long expiration) {
+        throw new UnsupportedOperationException("Updates are not supported by this StorageService implementation.");
+    }    
+    
+    /** {@inheritDoc} */
+    @Override
+    protected boolean deleteImpl(Long version, String context, String key)
+            throws IOException, VersionMismatchException {
+        throw new UnsupportedOperationException("Deletes are not supported by this StorageService implementation.");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public void deleteContext(@Nonnull @NotEmpty final String context) throws IOException {
+        throw new UnsupportedOperationException("Deletes are not supported by this StorageService implementation.");
+    }
+    
+// Checkstyle: AnonInnerLength OFF
+    /** {@inheritDoc} */
+    @Override
+    @Nullable protected TimerTask getCleanupTask() {
+        return new TimerTask() {
+            
+            /** {@inheritDoc} */
+            @Override
+            public void run() {
+                log.debug("Running reload task");
+                
+                final Lock writeLock = getLock().writeLock();
+                
+                try {
+                    writeLock.lock();
+
+                    final Resource resource = storageResource;
+
+                    try {
+                        if (resource != null && resource.isFile() && resource.exists()) {
+                            final long modTime = resource.lastModified();
+                            if (modTime > lastModified) {
+                                log.info("Resource {} modified, attempting reload", resource);
+                                try (final InputStream is = resource.getInputStream()) {
+                                    contextMap = load(is);
+                                }
+                                lastModified = modTime;
+                            } else {
+                                log.info("Resource {} not modified, skipping reload", resource);
+                            }
+                        } else {
+                            log.warn("Non-file resource, reload monitoring not supported");
+                        }
+                    } catch (final IOException e) {
+                        log.error("Error reloading records", e);
+                    }
+                    
+                } finally {
+                    writeLock.unlock();
+                }
+            }
+        };
+    }
+// Checkstyle: AnonInnerLength ON
+    
+    /**
+     * Loads data from the supplied input stream.
+     * 
+     * <p>Must be called while holding the write lock.</p>
+     * 
+     * @param is
+     * 
+     * @return the constructed map of records
+     * 
+     * @throws IOException on error
+     */
+    @Nonnull @Unmodifiable @NotLive private Map<String, Map<String, MutableStorageRecord<?>>> load(
+            @Nonnull final InputStream is) throws IOException {
+
+        final Map<String, Map<String, MutableStorageRecord<?>>> theMap = new HashMap<>(); 
+        
+        try (final BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
+            String line;
+            while ((line = reader.readLine()) != null) {
+                if (line.startsWith("#")) {
+                    continue;
+                }
+                final String[] sploot = line.split(delimiter, 3);
+                if (sploot != null && sploot.length == 3 &&
+                        sploot[0] != null && sploot[1] != null && sploot[2] != null) {
+                    
+                    final String value;
+                    if (dataSealer != null) {
+                        value = dataSealer.unwrap(sploot[2]);
+                    } else {
+                        value = sploot[2];
+                    }
+                    
+                    if (!theMap.containsKey(sploot[0])) {
+                        theMap.put(sploot[0], new HashMap<>());
+                    }
+                                        
+                    theMap.get(sploot[0]).put(sploot[1], new MutableStorageRecord<>(value, null));
+                    
+                } else {
+                    throw new IOException("Improper format detected.");
+                }
+            }
+        } catch (final DataSealerException e) {
+            throw new IOException(e);
+        }
+        
+        return theMap;
+    }
+
+}
\ No newline at end of file
diff --git a/opensaml-storage-impl/src/test/java/org/opensaml/storage/impl/FilesystemStorageServiceTest.java b/opensaml-storage-impl/src/test/java/org/opensaml/storage/impl/FilesystemStorageServiceTest.java
new file mode 100644
index 000000000..cea937e69
--- /dev/null
+++ b/opensaml-storage-impl/src/test/java/org/opensaml/storage/impl/FilesystemStorageServiceTest.java
@@ -0,0 +1,239 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.opensaml.storage.impl;
+
+import java.io.IOException;
+import java.nio.file.DirectoryNotEmptyException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.time.Instant;
+
+import javax.annotation.Nonnull;
+
+import org.opensaml.storage.StorageRecord;
+import org.opensaml.storage.StorageService;
+import org.opensaml.storage.VersionMismatchException;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import net.shibboleth.shared.component.ComponentInitializationException;
+
+/**
+ * Unit tests for {@link FilesystemStorageService}.
+ */
+ at SuppressWarnings("javadoc")
+public class FilesystemStorageServiceTest {
+
+    private Path testHome;
+    
+    @BeforeMethod
+    public void setUp() throws IOException {
+        testHome = Files.createTempDirectory("test-storage-service");
+    }
+ 
+    private void tearDownWorker() throws IOException {
+        if (testHome != null) {
+            Files.walkFileTree(testHome, new SimpleFileVisitor<Path>() {
+                @Override
+                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
+                    throws IOException
+                {
+                    Files.delete(file);
+                    return FileVisitResult.CONTINUE;
+                }
+                @Override
+                public FileVisitResult postVisitDirectory(Path dir, IOException e)
+                    throws IOException
+                {
+                    if (e == null) {
+                        Files.delete(dir);
+                        return FileVisitResult.CONTINUE;
+                    }
+                    // directory iteration failed
+                    throw e;
+                }
+            });
+            testHome = null;
+        }
+    }
+
+    @AfterMethod
+    public void tearDown() throws IOException, InterruptedException {
+        try {
+            tearDownWorker();
+        } catch (final DirectoryNotEmptyException ex) {
+            // We hates the Microsoft Defender.  (it pins files so directories cannot be deleted)
+            Thread.sleep(10);
+            tearDownWorker();
+        }
+    }
+    
+    @Test
+    public void testSimple() throws ComponentInitializationException, IOException {
+        final StorageService storage = getService(false);
+        
+        Assert.assertTrue(storage.create("foo", "bar", "value", null));
+        
+        final StorageRecord<?> record = storage.read("foo", "bar");
+        assert record != null;
+        Assert.assertEquals(record.getVersion(), 1);
+        Assert.assertEquals(record.getValue(), "value");
+        Assert.assertNull(record.getExpiration());
+        
+        Assert.assertTrue(storage.delete("foo", "bar"));
+        
+        Assert.assertNull(storage.read("foo", "bar"));
+    }
+
+    @Test
+    public void testNested() throws ComponentInitializationException, IOException {
+        final StorageService storage = getService(false);
+        
+        Assert.assertTrue(storage.create("foo/bar", "zork/frobnitz", "BEGIN\nvalue\nEND\n", null));
+        
+        final StorageRecord<?> record = storage.read("foo/bar", "zork/frobnitz");
+        assert record != null;
+        Assert.assertEquals(record.getVersion(), 1);
+        Assert.assertEquals(record.getValue(), "BEGIN\nvalue\nEND\n");
+        Assert.assertNull(record.getExpiration());
+        
+        Assert.assertTrue(storage.delete("foo/bar", "zork/frobnitz"));
+        
+        Assert.assertNull(storage.read("foo/bar", "zork/frobnitz"));
+    }
+    
+    @Test(expectedExceptions=IOException.class)
+    public void testLengthLimit() throws ComponentInitializationException, IOException {
+        final StorageService storage = getService(false);
+
+        final StringBuilder key = new StringBuilder();
+        for (int i = 0; i < 4096; ++i) {
+            key.append("long");
+        }
+        storage.create("context", key.toString(), "value", null);
+    }
+    
+    @Test
+    public void testOperationViolations() throws ComponentInitializationException, IOException, VersionMismatchException {
+        final StorageService storage = getService(true);
+        
+        try {
+            storage.create("foo", "bar", "value", null);
+            Assert.fail("Should raise IOException");
+        } catch (final IOException e) {
+            // expected
+        }
+
+        try {
+            storage.delete("foo", "bar");
+            Assert.fail("Should raise IOException");
+        } catch (final IOException e) {
+            // expected
+        }
+
+        try {
+            storage.deleteContext("foo");
+            Assert.fail("Should raise IOException");
+        } catch (final IOException e) {
+            // expected
+        }
+        
+        try {
+            storage.deleteWithVersion(1, "foo", "bar");
+            Assert.fail("Should raise IOException");
+        } catch (final IOException e) {
+            // expected
+        }
+    }
+    
+    @Test
+    public void testUnsupportedOperations() throws ComponentInitializationException, IOException, VersionMismatchException {
+        final StorageService storage = getService(false);
+        
+        try {
+            storage.create("foo", "bar", "value", Instant.now().plusSeconds(360).toEpochMilli());
+            Assert.fail("Should raise UnsupportedOperationException");
+        } catch (final UnsupportedOperationException e) {
+            // expected
+        }
+        
+        try {
+            storage.update("foo", "bar", "value", null);
+            Assert.fail("Should raise UnsupportedOperationException");
+        } catch (final UnsupportedOperationException e) {
+            // expected
+        }
+
+        try {
+            storage.updateWithVersion(2, "foo", "bar", "value", null);
+            Assert.fail("Should raise UnsupportedOperationException");
+        } catch (final UnsupportedOperationException e) {
+            // expected
+        }
+
+        try {
+            storage.updateExpiration("foo", "bar", null);
+            Assert.fail("Should raise UnsupportedOperationException");
+        } catch (final UnsupportedOperationException e) {
+            // expected
+        }
+
+        try {
+            storage.updateContextExpiration("foo", null);
+            Assert.fail("Should raise UnsupportedOperationException");
+        } catch (final UnsupportedOperationException e) {
+            // expected
+        }
+                
+        try {
+            storage.deleteWithVersion(2, "foo", "bar");
+            Assert.fail("Should raise VersionMismatchException");
+        } catch (final VersionMismatchException e) {
+            // expected
+        }
+
+        try {
+            storage.deleteContext("foo");
+            Assert.fail("Should raise UnsupportedOperationException");
+        } catch (final UnsupportedOperationException e) {
+            // expected
+        }
+    }
+    
+    /**
+     * Instantiates the service with the specified option.
+     * 
+     * @param readOnly flag to pass to service
+     * 
+     * @return the service
+     * 
+     * @throws ComponentInitializationException 
+     */
+    @Nonnull private StorageService getService(final boolean readOnly)
+            throws ComponentInitializationException {
+    
+        final FilesystemStorageService ss = new FilesystemStorageService();
+        ss.setReadOnly(readOnly);
+        ss.setStorageBase(testHome.toString());
+        ss.initialize();
+        return ss;
+    }
+    
+}
\ No newline at end of file
diff --git a/opensaml-storage-impl/src/test/java/org/opensaml/storage/impl/ResourceBackedMemoryStorageServiceTest.java b/opensaml-storage-impl/src/test/java/org/opensaml/storage/impl/ResourceBackedMemoryStorageServiceTest.java
new file mode 100644
index 000000000..0805cc9b2
--- /dev/null
+++ b/opensaml-storage-impl/src/test/java/org/opensaml/storage/impl/ResourceBackedMemoryStorageServiceTest.java
@@ -0,0 +1,110 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.opensaml.storage.impl;
+
+import java.io.IOException;
+
+import javax.annotation.Nonnull;
+
+import org.opensaml.storage.StorageRecord;
+import org.opensaml.storage.StorageService;
+import org.springframework.core.io.ClassPathResource;
+import org.testng.Assert;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.component.ComponentInitializationException;
+import net.shibboleth.shared.resource.Resource;
+import net.shibboleth.shared.spring.resource.ResourceHelper;
+
+/**
+ * Unit tests for {@link ResourceBackedMemoryStorageService}.
+ */
+ at SuppressWarnings("javadoc")
+public class ResourceBackedMemoryStorageServiceTest {
+
+    @Nonnull @NotEmpty private static final String DATA_PATH = "/org/opensaml/storage/impl/";
+    
+    private Resource validResource;
+    private Resource invalidResource1;
+    private Resource invalidResource2;
+    
+    @BeforeClass
+    public void setUp() throws IOException {
+        validResource = ResourceHelper.of(new ClassPathResource(DATA_PATH + "valid-storage.txt"));
+        invalidResource1 = ResourceHelper.of(new ClassPathResource(DATA_PATH + "invalid-storage1.txt"));
+        invalidResource2 = ResourceHelper.of(new ClassPathResource(DATA_PATH + "invalid-storage2.txt"));
+    }
+    
+    @Test(expectedExceptions=ComponentInitializationException.class)
+    public void testInvalid1() throws ComponentInitializationException {
+        getService(invalidResource1);
+    }
+
+    @Test(expectedExceptions=ComponentInitializationException.class)
+    public void testInvalid2() throws ComponentInitializationException {
+        getService(invalidResource2);
+    }
+    
+    @Test(expectedExceptions=UnsupportedOperationException.class)
+    public void testCreate() throws ComponentInitializationException, IOException {
+        final var ss = getService(validResource);
+        ss.create("foo", "bar", "baz", null);
+    }
+    
+    @Test
+    public void test() throws ComponentInitializationException, IOException {
+        final var ss = getService(validResource);
+
+        StorageRecord<String> record = ss.read("bork", "bar");
+        Assert.assertNull(record);
+        
+        record = ss.read("foo", "bar");
+        assert record != null;
+        Assert.assertEquals(record.getVersion(), 1);
+        Assert.assertEquals(record.getExpiration(), null);
+        Assert.assertEquals(record.getValue(), "baz");
+
+        record = ss.read("foo", "bar2");
+        assert record != null;
+        Assert.assertEquals(record.getValue(), "baz2");
+
+        record = ss.read("foo2", "bar");
+        assert record != null;
+        Assert.assertEquals(record.getValue(), "zork:infocom");
+    }
+    
+    /**
+     * Instantiates the service with the specified resource.
+     * 
+     * @param resource resource to use
+     * 
+     * @return the service
+     * 
+     * @throws ComponentInitializationException 
+     */
+    @Nonnull private StorageService getService(@Nonnull final Resource resource)
+            throws ComponentInitializationException {
+    
+        final var ss = new ResourceBackedMemoryStorageService();
+        ss.setId("test");
+        ss.setResource(resource);
+        ss.setDelimiter(":");
+        ss.initialize();
+        return ss;
+    }
+    
+}
\ No newline at end of file
diff --git a/opensaml-storage-impl/src/test/java/org/opensaml/storage/impl/memcached/MemcachedStorageServiceTest.java b/opensaml-storage-impl/src/test/java/org/opensaml/storage/impl/memcached/MemcachedStorageServiceTest.java
index 798514f65..416d1046f 100644
--- a/opensaml-storage-impl/src/test/java/org/opensaml/storage/impl/memcached/MemcachedStorageServiceTest.java
+++ b/opensaml-storage-impl/src/test/java/org/opensaml/storage/impl/memcached/MemcachedStorageServiceTest.java
@@ -23,7 +23,6 @@ import org.cryptacular.generator.IdGenerator;
 import org.cryptacular.generator.RandomIdGenerator;
 import org.opensaml.storage.StorageRecord;
 import org.opensaml.storage.VersionMismatchException;
-import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
diff --git a/opensaml-storage-impl/src/test/resources/org/opensaml/storage/impl/invalid-storage1.txt b/opensaml-storage-impl/src/test/resources/org/opensaml/storage/impl/invalid-storage1.txt
new file mode 100644
index 000000000..ae3cdf5b8
--- /dev/null
+++ b/opensaml-storage-impl/src/test/resources/org/opensaml/storage/impl/invalid-storage1.txt
@@ -0,0 +1 @@
+foo:bar
diff --git a/opensaml-storage-impl/src/test/resources/org/opensaml/storage/impl/invalid-storage2.txt b/opensaml-storage-impl/src/test/resources/org/opensaml/storage/impl/invalid-storage2.txt
new file mode 100644
index 000000000..0152a7965
--- /dev/null
+++ b/opensaml-storage-impl/src/test/resources/org/opensaml/storage/impl/invalid-storage2.txt
@@ -0,0 +1 @@
+foo:
diff --git a/opensaml-storage-impl/src/test/resources/org/opensaml/storage/impl/valid-storage.txt b/opensaml-storage-impl/src/test/resources/org/opensaml/storage/impl/valid-storage.txt
new file mode 100644
index 000000000..9e6c2481d
--- /dev/null
+++ b/opensaml-storage-impl/src/test/resources/org/opensaml/storage/impl/valid-storage.txt
@@ -0,0 +1,4 @@
+foo:bar:baz2
+foo:bar:baz
+foo:bar2:baz2
+foo2:bar:zork:infocom
\ No newline at end of file

-- 
To stop receiving notification emails like this one, please contact
the administrator of this repository.


More information about the commits mailing list