create core-java-io module (#3397)
* make sure modules using java8 * move url matching code * upgrade boot parent * minor cleanup * fix blocking tests * add core-java-io module
This commit is contained in:
committed by
Grzegorz Piwowarek
parent
5d2f0542fa
commit
bff36974cd
26
core-java-io/.gitignore
vendored
Normal file
26
core-java-io/.gitignore
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
*.txt
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
||||
28
core-java-io/README.md
Normal file
28
core-java-io/README.md
Normal file
@@ -0,0 +1,28 @@
|
||||
=========
|
||||
|
||||
## Core Java IO Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Java - Reading a Large File Efficiently](http://www.baeldung.com/java-read-lines-large-file)
|
||||
- [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string)
|
||||
- [Java – Write to File](http://www.baeldung.com/java-write-to-file)
|
||||
- [Java - Convert File to InputStream](http://www.baeldung.com/convert-file-to-input-stream)
|
||||
- [Java Scanner](http://www.baeldung.com/java-scanner)
|
||||
- [Java – Byte Array to Writer](http://www.baeldung.com/java-convert-byte-array-to-writer)
|
||||
- [Java – Directory Size](http://www.baeldung.com/java-folder-size)
|
||||
- [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](http://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library)
|
||||
- [Calculate the Size of a File in Java](http://www.baeldung.com/java-file-size)
|
||||
- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
|
||||
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path)
|
||||
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer)
|
||||
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
|
||||
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
|
||||
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
||||
- [Java – Append Data to a File](http://www.baeldung.com/java-append-to-file)
|
||||
- [FileNotFoundException in Java](http://www.baeldung.com/java-filenotfound-exception)
|
||||
- [How to Read a File in Java](http://www.baeldung.com/reading-file-in-java)
|
||||
- [A Guide To NIO2 Asynchronous File Channel](http://www.baeldung.com/java-nio2-async-file-channel)
|
||||
- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor)
|
||||
- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute)
|
||||
- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api)
|
||||
- [Zipping and Unzipping in Java](http://www.baeldung.com/java-compress-and-uncompress)
|
||||
505
core-java-io/pom.xml
Normal file
505
core-java-io/pom.xml
Normal file
@@ -0,0 +1,505 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-io</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>core-java-io</name>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.collections</groupId>
|
||||
<artifactId>collections-generic</artifactId>
|
||||
<version>${collections-generic.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.decimal4j</groupId>
|
||||
<artifactId>decimal4j</artifactId>
|
||||
<version>${decimal4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
<version>${bouncycastle.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.unix4j</groupId>
|
||||
<artifactId>unix4j-command</artifactId>
|
||||
<version>${unix4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.googlecode.grep4j</groupId>
|
||||
<artifactId>grep4j</artifactId>
|
||||
<version>${grep4j.version}</version>
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
|
||||
<!-- marshalling -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>1.2.17</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-all</artifactId>
|
||||
<version>1.3</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${avaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.javamoney</groupId>
|
||||
<artifactId>moneta</artifactId>
|
||||
<version>1.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.owasp.esapi</groupId>
|
||||
<artifactId>esapi</artifactId>
|
||||
<version>2.1.0.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.messaging.mq</groupId>
|
||||
<artifactId>fscontext</artifactId>
|
||||
<version>${fscontext.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.codepoetics</groupId>
|
||||
<artifactId>protonpack</artifactId>
|
||||
<version>${protonpack.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>one.util</groupId>
|
||||
<artifactId>streamex</artifactId>
|
||||
<version>${streamex.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>1.19</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>1.19</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>4.3.4.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>1.5.8.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>2.4.0</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-io</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<testFailureIgnore>true</testFailureIgnore>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
<classpathPrefix>libs/</classpathPrefix>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<transformers>
|
||||
<transformer
|
||||
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>com.jolira</groupId>
|
||||
<artifactId>onejar-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<configuration>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<attachToBuild>true</attachToBuild>
|
||||
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
||||
</configuration>
|
||||
<goals>
|
||||
<goal>one-jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>spring-boot</classifier>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<configuration>
|
||||
<executable>java</executable>
|
||||
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
|
||||
<arguments>
|
||||
<argument>-Xmx300m</argument>
|
||||
<argument>-XX:+UseParallelGC</argument>
|
||||
<argument>-classpath</argument>
|
||||
<classpath/>
|
||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>3.0.0-M1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<test.mime>json</test.mime>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
|
||||
<executions>
|
||||
<execution>
|
||||
<id>run-benchmarks</id>
|
||||
<!-- <phase>integration-test</phase>-->
|
||||
<phase>none</phase>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classpathScope>test</classpathScope>
|
||||
<executable>java</executable>
|
||||
<arguments>
|
||||
<argument>-classpath</argument>
|
||||
<classpath/>
|
||||
<argument>org.openjdk.jmh.Main</argument>
|
||||
<argument>.*</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.8.5</jackson.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
<logback.version>1.1.7</logback.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>22.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<bouncycastle.version>1.55</bouncycastle.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<decimal4j.version>1.0.3</decimal4j.version>
|
||||
<commons-io.version>2.5</commons-io.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
<unix4j.version>0.4</unix4j.version>
|
||||
<grep4j.version>1.8.7</grep4j.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
<fscontext.version>4.6-b01</fscontext.version>
|
||||
<protonpack.version>1.13</protonpack.version>
|
||||
<streamex.version>0.6.5</streamex.version>
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>2.8.9</mockito.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.dirmonitoring;
|
||||
|
||||
import org.apache.commons.io.monitor.FileAlterationListener;
|
||||
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
|
||||
import org.apache.commons.io.monitor.FileAlterationMonitor;
|
||||
import org.apache.commons.io.monitor.FileAlterationObserver;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class DirectoryMonitoringExample {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
|
||||
|
||||
private static final int POLL_INTERVAL = 500;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
|
||||
FileAlterationMonitor monitor = new FileAlterationMonitor(POLL_INTERVAL);
|
||||
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
|
||||
@Override
|
||||
public void onFileCreate(File file) {
|
||||
LOG.debug("File: " + file.getName() + " created");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFileDelete(File file) {
|
||||
LOG.debug("File: " + file.getName() + " deleted");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFileChange(File file) {
|
||||
LOG.debug("File: " + file.getName() + " changed");
|
||||
}
|
||||
};
|
||||
observer.addListener(listener);
|
||||
monitor.addObserver(observer);
|
||||
monitor.start();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.filesystem.jndi;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Hashtable;
|
||||
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
|
||||
public class LookupFSJNDI {
|
||||
private InitialContext ctx = null;
|
||||
|
||||
public LookupFSJNDI() throws NamingException {
|
||||
super();
|
||||
init();
|
||||
}
|
||||
|
||||
private void init() throws NamingException {
|
||||
Hashtable<String, String> env = new Hashtable<String, String>();
|
||||
|
||||
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
|
||||
// URI to namespace (actual directory)
|
||||
env.put(Context.PROVIDER_URL, "file:./src/test/resources");
|
||||
|
||||
ctx = new InitialContext(env);
|
||||
}
|
||||
|
||||
public InitialContext getCtx() {
|
||||
return ctx;
|
||||
}
|
||||
|
||||
public File getFile(String fileName) {
|
||||
File file;
|
||||
try {
|
||||
file = (File) getCtx().lookup(fileName);
|
||||
} catch (NamingException e) {
|
||||
file = null;
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.java.nio.selector;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.SocketChannel;
|
||||
|
||||
public class EchoClient {
|
||||
private static SocketChannel client;
|
||||
private static ByteBuffer buffer;
|
||||
private static EchoClient instance;
|
||||
|
||||
public static EchoClient start() {
|
||||
if (instance == null)
|
||||
instance = new EchoClient();
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
public static void stop() throws IOException {
|
||||
client.close();
|
||||
buffer = null;
|
||||
}
|
||||
|
||||
private EchoClient() {
|
||||
try {
|
||||
client = SocketChannel.open(new InetSocketAddress("localhost", 5454));
|
||||
buffer = ByteBuffer.allocate(256);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public String sendMessage(String msg) {
|
||||
buffer = ByteBuffer.wrap(msg.getBytes());
|
||||
String response = null;
|
||||
try {
|
||||
client.write(buffer);
|
||||
buffer.clear();
|
||||
client.read(buffer);
|
||||
response = new String(buffer.array()).trim();
|
||||
System.out.println("response=" + response);
|
||||
buffer.clear();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return response;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.baeldung.java.nio.selector;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.SelectionKey;
|
||||
import java.nio.channels.Selector;
|
||||
import java.nio.channels.ServerSocketChannel;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
|
||||
public class EchoServer {
|
||||
|
||||
private static final String POISON_PILL = "POISON_PILL";
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
Selector selector = Selector.open();
|
||||
ServerSocketChannel serverSocket = ServerSocketChannel.open();
|
||||
serverSocket.bind(new InetSocketAddress("localhost", 5454));
|
||||
serverSocket.configureBlocking(false);
|
||||
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
|
||||
ByteBuffer buffer = ByteBuffer.allocate(256);
|
||||
|
||||
while (true) {
|
||||
selector.select();
|
||||
Set<SelectionKey> selectedKeys = selector.selectedKeys();
|
||||
Iterator<SelectionKey> iter = selectedKeys.iterator();
|
||||
while (iter.hasNext()) {
|
||||
|
||||
SelectionKey key = iter.next();
|
||||
|
||||
if (key.isAcceptable()) {
|
||||
register(selector, serverSocket);
|
||||
}
|
||||
|
||||
if (key.isReadable()) {
|
||||
answerWithEcho(buffer, key);
|
||||
}
|
||||
iter.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void answerWithEcho(ByteBuffer buffer, SelectionKey key) throws IOException {
|
||||
SocketChannel client = (SocketChannel) key.channel();
|
||||
client.read(buffer);
|
||||
if (new String(buffer.array()).trim().equals(POISON_PILL)) {
|
||||
client.close();
|
||||
System.out.println("Not accepting client messages anymore");
|
||||
}
|
||||
|
||||
buffer.flip();
|
||||
client.write(buffer);
|
||||
buffer.clear();
|
||||
}
|
||||
|
||||
private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException {
|
||||
SocketChannel client = serverSocket.accept();
|
||||
client.configureBlocking(false);
|
||||
client.register(selector, SelectionKey.OP_READ);
|
||||
}
|
||||
|
||||
public static Process start() throws IOException, InterruptedException {
|
||||
String javaHome = System.getProperty("java.home");
|
||||
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
||||
String classpath = System.getProperty("java.class.path");
|
||||
String className = EchoServer.class.getCanonicalName();
|
||||
|
||||
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
|
||||
|
||||
return builder.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
###Relevant Articles:
|
||||
- [Introduction to the Java NIO Selector](http://www.baeldung.com/java-nio-selector)
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.java.nio2.visitor;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
|
||||
import static java.nio.file.FileVisitResult.CONTINUE;
|
||||
import static java.nio.file.FileVisitResult.TERMINATE;
|
||||
|
||||
public class FileSearchExample implements FileVisitor<Path> {
|
||||
private final String fileName;
|
||||
private final Path startDir;
|
||||
|
||||
public FileSearchExample(String fileName, Path startingDir) {
|
||||
this.fileName = fileName;
|
||||
startDir = startingDir;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
|
||||
return CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
|
||||
String fileName = file.getFileName().toString();
|
||||
if (this.fileName.equals(fileName)) {
|
||||
System.out.println("File found: " + file.toString());
|
||||
return TERMINATE;
|
||||
}
|
||||
return CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
|
||||
System.out.println("Failed to access file: " + file.toString());
|
||||
return CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
|
||||
boolean finishedSearch = Files.isSameFile(dir, startDir);
|
||||
if (finishedSearch) {
|
||||
System.out.println("File:" + fileName + " not found");
|
||||
return TERMINATE;
|
||||
}
|
||||
return CONTINUE;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
Path startingDir = Paths.get("C:/Users/new/Desktop");
|
||||
FileSearchExample crawler = new FileSearchExample("hibernate.txt", startingDir);
|
||||
Files.walkFileTree(startingDir, crawler);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.java.nio2.visitor;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileVisitResult;
|
||||
import java.nio.file.FileVisitor;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
|
||||
public class FileVisitorImpl implements FileVisitor<Path> {
|
||||
|
||||
@Override
|
||||
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult visitFileFailed(Path file, IOException exc) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.java.nio2.watcher;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardWatchEventKinds;
|
||||
import java.nio.file.WatchEvent;
|
||||
import java.nio.file.WatchKey;
|
||||
import java.nio.file.WatchService;
|
||||
|
||||
public class DirectoryWatcherExample {
|
||||
|
||||
public static void main(String[] args) throws IOException, InterruptedException {
|
||||
WatchService watchService = FileSystems.getDefault().newWatchService();
|
||||
Path path = Paths.get(System.getProperty("user.home"));
|
||||
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
|
||||
WatchKey key;
|
||||
while ((key = watchService.take()) != null) {
|
||||
for (WatchEvent<?> event : key.pollEvents()) {
|
||||
System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
|
||||
}
|
||||
key.reset();
|
||||
}
|
||||
|
||||
watchService.close();
|
||||
}
|
||||
|
||||
}
|
||||
48
core-java-io/src/main/java/com/baeldung/stream/FileCopy.java
Normal file
48
core-java-io/src/main/java/com/baeldung/stream/FileCopy.java
Normal file
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.Files;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
|
||||
public class FileCopy {
|
||||
|
||||
public static void copyFileUsingStream(File source, File dest) throws IOException {
|
||||
InputStream is = null;
|
||||
OutputStream os = null;
|
||||
is = new FileInputStream(source);
|
||||
os = new FileOutputStream(dest);
|
||||
byte[] buffer = new byte[1024];
|
||||
int length;
|
||||
while ((length = is.read(buffer)) > 0) {
|
||||
os.write(buffer, 0, length);
|
||||
}
|
||||
is.close();
|
||||
os.close();
|
||||
}
|
||||
|
||||
public static void copyFileUsingChannel(File source, File dest) throws IOException {
|
||||
FileChannel sourceChannel = null;
|
||||
FileChannel destChannel = null;
|
||||
sourceChannel = new FileInputStream(source).getChannel();
|
||||
destChannel = new FileOutputStream(dest).getChannel();
|
||||
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
|
||||
sourceChannel.close();
|
||||
destChannel.close();
|
||||
}
|
||||
|
||||
public static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
|
||||
FileUtils.copyFile(source, dest);
|
||||
}
|
||||
|
||||
public static void copyFileUsingJavaFiles(File source, File dest) throws IOException {
|
||||
Files.copy(source.toPath(), dest.toPath());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import com.codepoetics.protonpack.Indexed;
|
||||
import com.codepoetics.protonpack.StreamUtils;
|
||||
|
||||
import io.vavr.collection.Stream;
|
||||
import one.util.streamex.EntryStream;
|
||||
|
||||
public class StreamIndices {
|
||||
|
||||
public static List<String> getEvenIndexedStrings(String[] names) {
|
||||
List<String> evenIndexedNames = IntStream.range(0, names.length)
|
||||
.filter(i -> i % 2 == 0)
|
||||
.mapToObj(i -> names[i])
|
||||
.collect(Collectors.toList());
|
||||
return evenIndexedNames;
|
||||
}
|
||||
|
||||
public List<String> getEvenIndexedStringsVersionTwo(List<String> names) {
|
||||
List<String> evenIndexedNames = EntryStream.of(names)
|
||||
.filterKeyValue((index, name) -> index % 2 == 0)
|
||||
.values()
|
||||
.toList();
|
||||
return evenIndexedNames;
|
||||
}
|
||||
|
||||
public static List<Indexed<String>> getEvenIndexedStrings(List<String> names) {
|
||||
List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream())
|
||||
.filter(i -> i.getIndex() % 2 == 0)
|
||||
.collect(Collectors.toList());
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<Indexed<String>> getOddIndexedStrings(List<String> names) {
|
||||
List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream())
|
||||
.filter(i -> i.getIndex() % 2 == 1)
|
||||
.collect(Collectors.toList());
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<String> getOddIndexedStrings(String[] names) {
|
||||
List<String> oddIndexedNames = IntStream.range(0, names.length)
|
||||
.filter(i -> i % 2 == 1)
|
||||
.mapToObj(i -> names[i])
|
||||
.collect(Collectors.toList());
|
||||
return oddIndexedNames;
|
||||
}
|
||||
|
||||
public static List<String> getOddIndexedStringsVersionTwo(String[] names) {
|
||||
List<String> oddIndexedNames = Stream.of(names)
|
||||
.zipWithIndex()
|
||||
.filter(tuple -> tuple._2 % 2 == 1)
|
||||
.map(tuple -> tuple._1)
|
||||
.toJavaList();
|
||||
return oddIndexedNames;
|
||||
}
|
||||
|
||||
}
|
||||
30
core-java-io/src/main/java/com/baeldung/unzip/UnzipFile.java
Normal file
30
core-java-io/src/main/java/com/baeldung/unzip/UnzipFile.java
Normal file
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.unzip;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
public class UnzipFile {
|
||||
public static void main(final String[] args) throws IOException {
|
||||
final String fileZip = "src/main/resources/compressed.zip";
|
||||
final byte[] buffer = new byte[1024];
|
||||
final ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
|
||||
ZipEntry zipEntry = zis.getNextEntry();
|
||||
while (zipEntry != null) {
|
||||
final String fileName = zipEntry.getName();
|
||||
final File newFile = new File("src/main/resources/unzipTest/" + fileName);
|
||||
final FileOutputStream fos = new FileOutputStream(newFile);
|
||||
int len;
|
||||
while ((len = zis.read(buffer)) > 0) {
|
||||
fos.write(buffer, 0, len);
|
||||
}
|
||||
fos.close();
|
||||
zipEntry = zis.getNextEntry();
|
||||
}
|
||||
zis.closeEntry();
|
||||
zis.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.StringWriter;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
public class StreamUtils {
|
||||
|
||||
public static String getStringFromInputStream(InputStream input) throws IOException {
|
||||
StringWriter writer = new StringWriter();
|
||||
IOUtils.copy(input, writer, "UTF-8");
|
||||
return writer.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.zip;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
public class ZipDirectory {
|
||||
public static void main(final String[] args) throws IOException {
|
||||
final String sourceFile = "src/main/resources/zipTest";
|
||||
final FileOutputStream fos = new FileOutputStream("src/main/resources/dirCompressed.zip");
|
||||
final ZipOutputStream zipOut = new ZipOutputStream(fos);
|
||||
final File fileToZip = new File(sourceFile);
|
||||
|
||||
zipFile(fileToZip, fileToZip.getName(), zipOut);
|
||||
zipOut.close();
|
||||
fos.close();
|
||||
}
|
||||
|
||||
private static void zipFile(final File fileToZip, final String fileName, final ZipOutputStream zipOut) throws IOException {
|
||||
if (fileToZip.isHidden()) {
|
||||
return;
|
||||
}
|
||||
if (fileToZip.isDirectory()) {
|
||||
final File[] children = fileToZip.listFiles();
|
||||
for (final File childFile : children) {
|
||||
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
|
||||
}
|
||||
return;
|
||||
}
|
||||
final FileInputStream fis = new FileInputStream(fileToZip);
|
||||
final ZipEntry zipEntry = new ZipEntry(fileName);
|
||||
zipOut.putNextEntry(zipEntry);
|
||||
final byte[] bytes = new byte[1024];
|
||||
int length;
|
||||
while ((length = fis.read(bytes)) >= 0) {
|
||||
zipOut.write(bytes, 0, length);
|
||||
}
|
||||
fis.close();
|
||||
}
|
||||
}
|
||||
28
core-java-io/src/main/java/com/baeldung/zip/ZipFile.java
Normal file
28
core-java-io/src/main/java/com/baeldung/zip/ZipFile.java
Normal file
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.zip;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
public class ZipFile {
|
||||
public static void main(final String[] args) throws IOException {
|
||||
final String sourceFile = "src/main/resources/zipTest/test1.txt";
|
||||
final FileOutputStream fos = new FileOutputStream("src/main/resources/compressed.zip");
|
||||
final ZipOutputStream zipOut = new ZipOutputStream(fos);
|
||||
final File fileToZip = new File(sourceFile);
|
||||
final FileInputStream fis = new FileInputStream(fileToZip);
|
||||
final ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
|
||||
zipOut.putNextEntry(zipEntry);
|
||||
final byte[] bytes = new byte[1024];
|
||||
int length;
|
||||
while ((length = fis.read(bytes)) >= 0) {
|
||||
zipOut.write(bytes, 0, length);
|
||||
}
|
||||
zipOut.close();
|
||||
fis.close();
|
||||
fos.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.zip;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
public class ZipMultipleFiles {
|
||||
public static void main(final String[] args) throws IOException {
|
||||
final List<String> srcFiles = Arrays.asList("src/main/resources/zipTest/test1.txt", "src/main/resources/zipTest/test2.txt");
|
||||
final FileOutputStream fos = new FileOutputStream("src/main/resources/multiCompressed.zip");
|
||||
final ZipOutputStream zipOut = new ZipOutputStream(fos);
|
||||
for (final String srcFile : srcFiles) {
|
||||
final File fileToZip = new File(srcFile);
|
||||
final FileInputStream fis = new FileInputStream(fileToZip);
|
||||
final ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
|
||||
zipOut.putNextEntry(zipEntry);
|
||||
|
||||
final byte[] bytes = new byte[1024];
|
||||
int length;
|
||||
while ((length = fis.read(bytes)) >= 0) {
|
||||
zipOut.write(bytes, 0, length);
|
||||
}
|
||||
fis.close();
|
||||
}
|
||||
zipOut.close();
|
||||
fos.close();
|
||||
}
|
||||
}
|
||||
453
core-java-io/src/main/resources/ESAPI.properties
Normal file
453
core-java-io/src/main/resources/ESAPI.properties
Normal file
@@ -0,0 +1,453 @@
|
||||
#
|
||||
# OWASP Enterprise Security API (ESAPI) Properties file -- PRODUCTION Version
|
||||
#
|
||||
# This file is part of the Open Web Application Security Project (OWASP)
|
||||
# Enterprise Security API (ESAPI) project. For details, please see
|
||||
# http://www.owasp.org/index.php/ESAPI.
|
||||
#
|
||||
# Copyright (c) 2008,2009 - The OWASP Foundation
|
||||
#
|
||||
# DISCUSS: This may cause a major backwards compatibility issue, etc. but
|
||||
# from a name space perspective, we probably should have prefaced
|
||||
# all the property names with ESAPI or at least OWASP. Otherwise
|
||||
# there could be problems is someone loads this properties file into
|
||||
# the System properties. We could also put this file into the
|
||||
# esapi.jar file (perhaps as a ResourceBundle) and then allow an external
|
||||
# ESAPI properties be defined that would overwrite these defaults.
|
||||
# That keeps the application's properties relatively simple as usually
|
||||
# they will only want to override a few properties. If looks like we
|
||||
# already support multiple override levels of this in the
|
||||
# DefaultSecurityConfiguration class, but I'm suggesting placing the
|
||||
# defaults in the esapi.jar itself. That way, if the jar is signed,
|
||||
# we could detect if those properties had been tampered with. (The
|
||||
# code to check the jar signatures is pretty simple... maybe 70-90 LOC,
|
||||
# but off course there is an execution penalty (similar to the way
|
||||
# that the separate sunjce.jar used to be when a class from it was
|
||||
# first loaded). Thoughts?
|
||||
###############################################################################
|
||||
#
|
||||
# WARNING: Operating system protection should be used to lock down the .esapi
|
||||
# resources directory and all the files inside and all the directories all the
|
||||
# way up to the root directory of the file system. Note that if you are using
|
||||
# file-based implementations, that some files may need to be read-write as they
|
||||
# get updated dynamically.
|
||||
#
|
||||
# Before using, be sure to update the MasterKey and MasterSalt as described below.
|
||||
# N.B.: If you had stored data that you have previously encrypted with ESAPI 1.4,
|
||||
# you *must* FIRST decrypt it using ESAPI 1.4 and then (if so desired)
|
||||
# re-encrypt it with ESAPI 2.0. If you fail to do this, you will NOT be
|
||||
# able to decrypt your data with ESAPI 2.0.
|
||||
#
|
||||
# YOU HAVE BEEN WARNED!!! More details are in the ESAPI 2.0 Release Notes.
|
||||
#
|
||||
#===========================================================================
|
||||
# ESAPI Configuration
|
||||
#
|
||||
# If true, then print all the ESAPI properties set here when they are loaded.
|
||||
# If false, they are not printed. Useful to reduce output when running JUnit tests.
|
||||
# If you need to troubleshoot a properties related problem, turning this on may help.
|
||||
# This is 'false' in the src/test/resources/.esapi version. It is 'true' by
|
||||
# default for reasons of backward compatibility with earlier ESAPI versions.
|
||||
ESAPI.printProperties=true
|
||||
|
||||
# ESAPI is designed to be easily extensible. You can use the reference implementation
|
||||
# or implement your own providers to take advantage of your enterprise's security
|
||||
# infrastructure. The functions in ESAPI are referenced using the ESAPI locator, like:
|
||||
#
|
||||
# String ciphertext =
|
||||
# ESAPI.encryptor().encrypt("Secret message"); // Deprecated in 2.0
|
||||
# CipherText cipherText =
|
||||
# ESAPI.encryptor().encrypt(new PlainText("Secret message")); // Preferred
|
||||
#
|
||||
# Below you can specify the classname for the provider that you wish to use in your
|
||||
# application. The only requirement is that it implement the appropriate ESAPI interface.
|
||||
# This allows you to switch security implementations in the future without rewriting the
|
||||
# entire application.
|
||||
#
|
||||
# ExperimentalAccessController requires ESAPI-AccessControlPolicy.xml in .esapi directory
|
||||
ESAPI.AccessControl=org.owasp.esapi.reference.DefaultAccessController
|
||||
# FileBasedAuthenticator requires users.txt file in .esapi directory
|
||||
ESAPI.Authenticator=org.owasp.esapi.reference.FileBasedAuthenticator
|
||||
ESAPI.Encoder=org.owasp.esapi.reference.DefaultEncoder
|
||||
ESAPI.Encryptor=org.owasp.esapi.reference.crypto.JavaEncryptor
|
||||
|
||||
ESAPI.Executor=org.owasp.esapi.reference.DefaultExecutor
|
||||
ESAPI.HTTPUtilities=org.owasp.esapi.reference.DefaultHTTPUtilities
|
||||
ESAPI.IntrusionDetector=org.owasp.esapi.reference.DefaultIntrusionDetector
|
||||
# Log4JFactory Requires log4j.xml or log4j.properties in classpath - http://www.laliluna.de/log4j-tutorial.html
|
||||
ESAPI.Logger=org.owasp.esapi.reference.Log4JLogFactory
|
||||
#ESAPI.Logger=org.owasp.esapi.reference.JavaLogFactory
|
||||
ESAPI.Randomizer=org.owasp.esapi.reference.DefaultRandomizer
|
||||
ESAPI.Validator=org.owasp.esapi.reference.DefaultValidator
|
||||
|
||||
#===========================================================================
|
||||
# ESAPI Authenticator
|
||||
#
|
||||
Authenticator.AllowedLoginAttempts=3
|
||||
Authenticator.MaxOldPasswordHashes=13
|
||||
Authenticator.UsernameParameterName=username
|
||||
Authenticator.PasswordParameterName=password
|
||||
# RememberTokenDuration (in days)
|
||||
Authenticator.RememberTokenDuration=14
|
||||
# Session Timeouts (in minutes)
|
||||
Authenticator.IdleTimeoutDuration=20
|
||||
Authenticator.AbsoluteTimeoutDuration=120
|
||||
|
||||
#===========================================================================
|
||||
# ESAPI Encoder
|
||||
#
|
||||
# ESAPI canonicalizes input before validation to prevent bypassing filters with encoded attacks.
|
||||
# Failure to canonicalize input is a very common mistake when implementing validation schemes.
|
||||
# Canonicalization is automatic when using the ESAPI Validator, but you can also use the
|
||||
# following code to canonicalize data.
|
||||
#
|
||||
# ESAPI.Encoder().canonicalize( "%22hello world"" );
|
||||
#
|
||||
# Multiple encoding is when a single encoding format is applied multiple times. Allowing
|
||||
# multiple encoding is strongly discouraged.
|
||||
Encoder.AllowMultipleEncoding=false
|
||||
|
||||
# Mixed encoding is when multiple different encoding formats are applied, or when
|
||||
# multiple formats are nested. Allowing multiple encoding is strongly discouraged.
|
||||
Encoder.AllowMixedEncoding=false
|
||||
|
||||
# The default list of codecs to apply when canonicalizing untrusted data. The list should include the codecs
|
||||
# for all downstream interpreters or decoders. For example, if the data is likely to end up in a URL, HTML, or
|
||||
# inside JavaScript, then the list of codecs below is appropriate. The order of the list is not terribly important.
|
||||
Encoder.DefaultCodecList=HTMLEntityCodec,PercentCodec,JavaScriptCodec
|
||||
|
||||
|
||||
#===========================================================================
|
||||
# ESAPI Encryption
|
||||
#
|
||||
# The ESAPI Encryptor provides basic cryptographic functions with a simplified API.
|
||||
# To get started, generate a new key using java -classpath esapi.jar org.owasp.esapi.reference.crypto.JavaEncryptor
|
||||
# There is not currently any support for key rotation, so be careful when changing your key and salt as it
|
||||
# will invalidate all signed, encrypted, and hashed data.
|
||||
#
|
||||
# WARNING: Not all combinations of algorithms and key lengths are supported.
|
||||
# If you choose to use a key length greater than 128, you MUST download the
|
||||
# unlimited strength policy files and install in the lib directory of your JRE/JDK.
|
||||
# See http://java.sun.com/javase/downloads/index.jsp for more information.
|
||||
#
|
||||
# Backward compatibility with ESAPI Java 1.4 is supported by the two deprecated API
|
||||
# methods, Encryptor.encrypt(String) and Encryptor.decrypt(String). However, whenever
|
||||
# possible, these methods should be avoided as they use ECB cipher mode, which in almost
|
||||
# all circumstances a poor choice because of it's weakness. CBC cipher mode is the default
|
||||
# for the new Encryptor encrypt / decrypt methods for ESAPI Java 2.0. In general, you
|
||||
# should only use this compatibility setting if you have persistent data encrypted with
|
||||
# version 1.4 and even then, you should ONLY set this compatibility mode UNTIL
|
||||
# you have decrypted all of your old encrypted data and then re-encrypted it with
|
||||
# ESAPI 2.0 using CBC mode. If you have some reason to mix the deprecated 1.4 mode
|
||||
# with the new 2.0 methods, make sure that you use the same cipher algorithm for both
|
||||
# (256-bit AES was the default for 1.4; 128-bit is the default for 2.0; see below for
|
||||
# more details.) Otherwise, you will have to use the new 2.0 encrypt / decrypt methods
|
||||
# where you can specify a SecretKey. (Note that if you are using the 256-bit AES,
|
||||
# that requires downloading the special jurisdiction policy files mentioned above.)
|
||||
#
|
||||
# ***** IMPORTANT: Do NOT forget to replace these with your own values! *****
|
||||
# To calculate these values, you can run:
|
||||
# java -classpath esapi.jar org.owasp.esapi.reference.crypto.JavaEncryptor
|
||||
#
|
||||
Encryptor.MasterKey=tzfztf56ftv
|
||||
Encryptor.MasterSalt=123456ztrewq
|
||||
|
||||
# Provides the default JCE provider that ESAPI will "prefer" for its symmetric
|
||||
# encryption and hashing. (That is it will look to this provider first, but it
|
||||
# will defer to other providers if the requested algorithm is not implemented
|
||||
# by this provider.) If left unset, ESAPI will just use your Java VM's current
|
||||
# preferred JCE provider, which is generally set in the file
|
||||
# "$JAVA_HOME/jre/lib/security/java.security".
|
||||
#
|
||||
# The main intent of this is to allow ESAPI symmetric encryption to be
|
||||
# used with a FIPS 140-2 compliant crypto-module. For details, see the section
|
||||
# "Using ESAPI Symmetric Encryption with FIPS 140-2 Cryptographic Modules" in
|
||||
# the ESAPI 2.0 Symmetric Encryption User Guide, at:
|
||||
# http://owasp-esapi-java.googlecode.com/svn/trunk/documentation/esapi4java-core-2.0-symmetric-crypto-user-guide.html
|
||||
# However, this property also allows you to easily use an alternate JCE provider
|
||||
# such as "Bouncy Castle" without having to make changes to "java.security".
|
||||
# See Javadoc for SecurityProviderLoader for further details. If you wish to use
|
||||
# a provider that is not known to SecurityProviderLoader, you may specify the
|
||||
# fully-qualified class name of the JCE provider class that implements
|
||||
# java.security.Provider. If the name contains a '.', this is interpreted as
|
||||
# a fully-qualified class name that implements java.security.Provider.
|
||||
#
|
||||
# NOTE: Setting this property has the side-effect of changing it in your application
|
||||
# as well, so if you are using JCE in your application directly rather than
|
||||
# through ESAPI (you wouldn't do that, would you? ;-), it will change the
|
||||
# preferred JCE provider there as well.
|
||||
#
|
||||
# Default: Keeps the JCE provider set to whatever JVM sets it to.
|
||||
Encryptor.PreferredJCEProvider=
|
||||
|
||||
# AES is the most widely used and strongest encryption algorithm. This
|
||||
# should agree with your Encryptor.CipherTransformation property.
|
||||
# By default, ESAPI Java 1.4 uses "PBEWithMD5AndDES" and which is
|
||||
# very weak. It is essentially a password-based encryption key, hashed
|
||||
# with MD5 around 1K times and then encrypted with the weak DES algorithm
|
||||
# (56-bits) using ECB mode and an unspecified padding (it is
|
||||
# JCE provider specific, but most likely "NoPadding"). However, 2.0 uses
|
||||
# "AES/CBC/PKCSPadding". If you want to change these, change them here.
|
||||
# Warning: This property does not control the default reference implementation for
|
||||
# ESAPI 2.0 using JavaEncryptor. Also, this property will be dropped
|
||||
# in the future.
|
||||
# @deprecated
|
||||
Encryptor.EncryptionAlgorithm=AES
|
||||
# For ESAPI Java 2.0 - New encrypt / decrypt methods use this.
|
||||
Encryptor.CipherTransformation=AES/CBC/PKCS5Padding
|
||||
|
||||
# Applies to ESAPI 2.0 and later only!
|
||||
# Comma-separated list of cipher modes that provide *BOTH*
|
||||
# confidentiality *AND* message authenticity. (NIST refers to such cipher
|
||||
# modes as "combined modes" so that's what we shall call them.) If any of these
|
||||
# cipher modes are used then no MAC is calculated and stored
|
||||
# in the CipherText upon encryption. Likewise, if one of these
|
||||
# cipher modes is used with decryption, no attempt will be made
|
||||
# to validate the MAC contained in the CipherText object regardless
|
||||
# of whether it contains one or not. Since the expectation is that
|
||||
# these cipher modes support support message authenticity already,
|
||||
# injecting a MAC in the CipherText object would be at best redundant.
|
||||
#
|
||||
# Note that as of JDK 1.5, the SunJCE provider does not support *any*
|
||||
# of these cipher modes. Of these listed, only GCM and CCM are currently
|
||||
# NIST approved. YMMV for other JCE providers. E.g., Bouncy Castle supports
|
||||
# GCM and CCM with "NoPadding" mode, but not with "PKCS5Padding" or other
|
||||
# padding modes.
|
||||
Encryptor.cipher_modes.combined_modes=GCM,CCM,IAPM,EAX,OCB,CWC
|
||||
|
||||
# Applies to ESAPI 2.0 and later only!
|
||||
# Additional cipher modes allowed for ESAPI 2.0 encryption. These
|
||||
# cipher modes are in _addition_ to those specified by the property
|
||||
# 'Encryptor.cipher_modes.combined_modes'.
|
||||
# Note: We will add support for streaming modes like CFB & OFB once
|
||||
# we add support for 'specified' to the property 'Encryptor.ChooseIVMethod'
|
||||
# (probably in ESAPI 2.1).
|
||||
# DISCUSS: Better name?
|
||||
Encryptor.cipher_modes.additional_allowed=CBC
|
||||
|
||||
# 128-bit is almost always sufficient and appears to be more resistant to
|
||||
# related key attacks than is 256-bit AES. Use '_' to use default key size
|
||||
# for cipher algorithms (where it makes sense because the algorithm supports
|
||||
# a variable key size). Key length must agree to what's provided as the
|
||||
# cipher transformation, otherwise this will be ignored after logging a
|
||||
# warning.
|
||||
#
|
||||
# NOTE: This is what applies BOTH ESAPI 1.4 and 2.0. See warning above about mixing!
|
||||
Encryptor.EncryptionKeyLength=128
|
||||
|
||||
# Because 2.0 uses CBC mode by default, it requires an initialization vector (IV).
|
||||
# (All cipher modes except ECB require an IV.) There are two choices: we can either
|
||||
# use a fixed IV known to both parties or allow ESAPI to choose a random IV. While
|
||||
# the IV does not need to be hidden from adversaries, it is important that the
|
||||
# adversary not be allowed to choose it. Also, random IVs are generally much more
|
||||
# secure than fixed IVs. (In fact, it is essential that feed-back cipher modes
|
||||
# such as CFB and OFB use a different IV for each encryption with a given key so
|
||||
# in such cases, random IVs are much preferred. By default, ESAPI 2.0 uses random
|
||||
# IVs. If you wish to use 'fixed' IVs, set 'Encryptor.ChooseIVMethod=fixed' and
|
||||
# uncomment the Encryptor.fixedIV.
|
||||
#
|
||||
# Valid values: random|fixed|specified 'specified' not yet implemented; planned for 2.1
|
||||
Encryptor.ChooseIVMethod=random
|
||||
# If you choose to use a fixed IV, then you must place a fixed IV here that
|
||||
# is known to all others who are sharing your secret key. The format should
|
||||
# be a hex string that is the same length as the cipher block size for the
|
||||
# cipher algorithm that you are using. The following is an *example* for AES
|
||||
# from an AES test vector for AES-128/CBC as described in:
|
||||
# NIST Special Publication 800-38A (2001 Edition)
|
||||
# "Recommendation for Block Cipher Modes of Operation".
|
||||
# (Note that the block size for AES is 16 bytes == 128 bits.)
|
||||
#
|
||||
Encryptor.fixedIV=0x000102030405060708090a0b0c0d0e0f
|
||||
|
||||
# Whether or not CipherText should use a message authentication code (MAC) with it.
|
||||
# This prevents an adversary from altering the IV as well as allowing a more
|
||||
# fool-proof way of determining the decryption failed because of an incorrect
|
||||
# key being supplied. This refers to the "separate" MAC calculated and stored
|
||||
# in CipherText, not part of any MAC that is calculated as a result of a
|
||||
# "combined mode" cipher mode.
|
||||
#
|
||||
# If you are using ESAPI with a FIPS 140-2 cryptographic module, you *must* also
|
||||
# set this property to false.
|
||||
Encryptor.CipherText.useMAC=true
|
||||
|
||||
# Whether or not the PlainText object may be overwritten and then marked
|
||||
# eligible for garbage collection. If not set, this is still treated as 'true'.
|
||||
Encryptor.PlainText.overwrite=true
|
||||
|
||||
# Do not use DES except in a legacy situations. 56-bit is way too small key size.
|
||||
#Encryptor.EncryptionKeyLength=56
|
||||
#Encryptor.EncryptionAlgorithm=DES
|
||||
|
||||
# TripleDES is considered strong enough for most purposes.
|
||||
# Note: There is also a 112-bit version of DESede. Using the 168-bit version
|
||||
# requires downloading the special jurisdiction policy from Sun.
|
||||
#Encryptor.EncryptionKeyLength=168
|
||||
#Encryptor.EncryptionAlgorithm=DESede
|
||||
|
||||
Encryptor.HashAlgorithm=SHA-512
|
||||
Encryptor.HashIterations=1024
|
||||
Encryptor.DigitalSignatureAlgorithm=SHA1withDSA
|
||||
Encryptor.DigitalSignatureKeyLength=1024
|
||||
Encryptor.RandomAlgorithm=SHA1PRNG
|
||||
Encryptor.CharacterEncoding=UTF-8
|
||||
|
||||
# This is the Pseudo Random Function (PRF) that ESAPI's Key Derivation Function
|
||||
# (KDF) normally uses. Note this is *only* the PRF used for ESAPI's KDF and
|
||||
# *not* what is used for ESAPI's MAC. (Currently, HmacSHA1 is always used for
|
||||
# the MAC, mostly to keep the overall size at a minimum.)
|
||||
#
|
||||
# Currently supported choices for JDK 1.5 and 1.6 are:
|
||||
# HmacSHA1 (160 bits), HmacSHA256 (256 bits), HmacSHA384 (384 bits), and
|
||||
# HmacSHA512 (512 bits).
|
||||
# Note that HmacMD5 is *not* supported for the PRF used by the KDF even though
|
||||
# the JDKs support it. See the ESAPI 2.0 Symmetric Encryption User Guide
|
||||
# further details.
|
||||
Encryptor.KDF.PRF=HmacSHA256
|
||||
#===========================================================================
|
||||
# ESAPI HttpUtilties
|
||||
#
|
||||
# The HttpUtilities provide basic protections to HTTP requests and responses. Primarily these methods
|
||||
# protect against malicious data from attackers, such as unprintable characters, escaped characters,
|
||||
# and other simple attacks. The HttpUtilities also provides utility methods for dealing with cookies,
|
||||
# headers, and CSRF tokens.
|
||||
#
|
||||
# Default file upload location (remember to escape backslashes with \\)
|
||||
HttpUtilities.UploadDir=C:\\ESAPI\\testUpload
|
||||
HttpUtilities.UploadTempDir=C:\\temp
|
||||
# Force flags on cookies, if you use HttpUtilities to set cookies
|
||||
HttpUtilities.ForceHttpOnlySession=false
|
||||
HttpUtilities.ForceSecureSession=false
|
||||
HttpUtilities.ForceHttpOnlyCookies=true
|
||||
HttpUtilities.ForceSecureCookies=true
|
||||
# Maximum size of HTTP headers
|
||||
HttpUtilities.MaxHeaderSize=4096
|
||||
# File upload configuration
|
||||
HttpUtilities.ApprovedUploadExtensions=.zip,.pdf,.doc,.docx,.ppt,.pptx,.tar,.gz,.tgz,.rar,.war,.jar,.ear,.xls,.rtf,.properties,.java,.class,.txt,.xml,.jsp,.jsf,.exe,.dll
|
||||
HttpUtilities.MaxUploadFileBytes=500000000
|
||||
# Using UTF-8 throughout your stack is highly recommended. That includes your database driver,
|
||||
# container, and any other technologies you may be using. Failure to do this may expose you
|
||||
# to Unicode transcoding injection attacks. Use of UTF-8 does not hinder internationalization.
|
||||
HttpUtilities.ResponseContentType=text/html; charset=UTF-8
|
||||
# This is the name of the cookie used to represent the HTTP session
|
||||
# Typically this will be the default "JSESSIONID"
|
||||
HttpUtilities.HttpSessionIdName=JSESSIONID
|
||||
|
||||
|
||||
|
||||
#===========================================================================
|
||||
# ESAPI Executor
|
||||
# CHECKME - Not sure what this is used for, but surely it should be made OS independent.
|
||||
Executor.WorkingDirectory=C:\\Windows\\Temp
|
||||
Executor.ApprovedExecutables=C:\\Windows\\System32\\cmd.exe,C:\\Windows\\System32\\runas.exe
|
||||
|
||||
|
||||
#===========================================================================
|
||||
# ESAPI Logging
|
||||
# Set the application name if these logs are combined with other applications
|
||||
Logger.ApplicationName=ExampleApplication
|
||||
# If you use an HTML log viewer that does not properly HTML escape log data, you can set LogEncodingRequired to true
|
||||
Logger.LogEncodingRequired=false
|
||||
# Determines whether ESAPI should log the application name. This might be clutter in some single-server/single-app environments.
|
||||
Logger.LogApplicationName=true
|
||||
# Determines whether ESAPI should log the server IP and port. This might be clutter in some single-server environments.
|
||||
Logger.LogServerIP=true
|
||||
# LogFileName, the name of the logging file. Provide a full directory path (e.g., C:\\ESAPI\\ESAPI_logging_file) if you
|
||||
# want to place it in a specific directory.
|
||||
Logger.LogFileName=ESAPI_logging_file
|
||||
# MaxLogFileSize, the max size (in bytes) of a single log file before it cuts over to a new one (default is 10,000,000)
|
||||
Logger.MaxLogFileSize=10000000
|
||||
|
||||
|
||||
#===========================================================================
|
||||
# ESAPI Intrusion Detection
|
||||
#
|
||||
# Each event has a base to which .count, .interval, and .action are added
|
||||
# The IntrusionException will fire if we receive "count" events within "interval" seconds
|
||||
# The IntrusionDetector is configurable to take the following actions: log, logout, and disable
|
||||
# (multiple actions separated by commas are allowed e.g. event.test.actions=log,disable
|
||||
#
|
||||
# Custom Events
|
||||
# Names must start with "event." as the base
|
||||
# Use IntrusionDetector.addEvent( "test" ) in your code to trigger "event.test" here
|
||||
# You can also disable intrusion detection completely by changing
|
||||
# the following parameter to true
|
||||
#
|
||||
IntrusionDetector.Disable=false
|
||||
#
|
||||
IntrusionDetector.event.test.count=2
|
||||
IntrusionDetector.event.test.interval=10
|
||||
IntrusionDetector.event.test.actions=disable,log
|
||||
|
||||
# Exception Events
|
||||
# All EnterpriseSecurityExceptions are registered automatically
|
||||
# Call IntrusionDetector.getInstance().addException(e) for Exceptions that do not extend EnterpriseSecurityException
|
||||
# Use the fully qualified classname of the exception as the base
|
||||
|
||||
# any intrusion is an attack
|
||||
IntrusionDetector.org.owasp.esapi.errors.IntrusionException.count=1
|
||||
IntrusionDetector.org.owasp.esapi.errors.IntrusionException.interval=1
|
||||
IntrusionDetector.org.owasp.esapi.errors.IntrusionException.actions=log,disable,logout
|
||||
|
||||
# for test purposes
|
||||
# CHECKME: Shouldn't there be something in the property name itself that designates
|
||||
# that these are for testing???
|
||||
IntrusionDetector.org.owasp.esapi.errors.IntegrityException.count=10
|
||||
IntrusionDetector.org.owasp.esapi.errors.IntegrityException.interval=5
|
||||
IntrusionDetector.org.owasp.esapi.errors.IntegrityException.actions=log,disable,logout
|
||||
|
||||
# rapid validation errors indicate scans or attacks in progress
|
||||
# org.owasp.esapi.errors.ValidationException.count=10
|
||||
# org.owasp.esapi.errors.ValidationException.interval=10
|
||||
# org.owasp.esapi.errors.ValidationException.actions=log,logout
|
||||
|
||||
# sessions jumping between hosts indicates session hijacking
|
||||
IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.count=2
|
||||
IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.interval=10
|
||||
IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.actions=log,logout
|
||||
|
||||
|
||||
#===========================================================================
|
||||
# ESAPI Validation
|
||||
#
|
||||
# The ESAPI Validator works on regular expressions with defined names. You can define names
|
||||
# either here, or you may define application specific patterns in a separate file defined below.
|
||||
# This allows enterprises to specify both organizational standards as well as application specific
|
||||
# validation rules.
|
||||
#
|
||||
Validator.ConfigurationFile=validation.properties
|
||||
|
||||
# Validators used by ESAPI
|
||||
Validator.AccountName=^[a-zA-Z0-9]{3,20}$
|
||||
Validator.SystemCommand=^[a-zA-Z\\-\\/]{1,64}$
|
||||
Validator.RoleName=^[a-z]{1,20}$
|
||||
|
||||
#the word TEST below should be changed to your application
|
||||
#name - only relative URL's are supported
|
||||
Validator.Redirect=^\\/test.*$
|
||||
|
||||
# Global HTTP Validation Rules
|
||||
# Values with Base64 encoded data (e.g. encrypted state) will need at least [a-zA-Z0-9\/+=]
|
||||
Validator.HTTPScheme=^(http|https)$
|
||||
Validator.HTTPServerName=^[a-zA-Z0-9_.\\-]*$
|
||||
Validator.HTTPParameterName=^[a-zA-Z0-9_]{1,32}$
|
||||
Validator.HTTPParameterValue=^[a-zA-Z0-9.\\-\\/+=@_ ]*$
|
||||
Validator.HTTPCookieName=^[a-zA-Z0-9\\-_]{1,32}$
|
||||
Validator.HTTPCookieValue=^[a-zA-Z0-9\\-\\/+=_ ]*$
|
||||
Validator.HTTPHeaderName=^[a-zA-Z0-9\\-_]{1,32}$
|
||||
Validator.HTTPHeaderValue=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ ]*$
|
||||
Validator.HTTPContextPath=^\\/?[a-zA-Z0-9.\\-\\/_]*$
|
||||
Validator.HTTPServletPath=^[a-zA-Z0-9.\\-\\/_]*$
|
||||
Validator.HTTPPath=^[a-zA-Z0-9.\\-_]*$
|
||||
Validator.HTTPQueryString=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ %]*$
|
||||
Validator.HTTPURI=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ ]*$
|
||||
Validator.HTTPURL=^.*$
|
||||
Validator.HTTPJSESSIONID=^[A-Z0-9]{10,30}$
|
||||
|
||||
# Validation of file related input
|
||||
Validator.FileName=^[a-zA-Z0-9!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$
|
||||
Validator.DirectoryName=^[a-zA-Z0-9:/\\\\!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$
|
||||
|
||||
# Validation of dates. Controls whether or not 'lenient' dates are accepted.
|
||||
# See DataFormat.setLenient(boolean flag) for further details.
|
||||
Validator.AcceptLenientDates=false
|
||||
|
||||
0
core-java-io/src/main/resources/META-INF/BenchmarkList
Executable file
0
core-java-io/src/main/resources/META-INF/BenchmarkList
Executable file
20
core-java-io/src/main/resources/META-INF/persistence.xml
Normal file
20
core-java-io/src/main/resources/META-INF/persistence.xml
Normal file
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
|
||||
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1">
|
||||
|
||||
<!-- JDO tutorial "unit" -->
|
||||
<persistence-unit name="Tutorial">
|
||||
<exclude-unlisted-classes/>
|
||||
<properties>
|
||||
<property name="javax.jdo.PersistenceManagerFactoryClass" value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory"/>
|
||||
<property name="javax.jdo.option.ConnectionURL" value="jdbc:h2:mem:mypersistence"/>
|
||||
<property name="javax.jdo.option.ConnectionDriverName" value="org.h2.Driver"/>
|
||||
<property name="javax.jdo.option.ConnectionUserName" value="sa"/>
|
||||
<property name="javax.jdo.option.ConnectionPassword" value=""/>
|
||||
<property name="datanucleus.schema.autoCreateAll" value="true"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
</persistence>
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
com.baeldung.javac.SampleJavacPlugin
|
||||
3
core-java-io/src/main/resources/countries.properties
Normal file
3
core-java-io/src/main/resources/countries.properties
Normal file
@@ -0,0 +1,3 @@
|
||||
UK
|
||||
US
|
||||
Germany
|
||||
3
core-java-io/src/main/resources/data.csv
Normal file
3
core-java-io/src/main/resources/data.csv
Normal file
@@ -0,0 +1,3 @@
|
||||
1|IND|India
|
||||
2|MY|Malaysia
|
||||
3|AU|Australia
|
||||
|
6
core-java-io/src/main/resources/datasource.properties
Normal file
6
core-java-io/src/main/resources/datasource.properties
Normal file
@@ -0,0 +1,6 @@
|
||||
dataSourceClassName=//TBD
|
||||
dataSource.user=//TBD
|
||||
dataSource.password=//TBD
|
||||
dataSource.databaseName=//TBD
|
||||
dataSource.portNumber=//TBD
|
||||
dataSource.serverName=//TBD
|
||||
BIN
core-java-io/src/main/resources/dirCompressed.zip
Normal file
BIN
core-java-io/src/main/resources/dirCompressed.zip
Normal file
Binary file not shown.
15
core-java-io/src/main/resources/js/bind.js
Normal file
15
core-java-io/src/main/resources/js/bind.js
Normal file
@@ -0,0 +1,15 @@
|
||||
var first = {
|
||||
name: "Whiskey",
|
||||
age: 5
|
||||
};
|
||||
|
||||
var second = {
|
||||
volume: 100
|
||||
};
|
||||
|
||||
Object.bindProperties(first, second);
|
||||
|
||||
print(first.volume);
|
||||
|
||||
second.volume = 1000;
|
||||
print(first.volume);
|
||||
1
core-java-io/src/main/resources/js/locations.js
Normal file
1
core-java-io/src/main/resources/js/locations.js
Normal file
@@ -0,0 +1 @@
|
||||
print(__FILE__, __LINE__, __DIR__);
|
||||
19
core-java-io/src/main/resources/js/math_module.js
Normal file
19
core-java-io/src/main/resources/js/math_module.js
Normal file
@@ -0,0 +1,19 @@
|
||||
var math = {
|
||||
increment: function (num) {
|
||||
return ++num;
|
||||
},
|
||||
|
||||
failFunc: function () {
|
||||
try {
|
||||
throw "BOOM";
|
||||
} catch (e if typeof e === 'string') {
|
||||
print("String thrown: " + e);
|
||||
}
|
||||
catch (e) {
|
||||
print("this shouldn't happen!");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
math;
|
||||
11
core-java-io/src/main/resources/js/no_such.js
Normal file
11
core-java-io/src/main/resources/js/no_such.js
Normal file
@@ -0,0 +1,11 @@
|
||||
var demo = {
|
||||
__noSuchProperty__: function (propName) {
|
||||
print("Accessed non-existing property: " + propName);
|
||||
},
|
||||
|
||||
__noSuchMethod__: function (methodName) {
|
||||
print("Invoked non-existing method: " + methodName);
|
||||
}
|
||||
};
|
||||
|
||||
demo;
|
||||
1
core-java-io/src/main/resources/js/script.js
Normal file
1
core-java-io/src/main/resources/js/script.js
Normal file
@@ -0,0 +1 @@
|
||||
function increment(num) ++num;
|
||||
2
core-java-io/src/main/resources/js/trim.js
Normal file
2
core-java-io/src/main/resources/js/trim.js
Normal file
@@ -0,0 +1,2 @@
|
||||
print(" hello world".trimLeft());
|
||||
print("hello world ".trimRight());
|
||||
9
core-java-io/src/main/resources/js/typed_arrays.js
Normal file
9
core-java-io/src/main/resources/js/typed_arrays.js
Normal file
@@ -0,0 +1,9 @@
|
||||
function arrays(arr) {
|
||||
|
||||
var javaIntArray = Java.to(arr, "int[]");
|
||||
print(javaIntArray[0]);
|
||||
print(javaIntArray[1]);
|
||||
print(javaIntArray[2]);
|
||||
}
|
||||
|
||||
arrays([100, "1654", true]);
|
||||
6
core-java-io/src/main/resources/log4j.properties
Normal file
6
core-java-io/src/main/resources/log4j.properties
Normal file
@@ -0,0 +1,6 @@
|
||||
log4j.rootLogger=DEBUG, A1
|
||||
|
||||
log4j.appender.A1=org.apache.log4j.ConsoleAppender
|
||||
|
||||
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
|
||||
@@ -0,0 +1,9 @@
|
||||
|
||||
# Root logger
|
||||
log4j.rootLogger=INFO, file, stdout
|
||||
|
||||
# Write to console
|
||||
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
|
||||
log4j.appender.stdout.Target=System.out
|
||||
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
|
||||
19
core-java-io/src/main/resources/logback.xml
Normal file
19
core-java-io/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
BIN
core-java-io/src/main/resources/multiCompressed.zip
Normal file
BIN
core-java-io/src/main/resources/multiCompressed.zip
Normal file
Binary file not shown.
2
core-java-io/src/main/resources/targetFile.tmp
Normal file
2
core-java-io/src/main/resources/targetFile.tmp
Normal file
@@ -0,0 +1,2 @@
|
||||
line 1
|
||||
a second line
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.copyfiles;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class FileCopierTest {
|
||||
File original = new File("src/test/resources/original.txt");
|
||||
|
||||
@Before
|
||||
public void init() throws IOException {
|
||||
if (!original.exists())
|
||||
Files.createFile(original.toPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
|
||||
File copied = new File("src/test/resources/copiedWithIo.txt");
|
||||
try (InputStream in = new BufferedInputStream(new FileInputStream(original));
|
||||
OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) {
|
||||
byte[] buffer = new byte[1024];
|
||||
int lengthRead;
|
||||
while ((lengthRead = in.read(buffer)) > 0) {
|
||||
out.write(buffer, 0, lengthRead);
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
assertThat(copied).exists();
|
||||
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
|
||||
File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
|
||||
FileUtils.copyFile(original, copied);
|
||||
assertThat(copied).exists();
|
||||
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException {
|
||||
Path copied = Paths.get("src/test/resources/copiedWithNio.txt");
|
||||
Path originalPath = original.toPath();
|
||||
Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING);
|
||||
assertThat(copied).exists();
|
||||
assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException {
|
||||
File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
|
||||
com.google.common.io.Files.copy(original, copied);
|
||||
assertThat(copied).exists();
|
||||
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.baeldung.file;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class FileOperationsManualTest {
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingClassloader_thenFileData() throws IOException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||
InputStream inputStream = new FileInputStream(file);
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
Class clazz = FileOperationsManualTest.class;
|
||||
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingJarFile_thenFileData() throws IOException {
|
||||
String expectedData = "BSD License";
|
||||
|
||||
Class clazz = Matchers.class;
|
||||
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenURLName_whenUsingURL_thenFileData() throws IOException {
|
||||
String expectedData = "Example Domain";
|
||||
|
||||
URL urlObject = new URL("http://www.example.com/");
|
||||
|
||||
URLConnection urlConnection = urlObject.openConnection();
|
||||
|
||||
InputStream inputStream = urlConnection.getInputStream();
|
||||
String data = readFromInputStream(inputStream);
|
||||
|
||||
assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||
String data = FileUtils.readFileToString(file);
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||
|
||||
byte[] fileBytes = Files.readAllBytes(path);
|
||||
String data = new String(fileBytes);
|
||||
|
||||
assertEquals(expectedData, data.trim());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
|
||||
String expectedData = "Hello World from fileTest.txt!!!";
|
||||
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||
|
||||
StringBuilder data = new StringBuilder();
|
||||
Stream<String> lines = Files.lines(path);
|
||||
lines.forEach(line -> data.append(line).append("\n"));
|
||||
lines.close();
|
||||
|
||||
assertEquals(expectedData, data.toString().trim());
|
||||
}
|
||||
|
||||
private String readFromInputStream(InputStream inputStream) throws IOException {
|
||||
StringBuilder resultStringBuilder = new StringBuilder();
|
||||
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
|
||||
String line;
|
||||
while ((line = bufferedReader.readLine()) != null) {
|
||||
resultStringBuilder.append(line).append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
return resultStringBuilder.toString();
|
||||
}
|
||||
}
|
||||
94
core-java-io/src/test/java/com/baeldung/file/FilesTest.java
Normal file
94
core-java-io/src/test/java/com/baeldung/file/FilesTest.java
Normal file
@@ -0,0 +1,94 @@
|
||||
package com.baeldung.file;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.io.CharSink;
|
||||
import com.google.common.io.FileWriteMode;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.util.StreamUtils;
|
||||
|
||||
public class FilesTest {
|
||||
|
||||
public static final String fileName = "src/main/resources/countries.properties";
|
||||
|
||||
@Before
|
||||
@After
|
||||
public void setup() throws Exception {
|
||||
PrintWriter writer = new PrintWriter(fileName);
|
||||
writer.print("UK\r\n" + "US\r\n" + "Germany\r\n");
|
||||
writer.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendToFileUsingGuava_thenCorrect() throws IOException {
|
||||
File file = new File(fileName);
|
||||
CharSink chs = com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);
|
||||
chs.write("Spain\r\n");
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenAppendToFileUsingFiles_thenCorrect() throws IOException {
|
||||
Files.write(Paths.get(fileName), "Spain\r\n".getBytes(), StandardOpenOption.APPEND);
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendToFileUsingFileUtils_thenCorrect() throws IOException {
|
||||
File file = new File(fileName);
|
||||
FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true);
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendToFileUsingFileOutputStream_thenCorrect() throws Exception {
|
||||
FileOutputStream fos = new FileOutputStream(fileName, true);
|
||||
fos.write("Spain\r\n".getBytes());
|
||||
fos.close();
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendToFileUsingFileWriter_thenCorrect() throws IOException {
|
||||
FileWriter fw = new FileWriter(fileName, true);
|
||||
BufferedWriter bw = new BufferedWriter(fw);
|
||||
bw.write("Spain");
|
||||
bw.newLine();
|
||||
bw.close();
|
||||
|
||||
assertThat(
|
||||
StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.filesystem.jndi.test;
|
||||
|
||||
import com.baeldung.filesystem.jndi.LookupFSJNDI;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import java.io.File;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class LookupFSJNDIIntegrationTest {
|
||||
LookupFSJNDI fsjndi;
|
||||
InitialContext ctx = null;
|
||||
final String FILENAME = "test.find";
|
||||
|
||||
public LookupFSJNDIIntegrationTest() {
|
||||
try {
|
||||
fsjndi = new LookupFSJNDI();
|
||||
} catch (NamingException e) {
|
||||
fsjndi = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInitializationLookupFSJNDIIsNotNull_thenSuccess() {
|
||||
assertNotNull("Class LookupFSJNDI has instance", fsjndi);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLookupFSJNDI_whengetInitialContextIsNotNull_thenSuccess() {
|
||||
ctx = fsjndi.getCtx();
|
||||
assertNotNull("Context exists", ctx);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInitialContext_whenLokupFileExists_thenSuccess() {
|
||||
File file = fsjndi.getFile(FILENAME);
|
||||
assertNotNull("File exists", file);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.java.conversion;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
|
||||
|
||||
public class IterableStreamConversionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIterable_whenConvertedToStream_thenNotNull() {
|
||||
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||
|
||||
Assert.assertNotNull(StreamSupport.stream(iterable.spliterator(), false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedToList_thenCorrect() {
|
||||
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||
|
||||
List<String> result = StreamSupport.stream(iterable.spliterator(), false).map(String::toUpperCase).collect(Collectors.toList());
|
||||
|
||||
assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.java.nio.selector;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NioEchoLiveTest {
|
||||
|
||||
private Process server;
|
||||
private EchoClient client;
|
||||
|
||||
@Before
|
||||
public void setup() throws IOException, InterruptedException {
|
||||
server = EchoServer.start();
|
||||
client = EchoClient.start();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenServerClient_whenServerEchosMessage_thenCorrect() {
|
||||
String resp1 = client.sendMessage("hello");
|
||||
String resp2 = client.sendMessage("world");
|
||||
assertEquals("hello", resp1);
|
||||
assertEquals("world", resp2);
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() throws IOException {
|
||||
server.destroy();
|
||||
EchoClient.stop();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package com.baeldung.java.nio2;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class FileIntegrationTest {
|
||||
private static final String TEMP_DIR = String.format("%s/temp%s", System.getProperty("user.home"), UUID.randomUUID().toString());
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws IOException {
|
||||
Files.createDirectory(Paths.get(TEMP_DIR));
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void cleanup() throws IOException {
|
||||
FileUtils.deleteDirectory(new File(TEMP_DIR));
|
||||
}
|
||||
|
||||
// checking file or dir
|
||||
@Test
|
||||
public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
|
||||
Path p = Paths.get(TEMP_DIR);
|
||||
assertTrue(Files.exists(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonexistentPath_whenConfirmsFileNotExists_thenCorrect() {
|
||||
Path p = Paths.get(TEMP_DIR + "/inexistent_file.txt");
|
||||
assertTrue(Files.notExists(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
||||
Path p = Paths.get(TEMP_DIR);
|
||||
assertFalse(Files.isRegularFile(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() {
|
||||
Path p = Paths.get(TEMP_DIR);
|
||||
assertTrue(Files.isReadable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() {
|
||||
Path p = Paths.get(System.getProperty("user.home"));
|
||||
assertTrue(Files.isWritable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() {
|
||||
Path p = Paths.get(System.getProperty("user.home"));
|
||||
assertTrue(Files.isExecutable(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException {
|
||||
Path p1 = Paths.get(TEMP_DIR);
|
||||
Path p2 = Paths.get(TEMP_DIR);
|
||||
assertTrue(Files.isSameFile(p1, p2));
|
||||
}
|
||||
|
||||
// reading, writing and creating files
|
||||
// creating file
|
||||
@Test
|
||||
public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
|
||||
String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
|
||||
Path p = Paths.get(TEMP_DIR + "/" + fileName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createFile(p);
|
||||
assertTrue(Files.exists(p));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
|
||||
String dirName = "myDir_" + UUID.randomUUID().toString();
|
||||
Path p = Paths.get(TEMP_DIR + "/" + dirName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createDirectory(p);
|
||||
assertTrue(Files.exists(p));
|
||||
assertFalse(Files.isRegularFile(p));
|
||||
assertTrue(Files.isDirectory(p));
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
|
||||
String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir";
|
||||
Path p = Paths.get(TEMP_DIR + "/" + dirName);
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createDirectory(p);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException {
|
||||
Path dir = Paths.get(TEMP_DIR + "/myDir_" + UUID.randomUUID().toString());
|
||||
Path subdir = dir.resolve("subdir");
|
||||
assertFalse(Files.exists(dir));
|
||||
assertFalse(Files.exists(subdir));
|
||||
Files.createDirectories(subdir);
|
||||
assertTrue(Files.exists(dir));
|
||||
assertTrue(Files.exists(subdir));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFilePath_whenCreatesTempFile_thenCorrect() throws IOException {
|
||||
String prefix = "log_";
|
||||
String suffix = ".txt";
|
||||
Path p = Paths.get(TEMP_DIR + "/");
|
||||
p = Files.createTempFile(p, prefix, suffix);
|
||||
// like log_8821081429012075286.txt
|
||||
assertTrue(Files.exists(p));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(TEMP_DIR + "/");
|
||||
p = Files.createTempFile(p, null, null);
|
||||
// like 8600179353689423985.tmp
|
||||
assertTrue(Files.exists(p));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNoFilePath_whenCreatesTempFileInTempDir_thenCorrect() throws IOException {
|
||||
Path p = Files.createTempFile(null, null);
|
||||
// like C:\Users\new\AppData\Local\Temp\6100927974988978748.tmp
|
||||
assertTrue(Files.exists(p));
|
||||
|
||||
}
|
||||
|
||||
// delete file
|
||||
@Test
|
||||
public void givenPath_whenDeletes_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(TEMP_DIR + "/fileToDelete.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
Files.createFile(p);
|
||||
assertTrue(Files.exists(p));
|
||||
Files.delete(p);
|
||||
assertFalse(Files.exists(p));
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = DirectoryNotEmptyException.class)
|
||||
public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException {
|
||||
Path dir = Paths.get(TEMP_DIR + "/emptyDir" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir);
|
||||
assertTrue(Files.exists(dir));
|
||||
Path file = dir.resolve("file.txt");
|
||||
Files.createFile(file);
|
||||
Files.delete(dir);
|
||||
|
||||
assertTrue(Files.exists(dir));
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(TEMP_DIR + "/inexistentFile.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
Files.delete(p);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInexistentFile_whenDeleteIfExistsWorks_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(TEMP_DIR + "/inexistentFile.txt");
|
||||
assertFalse(Files.exists(p));
|
||||
Files.deleteIfExists(p);
|
||||
|
||||
}
|
||||
|
||||
// copy file
|
||||
@Test
|
||||
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Files.createFile(file1);
|
||||
assertTrue(Files.exists(file1));
|
||||
assertFalse(Files.exists(file2));
|
||||
Files.copy(file1, file2);
|
||||
assertTrue(Files.exists(file2));
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = FileAlreadyExistsException.class)
|
||||
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Files.createFile(file1);
|
||||
Files.createFile(file2);
|
||||
assertTrue(Files.exists(file1));
|
||||
assertTrue(Files.exists(file2));
|
||||
Files.copy(file1, file2);
|
||||
Files.copy(file1, file2, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
// moving files
|
||||
@Test
|
||||
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Files.createFile(file1);
|
||||
assertTrue(Files.exists(file1));
|
||||
assertFalse(Files.exists(file2));
|
||||
Files.move(file1, file2);
|
||||
assertTrue(Files.exists(file2));
|
||||
assertFalse(Files.exists(file1));
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = FileAlreadyExistsException.class)
|
||||
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||
Path dir1 = Paths.get(TEMP_DIR + "/firstdir_" + UUID.randomUUID().toString());
|
||||
Path dir2 = Paths.get(TEMP_DIR + "/otherdir_" + UUID.randomUUID().toString());
|
||||
Files.createDirectory(dir1);
|
||||
Files.createDirectory(dir2);
|
||||
Path file1 = dir1.resolve("filetocopy.txt");
|
||||
Path file2 = dir2.resolve("filetocopy.txt");
|
||||
Files.createFile(file1);
|
||||
Files.createFile(file2);
|
||||
assertTrue(Files.exists(file1));
|
||||
assertTrue(Files.exists(file2));
|
||||
Files.move(file1, file2);
|
||||
Files.move(file1, file2, StandardCopyOption.REPLACE_EXISTING);
|
||||
assertTrue(Files.exists(file2));
|
||||
assertFalse(Files.exists(file1));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package com.baeldung.java.nio2;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class PathManualTest {
|
||||
|
||||
private static final String HOME = System.getProperty("user.home");
|
||||
|
||||
// creating a path
|
||||
@Test
|
||||
public void givenPathString_whenCreatesPathObject_thenCorrect() {
|
||||
Path p = Paths.get("/articles/baeldung");
|
||||
assertEquals("\\articles\\baeldung", p.toString());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathParts_whenCreatesPathObject_thenCorrect() {
|
||||
Path p = Paths.get("/articles", "baeldung");
|
||||
assertEquals("\\articles\\baeldung", p.toString());
|
||||
|
||||
}
|
||||
|
||||
// retrieving path info
|
||||
@Test
|
||||
public void givenPath_whenRetrievesFileName_thenCorrect() {
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals("logs", p.getFileName().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenRetrievesNameByIndex_thenCorrect() {
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals("articles", p.getName(0).toString());
|
||||
assertEquals("baeldung", p.getName(1).toString());
|
||||
assertEquals("logs", p.getName(2).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenCountsParts_thenCorrect() {
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals(3, p.getNameCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenCanRetrieveSubsequenceByIndex_thenCorrect() {
|
||||
Path p = Paths.get("/articles/baeldung/logs");
|
||||
assertEquals("articles", p.subpath(0, 1).toString());
|
||||
assertEquals("articles\\baeldung", p.subpath(0, 2).toString());
|
||||
assertEquals("articles\\baeldung\\logs", p.subpath(0, 3).toString());
|
||||
assertEquals("baeldung", p.subpath(1, 2).toString());
|
||||
assertEquals("baeldung\\logs", p.subpath(1, 3).toString());
|
||||
assertEquals("logs", p.subpath(2, 3).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenRetrievesParent_thenCorrect() {
|
||||
Path p1 = Paths.get("/articles/baeldung/logs");
|
||||
Path p2 = Paths.get("/articles/baeldung");
|
||||
Path p3 = Paths.get("/articles");
|
||||
Path p4 = Paths.get("/");
|
||||
|
||||
assertEquals("\\articles\\baeldung", p1.getParent().toString());
|
||||
assertEquals("\\articles", p2.getParent().toString());
|
||||
assertEquals("\\", p3.getParent().toString());
|
||||
assertEquals(null, p4.getParent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenRetrievesRoot_thenCorrect() {
|
||||
Path p1 = Paths.get("/articles/baeldung/logs");
|
||||
Path p2 = Paths.get("c:/articles/baeldung/logs");
|
||||
|
||||
assertEquals("\\", p1.getRoot().toString());
|
||||
assertEquals("c:\\", p2.getRoot().toString());
|
||||
}
|
||||
|
||||
// removing redundancies from path
|
||||
@Test
|
||||
public void givenPath_whenRemovesRedundancies_thenCorrect1() {
|
||||
Path p = Paths.get("/home/./baeldung/articles");
|
||||
p = p.normalize();
|
||||
assertEquals("\\home\\baeldung\\articles", p.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenRemovesRedundancies_thenCorrect2() {
|
||||
Path p = Paths.get("/home/baeldung/../articles");
|
||||
p = p.normalize();
|
||||
assertEquals("\\home\\articles", p.toString());
|
||||
}
|
||||
|
||||
// converting a path
|
||||
@Test
|
||||
public void givenPath_whenConvertsToBrowseablePath_thenCorrect() {
|
||||
Path p = Paths.get("/home/baeldung/articles.html");
|
||||
URI uri = p.toUri();
|
||||
assertEquals("file:///E:/home/baeldung/articles.html", uri.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenConvertsToAbsolutePath_thenCorrect() {
|
||||
Path p = Paths.get("/home/baeldung/articles.html");
|
||||
assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePath_whenRetainsAsAbsolute_thenCorrect() {
|
||||
Path p = Paths.get("E:\\home\\baeldung\\articles.html");
|
||||
assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenGetsRealPathToFile_thenCorrect() throws IOException {
|
||||
Path p = Paths.get(HOME);
|
||||
assertEquals(HOME, p.toRealPath().toString());
|
||||
}
|
||||
|
||||
@Test(expected = NoSuchFileException.class)
|
||||
public void givenInExistentPath_whenFailsToConvert_thenCorrect() throws IOException {
|
||||
Path p = Paths.get("E:\\home\\baeldung\\articles.html");
|
||||
|
||||
p.toRealPath();
|
||||
}
|
||||
|
||||
// joining paths
|
||||
@Test
|
||||
public void givenTwoPaths_whenJoinsAndResolves_thenCorrect() throws IOException {
|
||||
Path p = Paths.get("/baeldung/articles");
|
||||
assertEquals("\\baeldung\\articles\\java", p.resolve("java").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsolutePath_whenResolutionRetainsIt_thenCorrect() throws IOException {
|
||||
Path p = Paths.get("/baeldung/articles");
|
||||
assertEquals("C:\\baeldung\\articles\\java", p.resolve("C:\\baeldung\\articles\\java").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathWithRoot_whenResolutionRetainsIt_thenCorrect2() throws IOException {
|
||||
Path p = Paths.get("/baeldung/articles");
|
||||
assertEquals("\\java", p.resolve("/java").toString());
|
||||
}
|
||||
|
||||
// creating a path between 2 paths
|
||||
@Test
|
||||
public void givenSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
|
||||
Path p1 = Paths.get("articles");
|
||||
Path p2 = Paths.get("authors");
|
||||
assertEquals("..\\authors", p1.relativize(p2).toString());
|
||||
assertEquals("..\\articles", p2.relativize(p1).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
|
||||
Path p1 = Paths.get("/baeldung");
|
||||
Path p2 = Paths.get("/baeldung/authors/articles");
|
||||
assertEquals("authors\\articles", p1.relativize(p2).toString());
|
||||
assertEquals("..\\..", p2.relativize(p1).toString());
|
||||
}
|
||||
|
||||
// comparing 2 paths
|
||||
@Test
|
||||
public void givenTwoPaths_whenTestsEquality_thenCorrect() throws IOException {
|
||||
Path p1 = Paths.get("/baeldung/articles");
|
||||
Path p2 = Paths.get("/baeldung/articles");
|
||||
Path p3 = Paths.get("/baeldung/authors");
|
||||
|
||||
assertTrue(p1.equals(p2));
|
||||
assertFalse(p1.equals(p3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenInspectsStart_thenCorrect() {
|
||||
Path p1 = Paths.get("/baeldung/articles");
|
||||
assertTrue(p1.startsWith("/baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenInspectsEnd_thenCorrect() {
|
||||
Path p1 = Paths.get("/baeldung/articles");
|
||||
assertTrue(p1.endsWith("articles"));
|
||||
}
|
||||
}
|
||||
11
core-java-io/src/test/java/com/baeldung/java/nio2/README.md
Normal file
11
core-java-io/src/test/java/com/baeldung/java/nio2/README.md
Normal file
@@ -0,0 +1,11 @@
|
||||
### Relevant Articles:
|
||||
- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api)
|
||||
- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path)
|
||||
- [A Guide To NIO2 Asynchronous File Channel](http://www.baeldung.com/java-nio2-async-file-channel)
|
||||
- [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng)
|
||||
- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel)
|
||||
- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor)
|
||||
- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute)
|
||||
- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean)
|
||||
- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice)
|
||||
- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels)
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.baeldung.java.nio2.async;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.AsynchronousSocketChannel;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class AsyncEchoClient {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(AsyncEchoClient.class);
|
||||
|
||||
private AsynchronousSocketChannel client;
|
||||
private Future<Void> future;
|
||||
private static AsyncEchoClient instance;
|
||||
|
||||
private AsyncEchoClient() {
|
||||
try {
|
||||
client = AsynchronousSocketChannel.open();
|
||||
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
|
||||
future = client.connect(hostAddress);
|
||||
start();
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static AsyncEchoClient getInstance() {
|
||||
if (instance == null)
|
||||
instance = new AsyncEchoClient();
|
||||
return instance;
|
||||
}
|
||||
|
||||
private void start() {
|
||||
try {
|
||||
future.get();
|
||||
} catch (InterruptedException | ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public String sendMessage(String message) {
|
||||
byte[] byteMsg = message.getBytes();
|
||||
ByteBuffer buffer = ByteBuffer.wrap(byteMsg);
|
||||
Future<Integer> writeResult = client.write(buffer);
|
||||
|
||||
try {
|
||||
writeResult.get();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
buffer.flip();
|
||||
Future<Integer> readResult = client.read(buffer);
|
||||
try {
|
||||
readResult.get();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
String echo = new String(buffer.array()).trim();
|
||||
buffer.clear();
|
||||
return echo;
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
try {
|
||||
client.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
AsyncEchoClient client = AsyncEchoClient.getInstance();
|
||||
client.start();
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
||||
String line;
|
||||
LOG.debug("Message to server:");
|
||||
while ((line = br.readLine()) != null) {
|
||||
String response = client.sendMessage(line);
|
||||
LOG.debug("response from server: " + response);
|
||||
LOG.debug("Message to server:");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.java.nio2.async;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class AsyncEchoIntegrationTest {
|
||||
|
||||
Process server;
|
||||
AsyncEchoClient client;
|
||||
|
||||
@Before
|
||||
public void setup() throws IOException, InterruptedException {
|
||||
server = AsyncEchoServer2.start();
|
||||
client = AsyncEchoClient.getInstance();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenServerClient_whenServerEchosMessage_thenCorrect() throws Exception {
|
||||
String resp1 = client.sendMessage("hello");
|
||||
String resp2 = client.sendMessage("world");
|
||||
assertEquals("hello", resp1);
|
||||
assertEquals("world", resp2);
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() throws IOException {
|
||||
server.destroy();
|
||||
client.stop();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.java.nio2.async;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.AsynchronousServerSocketChannel;
|
||||
import java.nio.channels.AsynchronousSocketChannel;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class AsyncEchoServer {
|
||||
private AsynchronousServerSocketChannel serverChannel;
|
||||
private Future<AsynchronousSocketChannel> acceptResult;
|
||||
private AsynchronousSocketChannel clientChannel;
|
||||
|
||||
public AsyncEchoServer() {
|
||||
try {
|
||||
serverChannel = AsynchronousServerSocketChannel.open();
|
||||
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
|
||||
serverChannel.bind(hostAddress);
|
||||
acceptResult = serverChannel.accept();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void runServer() {
|
||||
try {
|
||||
clientChannel = acceptResult.get();
|
||||
if ((clientChannel != null) && (clientChannel.isOpen())) {
|
||||
while (true) {
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||
Future<Integer> readResult = clientChannel.read(buffer);
|
||||
|
||||
// do some computation
|
||||
|
||||
readResult.get();
|
||||
|
||||
buffer.flip();
|
||||
String message = new String(buffer.array()).trim();
|
||||
if (message.equals("bye")) {
|
||||
break; // while loop
|
||||
}
|
||||
buffer = ByteBuffer.wrap(new String(message).getBytes());
|
||||
Future<Integer> writeResult = clientChannel.write(buffer);
|
||||
|
||||
// do some computation
|
||||
writeResult.get();
|
||||
buffer.clear();
|
||||
|
||||
} // while()
|
||||
|
||||
clientChannel.close();
|
||||
serverChannel.close();
|
||||
|
||||
}
|
||||
} catch (InterruptedException | ExecutionException | IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
AsyncEchoServer server = new AsyncEchoServer();
|
||||
server.runServer();
|
||||
}
|
||||
|
||||
public static Process start() throws IOException, InterruptedException {
|
||||
String javaHome = System.getProperty("java.home");
|
||||
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
||||
String classpath = System.getProperty("java.class.path");
|
||||
String className = AsyncEchoServer.class.getCanonicalName();
|
||||
|
||||
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
|
||||
|
||||
return builder.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.baeldung.java.nio2.async;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.AsynchronousServerSocketChannel;
|
||||
import java.nio.channels.AsynchronousSocketChannel;
|
||||
import java.nio.channels.CompletionHandler;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class AsyncEchoServer2 {
|
||||
private AsynchronousServerSocketChannel serverChannel;
|
||||
private AsynchronousSocketChannel clientChannel;
|
||||
|
||||
public AsyncEchoServer2() {
|
||||
try {
|
||||
serverChannel = AsynchronousServerSocketChannel.open();
|
||||
InetSocketAddress hostAddress = new InetSocketAddress("localhost", 4999);
|
||||
serverChannel.bind(hostAddress);
|
||||
while (true) {
|
||||
|
||||
serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
|
||||
|
||||
@Override
|
||||
public void completed(AsynchronousSocketChannel result, Object attachment) {
|
||||
if (serverChannel.isOpen())
|
||||
serverChannel.accept(null, this);
|
||||
clientChannel = result;
|
||||
if ((clientChannel != null) && (clientChannel.isOpen())) {
|
||||
ReadWriteHandler handler = new ReadWriteHandler();
|
||||
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||
Map<String, Object> readInfo = new HashMap<>();
|
||||
readInfo.put("action", "read");
|
||||
readInfo.put("buffer", buffer);
|
||||
clientChannel.read(buffer, readInfo, handler);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, Object attachment) {
|
||||
// process error
|
||||
}
|
||||
});
|
||||
try {
|
||||
System.in.read();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
class ReadWriteHandler implements CompletionHandler<Integer, Map<String, Object>> {
|
||||
|
||||
@Override
|
||||
public void completed(Integer result, Map<String, Object> attachment) {
|
||||
Map<String, Object> actionInfo = attachment;
|
||||
String action = (String) actionInfo.get("action");
|
||||
if ("read".equals(action)) {
|
||||
ByteBuffer buffer = (ByteBuffer) actionInfo.get("buffer");
|
||||
buffer.flip();
|
||||
actionInfo.put("action", "write");
|
||||
clientChannel.write(buffer, actionInfo, this);
|
||||
buffer.clear();
|
||||
} else if ("write".equals(action)) {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(32);
|
||||
actionInfo.put("action", "read");
|
||||
actionInfo.put("buffer", buffer);
|
||||
clientChannel.read(buffer, actionInfo, this);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, Map<String, Object> attachment) {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
new AsyncEchoServer2();
|
||||
}
|
||||
|
||||
public static Process start() throws IOException, InterruptedException {
|
||||
String javaHome = System.getProperty("java.home");
|
||||
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
|
||||
String classpath = System.getProperty("java.class.path");
|
||||
String className = AsyncEchoServer2.class.getCanonicalName();
|
||||
|
||||
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
|
||||
|
||||
return builder.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.baeldung.java.nio2.async;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.AsynchronousFileChannel;
|
||||
import java.nio.channels.CompletionHandler;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class AsyncFileIntegrationTest {
|
||||
@Test
|
||||
public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
|
||||
Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
|
||||
Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||
|
||||
operation.get();
|
||||
|
||||
String fileContent = new String(buffer.array()).trim();
|
||||
buffer.clear();
|
||||
|
||||
assertEquals(fileContent, "baeldung.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(URI.create(AsyncFileIntegrationTest.class.getResource("/file.txt").toString()));
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
|
||||
fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
|
||||
|
||||
@Override
|
||||
public void completed(Integer result, ByteBuffer attachment) {
|
||||
// result is number of bytes read
|
||||
// attachment is the buffer
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, ByteBuffer attachment) {
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
|
||||
String fileName = "temp";
|
||||
Path path = Paths.get(fileName);
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
long position = 0;
|
||||
|
||||
buffer.put("hello world".getBytes());
|
||||
buffer.flip();
|
||||
|
||||
Future<Integer> operation = fileChannel.write(buffer, position);
|
||||
buffer.clear();
|
||||
|
||||
operation.get();
|
||||
|
||||
String content = readContent(path);
|
||||
assertEquals("hello world", content);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathAndContent_whenWritesToFileWithHandler_thenCorrect() throws IOException {
|
||||
String fileName = UUID.randomUUID().toString();
|
||||
Path path = Paths.get(fileName);
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
buffer.put("hello world".getBytes());
|
||||
buffer.flip();
|
||||
|
||||
fileChannel.write(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
|
||||
|
||||
@Override
|
||||
public void completed(Integer result, ByteBuffer attachment) {
|
||||
// result is number of bytes written
|
||||
// attachment is the buffer
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, ByteBuffer attachment) {
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static String readContent(Path file) throws ExecutionException, InterruptedException {
|
||||
AsynchronousFileChannel fileChannel = null;
|
||||
try {
|
||||
fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
|
||||
Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||
|
||||
operation.get();
|
||||
|
||||
String fileContent = new String(buffer.array()).trim();
|
||||
buffer.clear();
|
||||
return fileContent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.baeldung.java.nio2.attributes;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.attribute.BasicFileAttributeView;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.nio.file.attribute.FileTime;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class BasicAttribsIntegrationTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(BasicAttribsIntegrationTest.class);
|
||||
|
||||
|
||||
private static final String HOME = System.getProperty("user.home");
|
||||
private static BasicFileAttributes basicAttribs;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws IOException {
|
||||
Path home = Paths.get(HOME);
|
||||
BasicFileAttributeView basicView = Files.getFileAttributeView(home, BasicFileAttributeView.class);
|
||||
basicAttribs = basicView.readAttributes();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFileTimes_whenComparesThem_ThenCorrect() {
|
||||
FileTime created = basicAttribs.creationTime();
|
||||
FileTime modified = basicAttribs.lastModifiedTime();
|
||||
FileTime accessed = basicAttribs.lastAccessTime();
|
||||
|
||||
LOG.debug("Created: " + created);
|
||||
LOG.debug("Modified: " + modified);
|
||||
LOG.debug("Accessed: " + accessed);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenGetsFileSize_thenCorrect() {
|
||||
long size = basicAttribs.size();
|
||||
assertTrue(size > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenChecksIfDirectory_thenCorrect() {
|
||||
boolean isDir = basicAttribs.isDirectory();
|
||||
assertTrue(isDir);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenChecksIfFile_thenCorrect() {
|
||||
boolean isFile = basicAttribs.isRegularFile();
|
||||
assertFalse(isFile);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenChecksIfSymLink_thenCorrect() {
|
||||
boolean isSymLink = basicAttribs.isSymbolicLink();
|
||||
assertFalse(isSymLink);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenChecksIfOther_thenCorrect() {
|
||||
boolean isOther = basicAttribs.isOther();
|
||||
assertFalse(isOther);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaFileSizeUnitTest {
|
||||
private static final long EXPECTED_FILE_SIZE_IN_BYTES = 11;
|
||||
private String filePath;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
final String separator = File.separator;
|
||||
filePath = String.join(separator, new String[] { "src", "test", "resources", "testFolder", "sample_file_1.in" });
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFileSize_thenCorrect() {
|
||||
final File file = new File(filePath);
|
||||
|
||||
final long size = getFileSize(file);
|
||||
|
||||
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFileSizeUsingNioApi_thenCorrect() throws IOException {
|
||||
final Path path = Paths.get(this.filePath);
|
||||
final FileChannel fileChannel = FileChannel.open(path);
|
||||
|
||||
final long fileSize = fileChannel.size();
|
||||
|
||||
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, fileSize);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFileSizeUsingApacheCommonsIO_thenCorrect() {
|
||||
final File file = new File(filePath);
|
||||
|
||||
final long size = FileUtils.sizeOf(file);
|
||||
|
||||
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetReadableFileSize_thenCorrect() {
|
||||
final File file = new File(filePath);
|
||||
|
||||
final long size = getFileSize(file);
|
||||
|
||||
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES + " bytes", FileUtils.byteCountToDisplaySize(size));
|
||||
}
|
||||
|
||||
private long getFileSize(final File file) {
|
||||
final long length = file.length();
|
||||
return length;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileVisitResult;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.SimpleFileVisitor;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.text.DecimalFormat;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaFolderSizeUnitTest {
|
||||
private final long EXPECTED_SIZE = 24;
|
||||
private String path;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
final String separator = File.separator;
|
||||
path = String.format("src%stest%sresources%stestFolder", separator, separator, separator);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFolderSizeRecursive_thenCorrect() {
|
||||
final File folder = new File(path);
|
||||
final long size = getFolderSize(folder);
|
||||
|
||||
assertEquals(EXPECTED_SIZE, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFolderSizeUsingJava7_thenCorrect() throws IOException {
|
||||
final AtomicLong size = new AtomicLong(0);
|
||||
final Path folder = Paths.get(path);
|
||||
|
||||
Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
|
||||
@Override
|
||||
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
|
||||
size.addAndGet(attrs.size());
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
|
||||
assertEquals(EXPECTED_SIZE, size.longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
|
||||
final Path folder = Paths.get(path);
|
||||
final long size = Files.walk(folder)
|
||||
.filter(p -> p.toFile()
|
||||
.isFile())
|
||||
.mapToLong(p -> p.toFile()
|
||||
.length())
|
||||
.sum();
|
||||
|
||||
assertEquals(EXPECTED_SIZE, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFolderSizeUsingApacheCommonsIO_thenCorrect() {
|
||||
final File folder = new File(path);
|
||||
final long size = FileUtils.sizeOfDirectory(folder);
|
||||
|
||||
assertEquals(EXPECTED_SIZE, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetFolderSizeUsingGuava_thenCorrect() {
|
||||
final File folder = new File(path);
|
||||
|
||||
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser()
|
||||
.breadthFirstTraversal(folder);
|
||||
final long size = StreamSupport.stream(files.spliterator(), false)
|
||||
.filter(File::isFile)
|
||||
.mapToLong(File::length)
|
||||
.sum();
|
||||
|
||||
assertEquals(EXPECTED_SIZE, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetReadableSize_thenCorrect() {
|
||||
final File folder = new File(path);
|
||||
final long size = getFolderSize(folder);
|
||||
|
||||
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
|
||||
final int unitIndex = (int) (Math.log10(size) / 3);
|
||||
final double unitValue = 1 << (unitIndex * 10);
|
||||
|
||||
final String readableSize = new DecimalFormat("#,##0.#").format(size / unitValue) + " " + units[unitIndex];
|
||||
assertEquals(EXPECTED_SIZE + " B", readableSize);
|
||||
}
|
||||
|
||||
private long getFolderSize(final File folder) {
|
||||
long length = 0;
|
||||
final File[] files = folder.listFiles();
|
||||
|
||||
for (final File file : files) {
|
||||
if (file.isFile()) {
|
||||
length += file.length();
|
||||
} else {
|
||||
length += getFolderSize(file);
|
||||
}
|
||||
}
|
||||
return length;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.mappedbytebuffer;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.CharBuffer;
|
||||
import java.nio.MappedByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class MappedByteBufferUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void givenFileChannel_whenReadToTheMappedByteBuffer_thenShouldSuccess() throws Exception {
|
||||
//given
|
||||
CharBuffer charBuffer = null;
|
||||
Path pathToRead = getFileURIFromResources("fileToRead.txt");
|
||||
|
||||
//when
|
||||
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToRead, EnumSet.of(StandardOpenOption.READ))) {
|
||||
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
|
||||
|
||||
if (mappedByteBuffer != null) {
|
||||
charBuffer = Charset.forName("UTF-8").decode(mappedByteBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
//then
|
||||
assertNotNull(charBuffer);
|
||||
assertEquals(charBuffer.toString(), "This is a content of the file");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenWriteToItUsingMappedByteBuffer_thenShouldSuccessfullyWrite() throws Exception {
|
||||
//given
|
||||
CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file");
|
||||
Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt");
|
||||
|
||||
//when
|
||||
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite,
|
||||
EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
|
||||
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length());
|
||||
|
||||
if (mappedByteBuffer != null) {
|
||||
mappedByteBuffer.put(Charset.forName("utf-8").encode(charBuffer));
|
||||
}
|
||||
}
|
||||
|
||||
//then
|
||||
List<String> fileContent = Files.readAllLines(pathToWrite);
|
||||
assertEquals(fileContent.get(0), "This will be written to the file");
|
||||
|
||||
}
|
||||
|
||||
private Path getFileURIFromResources(String fileName) throws Exception {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
return Paths.get(classLoader.getResource(fileName).toURI());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileCopyTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingStream_thenCopyFile() throws IOException {
|
||||
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_stream.txt");
|
||||
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_stream.txt");
|
||||
FileCopy.copyFileUsingStream(src, dest);
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFiles_thenCopyFile() throws IOException {
|
||||
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_files.txt");
|
||||
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_files.txt");
|
||||
FileCopy.copyFileUsingJavaFiles(src, dest);
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingChannel_thenCopyFile() throws IOException {
|
||||
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_channel.txt");
|
||||
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_channel.txt");
|
||||
FileCopy.copyFileUsingChannel(src, dest);
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingApache_thenCopyFile() throws IOException {
|
||||
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_apache.txt");
|
||||
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_apache.txt");
|
||||
FileCopy.copyFileUsingApacheCommonsIO(src, dest);
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import com.codepoetics.protonpack.Indexed;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamIndicesTest {
|
||||
|
||||
@Test
|
||||
public void whenCalled_thenReturnListOfEvenIndexedStrings() {
|
||||
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
|
||||
List<String> expectedResult = Arrays.asList("Afrim", "Besim", "Durim");
|
||||
List<String> actualResult = StreamIndices.getEvenIndexedStrings(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalled_thenReturnListOfEvenIndexedStringsVersionTwo() {
|
||||
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
|
||||
List<String> expectedResult = Arrays.asList("Afrim", "Besim", "Durim");
|
||||
List<String> actualResult = StreamIndices.getEvenIndexedStrings(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalled_thenReturnListOfOddStrings() {
|
||||
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
|
||||
List<String> expectedResult = Arrays.asList("Bashkim", "Lulzim", "Shpetim");
|
||||
List<String> actualResult = StreamIndices.getOddIndexedStrings(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenCalled_thenReturnListOfEvenIndexedStrings() {
|
||||
List<String> names = Arrays.asList("Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim");
|
||||
List<Indexed<String>> expectedResult = Arrays
|
||||
.asList(Indexed.index(0, "Afrim"), Indexed.index(2, "Besim"), Indexed
|
||||
.index(4, "Durim"));
|
||||
List<Indexed<String>> actualResult = StreamIndices.getEvenIndexedStrings(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenCalled_thenReturnListOfOddIndexedStrings() {
|
||||
List<String> names = Arrays.asList("Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim");
|
||||
List<Indexed<String>> expectedResult = Arrays
|
||||
.asList(Indexed.index(1, "Bashkim"), Indexed.index(3, "Lulzim"), Indexed
|
||||
.index(5, "Shpetim"));
|
||||
List<Indexed<String>> actualResult = StreamIndices.getOddIndexedStrings(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalled_thenReturnListOfOddStringsVersionTwo() {
|
||||
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
|
||||
List<String> expectedResult = Arrays.asList("Bashkim", "Lulzim", "Shpetim");
|
||||
List<String> actualResult = StreamIndices.getOddIndexedStringsVersionTwo(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.instanceOf;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class StringToCharStreamUnitTest {
|
||||
|
||||
private String testString = "Tests";
|
||||
|
||||
@Test
|
||||
public void givenTestString_whenChars_thenReturnIntStream() {
|
||||
assertThat(testString.chars(), instanceOf(IntStream.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestString_whenCodePoints_thenReturnIntStream() {
|
||||
assertThat(testString.codePoints(), instanceOf(IntStream.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestString_whenCodePoints_thenShowOccurences() throws Exception {
|
||||
Map<Character, Integer> map = testString.codePoints()
|
||||
.mapToObj(c -> (char) c)
|
||||
.filter(Character::isLetter)
|
||||
.collect(Collectors.toMap(c -> c, c -> 1, Integer::sum));
|
||||
|
||||
System.out.println(map);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntStream_whenMapToObj_thenReturnCharacterStream() {
|
||||
Stream<Character> characterStream = testString.chars()
|
||||
.mapToObj(c -> (char) c);
|
||||
Stream<Character> characterStream1 = testString.codePoints()
|
||||
.mapToObj(c -> (char) c);
|
||||
assertNotNull("IntStream returned by chars() did not map to Stream<Character>", characterStream);
|
||||
assertNotNull("IntStream returned by codePoints() did not map to Stream<Character>", characterStream1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntStream_whenMapToObj_thenReturnStringStream() {
|
||||
List<String> strings = testString.codePoints()
|
||||
.mapToObj(c -> String.valueOf((char) c))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(strings.size(), 5);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package org.baeldung.core.exceptions;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
public class FileNotFoundExceptionUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(FileNotFoundExceptionUnitTest.class);
|
||||
|
||||
private String fileName = Double.toString(Math.random());
|
||||
|
||||
@Test(expected = BusinessException.class)
|
||||
public void raiseBusinessSpecificException() throws IOException {
|
||||
try {
|
||||
readFailingFile();
|
||||
} catch (FileNotFoundException ex) {
|
||||
throw new BusinessException("BusinessException: necessary file was not present.");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createFile() throws IOException {
|
||||
try {
|
||||
readFailingFile();
|
||||
} catch (FileNotFoundException ex) {
|
||||
try {
|
||||
new File(fileName).createNewFile();
|
||||
readFailingFile();
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException("BusinessException: even creation is not possible.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void logError() throws IOException {
|
||||
try {
|
||||
readFailingFile();
|
||||
} catch (FileNotFoundException ex) {
|
||||
LOG.error("Optional file " + fileName + " was not found.");
|
||||
}
|
||||
}
|
||||
|
||||
private void readFailingFile() throws IOException {
|
||||
BufferedReader rd = new BufferedReader(new FileReader(new File(fileName)));
|
||||
rd.readLine();
|
||||
// no need to close file
|
||||
}
|
||||
|
||||
private class BusinessException extends RuntimeException {
|
||||
BusinessException(String string) {
|
||||
super(string);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Assume;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
public class JavaFilePathUnitTest {
|
||||
|
||||
private static String userDir;
|
||||
|
||||
@BeforeClass
|
||||
public static void createFilesAndFolders() throws IOException {
|
||||
userDir = System.getProperty("user.dir");
|
||||
|
||||
new File(userDir + "/baeldung/foo").mkdirs();
|
||||
new File(userDir + "/baeldung/bar/baz").mkdirs();
|
||||
new File(userDir + "/baeldung/foo/foo-one.txt").createNewFile();
|
||||
new File(userDir + "/baeldung/foo/foo-two.txt").createNewFile();
|
||||
new File(userDir + "/baeldung/bar/bar-one.txt").createNewFile();
|
||||
new File(userDir + "/baeldung/bar/bar-two.txt").createNewFile();
|
||||
new File(userDir + "/baeldung/bar/baz/baz-one.txt").createNewFile();
|
||||
new File(userDir + "/baeldung/bar/baz/baz-two.txt").createNewFile();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPathResolved_thenSuccess() {
|
||||
File file = new File("baeldung/foo/foo-one.txt");
|
||||
String expectedPath = isWindows() ? "baeldung\\foo\\foo-one.txt" : "baeldung/foo/foo-one.txt";
|
||||
String actualPath = file.getPath();
|
||||
assertEquals(expectedPath, actualPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAbsolutePathResolved_thenSuccess() {
|
||||
File file = new File("baeldung/foo/foo-one.txt");
|
||||
String expectedPath = isWindows() ? userDir + "\\baeldung\\foo\\foo-one.txt" : userDir + "/baeldung/foo/foo-one.txt";
|
||||
String actualPath = file.getAbsolutePath();
|
||||
assertEquals(expectedPath, actualPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAbsolutePathWithShorthandResolved_thenSuccess() {
|
||||
File file = new File("baeldung/bar/baz/../bar-one.txt");
|
||||
String expectedPath = isWindows() ? userDir + "\\baeldung\\bar\\baz\\..\\bar-one.txt" : userDir + "/baeldung/bar/baz/../bar-one.txt";
|
||||
String actualPath = file.getAbsolutePath();
|
||||
assertEquals(expectedPath, actualPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCanonicalPathWithShorthandResolved_thenSuccess() throws IOException {
|
||||
File file = new File("baeldung/bar/baz/../bar-one.txt");
|
||||
String expectedPath = isWindows() ? userDir + "\\baeldung\\bar\\bar-one.txt" : userDir + "/baeldung/bar/bar-one.txt";
|
||||
String actualPath = file.getCanonicalPath();
|
||||
assertEquals(expectedPath, actualPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCanonicalPathWithDotShorthandResolved_thenSuccess() throws IOException {
|
||||
File file = new File("baeldung/bar/baz/./baz-one.txt");
|
||||
String expectedPath = isWindows() ? userDir + "\\baeldung\\bar\\baz\\baz-one.txt" : userDir + "/baeldung/bar/baz/baz-one.txt";
|
||||
String actualPath = file.getCanonicalPath();
|
||||
assertEquals(expectedPath, actualPath);
|
||||
}
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void givenWindowsOs_whenCanonicalPathWithWildcard_thenIOException() throws IOException {
|
||||
Assume.assumeTrue(isWindows());
|
||||
new File("*").getCanonicalPath();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void deleteFilesAndFolders() {
|
||||
File baeldungDir = new File(userDir + "/baeldung");
|
||||
deleteRecursively(baeldungDir);
|
||||
}
|
||||
|
||||
private static void deleteRecursively(File dir) {
|
||||
for (File f : dir.listFiles()) {
|
||||
if (f.isDirectory()) {
|
||||
deleteRecursively(f);
|
||||
}
|
||||
f.delete();
|
||||
}
|
||||
dir.delete();
|
||||
}
|
||||
|
||||
private static boolean isWindows() {
|
||||
String osName = System.getProperty("os.name");
|
||||
return osName.contains("Windows");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileSystemException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class JavaFileUnitTest {
|
||||
|
||||
private static final String TEMP_DIR = "src/test/resources/temp" + UUID.randomUUID().toString();
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() throws IOException {
|
||||
Files.createDirectory(Paths.get(TEMP_DIR));
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void cleanup() throws IOException {
|
||||
FileUtils.deleteDirectory(new File(TEMP_DIR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException {
|
||||
final File newFile = new File(TEMP_DIR + "/newFile_jdk6.txt");
|
||||
final boolean success = newFile.createNewFile();
|
||||
|
||||
assertTrue(success);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK7nio2_whenCreatingFile_thenCorrect() throws IOException {
|
||||
final Path newFilePath = Paths.get(TEMP_DIR + "/newFile_jdk7.txt");
|
||||
Files.createFile(newFilePath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File(TEMP_DIR + "/newFile_commonsio.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
|
||||
com.google.common.io.Files.touch(new File(TEMP_DIR + "/newFile_guava.txt"));
|
||||
}
|
||||
|
||||
// move a file
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException {
|
||||
final File fileToMove = new File(TEMP_DIR + "/toMoveFile_jdk6.txt");
|
||||
fileToMove.createNewFile();// .exists();
|
||||
final File destDir = new File(TEMP_DIR + "/");
|
||||
destDir.mkdir();
|
||||
|
||||
final boolean isMoved = fileToMove.renameTo(new File(TEMP_DIR + "/movedFile_jdk6.txt"));
|
||||
if (!isMoved) {
|
||||
throw new FileSystemException(TEMP_DIR + "/movedFile_jdk6.txt");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException {
|
||||
final Path fileToMovePath = Files.createFile(Paths.get(TEMP_DIR + "/" + randomAlphabetic(5) + ".txt"));
|
||||
final Path targetPath = Paths.get(TEMP_DIR + "/");
|
||||
|
||||
Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException {
|
||||
final File fileToMove = new File(TEMP_DIR + "/fileToMove.txt");
|
||||
fileToMove.createNewFile();
|
||||
final File destDir = new File(TEMP_DIR + "/temp");
|
||||
final File targetFile = new File(destDir, fileToMove.getName());
|
||||
com.google.common.io.Files.createParentDirs(targetFile);
|
||||
com.google.common.io.Files.move(fileToMove, targetFile);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
|
||||
FileUtils.moveFile(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/fileMoved_apache2.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File(TEMP_DIR + "/fileToMove_apache.txt"));
|
||||
Files.createDirectory(Paths.get(TEMP_DIR + "/temp"));
|
||||
FileUtils.moveFileToDirectory(FileUtils.getFile(TEMP_DIR + "/fileToMove_apache.txt"), FileUtils.getFile(TEMP_DIR + "/temp"), true);
|
||||
}
|
||||
|
||||
// delete a file
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK6_whenDeletingAFile_thenCorrect() throws IOException {
|
||||
new File(TEMP_DIR + "/fileToDelete_jdk6.txt").createNewFile();
|
||||
|
||||
final File fileToDelete = new File(TEMP_DIR + "/fileToDelete_jdk6.txt");
|
||||
final boolean success = fileToDelete.delete();
|
||||
|
||||
assertTrue(success);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException {
|
||||
Files.createFile(Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt"));
|
||||
|
||||
final Path fileToDeletePath = Paths.get(TEMP_DIR + "/fileToDelete_jdk7.txt");
|
||||
Files.delete(fileToDeletePath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsIo_whenDeletingAFileV1_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File(TEMP_DIR + "/fileToDelete_commonsIo.txt"));
|
||||
|
||||
final File fileToDelete = FileUtils.getFile(TEMP_DIR + "/fileToDelete_commonsIo.txt");
|
||||
final boolean success = FileUtils.deleteQuietly(fileToDelete);
|
||||
|
||||
assertTrue(success);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException {
|
||||
FileUtils.touch(new File(TEMP_DIR + "/fileToDelete.txt"));
|
||||
|
||||
FileUtils.forceDelete(FileUtils.getFile(TEMP_DIR + "/fileToDelete.txt"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.io.ByteSource;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.google.common.io.CharStreams;
|
||||
import com.google.common.io.Files;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Scanner;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public class JavaInputStreamToXUnitTest {
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
private static final int DEFAULT_SIZE = 1500000;
|
||||
|
||||
// tests - InputStream to String
|
||||
|
||||
@Test
|
||||
public final void givenUsingJava5_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
|
||||
final String originalString = randomAlphabetic(DEFAULT_SIZE);
|
||||
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
|
||||
|
||||
final StringBuilder textBuilder = new StringBuilder();
|
||||
try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
|
||||
int c;
|
||||
while ((c = reader.read()) != -1) {
|
||||
textBuilder.append((char) c);
|
||||
}
|
||||
}
|
||||
assertEquals(textBuilder.toString(), originalString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingJava7_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
|
||||
final String originalString = randomAlphabetic(DEFAULT_SIZE);
|
||||
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes()); // exampleString.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
// When
|
||||
String text;
|
||||
try (Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
|
||||
text = scanner.useDelimiter("\\A").next();
|
||||
}
|
||||
|
||||
assertThat(text, equalTo(originalString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
|
||||
final String originalString = randomAlphabetic(DEFAULT_SIZE);
|
||||
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
|
||||
|
||||
final ByteSource byteSource = new ByteSource() {
|
||||
@Override
|
||||
public final InputStream openStream() throws IOException {
|
||||
return inputStream;
|
||||
}
|
||||
};
|
||||
|
||||
final String text = byteSource.asCharSource(Charsets.UTF_8).read();
|
||||
|
||||
assertThat(text, equalTo(originalString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuavaAndJava7_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
|
||||
final String originalString = randomAlphabetic(DEFAULT_SIZE);
|
||||
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
|
||||
|
||||
// When
|
||||
String text;
|
||||
try (final Reader reader = new InputStreamReader(inputStream)) {
|
||||
text = CharStreams.toString(reader);
|
||||
}
|
||||
|
||||
assertThat(text, equalTo(originalString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsIo_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
|
||||
final String originalString = randomAlphabetic(DEFAULT_SIZE);
|
||||
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
|
||||
|
||||
// When
|
||||
final String text = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
|
||||
assertThat(text, equalTo(originalString));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsIoWithCopy_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
|
||||
final String originalString = randomAlphabetic(DEFAULT_SIZE);
|
||||
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
|
||||
|
||||
// When
|
||||
final StringWriter writer = new StringWriter();
|
||||
final String encoding = StandardCharsets.UTF_8.name();
|
||||
IOUtils.copy(inputStream, writer, encoding);
|
||||
|
||||
assertThat(writer.toString(), equalTo(originalString));
|
||||
}
|
||||
|
||||
// tests - InputStream to byte[]
|
||||
|
||||
@Test
|
||||
public final void givenUsingPlainJavaOnFixedSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
|
||||
final byte[] targetArray = new byte[initialStream.available()];
|
||||
initialStream.read(targetArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingPlainJavaOnUnknownSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
|
||||
final InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
|
||||
|
||||
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
int nRead;
|
||||
final byte[] data = new byte[1024];
|
||||
while ((nRead = is.read(data, 0, data.length)) != -1) {
|
||||
buffer.write(data, 0, nRead);
|
||||
}
|
||||
|
||||
buffer.flush();
|
||||
final byte[] byteArray = buffer.toByteArray();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = ByteSource.wrap(new byte[] { 0, 1, 2 }).openStream();
|
||||
final byte[] targetArray = ByteStreams.toByteArray(initialStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsIO_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 });
|
||||
final byte[] targetArray = IOUtils.toByteArray(initialStream);
|
||||
}
|
||||
|
||||
// tests - InputStream to File
|
||||
|
||||
@Test
|
||||
public final void whenConvertingToFile_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final byte[] buffer = new byte[initialStream.available()];
|
||||
initialStream.read(buffer);
|
||||
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
final OutputStream outStream = new FileOutputStream(targetFile);
|
||||
outStream.write(buffer);
|
||||
|
||||
IOUtils.closeQuietly(initialStream);
|
||||
IOUtils.closeQuietly(outStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenConvertingInProgressToFile_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
final OutputStream outStream = new FileOutputStream(targetFile);
|
||||
|
||||
final byte[] buffer = new byte[8 * 1024];
|
||||
int bytesRead;
|
||||
while ((bytesRead = initialStream.read(buffer)) != -1) {
|
||||
outStream.write(buffer, 0, bytesRead);
|
||||
}
|
||||
|
||||
IOUtils.closeQuietly(initialStream);
|
||||
IOUtils.closeQuietly(outStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
|
||||
java.nio.file.Files.copy(initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
|
||||
IOUtils.closeQuietly(initialStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenConvertingInputStreamToFile_thenCorrect3() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final byte[] buffer = new byte[initialStream.available()];
|
||||
initialStream.read(buffer);
|
||||
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
Files.write(buffer, targetFile);
|
||||
|
||||
IOUtils.closeQuietly(initialStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenConvertingInputStreamToFile_thenCorrect4() throws IOException {
|
||||
final InputStream initialStream = FileUtils.openInputStream(new File("src/main/resources/sample.txt"));
|
||||
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
|
||||
FileUtils.copyInputStreamToFile(initialStream, targetFile);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingPlainJava_whenConvertingAnInputStreamToString_thenCorrect() throws IOException {
|
||||
String originalString = randomAlphabetic(8);
|
||||
InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
|
||||
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
int nRead;
|
||||
byte[] data = new byte[1024];
|
||||
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
|
||||
buffer.write(data, 0, nRead);
|
||||
}
|
||||
|
||||
buffer.flush();
|
||||
byte[] byteArray = buffer.toByteArray();
|
||||
|
||||
String text = new String(byteArray, StandardCharsets.UTF_8);
|
||||
assertThat(text, equalTo(originalString));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Scanner;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class JavaReadFromFileUnitTest {
|
||||
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(JavaReadFromFileUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void whenReadWithBufferedReader_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello world";
|
||||
|
||||
final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/test_read.in"));
|
||||
final String currentLine = reader.readLine();
|
||||
reader.close();
|
||||
|
||||
assertEquals(expected_value, currentLine);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadWithScanner_thenCorrect() throws IOException {
|
||||
final Scanner scanner = new Scanner(new File("src/test/resources/test_read1.in"));
|
||||
scanner.useDelimiter(" ");
|
||||
|
||||
assertTrue(scanner.hasNext());
|
||||
assertEquals("Hello", scanner.next());
|
||||
assertEquals("world", scanner.next());
|
||||
assertEquals(1, scanner.nextInt());
|
||||
|
||||
scanner.close();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadWithScannerTwoDelimiters_thenCorrect() throws IOException {
|
||||
final Scanner scanner = new Scanner(new File("src/test/resources/test_read2.in"));
|
||||
scanner.useDelimiter(",| ");
|
||||
|
||||
assertTrue(scanner.hasNextInt());
|
||||
assertEquals(2, scanner.nextInt());
|
||||
assertEquals(3, scanner.nextInt());
|
||||
assertEquals(4, scanner.nextInt());
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadWithStreamTokenizer_thenCorrectTokens() throws IOException {
|
||||
final FileReader reader = new FileReader("src/test/resources/test_read3.in");
|
||||
final StreamTokenizer tokenizer = new StreamTokenizer(reader);
|
||||
|
||||
tokenizer.nextToken();
|
||||
assertEquals(StreamTokenizer.TT_WORD, tokenizer.ttype);
|
||||
assertEquals("Hello", tokenizer.sval);
|
||||
tokenizer.nextToken();
|
||||
assertEquals(StreamTokenizer.TT_NUMBER, tokenizer.ttype);
|
||||
assertEquals(1, tokenizer.nval, 0.0000001);
|
||||
|
||||
tokenizer.nextToken();
|
||||
assertEquals(StreamTokenizer.TT_EOF, tokenizer.ttype);
|
||||
reader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadWithDataInputStream_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello";
|
||||
|
||||
String result;
|
||||
final DataInputStream reader = new DataInputStream(new FileInputStream("src/test/resources/test_read4.in"));
|
||||
result = reader.readUTF();
|
||||
reader.close();
|
||||
|
||||
assertEquals(expected_value, result);
|
||||
}
|
||||
|
||||
public void whenReadTwoFilesWithSequenceInputStream_thenCorrect() throws IOException {
|
||||
final int expected_value1 = 2000;
|
||||
final int expected_value2 = 5000;
|
||||
|
||||
final FileInputStream stream1 = new FileInputStream("src/test/resources/test_read5.in");
|
||||
final FileInputStream stream2 = new FileInputStream("src/test/resources/test_read6.in");
|
||||
|
||||
final SequenceInputStream sequence = new SequenceInputStream(stream1, stream2);
|
||||
final DataInputStream reader = new DataInputStream(sequence);
|
||||
|
||||
assertEquals(expected_value1, reader.readInt());
|
||||
assertEquals(expected_value2, reader.readInt());
|
||||
|
||||
reader.close();
|
||||
stream2.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadUTFEncodedFile_thenCorrect() throws IOException {
|
||||
final String expected_value = "青空";
|
||||
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));
|
||||
final String currentLine = reader.readLine();
|
||||
reader.close();
|
||||
LOG.debug(currentLine);
|
||||
assertEquals(expected_value, currentLine);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadFileContentsIntoString_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello world \n Test line \n";
|
||||
final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/test_read8.in"));
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
String currentLine = reader.readLine();
|
||||
while (currentLine != null) {
|
||||
builder.append(currentLine);
|
||||
builder.append("\n");
|
||||
currentLine = reader.readLine();
|
||||
}
|
||||
|
||||
reader.close();
|
||||
|
||||
assertEquals(expected_value, builder.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadWithFileChannel_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello world";
|
||||
final RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
|
||||
final FileChannel channel = reader.getChannel();
|
||||
|
||||
int bufferSize = 1024;
|
||||
if (bufferSize > channel.size()) {
|
||||
bufferSize = (int) channel.size();
|
||||
}
|
||||
final ByteBuffer buff = ByteBuffer.allocate(bufferSize);
|
||||
channel.read(buff);
|
||||
buff.flip();
|
||||
assertEquals(expected_value, new String(buff.array()));
|
||||
channel.close();
|
||||
reader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadSmallFileJava7_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello world";
|
||||
final Path path = Paths.get("src/test/resources/test_read.in");
|
||||
|
||||
final String read = Files.readAllLines(path, Charset.defaultCharset()).get(0);
|
||||
assertEquals(expected_value, read);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadLargeFileJava7_thenCorrect() throws IOException {
|
||||
final String expected_value = "Hello world";
|
||||
|
||||
final Path path = Paths.get("src/test/resources/test_read.in");
|
||||
final BufferedReader reader = Files.newBufferedReader(path, Charset.defaultCharset());
|
||||
final String line = reader.readLine();
|
||||
assertEquals(expected_value, line);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.Reader;
|
||||
import java.io.StringReader;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.commons.io.input.CharSequenceReader;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.io.CharSink;
|
||||
import com.google.common.io.CharSource;
|
||||
import com.google.common.io.CharStreams;
|
||||
import com.google.common.io.FileWriteMode;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public class JavaReaderToXUnitTest {
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
private static final int DEFAULT_SIZE = 1500000;
|
||||
|
||||
// tests - sandbox
|
||||
|
||||
// tests - Reader to String
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingReaderIntoStringV1_thenCorrect() throws IOException {
|
||||
final Reader reader = new StringReader("With Java 1");
|
||||
int intValueOfChar;
|
||||
String targetString = "";
|
||||
while ((intValueOfChar = reader.read()) != -1) {
|
||||
targetString += (char) intValueOfChar;
|
||||
}
|
||||
reader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingReaderIntoStringV2_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Java 1");
|
||||
final char[] arr = new char[8 * 1024];
|
||||
final StringBuilder buffer = new StringBuilder();
|
||||
int numCharsRead;
|
||||
while ((numCharsRead = initialReader.read(arr, 0, arr.length)) != -1) {
|
||||
buffer.append(arr, 0, numCharsRead);
|
||||
}
|
||||
initialReader.close();
|
||||
final String targetString = buffer.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingReaderIntoString_thenCorrect() throws IOException {
|
||||
final Reader initialReader = CharSource.wrap("With Google Guava").openStream();
|
||||
final String targetString = CharStreams.toString(initialReader);
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoString_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Apache Commons");
|
||||
final String targetString = IOUtils.toString(initialReader);
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
// tests - Reader WRITE TO File
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenWritingReaderContentsToFile_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("Some text");
|
||||
|
||||
int intValueOfChar;
|
||||
final StringBuilder buffer = new StringBuilder();
|
||||
while ((intValueOfChar = initialReader.read()) != -1) {
|
||||
buffer.append((char) intValueOfChar);
|
||||
}
|
||||
initialReader.close();
|
||||
|
||||
final File targetFile = new File("src/test/resources/targetFile.txt");
|
||||
targetFile.createNewFile();
|
||||
|
||||
final Writer targetFileWriter = new FileWriter(targetFile);
|
||||
targetFileWriter.write(buffer.toString());
|
||||
targetFileWriter.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenWritingReaderContentsToFile_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("Some text");
|
||||
|
||||
final File targetFile = new File("src/test/resources/targetFile.txt");
|
||||
com.google.common.io.Files.touch(targetFile);
|
||||
final CharSink charSink = com.google.common.io.Files.asCharSink(targetFile, Charset.defaultCharset(), FileWriteMode.APPEND);
|
||||
charSink.writeFrom(initialReader);
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenWritingReaderContentsToFile_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new CharSequenceReader("CharSequenceReader extends Reader");
|
||||
|
||||
final File targetFile = new File("src/test/resources/targetFile.txt");
|
||||
FileUtils.touch(targetFile);
|
||||
final byte[] buffer = IOUtils.toByteArray(initialReader);
|
||||
FileUtils.writeByteArrayToFile(targetFile, buffer);
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
// tests - Reader to byte[]
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingReaderIntoByteArray_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Java");
|
||||
|
||||
final char[] charArray = new char[8 * 1024];
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
int numCharsRead;
|
||||
while ((numCharsRead = initialReader.read(charArray, 0, charArray.length)) != -1) {
|
||||
builder.append(charArray, 0, numCharsRead);
|
||||
}
|
||||
final byte[] targetArray = builder.toString().getBytes();
|
||||
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingReaderIntoByteArray_thenCorrect() throws IOException {
|
||||
final Reader initialReader = CharSource.wrap("With Google Guava").openStream();
|
||||
|
||||
final byte[] targetArray = CharStreams.toString(initialReader).getBytes();
|
||||
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoByteArray_thenCorrect() throws IOException {
|
||||
final StringReader initialReader = new StringReader("With Commons IO");
|
||||
|
||||
final byte[] targetArray = IOUtils.toByteArray(initialReader);
|
||||
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
// tests - Reader to InputStream
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Java");
|
||||
|
||||
final char[] charBuffer = new char[8 * 1024];
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
int numCharsRead;
|
||||
while ((numCharsRead = initialReader.read(charBuffer, 0, charBuffer.length)) != -1) {
|
||||
builder.append(charBuffer, 0, numCharsRead);
|
||||
}
|
||||
final InputStream targetStream = new ByteArrayInputStream(builder.toString().getBytes());
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Guava");
|
||||
|
||||
final InputStream targetStream = new ByteArrayInputStream(CharStreams.toString(initialReader).getBytes());
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Commons IO");
|
||||
|
||||
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader));
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException {
|
||||
String initialString = "With Commons IO";
|
||||
final Reader initialReader = new StringReader(initialString);
|
||||
|
||||
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader));
|
||||
|
||||
final String finalString = IOUtils.toString(targetStream);
|
||||
assertThat(finalString, equalTo(initialString));
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
// tests - Reader to InputStream with encoding
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingReaderIntoInputStreamWithCharset() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Java");
|
||||
|
||||
final char[] charBuffer = new char[8 * 1024];
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
int numCharsRead;
|
||||
while ((numCharsRead = initialReader.read(charBuffer, 0, charBuffer.length)) != -1) {
|
||||
builder.append(charBuffer, 0, numCharsRead);
|
||||
}
|
||||
final InputStream targetStream = new ByteArrayInputStream(builder.toString().getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingReaderIntoInputStreamWithCharset_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Guava");
|
||||
|
||||
final InputStream targetStream = new ByteArrayInputStream(CharStreams.toString(initialReader).getBytes(Charsets.UTF_8));
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Commons IO");
|
||||
|
||||
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8);
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException {
|
||||
String initialString = "With Commons IO";
|
||||
final Reader initialReader = new StringReader(initialString);
|
||||
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8);
|
||||
|
||||
String finalString = IOUtils.toString(targetStream, Charsets.UTF_8);
|
||||
assertThat(finalString, equalTo(initialString));
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Locale;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaScannerUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenReadFileWithScanner_thenCorrect() throws IOException {
|
||||
final Scanner scanner = new Scanner(new File("src/test/resources/test_read.in"));
|
||||
|
||||
assertTrue(scanner.hasNext());
|
||||
assertEquals("Hello", scanner.next());
|
||||
assertEquals("world", scanner.next());
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertInputStreamToString_thenConverted() throws IOException {
|
||||
final String expectedValue = "Hello world";
|
||||
final FileInputStream inputStream = new FileInputStream("src/test/resources/test_read.in");
|
||||
final Scanner scanner = new Scanner(inputStream);
|
||||
scanner.useDelimiter("\\A");
|
||||
|
||||
final String result = scanner.next();
|
||||
assertEquals(expectedValue, result);
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadUsingBufferedReader_thenCorrect() throws IOException {
|
||||
final String firstLine = "Hello world";
|
||||
final String secondLine = "Hi, John";
|
||||
final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/test_read_multiple.in"));
|
||||
|
||||
String result = reader.readLine();
|
||||
assertEquals(firstLine, result);
|
||||
|
||||
result = reader.readLine();
|
||||
assertEquals(secondLine, result);
|
||||
|
||||
reader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadUsingScanner_thenCorrect() throws IOException {
|
||||
final String firstLine = "Hello world";
|
||||
final FileInputStream inputStream = new FileInputStream("src/test/resources/test_read_multiple.in");
|
||||
final Scanner scanner = new Scanner(inputStream);
|
||||
|
||||
final String result = scanner.nextLine();
|
||||
assertEquals(firstLine, result);
|
||||
|
||||
scanner.useDelimiter(", ");
|
||||
assertEquals("Hi", scanner.next());
|
||||
assertEquals("John", scanner.next());
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadingInputFromConsole_thenCorrect() {
|
||||
final String input = "Hello";
|
||||
final InputStream stdin = System.in;
|
||||
System.setIn(new ByteArrayInputStream(input.getBytes()));
|
||||
|
||||
final Scanner scanner = new Scanner(System.in);
|
||||
final String result = scanner.next();
|
||||
assertEquals(input, result);
|
||||
|
||||
System.setIn(stdin);
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidateInputUsingScanner_thenValidated() throws IOException {
|
||||
final String input = "2000";
|
||||
final InputStream stdin = System.in;
|
||||
System.setIn(new ByteArrayInputStream(input.getBytes()));
|
||||
|
||||
final Scanner scanner = new Scanner(System.in);
|
||||
|
||||
final boolean isIntInput = scanner.hasNextInt();
|
||||
assertTrue(isIntInput);
|
||||
|
||||
System.setIn(stdin);
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenScanString_thenCorrect() throws IOException {
|
||||
final String input = "Hello 1 F 3.5";
|
||||
final Scanner scanner = new Scanner(input);
|
||||
scanner.useLocale(Locale.US);
|
||||
|
||||
assertEquals("Hello", scanner.next());
|
||||
assertEquals(1, scanner.nextInt());
|
||||
assertEquals(15, scanner.nextInt(16));
|
||||
assertEquals(3.5, scanner.nextDouble(), 0.00000001);
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindPatternUsingScanner_thenFound() throws IOException {
|
||||
final String expectedValue = "world";
|
||||
final FileInputStream inputStream = new FileInputStream("src/test/resources/test_read.in");
|
||||
final Scanner scanner = new Scanner(inputStream);
|
||||
|
||||
final String result = scanner.findInLine("wo..d");
|
||||
assertEquals(expectedValue, result);
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFindPatternInHorizon_thenFound() throws IOException {
|
||||
final String expectedValue = "world";
|
||||
final FileInputStream inputStream = new FileInputStream("src/test/resources/test_read.in");
|
||||
final Scanner scanner = new Scanner(inputStream);
|
||||
|
||||
String result = scanner.findWithinHorizon("wo..d", 5);
|
||||
assertNull(result);
|
||||
|
||||
result = scanner.findWithinHorizon("wo..d", 100);
|
||||
assertEquals(expectedValue, result);
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSkipPatternUsingScanner_thenSkiped() throws IOException {
|
||||
final FileInputStream inputStream = new FileInputStream("src/test/resources/test_read.in");
|
||||
final Scanner scanner = new Scanner(inputStream);
|
||||
|
||||
scanner.skip(".e.lo");
|
||||
|
||||
assertEquals("world", scanner.next());
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenChangeScannerDelimiter_thenChanged() throws IOException {
|
||||
final String expectedValue = "Hello world";
|
||||
final String[] splited = expectedValue.split("o");
|
||||
|
||||
final FileInputStream inputStream = new FileInputStream("src/test/resources/test_read.in");
|
||||
final Scanner scanner = new Scanner(inputStream);
|
||||
scanner.useDelimiter("o");
|
||||
|
||||
assertEquals(splited[0], scanner.next());
|
||||
assertEquals(splited[1], scanner.next());
|
||||
assertEquals(splited[2], scanner.next());
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReadWithScannerTwoDelimiters_thenCorrect() throws IOException {
|
||||
final Scanner scanner = new Scanner(new File("src/test/resources/test_read_d.in"));
|
||||
scanner.useDelimiter(",|-");
|
||||
|
||||
assertEquals("John", scanner.next());
|
||||
assertEquals("Adam", scanner.next());
|
||||
assertEquals("Tom", scanner.next());
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileLock;
|
||||
import java.nio.channels.OverlappingFileLockException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaWriteToFileUnitTest {
|
||||
|
||||
private String fileName = "src/test/resources/test_write.txt";
|
||||
private String fileName1 = "src/test/resources/test_write_1.txt";
|
||||
private String fileName2 = "src/test/resources/test_write_2.txt";
|
||||
private String fileName3 = "src/test/resources/test_write_3.txt";
|
||||
private String fileName4 = "src/test/resources/test_write_4.txt";
|
||||
private String fileName5 = "src/test/resources/test_write_5.txt";
|
||||
|
||||
@Test
|
||||
public void whenWriteStringUsingBufferedWritter_thenCorrect() throws IOException {
|
||||
final String str = "Hello";
|
||||
final BufferedWriter writer = new BufferedWriter(new FileWriter(fileName3));
|
||||
writer.write(str);
|
||||
writer.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendStringUsingBufferedWritter_thenOldContentShouldExistToo() throws IOException {
|
||||
final String str = "World";
|
||||
final BufferedWriter writer = new BufferedWriter(new FileWriter(fileName3, true));
|
||||
writer.append(' ');
|
||||
writer.append(str);
|
||||
writer.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWritingStringToFile_whenUsingPrintWriter_thenCorrect() throws IOException {
|
||||
final FileWriter fileWriter = new FileWriter(fileName);
|
||||
final PrintWriter printWriter = new PrintWriter(fileWriter);
|
||||
printWriter.print("Some String");
|
||||
printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
|
||||
printWriter.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWritingStringToFile_whenUsingFileOutputStream_thenCorrect() throws IOException {
|
||||
final String str = "Hello";
|
||||
final FileOutputStream outputStream = new FileOutputStream(fileName3);
|
||||
final byte[] strToBytes = str.getBytes();
|
||||
outputStream.write(strToBytes);
|
||||
outputStream.close();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void givenWritingToFile_whenUsingDataOutputStream_thenCorrect() throws IOException {
|
||||
final String value = "Hello";
|
||||
final FileOutputStream fos = new FileOutputStream(fileName1);
|
||||
final DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
|
||||
outStream.writeUTF(value);
|
||||
outStream.close();
|
||||
|
||||
String result;
|
||||
final FileInputStream fis = new FileInputStream(fileName1);
|
||||
final DataInputStream reader = new DataInputStream(fis);
|
||||
result = reader.readUTF();
|
||||
reader.close();
|
||||
|
||||
assertEquals(value, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWritingToSpecificPositionInFile_thenCorrect() throws IOException {
|
||||
final int data1 = 2014;
|
||||
final int data2 = 1500;
|
||||
writeToPosition(fileName2, data1, 4);
|
||||
assertEquals(data1, readFromPosition(fileName2, 4));
|
||||
writeToPosition(fileName2, data2, 4);
|
||||
assertEquals(data2, readFromPosition(fileName2, 4));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTryToLockFile_thenItShouldBeLocked() throws IOException {
|
||||
final RandomAccessFile stream = new RandomAccessFile(fileName4, "rw");
|
||||
final FileChannel channel = stream.getChannel();
|
||||
|
||||
FileLock lock = null;
|
||||
try {
|
||||
lock = channel.tryLock();
|
||||
} catch (final OverlappingFileLockException e) {
|
||||
stream.close();
|
||||
channel.close();
|
||||
}
|
||||
stream.writeChars("test lock");
|
||||
lock.release();
|
||||
|
||||
stream.close();
|
||||
channel.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWritingToFile_whenUsingFileChannel_thenCorrect() throws IOException {
|
||||
final RandomAccessFile stream = new RandomAccessFile(fileName5, "rw");
|
||||
final FileChannel channel = stream.getChannel();
|
||||
final String value = "Hello";
|
||||
final byte[] strBytes = value.getBytes();
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
|
||||
buffer.put(strBytes);
|
||||
buffer.flip();
|
||||
channel.write(buffer);
|
||||
stream.close();
|
||||
channel.close();
|
||||
|
||||
final RandomAccessFile reader = new RandomAccessFile(fileName5, "r");
|
||||
assertEquals(value, reader.readLine());
|
||||
reader.close();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWriteToTmpFile_thenCorrect() throws IOException {
|
||||
final String toWrite = "Hello";
|
||||
final File tmpFile = File.createTempFile("test", ".tmp");
|
||||
final FileWriter writer = new FileWriter(tmpFile);
|
||||
writer.write(toWrite);
|
||||
writer.close();
|
||||
|
||||
final BufferedReader reader = new BufferedReader(new FileReader(tmpFile));
|
||||
assertEquals(toWrite, reader.readLine());
|
||||
reader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingJava7_whenWritingToFile_thenCorrect() throws IOException {
|
||||
final String str = "Hello";
|
||||
|
||||
final Path path = Paths.get(fileName3);
|
||||
final byte[] strToBytes = str.getBytes();
|
||||
|
||||
Files.write(path, strToBytes);
|
||||
|
||||
final String read = Files.readAllLines(path, Charset.defaultCharset()).get(0);
|
||||
assertEquals(str, read);
|
||||
}
|
||||
|
||||
// UTIL
|
||||
|
||||
// use RandomAccessFile to write data at specific position in the file
|
||||
private void writeToPosition(final String filename, final int data, final long position) throws IOException {
|
||||
final RandomAccessFile writer = new RandomAccessFile(filename, "rw");
|
||||
writer.seek(position);
|
||||
writer.writeInt(data);
|
||||
writer.close();
|
||||
}
|
||||
|
||||
// use RandomAccessFile to read data from specific position in the file
|
||||
private int readFromPosition(final String filename, final long position) throws IOException {
|
||||
int result = 0;
|
||||
final RandomAccessFile reader = new RandomAccessFile(filename, "r");
|
||||
reader.seek(position);
|
||||
result = reader.readInt();
|
||||
reader.close();
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class JavaXToByteArrayUnitTest {
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
// tests - X to Byte Array
|
||||
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.commons.io.input.ReaderInputStream;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.io.ByteSource;
|
||||
import com.google.common.io.CharSource;
|
||||
import com.google.common.io.Files;
|
||||
|
||||
public class JavaXToInputStreamUnitTest {
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
// tests - String - InputStream
|
||||
|
||||
@Test
|
||||
public final void givenUsingPlainJava_whenConvertingStringToInputStream_thenCorrect() throws IOException {
|
||||
final String initialString = "text";
|
||||
final InputStream targetStream = new ByteArrayInputStream(initialString.getBytes());
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenConvertingStringToInputStream_thenCorrect() throws IOException {
|
||||
final String initialString = "text";
|
||||
final InputStream targetStream = new ReaderInputStream(CharSource.wrap(initialString).openStream());
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsIO_whenConvertingStringToInputStream_thenCorrect() throws IOException {
|
||||
final String initialString = "text";
|
||||
final InputStream targetStream = IOUtils.toInputStream(initialString);
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
}
|
||||
|
||||
// byte array - InputStream
|
||||
|
||||
@Test
|
||||
public final void givenUsingPlainJava_whenConvertingByteArrayToInputStream_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = { 0, 1, 2 };
|
||||
final InputStream targetStream = new ByteArrayInputStream(initialArray);
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenConvertingByteArrayToInputStream_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = { 0, 1, 2 };
|
||||
final InputStream targetStream = ByteSource.wrap(initialArray).openStream();
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
}
|
||||
|
||||
// File - InputStream
|
||||
|
||||
@Test
|
||||
public final void givenUsingPlainJava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/main/resources/sample.txt");
|
||||
final InputStream targetStream = new FileInputStream(initialFile);
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/main/resources/sample.txt");
|
||||
final InputStream targetStream = Files.asByteSource(initialFile).openStream();
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsIO_whenConvertingFileToInputStream_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/main/resources/sample.txt");
|
||||
final InputStream targetStream = FileUtils.openInputStream(initialFile);
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.io.StringReader;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.commons.io.input.CharSequenceReader;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.io.ByteSource;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.google.common.io.CharSource;
|
||||
|
||||
public class JavaXToReaderUnitTest {
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
// tests - String to Reader
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingStringIntoReader_thenCorrect() throws IOException {
|
||||
final String initialString = "With Plain Java";
|
||||
final Reader targetReader = new StringReader(initialString);
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingStringIntoReader_thenCorrect() throws IOException {
|
||||
final String initialString = "With Google Guava";
|
||||
final Reader targetReader = CharSource.wrap(initialString).openStream();
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingStringIntoReader_thenCorrect() throws IOException {
|
||||
final String initialString = "With Apache Commons IO";
|
||||
final Reader targetReader = new CharSequenceReader(initialString);
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
// tests - byte array to Reader
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = "Hello world!".getBytes();
|
||||
final Reader targetReader = new StringReader(new String(initialArray));
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava2_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = "Hello world!".getBytes();
|
||||
final Reader targetReader = new InputStreamReader(new ByteArrayInputStream(initialArray));
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = "With Guava".getBytes();
|
||||
final String bufferString = new String(initialArray);
|
||||
final Reader targetReader = CharSource.wrap(bufferString).openStream();
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = "With Commons IO".getBytes();
|
||||
final Reader targetReader = new CharSequenceReader(new String(initialArray));
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
// tests - File to Reader
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingFileIntoReader_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/test/resources/initialFile.txt");
|
||||
initialFile.createNewFile();
|
||||
final Reader targetReader = new FileReader(initialFile);
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingFileIntoReader_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/test/resources/initialFile.txt");
|
||||
com.google.common.io.Files.touch(initialFile);
|
||||
final Reader targetReader = com.google.common.io.Files.newReader(initialFile, Charset.defaultCharset());
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingFileIntoReader_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/test/resources/initialFile.txt");
|
||||
FileUtils.touch(initialFile);
|
||||
FileUtils.write(initialFile, "With Commons IO");
|
||||
final byte[] buffer = FileUtils.readFileToByteArray(initialFile);
|
||||
final Reader targetReader = new CharSequenceReader(new String(buffer));
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
// tests - InputStream to Reader
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = new ByteArrayInputStream("With Java".getBytes());
|
||||
final Reader targetReader = new InputStreamReader(initialStream);
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = ByteSource.wrap("With Guava".getBytes()).openStream();
|
||||
final byte[] buffer = ByteStreams.toByteArray(initialStream);
|
||||
final Reader targetReader = CharSource.wrap(new String(buffer)).openStream();
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = IOUtils.toInputStream("With Commons IO");
|
||||
final byte[] buffer = IOUtils.toByteArray(initialStream);
|
||||
final Reader targetReader = new CharSequenceReader(new String(buffer));
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.io.Writer;
|
||||
|
||||
import org.apache.commons.io.output.StringBuilderWriter;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.io.CharSink;
|
||||
|
||||
public class JavaXToWriterUnitTest {
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
// tests - byte[] to Writer
|
||||
|
||||
@Test
|
||||
public void givenPlainJava_whenConvertingByteArrayIntoWriter_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = "With Java".getBytes();
|
||||
|
||||
final Writer targetWriter = new StringWriter().append(new String(initialArray));
|
||||
|
||||
targetWriter.close();
|
||||
|
||||
assertEquals("With Java", targetWriter.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingByteArrayIntoWriter_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = "With Guava".getBytes();
|
||||
|
||||
final String buffer = new String(initialArray);
|
||||
final StringWriter stringWriter = new StringWriter();
|
||||
final CharSink charSink = new CharSink() {
|
||||
@Override
|
||||
public final Writer openStream() throws IOException {
|
||||
return stringWriter;
|
||||
}
|
||||
};
|
||||
charSink.write(buffer);
|
||||
|
||||
stringWriter.close();
|
||||
|
||||
assertEquals("With Guava", stringWriter.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingByteArrayIntoWriter_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = "With Commons IO".getBytes();
|
||||
final Writer targetWriter = new StringBuilderWriter(new StringBuilder(new String(initialArray)));
|
||||
|
||||
targetWriter.close();
|
||||
|
||||
assertEquals("With Commons IO", targetWriter.toString());
|
||||
}
|
||||
|
||||
}
|
||||
13
core-java-io/src/test/resources/.gitignore
vendored
Normal file
13
core-java-io/src/test/resources/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
4
core-java-io/src/test/resources/configuration.properties
Normal file
4
core-java-io/src/test/resources/configuration.properties
Normal file
@@ -0,0 +1,4 @@
|
||||
# this is sample property file for PropertiesLoaderTest configuration needs
|
||||
! this is also a comment
|
||||
sampleConfEntry = sample String value
|
||||
colonSeparatedEntry : colon separated entry value
|
||||
178691
core-java-io/src/test/resources/dictionary.in
Normal file
178691
core-java-io/src/test/resources/dictionary.in
Normal file
File diff suppressed because it is too large
Load Diff
1
core-java-io/src/test/resources/test.find
Normal file
1
core-java-io/src/test/resources/test.find
Normal file
@@ -0,0 +1 @@
|
||||
Test of JNDI on file.
|
||||
@@ -0,0 +1 @@
|
||||
Hello world
|
||||
@@ -0,0 +1 @@
|
||||
Hello world !
|
||||
1
core-java-io/src/test/resources/test_read.in
Normal file
1
core-java-io/src/test/resources/test_read.in
Normal file
@@ -0,0 +1 @@
|
||||
Hello world
|
||||
1
core-java-io/src/test/resources/test_read1.in
Normal file
1
core-java-io/src/test/resources/test_read1.in
Normal file
@@ -0,0 +1 @@
|
||||
Hello world 1
|
||||
1
core-java-io/src/test/resources/test_read2.in
Normal file
1
core-java-io/src/test/resources/test_read2.in
Normal file
@@ -0,0 +1 @@
|
||||
2,3 4
|
||||
1
core-java-io/src/test/resources/test_read3.in
Normal file
1
core-java-io/src/test/resources/test_read3.in
Normal file
@@ -0,0 +1 @@
|
||||
Hello 1
|
||||
BIN
core-java-io/src/test/resources/test_read4.in
Normal file
BIN
core-java-io/src/test/resources/test_read4.in
Normal file
Binary file not shown.
1
core-java-io/src/test/resources/test_read7.in
Normal file
1
core-java-io/src/test/resources/test_read7.in
Normal file
@@ -0,0 +1 @@
|
||||
青空
|
||||
2
core-java-io/src/test/resources/test_read8.in
Normal file
2
core-java-io/src/test/resources/test_read8.in
Normal file
@@ -0,0 +1,2 @@
|
||||
Hello world
|
||||
Test line
|
||||
1
core-java-io/src/test/resources/test_read_d.in
Normal file
1
core-java-io/src/test/resources/test_read_d.in
Normal file
@@ -0,0 +1 @@
|
||||
John,Adam-Tom
|
||||
2
core-java-io/src/test/resources/test_read_multiple.in
Normal file
2
core-java-io/src/test/resources/test_read_multiple.in
Normal file
@@ -0,0 +1,2 @@
|
||||
Hello world
|
||||
Hi, John
|
||||
Reference in New Issue
Block a user