10000 Added support for getting a list of files from a jar directory in ResourceOf. by PeJetuz · Pull Request #1757 · yegor256/cactoos · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Added support for getting a list of files from a jar directory in ResourceOf. #1757

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ SOFTWARE.
<url>https://github.com/yegor256/cactoos</url>
</site>
</distributionManagement>
<properties>
<testLibPath>src/test/test-lib</testLibPath>
<testLibJarPath>${project.build.directory}/${project.artifactId}-test-lib-${project.version}.jar</testLibJarPath>
</properties>
<dependencies>
<dependency>
<groupId>org.takes</groupId>
Expand Down Expand Up @@ -144,6 +148,10 @@ SOFTWARE.
<threads>8</threads>
<mutationThreshold>75</mutationThreshold>
<timeoutConstant>500</timeoutConstant>
<additionalClasspathElements>
<additionalClasspathElement>${testLibJarPath}</additionalClasspathElement>
</additionalClasspathElements>
<useClasspathJar>true</useClasspathJar>
</configuration>
</execution>
</executions>
Expand Down Expand Up @@ -172,6 +180,59 @@ SOFTWARE.
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
8000 <artifactId>maven-surefire-plugin</artifactId>
<configuration>
<additionalClasspathDependencies>
<additionalClasspathDependency>
<groupId>org.cactoos</groupId>
<artifactId>${project.artifactId}-test-lib</artifactId>
<version>${project.version}</version>
</additionalClasspathDependency>
</additionalClasspathDependencies>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>make-test-lib</id>
<phase>initialize</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>${project.artifactId}-test-lib-${project.version}</finalName>
<descriptors>
<descriptor>${testLibPath}/assembly.xml</descriptor>
</descriptors>
<appendAssemblyId>false</appendAssemblyId>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<executions>
<execution>
<id>make-test-lib</id>
<phase>initialize</phase>
<goals>
<goal>install-file</goal>
</goals>
<configuration>
<file>${testLibJarPath}</file>
<groupId>org.cactoos</groupId>
<artifactId>${project.artifactId}-test-lib</artifactId>
<version>${project.version}</version>
<packaging>jar</packaging>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
Expand Down
86 changes: 82 additions & 4 deletions src/main/java/org/cactoos/io/ResourceOf.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
import org.cactoos.Func;
import org.cactoos.Input;
import org.cactoos.Text;
Expand Down Expand Up @@ -225,10 +231,18 @@ public InputStream stream() throws Exception {
"The \"classloader\" is NULL, which is not allowed"
);
}
InputStream input = this.loader.getResourceAsStream(
this.path.asString()
);
if (input == null) {
final InputStream input;
final String pth = this.path.asString();
final URL resource = this.loader.getResource(pth);
if (pth.endsWith("/")
&& resource != null
&& "jar".equals(resource.getProtocol())
) {
input = new JarDirectoryFileNameStream(resource, pth)
.files();
} else if (resource != null) {
input = resource.openStream();
} else {
if (this.fallback == null) {
throw new IllegalArgumentException(
"The \"fallback\" is NULL, which is not allowed"
Expand All @@ -240,4 +254,68 @@ public InputStream stream() throws Exception {
}
return input;
}

/**
* Class for creating a stream of file names from a directory to a jar.
*
* @since 0.56.2
*/
private static final class JarDirectoryFileNameStream {

/**
* URL of the jar file.
*/
private final URL url;

/**
* Path to the directory in the jar file.
*/
private final String path;

/**
* Ctor.
*
* @param jarurl URL of the jar file.
* @param pth The directory for which we want to get a list of files.
*/
JarDirectoryFileNameStream(final URL jarurl, final String pth) {
this.url = jarurl;
this.path = pth;
}

/**
* Create InputStream of file names from directory to jar.
*
* @return Stream with file names.
* @throws Exception If something goes wrong
*/
public InputStream files() throws Exception {
try (JarFile jar = new JarFile(this.extract())) {
return new InputStreamOf(
jar
.stream()
.map(JarEntry::getName)
.filter(
name -> !this.path.equals(name)
&& name.lastIndexOf(this.path) >= 0
)
.map(name -> name.substring(this.path.length()))
.collect(Collectors.joining("\n"))
.getBytes(StandardCharsets.UTF_8)
);
}
}

/**
* Extracts the path to a jar file from a URL.
*
* @return Path to jar file.
* @throws URISyntaxException If this URL cannot be converted to a URI.
*/
private String extract() throws URISyntaxException {
final String fullpath = this.url.toURI().getSchemeSpecificPart();
final int idx = fullpath.indexOf("!/");
return fullpath.substring("file:".length(), idx);
}
}
}
64 changes: 63 additions & 1 deletion src/test/java/org/cactoos/io/ResourceOfTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,13 @@
import org.cactoos.Text;
import org.cactoos.bytes.BytesOf;
import org.cactoos.text.FormattedText;
import org.cactoos.text.Split;
import org.cactoos.text.TextOf;
import org.hamcrest.core.IsEqual;
import org.junit.jupiter.api.Test;
import org.llorllale.cactoos.matchers.Assertion;
import org.llorllale.cactoos.matchers.EndsWith;
import org.llorllale.cactoos.matchers.HasValues;
import org.llorllale.cactoos.matchers.StartsWith;
import org.llorllale.cactoos.matchers.Throws;

Expand All @@ -42,7 +44,7 @@
* @since 0.1
* @checkstyle JavadocMethodCheck (500 lines)
*/
@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert")
@SuppressWarnings({"PMD.JUnitTestsShouldIncludeAssert", "PMD.TooManyMethods"})
final class ResourceOfTest {

@Test
Expand Down Expand Up @@ -113,6 +115,66 @@ void throwsWhenResourceIsAbsent() {
).affirm();
}

@Test
void readTextFromJar() {
new Assertion<>(
"Can't to read file from jar",
new TextOf(
new BytesOf(
new ResourceOf(
"org/cactoos/io/small-text-file.txt",
"the replacement"
)
)
),
new EndsWith("parent directory.")
).affirm();
}

@Test
void readDirectoryFromJar() {
new Assertion< 1E79 >(
"Unable to read file names from jar directory",
new Split(
new TextOf(
new BytesOf(
new ResourceOf(
"org/cactoos/io/dir/",
"the replacement"
)
)
),
new TextOf("\\n")
),
new HasValues<>(
new TextOf(&q F438 uot;second-text-file.txt"),
new TextOf("small-file-in-dir.txt")
)
).affirm();
}

@Test
void readDirectory() {
new Assertion<>(
"Unable to read file names from directory",
new Split(
new TextOf(
new BytesOf(
new ResourceOf(
"org/cactoos/",
"the replacement"
)
)
),
new TextOf("\\n")
),
new HasValues<>(
new TextOf("digest-calculation.txt"),
new TextOf("small-text.txt")
)
).affirm();
}

@Test
void acceptsTextAsResourceName() {
new Assertion<>(
Expand Down
42 changes: 42 additions & 0 deletions src/test/test-lib/assembly.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
The MIT License (MIT)

Copyright (c) 2017-2025 Yegor Bugayenko

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.2.0 https://maven.apache.org/xsd/assembly-2.2.0.xsd">
<id>test-lib</id>
<formats>
<format>jar</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
<fileSet>
<directory>${project.basedir}/${testLibPath}</directory>
<outputDirectory>/</outputDirectory>
<includes>
<include>org/cactoos/io/small-text-file.txt</include>
<include>org/cactoos/io/dir/second-text-file.txt</include>
<include>org/cactoos/io/dir/small-file-in-dir.txt</include>
</includes>
</fileSet>
</fileSets>
</assembly>
1 change: 1 addition & 0 deletions src/test/test-lib/org/cactoos/io/dir/second-text-file.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Second text file.
1 change: 1 addition & 0 deletions src/test/test-lib/org/cactoos/io/dir/small-file-in-dir.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Small file in the directory.
1 change: 1 addition & 0 deletions src/test/test-lib/org/cactoos/io/small-text-file.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Small file in the parent directory.
0