mirror of
https://github.com/cryptomator/cryptomator.git
synced 2026-05-16 01:31:28 +00:00
Compare commits
106 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b7684f0af | ||
|
|
bff3dbd777 | ||
|
|
0fc2b18f68 | ||
|
|
e5dff4322a | ||
|
|
167944e8ed | ||
|
|
1af94c9c21 | ||
|
|
63df9a4d8f | ||
|
|
24c45c8539 | ||
|
|
d1d3974610 | ||
|
|
e6cd505767 | ||
|
|
2d68e27d3d | ||
|
|
05cc248417 | ||
|
|
10bff4c4fd | ||
|
|
b53da45a15 | ||
|
|
67a7dcdc4b | ||
|
|
f87f10f332 | ||
|
|
3d47b30193 | ||
|
|
1370b200bb | ||
|
|
2f249d557e | ||
|
|
ce17fff1ac | ||
|
|
2d55da309b | ||
|
|
761207155d | ||
|
|
456a879181 | ||
|
|
2e02e70916 | ||
|
|
dbc803a0d9 | ||
|
|
fdccafaa68 | ||
|
|
deebd82ecd | ||
|
|
0906abdea9 | ||
|
|
da94fe4f6f | ||
|
|
79672a28ee | ||
|
|
e052a4b261 | ||
|
|
425d4e8fed | ||
|
|
d2a2e2304d | ||
|
|
e7157a64ed | ||
|
|
245a995203 | ||
|
|
c29d7fb6a2 | ||
|
|
8cada6d0a2 | ||
|
|
d03446beef | ||
|
|
f62c0b4ca8 | ||
|
|
c046056736 | ||
|
|
e63cbf94d0 | ||
|
|
d48247b7c6 | ||
|
|
695dcd5de7 | ||
|
|
5e35985a3f | ||
|
|
d9325819fd | ||
|
|
f960238b47 | ||
|
|
d0aef5b683 | ||
|
|
c69fc95126 | ||
|
|
51cb41975b | ||
|
|
0debbb83b1 | ||
|
|
fbfe2b0a31 | ||
|
|
a719a83bce | ||
|
|
d353a9cb9d | ||
|
|
ee2e07a9a3 | ||
|
|
f6689043c7 | ||
|
|
45531dc54a | ||
|
|
0a26c192fe | ||
|
|
281cfb74d9 | ||
|
|
0d03eeb5bd | ||
|
|
36e669d729 | ||
|
|
b1f55d7cfe | ||
|
|
9aa8c46560 | ||
|
|
2ed00ed02d | ||
|
|
5d56f5beb6 | ||
|
|
1b937dfb06 | ||
|
|
42be5330fe | ||
|
|
be8949157f | ||
|
|
93b2a4e07a | ||
|
|
ada1195a26 | ||
|
|
93563f68e0 | ||
|
|
3faa0e83cc | ||
|
|
1985e2af72 | ||
|
|
3f03d36ad6 | ||
|
|
8359deb8eb | ||
|
|
e1f2330f95 | ||
|
|
87014c4db2 | ||
|
|
c9eb9b1938 | ||
|
|
28cb2e1301 | ||
|
|
277999112e | ||
|
|
a7fdf3d325 | ||
|
|
54ae332364 | ||
|
|
76075ffec4 | ||
|
|
ed448146f7 | ||
|
|
638e9c1a8b | ||
|
|
1624cffb2a | ||
|
|
f391a6521d | ||
|
|
02ae2e7ca0 | ||
|
|
40bd84a09c | ||
|
|
0c0fb1c4c5 | ||
|
|
ab39bd1667 | ||
|
|
b41636a208 | ||
|
|
0902de821a | ||
|
|
8a6265658e | ||
|
|
7750a49e65 | ||
|
|
b75b9781c1 | ||
|
|
2687c02e31 | ||
|
|
71b65e03d6 | ||
|
|
e09ee27219 | ||
|
|
5a3428d9b0 | ||
|
|
ed109977f8 | ||
|
|
d6c6f177e8 | ||
|
|
97f2cee1ae | ||
|
|
4fb8a27a78 | ||
|
|
79b825aaad | ||
|
|
28fedafb59 | ||
|
|
d9bff68555 |
23
.travis.yml
23
.travis.yml
@@ -8,8 +8,9 @@ cache:
|
||||
- $HOME/.m2
|
||||
env:
|
||||
global:
|
||||
- secure: "IfYURwZaDWuBDvyn47n0k1Zod/IQw1FF+CS5nnV08Q+NfC3vGGJMwV8m59XnbfwnWGxwvCaAbk4qP6s6+ijgZNKkvgfFMo3rfTok5zt43bIqgaFOANYV+OC/1c59gYD6ZUxhW5iNgMgU3qdsRtJuwSmfkVv/jKyLGfAbS4kN8BA=" #coverity
|
||||
- secure: "lV9OwUbHMrMpLUH1CY+Z4puLDdFXytudyPlG1eGRsesdpuG6KM3uQVz6uAtf6lrU8DRbMM/T7ML+PmvQ4UoPPYLdLxESLLBat2qUPOIVBOhTSlCc7I0DmGy04CSvkeMy8dPaQC0ukgNiR7zwoNzfcpGRN/U9S8tziDruuHoZSrg=" #bintray
|
||||
- secure: "IfYURwZaDWuBDvyn47n0k1Zod/IQw1FF+CS5nnV08Q+NfC3vGGJMwV8m59XnbfwnWGxwvCaAbk4qP6s6+ijgZNKkvgfFMo3rfTok5zt43bIqgaFOANYV+OC/1c59gYD6ZUxhW5iNgMgU3qdsRtJuwSmfkVv/jKyLGfAbS4kN8BA=" # COVERITY_SCAN_TOKEN
|
||||
- secure: "lV9OwUbHMrMpLUH1CY+Z4puLDdFXytudyPlG1eGRsesdpuG6KM3uQVz6uAtf6lrU8DRbMM/T7ML+PmvQ4UoPPYLdLxESLLBat2qUPOIVBOhTSlCc7I0DmGy04CSvkeMy8dPaQC0ukgNiR7zwoNzfcpGRN/U9S8tziDruuHoZSrg=" # BINTRAY_API_KEY
|
||||
- secure: "oWFgRTVP6lyTa7qVxlvkpm20MtVc3BtmsNXQJS6bfg2A0o/iCQMNx7OD59BaafCLGRKvCcJVESiC8FlSylVMS7CDSyYu0gg70NUiIuHp4NBM5inFWYCy/PdQsCTzr5uvNG+rMFQpMFRaCV0FrfM3tLondcVkhsHL68l93Xoexx4=" # CODACY_PROJECT_TOKEN
|
||||
addons:
|
||||
coverity_scan:
|
||||
project:
|
||||
@@ -19,24 +20,10 @@ addons:
|
||||
branch_pattern: release.*
|
||||
install:
|
||||
# "clean" needed until https://bugs.openjdk.java.net/browse/JDK-8067747 is resolved.
|
||||
- mvn -fmain/pom.xml clean package -DskipTests dependency:go-offline -Ptest-coverage
|
||||
- mvn -fmain/pom.xml clean package -DskipTests dependency:go-offline -Pcoverage
|
||||
- mvn -fmain/pom.xml clean package -DskipTests dependency:go-offline -Prelease
|
||||
script:
|
||||
- mvn --update-snapshots -fmain/pom.xml -Ptest-coverage clean test jacoco:report-aggregate
|
||||
after_success:
|
||||
- "bash <(curl -s https://codecov.io/bash)"
|
||||
notifications:
|
||||
webhooks:
|
||||
urls:
|
||||
- https://webhooks.gitter.im/e/7d429ab35361726e26f2
|
||||
on_success: change
|
||||
on_failure: always
|
||||
on_start: false
|
||||
slack:
|
||||
rooms:
|
||||
secure: "lngJ/HEAFBbD5AdiO9avMqptKpZHdmEwOzS9FabZjkdFh7yAYueTk5RniPUvShjsKtThYm7cJ8AtDMDwc07NvPrzbMBRtUJGwuDT+7c7YFALGFJ1NYi+emkC9x1oafvmPgEYSE+tMKzNcwrHi3ytGgKdIotsKwaF35QNXYA9aMs="
|
||||
on_success: change
|
||||
on_failure: always
|
||||
- mvn --update-snapshots -fmain/pom.xml clean test jacoco:report verify -Pcoverage
|
||||
before_deploy:
|
||||
- mvn -fmain/pom.xml -Prelease clean package -DskipTests
|
||||
deploy:
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
## Did you find a bug?
|
||||
|
||||
- Ensure you're running the latest version of Cryptomator.
|
||||
- Ensure the bug is related to the desktop version of Cryptomator. Bugs concerning the Cryptomator iOS app can be reported on the [Cryptomator for iOS issues list](https://github.com/cryptomator/cryptomator-ios/issues).
|
||||
- Ensure the bug was not [already reported](https://github.com/cryptomator/cryptomator/issues). You can also check out our [FAQ](https://cryptomator.org/faq/) and our [Wiki](https://github.com/cryptomator/cryptomator/wiki).
|
||||
- Ensure the bug is related to the desktop version of Cryptomator. Bugs concerning the Cryptomator iOS and Android app can be reported on the [Cryptomator for iOS issues list](https://github.com/cryptomator/cryptomator-ios/issues) and [Cryptomator for Android issues list](https://github.com/cryptomator/cryptomator-android/issues) respectively.
|
||||
- Ensure the bug was not [already reported](https://github.com/cryptomator/cryptomator/issues). You can also check out our [knowledge base](https://cryptomator.freshdesk.com/support/solutions) and our [Wiki](https://github.com/cryptomator/cryptomator/wiki).
|
||||
- If you're unable to find an open issue addressing the problem, [submit a new one](https://github.com/cryptomator/cryptomator/issues/new).
|
||||
|
||||
## Do you have questions?
|
||||
@@ -13,6 +13,11 @@
|
||||
- [Contact us](https://cryptomator.org/contact/) directly by writing an email. Wir sprechen auch Deutsch!
|
||||
- Have a chat with us on [Gitter](https://gitter.im/cryptomator/cryptomator).
|
||||
|
||||
## Do you miss a feature?
|
||||
|
||||
- Ensure the feature was not [already requested](https://github.com/cryptomator/cryptomator/issues).
|
||||
- You're welcome to suggest a feature by [submitting a new issue](https://github.com/cryptomator/cryptomator/issues/new).
|
||||
|
||||
## Did you write a patch that fixes a bug?
|
||||
|
||||
- Open a new pull request with the patch.
|
||||
|
||||
@@ -1,19 +1,38 @@
|
||||
### Basic Info
|
||||
To tick a checkbox replace [ ] with [x]. Make sure to replace placeholders (…) accordingly.
|
||||
|
||||
- I'm running Cryptomator on: [Windows, OS X, and/or Debian (or other Linux Distribution), don't forget the version]
|
||||
- I'm using Cryptomator in version: [you can check the version in the settings of Cryptomator]
|
||||
## Issue Checklist
|
||||
|
||||
### Description
|
||||
Before creating a new issue make sure that you
|
||||
- [ ] searched [existing (and closed) issues](https://github.com/cryptomator/cryptomator/issues).
|
||||
- [ ] searched the [knowledge base](https://cryptomator.freshdesk.com/support/solutions).
|
||||
- [ ] have read the [contribution guide](https://github.com/cryptomator/cryptomator/blob/master/CONTRIBUTING.md).
|
||||
- [ ] have read the [Code of Conduct](https://github.com/cryptomator/cryptomator/blob/master/CODE_OF_CONDUCT.md).
|
||||
|
||||
[description of the bug, question or feature - what did you do? what problem occurred? etc.]
|
||||
## Basic Info
|
||||
|
||||
### Log File (optional)
|
||||
This is a
|
||||
- [ ] bug report.
|
||||
- [ ] feature request.
|
||||
- [ ] question or something else.
|
||||
|
||||
```
|
||||
[insert relevant parts of the log file here if applicable,
|
||||
don't forget to redact sensitive information
|
||||
I'm using
|
||||
- [ ] Windows in version: …
|
||||
- [ ] macOS in version: …
|
||||
- [ ] Linux in version: …
|
||||
|
||||
on Windows: %appdata%/Cryptomator/cryptomator.log
|
||||
on OS X: ~/Library/Logs/Cryptomator/cryptomator.log
|
||||
on Debian: ~/.Cryptomator/cryptomator.log]
|
||||
```
|
||||
I'm running Cryptomator in version: …
|
||||
(You can check the version in the Cryptomator settings.)
|
||||
|
||||
## Description
|
||||
|
||||
…
|
||||
(Please describe in detail what you did, what you expected, and what really happened.)
|
||||
|
||||
## Attachments (optional)
|
||||
|
||||
If you want to add the log file or screenshots, please add them as attachments. If your log file seems empty and doesn't show any errors, you may enable the [debug mode](https://cryptomator.freshdesk.com/support/solutions/articles/16000046480) first and reproduce the problem to ensure all important information is contained in there. You may use test data or redact sensitive information from the log file.
|
||||
|
||||
You can find the log file
|
||||
- on Windows: %appdata%/Cryptomator/cryptomator.log
|
||||
- on macOS: ~/Library/Logs/Cryptomator/cryptomator.log
|
||||
- on Linux: ~/.Cryptomator/cryptomator.log
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
[](https://travis-ci.org/cryptomator/cryptomator)
|
||||
[](https://scan.coverity.com/projects/cryptomator-cryptomator)
|
||||
[](https://www.codacy.com/app/cryptomator/cryptomator?utm_source=github.com&utm_medium=referral&utm_content=cryptomator/cryptomator&utm_campaign=Badge_Grade)
|
||||
[](https://coveralls.io/github/cryptomator/cryptomator?branch=master)
|
||||
[](https://gitter.im/cryptomator/cryptomator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
[](http://twitter.com/Cryptomator)
|
||||
[](https://poeditor.com/join/project/bHwbvJmx0E)
|
||||
|
||||
@@ -45,7 +43,8 @@ For more information on the security details visit [cryptomator.org](https://cry
|
||||
|
||||
### Dependencies
|
||||
|
||||
* Java 8 + JCE unlimited strength policy files (needed for 256-bit keys)
|
||||
* Java 8 (min. 8u51, we recommend to use the current version)
|
||||
* [JCE unlimited strength policy files](http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html) (needed for 256-bit keys)
|
||||
* Maven 3
|
||||
* Optional: OS-dependent build tools for native packaging (see [Windows](https://github.com/cryptomator/cryptomator-win), [OS X](https://github.com/cryptomator/cryptomator-osx), [Linux](https://github.com/cryptomator/builder-containers))
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
<parent>
|
||||
<groupId>org.cryptomator</groupId>
|
||||
<artifactId>main</artifactId>
|
||||
<version>1.2.3</version>
|
||||
<version>1.3.0-rc6</version>
|
||||
</parent>
|
||||
<artifactId>ant-kit</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
@@ -18,7 +18,7 @@
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.cryptomator</groupId>
|
||||
<artifactId>ui</artifactId>
|
||||
<artifactId>launcher</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
<!-- copy resources to target/: -->
|
||||
<plugin>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>2.7</version>
|
||||
<version>3.0.2</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-resources</id>
|
||||
@@ -79,8 +79,8 @@
|
||||
|
||||
<!-- create antkit.tar.gz: -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>make-assembly</id>
|
||||
|
||||
@@ -3,15 +3,15 @@
|
||||
<taskdef uri="javafx:com.sun.javafx.tools.ant" resource="com/sun/javafx/tools/ant/antlib.xml" classpath="\${java.class.path}:\${java.home}/../lib/ant-javafx.jar:." />
|
||||
|
||||
<!-- Define application to build -->
|
||||
<fx:application id="Cryptomator" name="Cryptomator" version="${project.version}" mainClass="org.cryptomator.ui.Cryptomator" />
|
||||
<fx:application id="Cryptomator" name="Cryptomator" version="${project.version}" mainClass="org.cryptomator.launcher.Cryptomator" />
|
||||
|
||||
<!-- Create main application jar -->
|
||||
<target name="create-jar">
|
||||
<fx:jar destfile="antbuild/Cryptomator-${project.version}.jar">
|
||||
<fx:application refid="Cryptomator" />
|
||||
<fx:fileset dir="libs" includes="ui-${project.version}.jar" />
|
||||
<fx:fileset dir="libs" includes="launcher-${project.version}.jar" />
|
||||
<fx:resources>
|
||||
<fx:fileset dir="libs" type="jar" includes="*.jar" excludes="ui-${project.version}.jar" />
|
||||
<fx:fileset dir="libs" type="jar" includes="*.jar" excludes="launcher-${project.version}.jar" />
|
||||
</fx:resources>
|
||||
<fx:manifest>
|
||||
<fx:attribute name="Implementation-Vendor" value="cryptomator.org" />
|
||||
@@ -29,14 +29,15 @@
|
||||
<fx:association mimetype="application/x-vnd.cryptomator-vault-metadata" extension="cryptomator" description="Cryptomator Vault Metadata" />
|
||||
</fx:info>
|
||||
<fx:platform j2se="8.0">
|
||||
<fx:property name="cryptomator.logPath" value="~/.Cryptomator/cryptomator.log" />
|
||||
<fx:property name="cryptomator.upgradeLogPath" value="~/.Cryptomator/upgrade.log" />
|
||||
<fx:property name="logback.configurationFile" value="logback.xml" />
|
||||
<fx:property name="cryptomator.settingsPath" value="~/.Cryptomator/settings.json" />
|
||||
<fx:property name="cryptomator.ipcPortPath" value="~/.Cryptomator/ipcPort.bin" />
|
||||
<fx:jvmarg value="-Xmx512m"/>
|
||||
</fx:platform>
|
||||
<fx:resources>
|
||||
<fx:fileset dir="." type="data" includes="logback.xml" />
|
||||
<fx:fileset dir="antbuild" type="jar" includes="Cryptomator-${project.version}.jar" />
|
||||
<fx:fileset dir="libs" type="jar" includes="*.jar" excludes="ui-${project.version}.jar"/>
|
||||
<fx:fileset dir="libs" type="jar" includes="*.jar" excludes="launcher-${project.version}.jar"/>
|
||||
<fx:fileset dir="fixed-binaries" type="data" includes="linux-launcher-*" arch=""/>
|
||||
</fx:resources>
|
||||
<fx:permissions elevated="false" />
|
||||
@@ -52,14 +53,16 @@
|
||||
<fx:association mimetype="application/x-vnd.cryptomator-vault-metadata" extension="cryptomator" description="Cryptomator Vault Metadata" />
|
||||
</fx:info>
|
||||
<fx:platform j2se="8.0">
|
||||
<fx:property name="cryptomator.logPath" value="~/.Cryptomator/cryptomator.log" />
|
||||
<fx:property name="cryptomator.upgradeLogPath" value="~/.Cryptomator/upgrade.log" />
|
||||
<fx:property name="logback.configurationFile" value="logback.xml" />
|
||||
<fx:property name="cryptomator.settingsPath" value="~/.Cryptomator/settings.json" />
|
||||
<fx:property name="cryptomator.ipcPortPath" value="~/.Cryptomator/ipcPort.bin" />
|
||||
<fx:jvmarg value="-Xmx512m"/>
|
||||
</fx:platform>
|
||||
<fx:resources>
|
||||
<fx:fileset dir="." type="data" includes="logback.xml" />
|
||||
<fx:fileset dir="antbuild" type="jar" includes="Cryptomator-${project.version}.jar" />
|
||||
<fx:fileset dir="libs" type="jar" includes="*.jar" excludes="ui-${project.version}.jar"/>
|
||||
<fx:fileset dir="libs" type="jar" includes="*.jar" excludes="launcher-${project.version}.jar"/>
|
||||
<fx:fileset dir="fixed-binaries" type="data" includes="linux-launcher-*" arch=""/>
|
||||
</fx:resources>
|
||||
<fx:permissions elevated="false" />
|
||||
<fx:preferences install="true" />
|
||||
|
||||
43
main/ant-kit/src/main/resources/logback.xml
Normal file
43
main/ant-kit/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,43 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE xml>
|
||||
<configuration scan="true" debug="true">
|
||||
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${user.home}/.Cryptomator/cryptomator.log</file>
|
||||
<append>false</append>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
|
||||
<fileNamePattern>${user.home}/.Cryptomator/cryptomator%i.log</fileNamePattern>
|
||||
<minIndex>0</minIndex>
|
||||
<maxIndex>9</maxIndex>
|
||||
</rollingPolicy>
|
||||
<triggeringPolicy class="org.cryptomator.logging.LaunchBasedTriggeringPolicy" />
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<appender name="UPGRADE_FILE" class="ch.qos.logback.core.FileAppender">
|
||||
<file>${user.home}/.Cryptomator/cryptomator.log</file>
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.cryptomator" level="INFO" />
|
||||
<logger name="org.eclipse.jetty.server.Server" level="INFO" />
|
||||
<logger name="org.cryptomator.ui.model" level="INFO">
|
||||
<appender-ref ref="UPGRADE_FILE" />
|
||||
</logger>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
<appender-ref ref="FILE" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
||||
1
main/commons-test/.gitignore
vendored
1
main/commons-test/.gitignore
vendored
@@ -1 +0,0 @@
|
||||
/target/
|
||||
@@ -1,43 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
Copyright (c) 2015 Markus Kreusch
|
||||
This file is licensed under the terms of the MIT license.
|
||||
See the LICENSE.txt file for more info.
|
||||
-->
|
||||
<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>
|
||||
<parent>
|
||||
<groupId>org.cryptomator</groupId>
|
||||
<artifactId>main</artifactId>
|
||||
<version>1.2.3</version>
|
||||
</parent>
|
||||
<artifactId>commons-test</artifactId>
|
||||
<name>Cryptomator common test dependencies</name>
|
||||
<description>Shared utilities for tests</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.cryptomator</groupId>
|
||||
<artifactId>commons</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>de.bechte.junit</groupId>
|
||||
<artifactId>junit-hierarchicalcontextrunner</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-all</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -1,73 +0,0 @@
|
||||
package org.cryptomator.common.test;
|
||||
|
||||
import static java.nio.file.Files.walkFileTree;
|
||||
import static java.util.Collections.synchronizedSet;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileVisitResult;
|
||||
import java.nio.file.FileVisitor;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class TempFilesRemovedOnShutdown {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(TempFilesRemovedOnShutdown.class);
|
||||
|
||||
private static final Set<Path> PATHS_TO_REMOVE_ON_SHUTDOWN = synchronizedSet(new HashSet<>());
|
||||
private static final Thread ON_SHUTDOWN_DELETER = new Thread(TempFilesRemovedOnShutdown::removeAll);
|
||||
|
||||
static {
|
||||
Runtime.getRuntime().addShutdownHook(ON_SHUTDOWN_DELETER);
|
||||
}
|
||||
|
||||
public static Path createTempDirectory(String prefix) throws IOException {
|
||||
Path path = Files.createTempDirectory(prefix);
|
||||
PATHS_TO_REMOVE_ON_SHUTDOWN.add(path);
|
||||
return path;
|
||||
}
|
||||
|
||||
private static void removeAll() {
|
||||
PATHS_TO_REMOVE_ON_SHUTDOWN.forEach(TempFilesRemovedOnShutdown::remove);
|
||||
}
|
||||
|
||||
private static void remove(Path path) {
|
||||
try {
|
||||
tryRemove(path);
|
||||
} catch (Throwable e) {
|
||||
LOG.debug("Failed to remove " + path, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void tryRemove(Path path) throws IOException {
|
||||
walkFileTree(path, new FileVisitor<Path>() {
|
||||
@Override
|
||||
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
|
||||
Files.delete(file);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
|
||||
Files.delete(dir);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package org.cryptomator.common.test.matcher;
|
||||
|
||||
import org.hamcrest.Matcher;
|
||||
import org.hamcrest.Matchers;
|
||||
|
||||
/**
|
||||
* Wraps hamcrest contains and containsInAnyOrder matcher factory methods to
|
||||
* avoid problems due to incorrect / inconsistent handling of generics by
|
||||
* several java compilers.
|
||||
*
|
||||
* @author Markus Kreusch
|
||||
*/
|
||||
public class ContainsMatcher {
|
||||
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
@SafeVarargs
|
||||
public static <T> Matcher<Iterable<? super T>> containsInAnyOrder(Matcher<? extends T>... matchers) {
|
||||
return Matchers.containsInAnyOrder((Matcher[]) matchers);
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
@SafeVarargs
|
||||
public static <T> Matcher<Iterable<? super T>> contains(Matcher<? extends T>... matchers) {
|
||||
return Matchers.contains((Matcher[]) matchers);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package org.cryptomator.common.test.matcher;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.hamcrest.Description;
|
||||
import org.hamcrest.Matcher;
|
||||
import org.hamcrest.TypeSafeDiagnosingMatcher;
|
||||
|
||||
public class ExceptionMatcher<T extends Throwable> extends TypeSafeDiagnosingMatcher<T> {
|
||||
|
||||
public static <T extends Throwable> ExceptionMatcher<T> ofType(Class<T> exceptionType) {
|
||||
return new ExceptionMatcher<>(exceptionType);
|
||||
}
|
||||
|
||||
private final Class<T> exceptionType;
|
||||
private final Optional<Matcher<T>> subMatcher;
|
||||
|
||||
private ExceptionMatcher(Class<T> exceptionType) {
|
||||
super(exceptionType);
|
||||
this.exceptionType = exceptionType;
|
||||
this.subMatcher = Optional.empty();
|
||||
}
|
||||
|
||||
private ExceptionMatcher(Class<T> exceptionType, Matcher<T> subMatcher) {
|
||||
super(exceptionType);
|
||||
this.exceptionType = exceptionType;
|
||||
this.subMatcher = Optional.of(subMatcher);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void describeTo(Description description) {
|
||||
subMatcher.ifPresent(description::appendDescriptionOf);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean matchesSafely(T item, Description mismatchDescription) {
|
||||
if (subMatcher.map(matcher -> !matcher.matches(item)).orElse(false)) {
|
||||
subMatcher.get().describeMismatch(item, mismatchDescription);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public Matcher<T> withCauseThat(Matcher<? super Throwable> matcher) {
|
||||
return new ExceptionMatcher<T>(exceptionType, new PropertyMatcher<>(exceptionType, Throwable::getCause, "cause", matcher));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package org.cryptomator.common.test.matcher;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.hamcrest.Description;
|
||||
import org.hamcrest.Matcher;
|
||||
import org.hamcrest.TypeSafeDiagnosingMatcher;
|
||||
|
||||
public class OptionalMatcher {
|
||||
|
||||
public static <T> Matcher<Optional<T>> presentOptionalWithValueThat(Matcher<? super T> valueMatcher) {
|
||||
return new TypeSafeDiagnosingMatcher<Optional<T>>(Optional.class) {
|
||||
@Override
|
||||
public void describeTo(Description description) {
|
||||
description //
|
||||
.appendText("a present Optional with a value that ") //
|
||||
.appendDescriptionOf(valueMatcher);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean matchesSafely(Optional<T> item, Description mismatchDescription) {
|
||||
if (item.isPresent()) {
|
||||
if (valueMatcher.matches(item.get())) {
|
||||
return true;
|
||||
} else {
|
||||
mismatchDescription.appendText("a present Optional with value that ");
|
||||
valueMatcher.describeMismatch(item, mismatchDescription);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
mismatchDescription.appendText("an empty Optional");
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
public static <T> Matcher<Optional<T>> emptyOptional() {
|
||||
return new TypeSafeDiagnosingMatcher<Optional<T>>(Optional.class) {
|
||||
@Override
|
||||
public void describeTo(Description description) {
|
||||
description.appendText("an empty Optional");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean matchesSafely(Optional<T> item, Description mismatchDescription) {
|
||||
if (item.isPresent()) {
|
||||
mismatchDescription.appendText("a present Optional of ").appendValue(item.get());
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Markus Kreusch
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
******************************************************************************/
|
||||
package org.cryptomator.common.test.matcher;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.hamcrest.Description;
|
||||
import org.hamcrest.Matcher;
|
||||
import org.hamcrest.TypeSafeDiagnosingMatcher;
|
||||
|
||||
public class PropertyMatcher<T, P> extends TypeSafeDiagnosingMatcher<T> {
|
||||
|
||||
private final Class<T> expectedType;
|
||||
private final Function<? super T, P> getter;
|
||||
private final String name;
|
||||
private final Matcher<? super P> subMatcher;
|
||||
|
||||
public PropertyMatcher(Class<T> type, Function<? super T, P> getter, String name, Matcher<? super P> subMatcher) {
|
||||
super(type);
|
||||
this.expectedType = type;
|
||||
this.getter = getter;
|
||||
this.name = name;
|
||||
this.subMatcher = subMatcher;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void describeTo(Description description) {
|
||||
description.appendText("a ") //
|
||||
.appendText(expectedType.getSimpleName()) //
|
||||
.appendText(" with a ") //
|
||||
.appendText(name) //
|
||||
.appendText(" that ") //
|
||||
.appendDescriptionOf(subMatcher);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean matchesSafely(T item, Description mismatchDescription) {
|
||||
P propertyValue = getter.apply(item);
|
||||
if (subMatcher.matches(propertyValue)) {
|
||||
return true;
|
||||
} else {
|
||||
mismatchDescription.appendText("a ") //
|
||||
.appendText(expectedType.getSimpleName()) //
|
||||
.appendText(" with a ") //
|
||||
.appendText(name) //
|
||||
.appendText(" that ");
|
||||
subMatcher.describeMismatch(propertyValue, mismatchDescription);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package org.cryptomator.common.test.mockito;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
public class Answers {
|
||||
|
||||
public static <T> Answer<T> collectParameters(Answer<T> answer, Consumer<?>... parameterConsumers) {
|
||||
return new Answer<T>() {
|
||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||
@Override
|
||||
public T answer(InvocationOnMock invocation) throws Throwable {
|
||||
for (int i = 0; i < invocation.getArguments().length; i++) {
|
||||
if (parameterConsumers.length > i) {
|
||||
((Consumer) parameterConsumers[i]).accept(invocation.getArguments()[i]);
|
||||
}
|
||||
}
|
||||
return answer.answer(invocation);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
public static <T> Answer<T> consecutiveAnswers(Answer<T>... answers) {
|
||||
if (answers == null || answers.length == 0) {
|
||||
throw new IllegalArgumentException("Required at least one answer");
|
||||
}
|
||||
if (asList(answers).contains(null)) {
|
||||
throw new IllegalArgumentException("No answers must be null");
|
||||
}
|
||||
return new Answer<T>() {
|
||||
private int nextIndex = 0;
|
||||
|
||||
@Override
|
||||
public T answer(InvocationOnMock invocation) throws Throwable {
|
||||
try {
|
||||
return answers[nextIndex].answer(invocation);
|
||||
} finally {
|
||||
nextIndex = (nextIndex + 1) % answers.length;
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
public static <T> Answer<T> value(T value) {
|
||||
return new Answer<T>() {
|
||||
@Override
|
||||
public T answer(InvocationOnMock invocation) throws Throwable {
|
||||
return value;
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -10,10 +10,10 @@
|
||||
<parent>
|
||||
<groupId>org.cryptomator</groupId>
|
||||
<artifactId>main</artifactId>
|
||||
<version>1.2.3</version>
|
||||
<version>1.3.0-rc6</version>
|
||||
</parent>
|
||||
<artifactId>commons</artifactId>
|
||||
<name>Cryptomator common</name>
|
||||
<name>Cryptomator Commons</name>
|
||||
<description>Shared utilities</description>
|
||||
|
||||
<dependencies>
|
||||
@@ -26,47 +26,26 @@
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.fxmisc.easybind</groupId>
|
||||
<artifactId>easybind</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- DI -->
|
||||
<dependency>
|
||||
<groupId>com.google.dagger</groupId>
|
||||
<artifactId>dagger</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.dagger</groupId>
|
||||
<artifactId>dagger-compiler</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Test -->
|
||||
<!-- Logging -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>de.bechte.junit</groupId>
|
||||
<artifactId>junit-hierarchicalcontextrunner</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-all</artifactId>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
package org.cryptomator.common;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class CachingSupplier<T> implements Supplier<T> {
|
||||
|
||||
public static <T> Supplier<T> from(Supplier<T> delegate) {
|
||||
return new CachingSupplier<>(delegate);
|
||||
}
|
||||
|
||||
private Supplier<T> delegate;
|
||||
|
||||
private CachingSupplier(Supplier<T> delegate) {
|
||||
this.delegate = () -> {
|
||||
T result = delegate.get();
|
||||
CachingSupplier.this.delegate = () -> result;
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public T get() {
|
||||
return delegate.get();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package org.cryptomator.common;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class Holder<V> implements Supplier<V>, Consumer<V> {
|
||||
|
||||
private final V initial;
|
||||
|
||||
private V value;
|
||||
|
||||
public <W extends V> Holder(W initial) {
|
||||
this.initial = initial;
|
||||
reset();
|
||||
}
|
||||
|
||||
public V get() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void set(V value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
set(initial);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(V value) {
|
||||
set(value);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,6 +2,9 @@ package org.cryptomator.common;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
import com.google.common.base.Throwables;
|
||||
|
||||
public final class LazyInitializer {
|
||||
|
||||
@@ -9,7 +12,7 @@ public final class LazyInitializer {
|
||||
}
|
||||
|
||||
/**
|
||||
* Threadsafe lazy initialization pattern as proposed on http://stackoverflow.com/a/30247202/4014509
|
||||
* Same as {@link #initializeLazily(AtomicReference, SupplierThrowingException, Class)} except that no checked exception may be thrown by the factory function.
|
||||
*
|
||||
* @param <T> Type of the value
|
||||
* @param reference A reference to a maybe not yet initialized value.
|
||||
@@ -17,18 +20,56 @@ public final class LazyInitializer {
|
||||
* @return The initialized value
|
||||
*/
|
||||
public static <T> T initializeLazily(AtomicReference<T> reference, Supplier<T> factory) {
|
||||
SupplierThrowingException<T, RuntimeException> factoryThrowingRuntimeExceptions = () -> factory.get();
|
||||
return initializeLazily(reference, factoryThrowingRuntimeExceptions, RuntimeException.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Threadsafe lazy initialization pattern as proposed on http://stackoverflow.com/a/30247202/4014509
|
||||
*
|
||||
* @param <T> Type of the value
|
||||
* @param <E> Type of the any expected exception that may occur during initialization
|
||||
* @param reference A reference to a maybe not yet initialized value.
|
||||
* @param factory A factory providing a value for the reference, if it doesn't exist yet. The factory may be invoked multiple times, but only one result will survive.
|
||||
* @param exceptionType Expected exception type.
|
||||
* @return The initialized value
|
||||
* @throws E Exception thrown by the factory function.
|
||||
*/
|
||||
public static <T, E extends Exception> T initializeLazily(AtomicReference<T> reference, SupplierThrowingException<T, E> factory, Class<E> exceptionType) throws E {
|
||||
final T existing = reference.get();
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
} else {
|
||||
return reference.updateAndGet(currentValue -> {
|
||||
if (currentValue == null) {
|
||||
return factory.get();
|
||||
} else {
|
||||
return currentValue;
|
||||
}
|
||||
});
|
||||
try {
|
||||
return reference.updateAndGet(invokeFactoryIfNull(factory));
|
||||
} catch (InitializationException e) {
|
||||
Throwables.throwIfUnchecked(e);
|
||||
Throwables.throwIfInstanceOf(e.getCause(), exceptionType);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static <T, E extends Exception> UnaryOperator<T> invokeFactoryIfNull(SupplierThrowingException<T, E> factory) throws InitializationException {
|
||||
return currentValue -> {
|
||||
if (currentValue == null) {
|
||||
try {
|
||||
return factory.get();
|
||||
} catch (Exception e) {
|
||||
Throwables.throwIfUnchecked(e); // don't catch unchecked exceptions
|
||||
throw new InitializationException(e);
|
||||
}
|
||||
} else {
|
||||
return currentValue;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static class InitializationException extends RuntimeException {
|
||||
|
||||
public InitializationException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
package org.cryptomator.common;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
public final class Optionals {
|
||||
|
||||
private Optionals() {
|
||||
}
|
||||
|
||||
public static <T, E extends Exception> void ifPresent(Optional<T> optional, ConsumerThrowingException<T, E> consumer) throws E {
|
||||
final T t = optional.orElse(null);
|
||||
if (t != null) {
|
||||
consumer.accept(t);
|
||||
}
|
||||
/**
|
||||
* Returns a function that is equivalent to the input function but immediately gets the value of the returned optional when invoked.
|
||||
*
|
||||
* @param <T> the type of the input to the function
|
||||
* @param <R> the type of the result of the function
|
||||
* @param function An {@code Optional}-bearing input function {@code Function<Foo, Optional<Bar>>}
|
||||
* @return A {@code Function<Foo, Bar>}, that may throw a NoSuchElementException, if the original function returns an empty optional.
|
||||
*/
|
||||
public static <T, R> Function<T, R> unwrap(Function<T, Optional<R>> function) {
|
||||
return t -> function.apply(t).get();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -12,12 +12,51 @@ import java.util.Comparator;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
/**
|
||||
* Compares version strings according to <a href="http://semver.org/spec/v2.0.0.html">SemVer 2.0.0</a>.
|
||||
*/
|
||||
public class SemVerComparator implements Comparator<String> {
|
||||
|
||||
private static final char VERSION_SEP = '.'; // http://semver.org/spec/v2.0.0.html#spec-item-2
|
||||
private static final String PRE_RELEASE_SEP = "-"; // http://semver.org/spec/v2.0.0.html#spec-item-9
|
||||
private static final String BUILD_SEP = "+"; // http://semver.org/spec/v2.0.0.html#spec-item-10
|
||||
|
||||
@Override
|
||||
public int compare(String version1, String version2) {
|
||||
final String[] vComps1 = StringUtils.split(version1, '.');
|
||||
final String[] vComps2 = StringUtils.split(version2, '.');
|
||||
// "Build metadata SHOULD be ignored when determining version precedence.
|
||||
// Thus two versions that differ only in the build metadata, have the same precedence."
|
||||
String v1WithoutBuildMetadata = StringUtils.substringBefore(version1, BUILD_SEP);
|
||||
String v2WithoutBuildMetadata = StringUtils.substringBefore(version2, BUILD_SEP);
|
||||
|
||||
if (v1WithoutBuildMetadata.equals(v2WithoutBuildMetadata)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
String v1MajorMinorPatch = StringUtils.substringBefore(v1WithoutBuildMetadata, PRE_RELEASE_SEP);
|
||||
String v2MajorMinorPatch = StringUtils.substringBefore(v2WithoutBuildMetadata, PRE_RELEASE_SEP);
|
||||
String v1PreReleaseVersion = StringUtils.substringAfter(v1WithoutBuildMetadata, PRE_RELEASE_SEP);
|
||||
String v2PreReleaseVersion = StringUtils.substringAfter(v2WithoutBuildMetadata, PRE_RELEASE_SEP);
|
||||
return compare(v1MajorMinorPatch, v1PreReleaseVersion, v2MajorMinorPatch, v2PreReleaseVersion);
|
||||
}
|
||||
|
||||
private int compare(String v1MajorMinorPatch, String v1PreReleaseVersion, String v2MajorMinorPatch, String v2PreReleaseVersion) {
|
||||
int comparisonResult = compareNumericallyThenLexicographically(v1MajorMinorPatch, v2MajorMinorPatch);
|
||||
if (comparisonResult == 0) {
|
||||
if (v1PreReleaseVersion.isEmpty()) {
|
||||
return 1; // 1.0.0 > 1.0.0-BETA
|
||||
} else if (v2PreReleaseVersion.isEmpty()) {
|
||||
return -1; // 1.0.0-BETA < 1.0.0
|
||||
} else {
|
||||
return compareNumericallyThenLexicographically(v1PreReleaseVersion, v2PreReleaseVersion);
|
||||
}
|
||||
} else {
|
||||
return comparisonResult;
|
||||
}
|
||||
}
|
||||
|
||||
private int compareNumericallyThenLexicographically(String version1, String version2) {
|
||||
final String[] vComps1 = StringUtils.split(version1, VERSION_SEP);
|
||||
final String[] vComps2 = StringUtils.split(version2, VERSION_SEP);
|
||||
final int commonCompCount = Math.min(vComps1.length, vComps2.length);
|
||||
|
||||
for (int i = 0; i < commonCompCount; i++) {
|
||||
@@ -35,7 +74,7 @@ public class SemVerComparator implements Comparator<String> {
|
||||
}
|
||||
}
|
||||
|
||||
// all in common so far? longest version string wins:
|
||||
// all in common so far? longest version string is considered the higher version:
|
||||
return vComps1.length - vComps2.length;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2016 Markus Kreusch and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Markus Kreusch - initial implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.common;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Utility to print stack traces while analyzing issues.
|
||||
*
|
||||
* @author Markus Kreusch
|
||||
*/
|
||||
public class StackTrace {
|
||||
|
||||
public static void print(String message) {
|
||||
Thread thread = Thread.currentThread();
|
||||
System.err.println(stackTraceFor(message, thread));
|
||||
}
|
||||
|
||||
private static String stackTraceFor(String message, Thread thread) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
appendMessageAndThreadName(result, message, thread);
|
||||
appendStackTrace(thread, result);
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private static void appendStackTrace(Thread thread, StringBuilder result) {
|
||||
Stream.of(thread.getStackTrace()) //
|
||||
.skip(4) //
|
||||
.forEach(stackTraceElement -> append(stackTraceElement, result));
|
||||
}
|
||||
|
||||
private static void appendMessageAndThreadName(StringBuilder result, String message, Thread thread) {
|
||||
result //
|
||||
.append('[') //
|
||||
.append(thread.getName()) //
|
||||
.append("] ") //
|
||||
.append(message);
|
||||
}
|
||||
|
||||
private static void append(StackTraceElement stackTraceElement, StringBuilder result) {
|
||||
String className = stackTraceElement.getClassName();
|
||||
String methodName = stackTraceElement.getMethodName();
|
||||
String fileName = stackTraceElement.getFileName();
|
||||
int lineNumber = stackTraceElement.getLineNumber();
|
||||
result.append('\n') //
|
||||
.append(className).append(':').append(methodName) //
|
||||
.append(" (").append(fileName).append(':').append(lineNumber).append(')');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package org.cryptomator.common;
|
||||
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
import com.google.common.util.concurrent.ExecutionError;
|
||||
import com.google.common.util.concurrent.UncheckedExecutionException;
|
||||
|
||||
public class WeakValuedCache<Key, Value> {
|
||||
|
||||
private final LoadingCache<Key, Value> delegate;
|
||||
|
||||
private WeakValuedCache(Function<Key, Value> loader) {
|
||||
delegate = CacheBuilder.newBuilder() //
|
||||
.weakValues() //
|
||||
.build(new CacheLoader<Key, Value>() {
|
||||
@Override
|
||||
public Value load(Key key) {
|
||||
return loader.apply(key);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static <Key, Value> WeakValuedCache<Key, Value> usingLoader(Function<Key, Value> loader) {
|
||||
return new WeakValuedCache<>(loader);
|
||||
}
|
||||
|
||||
public Value get(Key key) {
|
||||
try {
|
||||
return delegate.get(key);
|
||||
} catch (ExecutionException e) {
|
||||
throw new IllegalStateException("No checked exception can be thrown by loader", e);
|
||||
} catch (UncheckedExecutionException e) {
|
||||
throw (RuntimeException) e.getCause();
|
||||
} catch (ExecutionError e) {
|
||||
throw (Error) e.getCause();
|
||||
}
|
||||
}
|
||||
|
||||
public void forEach(BiConsumer<Key, Value> function) {
|
||||
delegate.asMap().forEach(function);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2014, 2016 Sebastian Stenzel
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
******************************************************************************/
|
||||
package org.cryptomator.common.settings;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.apache.commons.lang3.SystemUtils;
|
||||
|
||||
import javafx.beans.property.BooleanProperty;
|
||||
import javafx.beans.property.IntegerProperty;
|
||||
import javafx.beans.property.SimpleBooleanProperty;
|
||||
import javafx.beans.property.SimpleIntegerProperty;
|
||||
import javafx.beans.property.SimpleStringProperty;
|
||||
import javafx.beans.property.StringProperty;
|
||||
import javafx.beans.value.ObservableValue;
|
||||
import javafx.collections.FXCollections;
|
||||
import javafx.collections.ListChangeListener;
|
||||
import javafx.collections.ObservableList;
|
||||
|
||||
public class Settings {
|
||||
|
||||
public static final int MIN_PORT = 1024;
|
||||
public static final int MAX_PORT = 65535;
|
||||
public static final boolean DEFAULT_CHECK_FOR_UDPATES = true;
|
||||
public static final int DEFAULT_PORT = 42427;
|
||||
public static final boolean DEFAULT_USE_IPV6 = SystemUtils.IS_OS_WINDOWS;
|
||||
public static final int DEFAULT_NUM_TRAY_NOTIFICATIONS = 3;
|
||||
public static final String DEFAULT_GVFS_SCHEME = "dav";
|
||||
public static final boolean DEFAULT_DEBUG_MODE = false;
|
||||
|
||||
private final ObservableList<VaultSettings> directories = FXCollections.observableArrayList(VaultSettings::observables);
|
||||
private final BooleanProperty checkForUpdates = new SimpleBooleanProperty(DEFAULT_CHECK_FOR_UDPATES);
|
||||
private final IntegerProperty port = new SimpleIntegerProperty(DEFAULT_PORT);
|
||||
private final BooleanProperty useIpv6 = new SimpleBooleanProperty(DEFAULT_USE_IPV6);
|
||||
private final IntegerProperty numTrayNotifications = new SimpleIntegerProperty(DEFAULT_NUM_TRAY_NOTIFICATIONS);
|
||||
private final StringProperty preferredGvfsScheme = new SimpleStringProperty(DEFAULT_GVFS_SCHEME);
|
||||
private final BooleanProperty debugMode = new SimpleBooleanProperty(DEFAULT_DEBUG_MODE);
|
||||
private Consumer<Settings> saveCmd;
|
||||
|
||||
/**
|
||||
* Package-private constructor; use {@link SettingsProvider}.
|
||||
*/
|
||||
Settings() {
|
||||
directories.addListener((ListChangeListener.Change<? extends VaultSettings> change) -> this.save());
|
||||
checkForUpdates.addListener(this::somethingChanged);
|
||||
port.addListener(this::somethingChanged);
|
||||
useIpv6.addListener(this::somethingChanged);
|
||||
numTrayNotifications.addListener(this::somethingChanged);
|
||||
preferredGvfsScheme.addListener(this::somethingChanged);
|
||||
debugMode.addListener(this::somethingChanged);
|
||||
}
|
||||
|
||||
void setSaveCmd(Consumer<Settings> saveCmd) {
|
||||
this.saveCmd = saveCmd;
|
||||
}
|
||||
|
||||
private void somethingChanged(ObservableValue<?> observable, Object oldValue, Object newValue) {
|
||||
this.save();
|
||||
}
|
||||
|
||||
void save() {
|
||||
if (saveCmd != null) {
|
||||
saveCmd.accept(this);
|
||||
}
|
||||
}
|
||||
|
||||
/* Getter/Setter */
|
||||
|
||||
public ObservableList<VaultSettings> getDirectories() {
|
||||
return directories;
|
||||
}
|
||||
|
||||
public BooleanProperty checkForUpdates() {
|
||||
return checkForUpdates;
|
||||
}
|
||||
|
||||
public IntegerProperty port() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public BooleanProperty useIpv6() {
|
||||
return useIpv6;
|
||||
}
|
||||
|
||||
public IntegerProperty numTrayNotifications() {
|
||||
return numTrayNotifications;
|
||||
}
|
||||
|
||||
public StringProperty preferredGvfsScheme() {
|
||||
return preferredGvfsScheme;
|
||||
}
|
||||
|
||||
public BooleanProperty debugMode() {
|
||||
return debugMode;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2017 Skymatic UG (haftungsbeschränkt).
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the accompanying LICENSE file.
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.common.settings;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.gson.TypeAdapter;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonToken;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
|
||||
public class SettingsJsonAdapter extends TypeAdapter<Settings> {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(SettingsJsonAdapter.class);
|
||||
|
||||
private final VaultSettingsJsonAdapter vaultSettingsJsonAdapter = new VaultSettingsJsonAdapter();
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter out, Settings value) throws IOException {
|
||||
out.beginObject();
|
||||
out.name("directories");
|
||||
writeVaultSettingsArray(out, value.getDirectories());
|
||||
out.name("checkForUpdatesEnabled").value(value.checkForUpdates().get());
|
||||
out.name("port").value(value.port().get());
|
||||
out.name("useIpv6").value(value.useIpv6().get());
|
||||
out.name("numTrayNotifications").value(value.numTrayNotifications().get());
|
||||
out.name("preferredGvfsScheme").value(value.preferredGvfsScheme().get());
|
||||
out.name("debugMode").value(value.debugMode().get());
|
||||
out.endObject();
|
||||
}
|
||||
|
||||
private void writeVaultSettingsArray(JsonWriter out, Iterable<VaultSettings> vaultSettings) throws IOException {
|
||||
out.beginArray();
|
||||
for (VaultSettings value : vaultSettings) {
|
||||
vaultSettingsJsonAdapter.write(out, value);
|
||||
}
|
||||
out.endArray();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Settings read(JsonReader in) throws IOException {
|
||||
Settings settings = new Settings();
|
||||
|
||||
in.beginObject();
|
||||
while (in.hasNext()) {
|
||||
String name = in.nextName();
|
||||
switch (name) {
|
||||
case "directories":
|
||||
settings.getDirectories().addAll(readVaultSettingsArray(in));
|
||||
break;
|
||||
case "checkForUpdatesEnabled":
|
||||
settings.checkForUpdates().set(in.nextBoolean());
|
||||
break;
|
||||
case "port":
|
||||
settings.port().set(in.nextInt());
|
||||
break;
|
||||
case "useIpv6":
|
||||
// Temporarily we will disable loading this setting, as we want the default value on each app start.
|
||||
// This setting might be removed completely in the future
|
||||
// settings.useIpv6().set(in.nextBoolean());
|
||||
in.skipValue();
|
||||
break;
|
||||
case "numTrayNotifications":
|
||||
settings.numTrayNotifications().set(in.nextInt());
|
||||
break;
|
||||
case "preferredGvfsScheme":
|
||||
settings.preferredGvfsScheme().set(in.nextString());
|
||||
break;
|
||||
case "debugMode":
|
||||
settings.debugMode().set(in.nextBoolean());
|
||||
break;
|
||||
default:
|
||||
LOG.warn("Unsupported vault setting found in JSON: " + name);
|
||||
in.skipValue();
|
||||
}
|
||||
}
|
||||
in.endObject();
|
||||
|
||||
return settings;
|
||||
}
|
||||
|
||||
private List<VaultSettings> readVaultSettingsArray(JsonReader in) throws IOException {
|
||||
List<VaultSettings> result = new ArrayList<>();
|
||||
in.beginArray();
|
||||
while (!JsonToken.END_ARRAY.equals(in.peek())) {
|
||||
result.add(vaultSettingsJsonAdapter.read(in));
|
||||
}
|
||||
in.endArray();
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,17 +6,21 @@
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.ui.settings;
|
||||
package org.cryptomator.common.settings;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.Reader;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.FileSystem;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
@@ -25,16 +29,17 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Named;
|
||||
import javax.inject.Provider;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.SystemUtils;
|
||||
import org.cryptomator.common.LazyInitializer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
@Singleton
|
||||
public class SettingsProvider implements Provider<Settings> {
|
||||
@@ -54,16 +59,21 @@ public class SettingsProvider implements Provider<Settings> {
|
||||
}
|
||||
}
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ScheduledExecutorService saveScheduler = Executors.newSingleThreadScheduledExecutor();
|
||||
private final AtomicReference<ScheduledFuture<?>> scheduledSaveCmd = new AtomicReference<>();
|
||||
private final AtomicReference<Settings> settings = new AtomicReference<>();
|
||||
private final SettingsJsonAdapter settingsJsonAdapter = new SettingsJsonAdapter();
|
||||
private final Gson gson;
|
||||
|
||||
@Inject
|
||||
public SettingsProvider(@Named("VaultJsonMapper") ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
public SettingsProvider() {
|
||||
this.gson = new GsonBuilder() //
|
||||
.setPrettyPrinting().setLenient().disableHtmlEscaping() //
|
||||
.registerTypeAdapter(Settings.class, settingsJsonAdapter) //
|
||||
.create();
|
||||
}
|
||||
|
||||
private Path getSettingsPath() throws IOException {
|
||||
private Path getSettingsPath() {
|
||||
final String settingsPathProperty = System.getProperty("cryptomator.settingsPath");
|
||||
return Optional.ofNullable(settingsPathProperty).filter(StringUtils::isNotBlank).map(this::replaceHomeDir).map(FileSystems.getDefault()::getPath).orElse(DEFAULT_SETTINGS_PATH);
|
||||
}
|
||||
@@ -78,15 +88,24 @@ public class SettingsProvider implements Provider<Settings> {
|
||||
|
||||
@Override
|
||||
public Settings get() {
|
||||
final Settings settings = new Settings(this::scheduleSave);
|
||||
try {
|
||||
final Path settingsPath = getSettingsPath();
|
||||
final InputStream in = Files.newInputStream(settingsPath, StandardOpenOption.READ);
|
||||
objectMapper.readerForUpdating(settings).readValue(in);
|
||||
return LazyInitializer.initializeLazily(settings, this::load);
|
||||
}
|
||||
|
||||
private Settings load() {
|
||||
Settings settings;
|
||||
final Path settingsPath = getSettingsPath();
|
||||
try (InputStream in = Files.newInputStream(settingsPath, StandardOpenOption.READ); //
|
||||
Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
|
||||
settings = gson.fromJson(reader, Settings.class);
|
||||
if (settings == null) {
|
||||
throw new IOException("Unexpected EOF");
|
||||
}
|
||||
LOG.info("Settings loaded from " + settingsPath);
|
||||
} catch (IOException e) {
|
||||
LOG.info("Failed to load settings, creating new one.");
|
||||
settings = new Settings();
|
||||
}
|
||||
settings.setSaveCmd(this::scheduleSave);
|
||||
return settings;
|
||||
}
|
||||
|
||||
@@ -104,13 +123,15 @@ public class SettingsProvider implements Provider<Settings> {
|
||||
}
|
||||
|
||||
private void save(Settings settings) {
|
||||
Objects.requireNonNull(settings);
|
||||
assert settings != null : "method should only be invoked by #scheduleSave, which checks for null";
|
||||
final Path settingsPath = getSettingsPath();
|
||||
try {
|
||||
final Path settingsPath = getSettingsPath();
|
||||
Files.createDirectories(settingsPath.getParent());
|
||||
final OutputStream out = Files.newOutputStream(settingsPath, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
|
||||
objectMapper.writeValue(out, settings);
|
||||
LOG.info("Settings saved to " + settingsPath);
|
||||
try (OutputStream out = Files.newOutputStream(settingsPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); //
|
||||
Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
|
||||
gson.toJson(settings, writer);
|
||||
LOG.info("Settings saved to " + settingsPath);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.error("Failed to save settings.", e);
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2017 Skymatic UG (haftungsbeschränkt).
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the accompanying LICENSE file.
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.common.settings;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Base64;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.fxmisc.easybind.EasyBind;
|
||||
|
||||
import javafx.beans.Observable;
|
||||
import javafx.beans.property.BooleanProperty;
|
||||
import javafx.beans.property.ObjectProperty;
|
||||
import javafx.beans.property.SimpleBooleanProperty;
|
||||
import javafx.beans.property.SimpleObjectProperty;
|
||||
import javafx.beans.property.SimpleStringProperty;
|
||||
import javafx.beans.property.StringProperty;
|
||||
|
||||
public class VaultSettings {
|
||||
|
||||
public static final boolean DEFAULT_UNLOCK_AFTER_STARTUP = false;
|
||||
public static final boolean DEFAULT_MOUNT_AFTER_UNLOCK = true;
|
||||
public static final boolean DEFAULT_REAVEAL_AFTER_MOUNT = true;
|
||||
|
||||
private final String id;
|
||||
private final ObjectProperty<Path> path = new SimpleObjectProperty<>();
|
||||
private final StringProperty mountName = new SimpleStringProperty();
|
||||
private final StringProperty winDriveLetter = new SimpleStringProperty();
|
||||
private final BooleanProperty unlockAfterStartup = new SimpleBooleanProperty(DEFAULT_UNLOCK_AFTER_STARTUP);
|
||||
private final BooleanProperty mountAfterUnlock = new SimpleBooleanProperty(DEFAULT_MOUNT_AFTER_UNLOCK);
|
||||
private final BooleanProperty revealAfterMount = new SimpleBooleanProperty(DEFAULT_REAVEAL_AFTER_MOUNT);
|
||||
|
||||
public VaultSettings(String id) {
|
||||
this.id = Objects.requireNonNull(id);
|
||||
|
||||
EasyBind.subscribe(path, this::deriveMountNameFromPath);
|
||||
}
|
||||
|
||||
Observable[] observables() {
|
||||
return new Observable[] {path, mountName, winDriveLetter, unlockAfterStartup, mountAfterUnlock, revealAfterMount};
|
||||
}
|
||||
|
||||
private void deriveMountNameFromPath(Path path) {
|
||||
if (path != null && StringUtils.isBlank(mountName.get())) {
|
||||
mountName.set(normalizeMountName(path.getFileName().toString()));
|
||||
}
|
||||
}
|
||||
|
||||
public static VaultSettings withRandomId() {
|
||||
return new VaultSettings(generateId());
|
||||
}
|
||||
|
||||
private static String generateId() {
|
||||
return asBase64String(nineBytesFrom(UUID.randomUUID()));
|
||||
}
|
||||
|
||||
private static String asBase64String(byte[] bytes) {
|
||||
byte[] base64Bytes = Base64.getUrlEncoder().encode(bytes);
|
||||
return new String(base64Bytes, StandardCharsets.US_ASCII);
|
||||
}
|
||||
|
||||
private static byte[] nineBytesFrom(UUID uuid) {
|
||||
ByteBuffer uuidBuffer = ByteBuffer.allocate(9);
|
||||
uuidBuffer.putLong(uuid.getMostSignificantBits());
|
||||
uuidBuffer.put((byte) (uuid.getLeastSignificantBits() & 0xFF));
|
||||
uuidBuffer.flip();
|
||||
return uuidBuffer.array();
|
||||
}
|
||||
|
||||
public static String normalizeMountName(String mountName) {
|
||||
String normalizedMountName = StringUtils.stripAccents(mountName);
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (char c : normalizedMountName.toCharArray()) {
|
||||
if (Character.isWhitespace(c)) {
|
||||
if (builder.length() == 0 || builder.charAt(builder.length() - 1) != '_') {
|
||||
builder.append('_');
|
||||
}
|
||||
} else if (c < 127 && Character.isLetterOrDigit(c)) {
|
||||
builder.append(c);
|
||||
} else {
|
||||
if (builder.length() == 0 || builder.charAt(builder.length() - 1) != '_') {
|
||||
builder.append('_');
|
||||
}
|
||||
}
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/* Getter/Setter */
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public ObjectProperty<Path> path() {
|
||||
return path;
|
||||
}
|
||||
|
||||
public StringProperty mountName() {
|
||||
return mountName;
|
||||
}
|
||||
|
||||
public StringProperty winDriveLetter() {
|
||||
return winDriveLetter;
|
||||
}
|
||||
|
||||
public BooleanProperty unlockAfterStartup() {
|
||||
return unlockAfterStartup;
|
||||
}
|
||||
|
||||
public BooleanProperty mountAfterUnlock() {
|
||||
return mountAfterUnlock;
|
||||
}
|
||||
|
||||
public BooleanProperty revealAfterMount() {
|
||||
return revealAfterMount;
|
||||
}
|
||||
|
||||
/* Hashcode/Equals */
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof VaultSettings && obj.getClass().equals(this.getClass())) {
|
||||
VaultSettings other = (VaultSettings) obj;
|
||||
return Objects.equals(this.id, other.id);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2017 Skymatic UG (haftungsbeschränkt).
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the accompanying LICENSE file.
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.common.settings;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
|
||||
class VaultSettingsJsonAdapter {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(VaultSettingsJsonAdapter.class);
|
||||
|
||||
public void write(JsonWriter out, VaultSettings value) throws IOException {
|
||||
out.beginObject();
|
||||
out.name("id").value(value.getId());
|
||||
out.name("path").value(value.path().get().toString());
|
||||
out.name("mountName").value(value.mountName().get());
|
||||
out.name("winDriveLetter").value(value.winDriveLetter().get());
|
||||
out.name("unlockAfterStartup").value(value.unlockAfterStartup().get());
|
||||
out.name("mountAfterUnlock").value(value.mountAfterUnlock().get());
|
||||
out.name("revealAfterMount").value(value.revealAfterMount().get());
|
||||
out.endObject();
|
||||
}
|
||||
|
||||
public VaultSettings read(JsonReader in) throws IOException {
|
||||
String id = null;
|
||||
String path = null;
|
||||
String mountName = null;
|
||||
String winDriveLetter = null;
|
||||
boolean unlockAfterStartup = VaultSettings.DEFAULT_UNLOCK_AFTER_STARTUP;
|
||||
boolean mountAfterUnlock = VaultSettings.DEFAULT_MOUNT_AFTER_UNLOCK;
|
||||
boolean revealAfterMount = VaultSettings.DEFAULT_REAVEAL_AFTER_MOUNT;
|
||||
|
||||
in.beginObject();
|
||||
while (in.hasNext()) {
|
||||
String name = in.nextName();
|
||||
switch (name) {
|
||||
case "id":
|
||||
id = in.nextString();
|
||||
break;
|
||||
case "path":
|
||||
path = in.nextString();
|
||||
break;
|
||||
case "mountName":
|
||||
mountName = in.nextString();
|
||||
break;
|
||||
case "winDriveLetter":
|
||||
winDriveLetter = in.nextString();
|
||||
break;
|
||||
case "unlockAfterStartup":
|
||||
unlockAfterStartup = in.nextBoolean();
|
||||
break;
|
||||
case "mountAfterUnlock":
|
||||
mountAfterUnlock = in.nextBoolean();
|
||||
break;
|
||||
case "revealAfterMount":
|
||||
revealAfterMount = in.nextBoolean();
|
||||
break;
|
||||
default:
|
||||
LOG.warn("Unsupported vault setting found in JSON: " + name);
|
||||
in.skipValue();
|
||||
}
|
||||
}
|
||||
in.endObject();
|
||||
|
||||
VaultSettings vaultSettings = (id == null) ? VaultSettings.withRandomId() : new VaultSettings(id);
|
||||
vaultSettings.mountName().set(mountName);
|
||||
vaultSettings.path().set(Paths.get(path));
|
||||
vaultSettings.winDriveLetter().set(winDriveLetter);
|
||||
vaultSettings.unlockAfterStartup().set(unlockAfterStartup);
|
||||
vaultSettings.mountAfterUnlock().set(mountAfterUnlock);
|
||||
vaultSettings.revealAfterMount().set(revealAfterMount);
|
||||
return vaultSettings;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
package org.cryptomator.common.streams;
|
||||
|
||||
import static org.cryptomator.common.streams.AutoClosingStreamFactory.AUTO_CLOSING_STREAM_FACTORY;
|
||||
|
||||
import java.util.DoubleSummaryStatistics;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.DoubleBinaryOperator;
|
||||
import java.util.function.DoubleConsumer;
|
||||
import java.util.function.DoublePredicate;
|
||||
import java.util.function.ObjDoubleConsumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.DoubleStream;
|
||||
|
||||
public class AutoClosingDoubleStream extends DelegatingDoubleStream {
|
||||
|
||||
public static DoubleStream from(DoubleStream delegate) {
|
||||
return new AutoClosingDoubleStream(delegate);
|
||||
}
|
||||
|
||||
public AutoClosingDoubleStream(DoubleStream delegate) {
|
||||
super(delegate, AUTO_CLOSING_STREAM_FACTORY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forEach(DoubleConsumer action) {
|
||||
try {
|
||||
super.forEach(action);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forEachOrdered(DoubleConsumer action) {
|
||||
try {
|
||||
super.forEachOrdered(action);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public double[] toArray() {
|
||||
try {
|
||||
return super.toArray();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public double reduce(double identity, DoubleBinaryOperator op) {
|
||||
try {
|
||||
return super.reduce(identity, op);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalDouble reduce(DoubleBinaryOperator op) {
|
||||
try {
|
||||
return super.reduce(op);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <R> R collect(Supplier<R> supplier, ObjDoubleConsumer<R> accumulator, BiConsumer<R, R> combiner) {
|
||||
try {
|
||||
return super.collect(supplier, accumulator, combiner);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public double sum() {
|
||||
try {
|
||||
return super.sum();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalDouble min() {
|
||||
try {
|
||||
return super.min();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalDouble max() {
|
||||
try {
|
||||
return super.max();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long count() {
|
||||
try {
|
||||
return super.count();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalDouble average() {
|
||||
try {
|
||||
return super.average();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleSummaryStatistics summaryStatistics() {
|
||||
try {
|
||||
return super.summaryStatistics();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean anyMatch(DoublePredicate predicate) {
|
||||
try {
|
||||
return super.anyMatch(predicate);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean allMatch(DoublePredicate predicate) {
|
||||
try {
|
||||
return super.allMatch(predicate);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean noneMatch(DoublePredicate predicate) {
|
||||
try {
|
||||
return super.noneMatch(predicate);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalDouble findFirst() {
|
||||
try {
|
||||
return super.findFirst();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalDouble findAny() {
|
||||
try {
|
||||
return super.findAny();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
package org.cryptomator.common.streams;
|
||||
|
||||
import static org.cryptomator.common.streams.AutoClosingStreamFactory.AUTO_CLOSING_STREAM_FACTORY;
|
||||
|
||||
import java.util.IntSummaryStatistics;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.IntBinaryOperator;
|
||||
import java.util.function.IntConsumer;
|
||||
import java.util.function.IntPredicate;
|
||||
import java.util.function.ObjIntConsumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class AutoClosingIntStream extends DelegatingIntStream {
|
||||
|
||||
public static IntStream from(IntStream delegate) {
|
||||
return new AutoClosingIntStream(delegate);
|
||||
}
|
||||
|
||||
public AutoClosingIntStream(IntStream delegate) {
|
||||
super(delegate, AUTO_CLOSING_STREAM_FACTORY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forEach(IntConsumer action) {
|
||||
try {
|
||||
super.forEach(action);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forEachOrdered(IntConsumer action) {
|
||||
try {
|
||||
super.forEachOrdered(action);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int[] toArray() {
|
||||
try {
|
||||
return super.toArray();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int reduce(int identity, IntBinaryOperator op) {
|
||||
try {
|
||||
return super.reduce(identity, op);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalInt reduce(IntBinaryOperator op) {
|
||||
try {
|
||||
return super.reduce(op);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <R> R collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R, R> combiner) {
|
||||
try {
|
||||
return super.collect(supplier, accumulator, combiner);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int sum() {
|
||||
try {
|
||||
return super.sum();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalInt min() {
|
||||
try {
|
||||
return super.min();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalInt max() {
|
||||
try {
|
||||
return super.max();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long count() {
|
||||
try {
|
||||
return super.count();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalDouble average() {
|
||||
try {
|
||||
return super.average();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IntSummaryStatistics summaryStatistics() {
|
||||
try {
|
||||
return super.summaryStatistics();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean anyMatch(IntPredicate predicate) {
|
||||
try {
|
||||
return super.anyMatch(predicate);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean allMatch(IntPredicate predicate) {
|
||||
try {
|
||||
return super.allMatch(predicate);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean noneMatch(IntPredicate predicate) {
|
||||
try {
|
||||
return super.noneMatch(predicate);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalInt findFirst() {
|
||||
try {
|
||||
return super.findFirst();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalInt findAny() {
|
||||
try {
|
||||
return super.findAny();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
package org.cryptomator.common.streams;
|
||||
|
||||
import static org.cryptomator.common.streams.AutoClosingStreamFactory.AUTO_CLOSING_STREAM_FACTORY;
|
||||
|
||||
import java.util.LongSummaryStatistics;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.OptionalLong;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.LongBinaryOperator;
|
||||
import java.util.function.LongConsumer;
|
||||
import java.util.function.LongPredicate;
|
||||
import java.util.function.ObjLongConsumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.LongStream;
|
||||
|
||||
public class AutoClosingLongStream extends DelegatingLongStream {
|
||||
|
||||
public static LongStream from(LongStream delegate) {
|
||||
return new AutoClosingLongStream(delegate);
|
||||
}
|
||||
|
||||
public AutoClosingLongStream(LongStream delegate) {
|
||||
super(delegate, AUTO_CLOSING_STREAM_FACTORY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forEach(LongConsumer action) {
|
||||
try {
|
||||
super.forEach(action);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forEachOrdered(LongConsumer action) {
|
||||
try {
|
||||
super.forEachOrdered(action);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long[] toArray() {
|
||||
try {
|
||||
return super.toArray();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long reduce(long identity, LongBinaryOperator op) {
|
||||
try {
|
||||
return super.reduce(identity, op);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalLong reduce(LongBinaryOperator op) {
|
||||
try {
|
||||
return super.reduce(op);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <R> R collect(Supplier<R> supplier, ObjLongConsumer<R> accumulator, BiConsumer<R, R> combiner) {
|
||||
try {
|
||||
return super.collect(supplier, accumulator, combiner);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long sum() {
|
||||
try {
|
||||
return super.sum();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalLong min() {
|
||||
try {
|
||||
return super.min();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalLong max() {
|
||||
try {
|
||||
return super.max();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long count() {
|
||||
try {
|
||||
return super.count();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalDouble average() {
|
||||
try {
|
||||
return super.average();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public LongSummaryStatistics summaryStatistics() {
|
||||
try {
|
||||
return super.summaryStatistics();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean anyMatch(LongPredicate predicate) {
|
||||
try {
|
||||
return super.anyMatch(predicate);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean allMatch(LongPredicate predicate) {
|
||||
try {
|
||||
return super.allMatch(predicate);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean noneMatch(LongPredicate predicate) {
|
||||
try {
|
||||
return super.noneMatch(predicate);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalLong findFirst() {
|
||||
try {
|
||||
return super.findFirst();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionalLong findAny() {
|
||||
try {
|
||||
return super.findAny();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
package org.cryptomator.common.streams;
|
||||
|
||||
import static org.cryptomator.common.streams.AutoClosingStreamFactory.AUTO_CLOSING_STREAM_FACTORY;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.Optional;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.BinaryOperator;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.IntFunction;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collector;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* A Stream which is automatically closed after execution of a terminal operation.
|
||||
* <p>
|
||||
* Streams returned by intermediate operations are also auto closing.
|
||||
* <p>
|
||||
* <b>Note:</b> When using {@link #iterator()} or {@link #spliterator()} auto closing does not occur.
|
||||
*
|
||||
* @author Markus Kreusch
|
||||
*/
|
||||
public class AutoClosingStream<T> extends DelegatingStream<T> {
|
||||
|
||||
public static <T> Stream<T> from(Stream<T> delegate) {
|
||||
return new AutoClosingStream<>(delegate);
|
||||
}
|
||||
|
||||
private AutoClosingStream(Stream<T> delegate) {
|
||||
super(delegate, AUTO_CLOSING_STREAM_FACTORY);
|
||||
}
|
||||
|
||||
public void forEach(Consumer<? super T> action) {
|
||||
try {
|
||||
super.forEach(action);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public void forEachOrdered(Consumer<? super T> action) {
|
||||
try {
|
||||
super.forEachOrdered(action);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public Object[] toArray() {
|
||||
try {
|
||||
return super.toArray();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public <A> A[] toArray(IntFunction<A[]> generator) {
|
||||
try {
|
||||
return super.toArray(generator);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public T reduce(T identity, BinaryOperator<T> accumulator) {
|
||||
try {
|
||||
return super.reduce(identity, accumulator);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<T> reduce(BinaryOperator<T> accumulator) {
|
||||
try {
|
||||
return super.reduce(accumulator);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner) {
|
||||
try {
|
||||
return super.reduce(identity, accumulator, combiner);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public <R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner) {
|
||||
try {
|
||||
return super.collect(supplier, accumulator, combiner);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public <R, A> R collect(Collector<? super T, A, R> collector) {
|
||||
try {
|
||||
return super.collect(collector);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<T> min(Comparator<? super T> comparator) {
|
||||
try {
|
||||
return super.min(comparator);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<T> max(Comparator<? super T> comparator) {
|
||||
try {
|
||||
return super.max(comparator);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public long count() {
|
||||
try {
|
||||
return super.count();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean anyMatch(Predicate<? super T> predicate) {
|
||||
try {
|
||||
return super.anyMatch(predicate);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean allMatch(Predicate<? super T> predicate) {
|
||||
try {
|
||||
return super.allMatch(predicate);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean noneMatch(Predicate<? super T> predicate) {
|
||||
try {
|
||||
return super.noneMatch(predicate);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<T> findFirst() {
|
||||
try {
|
||||
return super.findFirst();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<T> findAny() {
|
||||
try {
|
||||
return super.findAny();
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package org.cryptomator.common.streams;
|
||||
|
||||
import java.util.stream.DoubleStream;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
class AutoClosingStreamFactory implements DelegatingStreamFactory {
|
||||
|
||||
public static final DelegatingStreamFactory AUTO_CLOSING_STREAM_FACTORY = new AutoClosingStreamFactory();
|
||||
|
||||
private AutoClosingStreamFactory() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public <S> Stream<S> from(Stream<S> other) {
|
||||
if (AutoClosingStream.class.isInstance(other)) {
|
||||
return other;
|
||||
} else {
|
||||
return AutoClosingStream.from(other);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IntStream from(IntStream other) {
|
||||
if (AutoClosingIntStream.class.isInstance(other)) {
|
||||
return other;
|
||||
} else {
|
||||
return AutoClosingIntStream.from(other);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public LongStream from(LongStream other) {
|
||||
if (AutoClosingLongStream.class.isInstance(other)) {
|
||||
return other;
|
||||
} else {
|
||||
return AutoClosingLongStream.from(other);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public DoubleStream from(DoubleStream other) {
|
||||
if (AutoClosingDoubleStream.class.isInstance(other)) {
|
||||
return other;
|
||||
} else {
|
||||
return AutoClosingDoubleStream.from(other);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
package org.cryptomator.common.streams;
|
||||
|
||||
import java.util.DoubleSummaryStatistics;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.PrimitiveIterator.OfDouble;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.DoubleBinaryOperator;
|
||||
import java.util.function.DoubleConsumer;
|
||||
import java.util.function.DoubleFunction;
|
||||
import java.util.function.DoublePredicate;
|
||||
import java.util.function.DoubleToIntFunction;
|
||||
import java.util.function.DoubleToLongFunction;
|
||||
import java.util.function.DoubleUnaryOperator;
|
||||
import java.util.function.ObjDoubleConsumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.DoubleStream;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
abstract class DelegatingDoubleStream implements DoubleStream {
|
||||
|
||||
private final DoubleStream delegate;
|
||||
private final DelegatingStreamFactory wrapper;
|
||||
|
||||
public DelegatingDoubleStream(DoubleStream delegate, DelegatingStreamFactory wrapper) {
|
||||
this.delegate = delegate;
|
||||
this.wrapper = wrapper;
|
||||
}
|
||||
|
||||
public DoubleStream filter(DoublePredicate predicate) {
|
||||
return wrapper.from(delegate.filter(predicate));
|
||||
}
|
||||
|
||||
public boolean isParallel() {
|
||||
return delegate.isParallel();
|
||||
}
|
||||
|
||||
public DoubleStream map(DoubleUnaryOperator mapper) {
|
||||
return wrapper.from(delegate.map(mapper));
|
||||
}
|
||||
|
||||
public <U> Stream<U> mapToObj(DoubleFunction<? extends U> mapper) {
|
||||
return wrapper.from(delegate.mapToObj(mapper));
|
||||
}
|
||||
|
||||
public DoubleStream unordered() {
|
||||
return wrapper.from(delegate.unordered());
|
||||
}
|
||||
|
||||
public DoubleStream onClose(Runnable closeHandler) {
|
||||
return wrapper.from(delegate.onClose(closeHandler));
|
||||
}
|
||||
|
||||
public IntStream mapToInt(DoubleToIntFunction mapper) {
|
||||
return wrapper.from(delegate.mapToInt(mapper));
|
||||
}
|
||||
|
||||
public LongStream mapToLong(DoubleToLongFunction mapper) {
|
||||
return wrapper.from(delegate.mapToLong(mapper));
|
||||
}
|
||||
|
||||
public void close() {
|
||||
delegate.close();
|
||||
}
|
||||
|
||||
public DoubleStream flatMap(DoubleFunction<? extends DoubleStream> mapper) {
|
||||
return wrapper.from(delegate.flatMap(mapper));
|
||||
}
|
||||
|
||||
public DoubleStream distinct() {
|
||||
return wrapper.from(delegate.distinct());
|
||||
}
|
||||
|
||||
public DoubleStream sorted() {
|
||||
return wrapper.from(delegate.sorted());
|
||||
}
|
||||
|
||||
public DoubleStream peek(DoubleConsumer action) {
|
||||
return wrapper.from(delegate.peek(action));
|
||||
}
|
||||
|
||||
public DoubleStream limit(long maxSize) {
|
||||
return wrapper.from(delegate.limit(maxSize));
|
||||
}
|
||||
|
||||
public DoubleStream skip(long n) {
|
||||
return wrapper.from(delegate.skip(n));
|
||||
}
|
||||
|
||||
public void forEach(DoubleConsumer action) {
|
||||
delegate.forEach(action);
|
||||
}
|
||||
|
||||
public void forEachOrdered(DoubleConsumer action) {
|
||||
delegate.forEachOrdered(action);
|
||||
}
|
||||
|
||||
public double[] toArray() {
|
||||
return delegate.toArray();
|
||||
}
|
||||
|
||||
public double reduce(double identity, DoubleBinaryOperator op) {
|
||||
return delegate.reduce(identity, op);
|
||||
}
|
||||
|
||||
public OptionalDouble reduce(DoubleBinaryOperator op) {
|
||||
return delegate.reduce(op);
|
||||
}
|
||||
|
||||
public <R> R collect(Supplier<R> supplier, ObjDoubleConsumer<R> accumulator, BiConsumer<R, R> combiner) {
|
||||
return delegate.collect(supplier, accumulator, combiner);
|
||||
}
|
||||
|
||||
public double sum() {
|
||||
return delegate.sum();
|
||||
}
|
||||
|
||||
public OptionalDouble min() {
|
||||
return delegate.min();
|
||||
}
|
||||
|
||||
public OptionalDouble max() {
|
||||
return delegate.max();
|
||||
}
|
||||
|
||||
public long count() {
|
||||
return delegate.count();
|
||||
}
|
||||
|
||||
public OptionalDouble average() {
|
||||
return delegate.average();
|
||||
}
|
||||
|
||||
public DoubleSummaryStatistics summaryStatistics() {
|
||||
return delegate.summaryStatistics();
|
||||
}
|
||||
|
||||
public boolean anyMatch(DoublePredicate predicate) {
|
||||
return delegate.anyMatch(predicate);
|
||||
}
|
||||
|
||||
public boolean allMatch(DoublePredicate predicate) {
|
||||
return delegate.allMatch(predicate);
|
||||
}
|
||||
|
||||
public boolean noneMatch(DoublePredicate predicate) {
|
||||
return delegate.noneMatch(predicate);
|
||||
}
|
||||
|
||||
public OptionalDouble findFirst() {
|
||||
return delegate.findFirst();
|
||||
}
|
||||
|
||||
public OptionalDouble findAny() {
|
||||
return delegate.findAny();
|
||||
}
|
||||
|
||||
public Stream<Double> boxed() {
|
||||
return wrapper.from(delegate.boxed());
|
||||
}
|
||||
|
||||
public DoubleStream sequential() {
|
||||
return wrapper.from(delegate.sequential());
|
||||
}
|
||||
|
||||
public DoubleStream parallel() {
|
||||
return wrapper.from(delegate.parallel());
|
||||
}
|
||||
|
||||
public OfDouble iterator() {
|
||||
return delegate.iterator();
|
||||
}
|
||||
|
||||
public java.util.Spliterator.OfDouble spliterator() {
|
||||
return delegate.spliterator();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
package org.cryptomator.common.streams;
|
||||
|
||||
import java.util.IntSummaryStatistics;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.PrimitiveIterator.OfInt;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.IntBinaryOperator;
|
||||
import java.util.function.IntConsumer;
|
||||
import java.util.function.IntFunction;
|
||||
import java.util.function.IntPredicate;
|
||||
import java.util.function.IntToDoubleFunction;
|
||||
import java.util.function.IntToLongFunction;
|
||||
import java.util.function.IntUnaryOperator;
|
||||
import java.util.function.ObjIntConsumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.DoubleStream;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
abstract class DelegatingIntStream implements IntStream {
|
||||
|
||||
private final IntStream delegate;
|
||||
private final DelegatingStreamFactory wrapper;
|
||||
|
||||
public DelegatingIntStream(IntStream delegate, DelegatingStreamFactory wrapper) {
|
||||
this.delegate = delegate;
|
||||
this.wrapper = wrapper;
|
||||
}
|
||||
|
||||
public IntStream filter(IntPredicate predicate) {
|
||||
return wrapper.from(delegate.filter(predicate));
|
||||
}
|
||||
|
||||
public boolean isParallel() {
|
||||
return delegate.isParallel();
|
||||
}
|
||||
|
||||
public IntStream map(IntUnaryOperator mapper) {
|
||||
return wrapper.from(delegate.map(mapper));
|
||||
}
|
||||
|
||||
public <U> Stream<U> mapToObj(IntFunction<? extends U> mapper) {
|
||||
return wrapper.from(delegate.mapToObj(mapper));
|
||||
}
|
||||
|
||||
public IntStream unordered() {
|
||||
return wrapper.from(delegate.unordered());
|
||||
}
|
||||
|
||||
public LongStream mapToLong(IntToLongFunction mapper) {
|
||||
return wrapper.from(delegate.mapToLong(mapper));
|
||||
}
|
||||
|
||||
public IntStream onClose(Runnable closeHandler) {
|
||||
return wrapper.from(delegate.onClose(closeHandler));
|
||||
}
|
||||
|
||||
public DoubleStream mapToDouble(IntToDoubleFunction mapper) {
|
||||
return wrapper.from(delegate.mapToDouble(mapper));
|
||||
}
|
||||
|
||||
public void close() {
|
||||
delegate.close();
|
||||
}
|
||||
|
||||
public IntStream flatMap(IntFunction<? extends IntStream> mapper) {
|
||||
return wrapper.from(delegate.flatMap(mapper));
|
||||
}
|
||||
|
||||
public IntStream distinct() {
|
||||
return wrapper.from(delegate.distinct());
|
||||
}
|
||||
|
||||
public IntStream sorted() {
|
||||
return wrapper.from(delegate.sorted());
|
||||
}
|
||||
|
||||
public IntStream peek(IntConsumer action) {
|
||||
return wrapper.from(delegate.peek(action));
|
||||
}
|
||||
|
||||
public IntStream limit(long maxSize) {
|
||||
return wrapper.from(delegate.limit(maxSize));
|
||||
}
|
||||
|
||||
public IntStream skip(long n) {
|
||||
return wrapper.from(delegate.skip(n));
|
||||
}
|
||||
|
||||
public void forEach(IntConsumer action) {
|
||||
delegate.forEach(action);
|
||||
}
|
||||
|
||||
public void forEachOrdered(IntConsumer action) {
|
||||
delegate.forEachOrdered(action);
|
||||
}
|
||||
|
||||
public int[] toArray() {
|
||||
return delegate.toArray();
|
||||
}
|
||||
|
||||
public int reduce(int identity, IntBinaryOperator op) {
|
||||
return delegate.reduce(identity, op);
|
||||
}
|
||||
|
||||
public OptionalInt reduce(IntBinaryOperator op) {
|
||||
return delegate.reduce(op);
|
||||
}
|
||||
|
||||
public <R> R collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R, R> combiner) {
|
||||
return delegate.collect(supplier, accumulator, combiner);
|
||||
}
|
||||
|
||||
public int sum() {
|
||||
return delegate.sum();
|
||||
}
|
||||
|
||||
public OptionalInt min() {
|
||||
return delegate.min();
|
||||
}
|
||||
|
||||
public OptionalInt max() {
|
||||
return delegate.max();
|
||||
}
|
||||
|
||||
public long count() {
|
||||
return delegate.count();
|
||||
}
|
||||
|
||||
public OptionalDouble average() {
|
||||
return delegate.average();
|
||||
}
|
||||
|
||||
public IntSummaryStatistics summaryStatistics() {
|
||||
return delegate.summaryStatistics();
|
||||
}
|
||||
|
||||
public boolean anyMatch(IntPredicate predicate) {
|
||||
return delegate.anyMatch(predicate);
|
||||
}
|
||||
|
||||
public boolean allMatch(IntPredicate predicate) {
|
||||
return delegate.allMatch(predicate);
|
||||
}
|
||||
|
||||
public boolean noneMatch(IntPredicate predicate) {
|
||||
return delegate.noneMatch(predicate);
|
||||
}
|
||||
|
||||
public OptionalInt findFirst() {
|
||||
return delegate.findFirst();
|
||||
}
|
||||
|
||||
public OptionalInt findAny() {
|
||||
return delegate.findAny();
|
||||
}
|
||||
|
||||
public LongStream asLongStream() {
|
||||
return wrapper.from(delegate.asLongStream());
|
||||
}
|
||||
|
||||
public DoubleStream asDoubleStream() {
|
||||
return wrapper.from(delegate.asDoubleStream());
|
||||
}
|
||||
|
||||
public Stream<Integer> boxed() {
|
||||
return wrapper.from(delegate.boxed());
|
||||
}
|
||||
|
||||
public IntStream sequential() {
|
||||
return wrapper.from(delegate.sequential());
|
||||
}
|
||||
|
||||
public IntStream parallel() {
|
||||
return wrapper.from(delegate.parallel());
|
||||
}
|
||||
|
||||
public OfInt iterator() {
|
||||
return delegate.iterator();
|
||||
}
|
||||
|
||||
public java.util.Spliterator.OfInt spliterator() {
|
||||
return delegate.spliterator();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
package org.cryptomator.common.streams;
|
||||
|
||||
import java.util.LongSummaryStatistics;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.OptionalLong;
|
||||
import java.util.PrimitiveIterator.OfLong;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.LongBinaryOperator;
|
||||
import java.util.function.LongConsumer;
|
||||
import java.util.function.LongFunction;
|
||||
import java.util.function.LongPredicate;
|
||||
import java.util.function.LongToDoubleFunction;
|
||||
import java.util.function.LongToIntFunction;
|
||||
import java.util.function.LongUnaryOperator;
|
||||
import java.util.function.ObjLongConsumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.DoubleStream;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
abstract class DelegatingLongStream implements LongStream {
|
||||
|
||||
private final LongStream delegate;
|
||||
private final DelegatingStreamFactory wrapper;
|
||||
|
||||
public DelegatingLongStream(LongStream delegate, DelegatingStreamFactory wrapper) {
|
||||
this.delegate = delegate;
|
||||
this.wrapper = wrapper;
|
||||
}
|
||||
|
||||
public LongStream filter(LongPredicate predicate) {
|
||||
return wrapper.from(delegate.filter(predicate));
|
||||
}
|
||||
|
||||
public boolean isParallel() {
|
||||
return delegate.isParallel();
|
||||
}
|
||||
|
||||
public LongStream map(LongUnaryOperator mapper) {
|
||||
return wrapper.from(delegate.map(mapper));
|
||||
}
|
||||
|
||||
public <U> Stream<U> mapToObj(LongFunction<? extends U> mapper) {
|
||||
return wrapper.from(delegate.mapToObj(mapper));
|
||||
}
|
||||
|
||||
public LongStream unordered() {
|
||||
return wrapper.from(delegate.unordered());
|
||||
}
|
||||
|
||||
public LongStream onClose(Runnable closeHandler) {
|
||||
return wrapper.from(delegate.onClose(closeHandler));
|
||||
}
|
||||
|
||||
public IntStream mapToInt(LongToIntFunction mapper) {
|
||||
return wrapper.from(delegate.mapToInt(mapper));
|
||||
}
|
||||
|
||||
public DoubleStream mapToDouble(LongToDoubleFunction mapper) {
|
||||
return wrapper.from(delegate.mapToDouble(mapper));
|
||||
}
|
||||
|
||||
public void close() {
|
||||
delegate.close();
|
||||
}
|
||||
|
||||
public LongStream flatMap(LongFunction<? extends LongStream> mapper) {
|
||||
return wrapper.from(delegate.flatMap(mapper));
|
||||
}
|
||||
|
||||
public LongStream distinct() {
|
||||
return wrapper.from(delegate.distinct());
|
||||
}
|
||||
|
||||
public LongStream sorted() {
|
||||
return wrapper.from(delegate.sorted());
|
||||
}
|
||||
|
||||
public LongStream peek(LongConsumer action) {
|
||||
return wrapper.from(delegate.peek(action));
|
||||
}
|
||||
|
||||
public LongStream limit(long maxSize) {
|
||||
return wrapper.from(delegate.limit(maxSize));
|
||||
}
|
||||
|
||||
public LongStream skip(long n) {
|
||||
return wrapper.from(delegate.skip(n));
|
||||
}
|
||||
|
||||
public void forEach(LongConsumer action) {
|
||||
delegate.forEach(action);
|
||||
}
|
||||
|
||||
public void forEachOrdered(LongConsumer action) {
|
||||
delegate.forEachOrdered(action);
|
||||
}
|
||||
|
||||
public long[] toArray() {
|
||||
return delegate.toArray();
|
||||
}
|
||||
|
||||
public long reduce(long identity, LongBinaryOperator op) {
|
||||
return delegate.reduce(identity, op);
|
||||
}
|
||||
|
||||
public OptionalLong reduce(LongBinaryOperator op) {
|
||||
return delegate.reduce(op);
|
||||
}
|
||||
|
||||
public <R> R collect(Supplier<R> supplier, ObjLongConsumer<R> accumulator, BiConsumer<R, R> combiner) {
|
||||
return delegate.collect(supplier, accumulator, combiner);
|
||||
}
|
||||
|
||||
public long sum() {
|
||||
return delegate.sum();
|
||||
}
|
||||
|
||||
public OptionalLong min() {
|
||||
return delegate.min();
|
||||
}
|
||||
|
||||
public OptionalLong max() {
|
||||
return delegate.max();
|
||||
}
|
||||
|
||||
public long count() {
|
||||
return delegate.count();
|
||||
}
|
||||
|
||||
public OptionalDouble average() {
|
||||
return delegate.average();
|
||||
}
|
||||
|
||||
public LongSummaryStatistics summaryStatistics() {
|
||||
return delegate.summaryStatistics();
|
||||
}
|
||||
|
||||
public boolean anyMatch(LongPredicate predicate) {
|
||||
return delegate.anyMatch(predicate);
|
||||
}
|
||||
|
||||
public boolean allMatch(LongPredicate predicate) {
|
||||
return delegate.allMatch(predicate);
|
||||
}
|
||||
|
||||
public boolean noneMatch(LongPredicate predicate) {
|
||||
return delegate.noneMatch(predicate);
|
||||
}
|
||||
|
||||
public OptionalLong findFirst() {
|
||||
return delegate.findFirst();
|
||||
}
|
||||
|
||||
public OptionalLong findAny() {
|
||||
return delegate.findAny();
|
||||
}
|
||||
|
||||
public DoubleStream asDoubleStream() {
|
||||
return wrapper.from(delegate.asDoubleStream());
|
||||
}
|
||||
|
||||
public Stream<Long> boxed() {
|
||||
return wrapper.from(delegate.boxed());
|
||||
}
|
||||
|
||||
public LongStream sequential() {
|
||||
return wrapper.from(delegate.sequential());
|
||||
}
|
||||
|
||||
public LongStream parallel() {
|
||||
return wrapper.from(delegate.parallel());
|
||||
}
|
||||
|
||||
public OfLong iterator() {
|
||||
return delegate.iterator();
|
||||
}
|
||||
|
||||
public java.util.Spliterator.OfLong spliterator() {
|
||||
return delegate.spliterator();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
package org.cryptomator.common.streams;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.Optional;
|
||||
import java.util.Spliterator;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.BinaryOperator;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.IntFunction;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.function.ToDoubleFunction;
|
||||
import java.util.function.ToIntFunction;
|
||||
import java.util.function.ToLongFunction;
|
||||
import java.util.stream.Collector;
|
||||
import java.util.stream.DoubleStream;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
abstract class DelegatingStream<T> implements Stream<T> {
|
||||
|
||||
private final Stream<T> delegate;
|
||||
private final DelegatingStreamFactory wrapper;
|
||||
|
||||
protected DelegatingStream(Stream<T> delegate, DelegatingStreamFactory wrapper) {
|
||||
this.delegate = delegate;
|
||||
this.wrapper = wrapper;
|
||||
}
|
||||
|
||||
public Iterator<T> iterator() {
|
||||
return delegate.iterator();
|
||||
}
|
||||
|
||||
public Spliterator<T> spliterator() {
|
||||
return delegate.spliterator();
|
||||
}
|
||||
|
||||
public boolean isParallel() {
|
||||
return delegate.isParallel();
|
||||
}
|
||||
|
||||
public Stream<T> sequential() {
|
||||
return wrapper.from(delegate.sequential());
|
||||
}
|
||||
|
||||
public Stream<T> parallel() {
|
||||
return wrapper.from(delegate.parallel());
|
||||
}
|
||||
|
||||
public Stream<T> unordered() {
|
||||
return wrapper.from(delegate.unordered());
|
||||
}
|
||||
|
||||
public Stream<T> onClose(Runnable closeHandler) {
|
||||
return wrapper.from(delegate.onClose(closeHandler));
|
||||
}
|
||||
|
||||
public void close() {
|
||||
delegate.close();
|
||||
}
|
||||
|
||||
public Stream<T> filter(Predicate<? super T> predicate) {
|
||||
return wrapper.from(delegate.filter(predicate));
|
||||
}
|
||||
|
||||
public <R> Stream<R> map(Function<? super T, ? extends R> mapper) {
|
||||
return wrapper.from(delegate.map(mapper));
|
||||
}
|
||||
|
||||
public IntStream mapToInt(ToIntFunction<? super T> mapper) {
|
||||
return wrapper.from(delegate.mapToInt(mapper));
|
||||
}
|
||||
|
||||
public LongStream mapToLong(ToLongFunction<? super T> mapper) {
|
||||
return wrapper.from(delegate.mapToLong(mapper));
|
||||
}
|
||||
|
||||
public DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper) {
|
||||
return wrapper.from(delegate.mapToDouble(mapper));
|
||||
}
|
||||
|
||||
public <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper) {
|
||||
return wrapper.from(delegate.flatMap(mapper));
|
||||
}
|
||||
|
||||
public IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper) {
|
||||
return wrapper.from(delegate.flatMapToInt(mapper));
|
||||
}
|
||||
|
||||
public LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper) {
|
||||
return wrapper.from(delegate.flatMapToLong(mapper));
|
||||
}
|
||||
|
||||
public DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper) {
|
||||
return wrapper.from(delegate.flatMapToDouble(mapper));
|
||||
}
|
||||
|
||||
public Stream<T> distinct() {
|
||||
return wrapper.from(delegate.distinct());
|
||||
}
|
||||
|
||||
public Stream<T> sorted() {
|
||||
return wrapper.from(delegate.sorted());
|
||||
}
|
||||
|
||||
public Stream<T> sorted(Comparator<? super T> comparator) {
|
||||
return wrapper.from(delegate.sorted(comparator));
|
||||
}
|
||||
|
||||
public Stream<T> peek(Consumer<? super T> action) {
|
||||
return wrapper.from(delegate.peek(action));
|
||||
}
|
||||
|
||||
public Stream<T> limit(long maxSize) {
|
||||
return wrapper.from(delegate.limit(maxSize));
|
||||
}
|
||||
|
||||
public Stream<T> skip(long n) {
|
||||
return wrapper.from(delegate.skip(n));
|
||||
}
|
||||
|
||||
public void forEach(Consumer<? super T> action) {
|
||||
delegate.forEach(action);
|
||||
}
|
||||
|
||||
public void forEachOrdered(Consumer<? super T> action) {
|
||||
delegate.forEachOrdered(action);
|
||||
}
|
||||
|
||||
public Object[] toArray() {
|
||||
return delegate.toArray();
|
||||
}
|
||||
|
||||
public <A> A[] toArray(IntFunction<A[]> generator) {
|
||||
return delegate.toArray(generator);
|
||||
}
|
||||
|
||||
public T reduce(T identity, BinaryOperator<T> accumulator) {
|
||||
return delegate.reduce(identity, accumulator);
|
||||
}
|
||||
|
||||
public Optional<T> reduce(BinaryOperator<T> accumulator) {
|
||||
return delegate.reduce(accumulator);
|
||||
}
|
||||
|
||||
public <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner) {
|
||||
return delegate.reduce(identity, accumulator, combiner);
|
||||
}
|
||||
|
||||
public <R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner) {
|
||||
return delegate.collect(supplier, accumulator, combiner);
|
||||
}
|
||||
|
||||
public <R, A> R collect(Collector<? super T, A, R> collector) {
|
||||
return delegate.collect(collector);
|
||||
}
|
||||
|
||||
public Optional<T> min(Comparator<? super T> comparator) {
|
||||
return delegate.min(comparator);
|
||||
}
|
||||
|
||||
public Optional<T> max(Comparator<? super T> comparator) {
|
||||
return delegate.max(comparator);
|
||||
}
|
||||
|
||||
public long count() {
|
||||
return delegate.count();
|
||||
}
|
||||
|
||||
public boolean anyMatch(Predicate<? super T> predicate) {
|
||||
return delegate.anyMatch(predicate);
|
||||
}
|
||||
|
||||
public boolean allMatch(Predicate<? super T> predicate) {
|
||||
return delegate.allMatch(predicate);
|
||||
}
|
||||
|
||||
public boolean noneMatch(Predicate<? super T> predicate) {
|
||||
return delegate.noneMatch(predicate);
|
||||
}
|
||||
|
||||
public Optional<T> findFirst() {
|
||||
return delegate.findFirst();
|
||||
}
|
||||
|
||||
public Optional<T> findAny() {
|
||||
return delegate.findAny();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package org.cryptomator.common.streams;
|
||||
|
||||
import java.util.stream.DoubleStream;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public interface DelegatingStreamFactory {
|
||||
|
||||
<S> Stream<S> from(Stream<S> other);
|
||||
|
||||
IntStream from(IntStream other);
|
||||
|
||||
LongStream from(LongStream other);
|
||||
|
||||
DoubleStream from(DoubleStream other);
|
||||
|
||||
public interface ObjectStreamWrapper {
|
||||
<S> Stream<S> from(Stream<S> other);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package org.cryptomator.common;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CachingSupplierTest {
|
||||
|
||||
@Test
|
||||
public void testInvokingGetInvokesDelegate() {
|
||||
@SuppressWarnings("unchecked")
|
||||
Supplier<Object> delegate = mock(Supplier.class);
|
||||
Object expectedResult = new Object();
|
||||
when(delegate.get()).thenReturn(expectedResult);
|
||||
Supplier<Object> inTest = CachingSupplier.from(delegate);
|
||||
|
||||
Object result = inTest.get();
|
||||
|
||||
assertThat(result, is(expectedResult));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInvokingGetTwiceDoesNotInvokeDelegateTwice() {
|
||||
@SuppressWarnings("unchecked")
|
||||
Supplier<Object> delegate = mock(Supplier.class);
|
||||
Object expectedResult = new Object();
|
||||
when(delegate.get()).thenReturn(expectedResult);
|
||||
Supplier<Object> inTest = CachingSupplier.from(delegate);
|
||||
|
||||
inTest.get();
|
||||
Object result = inTest.get();
|
||||
|
||||
assertThat(result, is(expectedResult));
|
||||
verify(delegate).get();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package org.cryptomator.common;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class HolderTest {
|
||||
|
||||
private static final Object INITIAL = new Object();
|
||||
private static final Object VALUE = new Object();
|
||||
|
||||
private Holder<Object> inTest = new Holder<>(INITIAL);
|
||||
|
||||
@Test
|
||||
public void testInitialValueIsInitial() {
|
||||
assertThat(inTest.get(), is(INITIAL));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetChangesValue() {
|
||||
inTest.set(VALUE);
|
||||
|
||||
assertThat(inTest.get(), is(VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAcceptChangesValue() {
|
||||
inTest.accept(VALUE);
|
||||
|
||||
assertThat(inTest.get(), is(VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResetChangesValueToInitial() {
|
||||
inTest.set(VALUE);
|
||||
inTest.reset();
|
||||
|
||||
assertThat(inTest.get(), is(INITIAL));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -10,7 +10,6 @@ package org.cryptomator.common;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
import org.cryptomator.common.SemVerComparator;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -22,8 +21,10 @@ public class SemVerComparatorTest {
|
||||
|
||||
@Test
|
||||
public void compareEqualVersions() {
|
||||
final int comparisonResult = semVerComparator.compare("1.23.4", "1.23.4");
|
||||
Assert.assertEquals(0, Integer.signum(comparisonResult));
|
||||
Assert.assertEquals(0, Integer.signum(semVerComparator.compare("1.23.4", "1.23.4")));
|
||||
Assert.assertEquals(0, Integer.signum(semVerComparator.compare("1.23.4-alpha", "1.23.4-alpha")));
|
||||
Assert.assertEquals(0, Integer.signum(semVerComparator.compare("1.23.4+20170101", "1.23.4+20171231")));
|
||||
Assert.assertEquals(0, Integer.signum(semVerComparator.compare("1.23.4-alpha+20170101", "1.23.4-alpha+20171231")));
|
||||
}
|
||||
|
||||
// newer versions in first argument
|
||||
@@ -33,7 +34,11 @@ public class SemVerComparatorTest {
|
||||
Assert.assertEquals(1, Integer.signum(semVerComparator.compare("1.23.5", "1.23.4")));
|
||||
Assert.assertEquals(1, Integer.signum(semVerComparator.compare("1.24.4", "1.23.4")));
|
||||
Assert.assertEquals(1, Integer.signum(semVerComparator.compare("1.23.4", "1.23")));
|
||||
Assert.assertEquals(1, Integer.signum(semVerComparator.compare("1.23.4a", "1.23.4")));
|
||||
Assert.assertEquals(1, Integer.signum(semVerComparator.compare("1.23.4", "1.23.4-SNAPSHOT")));
|
||||
Assert.assertEquals(1, Integer.signum(semVerComparator.compare("1.23.4", "1.23.4-56.78")));
|
||||
Assert.assertEquals(1, Integer.signum(semVerComparator.compare("1.23.4-beta", "1.23.4-alpha")));
|
||||
Assert.assertEquals(1, Integer.signum(semVerComparator.compare("1.23.4-alpha.1", "1.23.4-alpha")));
|
||||
Assert.assertEquals(1, Integer.signum(semVerComparator.compare("1.23.4-56.79", "1.23.4-56.78")));
|
||||
}
|
||||
|
||||
// newer versions in second argument
|
||||
@@ -43,7 +48,11 @@ public class SemVerComparatorTest {
|
||||
Assert.assertEquals(-1, Integer.signum(semVerComparator.compare("1.23.4", "1.23.5")));
|
||||
Assert.assertEquals(-1, Integer.signum(semVerComparator.compare("1.23.4", "1.24.4")));
|
||||
Assert.assertEquals(-1, Integer.signum(semVerComparator.compare("1.23", "1.23.4")));
|
||||
Assert.assertEquals(-1, Integer.signum(semVerComparator.compare("1.23.4", "1.23.4a")));
|
||||
Assert.assertEquals(-1, Integer.signum(semVerComparator.compare("1.23.4-SNAPSHOT", "1.23.4")));
|
||||
Assert.assertEquals(-1, Integer.signum(semVerComparator.compare("1.23.4-56.78", "1.23.4")));
|
||||
Assert.assertEquals(-1, Integer.signum(semVerComparator.compare("1.23.4-alpha", "1.23.4-beta")));
|
||||
Assert.assertEquals(-1, Integer.signum(semVerComparator.compare("1.23.4-alpha", "1.23.4-alpha.1")));
|
||||
Assert.assertEquals(-1, Integer.signum(semVerComparator.compare("1.23.4-56.78", "1.23.4-56.79")));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,156 +0,0 @@
|
||||
package org.cryptomator.common;
|
||||
|
||||
import static java.lang.String.format;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.CoreMatchers.sameInstance;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
|
||||
public class WeakValuedCacheTest {
|
||||
|
||||
private final String A_KEY = "aKey";
|
||||
private final String ANOTHER_KEY = "anotherKey";
|
||||
|
||||
private WeakValuedCache<String, Value> inTest;
|
||||
|
||||
private Function<String, Value> loader;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Before
|
||||
public void setup() {
|
||||
loader = Mockito.mock(Function.class);
|
||||
inTest = WeakValuedCache.usingLoader(loader);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResultOfGetIsResultOfLoaderForTheSameKey() {
|
||||
Value theValue = new Value();
|
||||
Value theOtherValue = new Value();
|
||||
when(loader.apply(A_KEY)).thenReturn(theValue);
|
||||
when(loader.apply(ANOTHER_KEY)).thenReturn(theOtherValue);
|
||||
|
||||
Value result = inTest.get(A_KEY);
|
||||
Value anotherResult = inTest.get(ANOTHER_KEY);
|
||||
|
||||
assertThat(result, is(sameInstance(theValue)));
|
||||
assertThat(anotherResult, is(sameInstance(theOtherValue)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCachedResultIsResultOfLoaderForTheSameKey() {
|
||||
Value theValue = new Value();
|
||||
Value theOtherValue = new Value();
|
||||
when(loader.apply(A_KEY)).thenReturn(theValue);
|
||||
when(loader.apply(ANOTHER_KEY)).thenReturn(theOtherValue);
|
||||
|
||||
inTest.get(A_KEY);
|
||||
inTest.get(ANOTHER_KEY);
|
||||
Value result = inTest.get(A_KEY);
|
||||
Value anotherResult = inTest.get(ANOTHER_KEY);
|
||||
|
||||
assertThat(result, is(sameInstance(theValue)));
|
||||
assertThat(anotherResult, is(sameInstance(theOtherValue)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTwiceInvocationOfGetDoesNotInvokeLoaderTwice() {
|
||||
Value theValue = new Value();
|
||||
when(loader.apply(A_KEY)).thenReturn(theValue);
|
||||
|
||||
inTest.get(A_KEY);
|
||||
inTest.get(A_KEY);
|
||||
|
||||
verify(loader).apply(A_KEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSecondInvocationOfGetReturnsTheSameResult() {
|
||||
Value theValue = new Value();
|
||||
when(loader.apply(A_KEY)).thenReturn(theValue);
|
||||
|
||||
inTest.get(A_KEY);
|
||||
Value result = inTest.get(A_KEY);
|
||||
|
||||
assertThat(result, is(sameInstance(theValue)));
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void testCacheDoesNotPreventGarbageCollectionOfValues() {
|
||||
when(loader.apply(A_KEY)).thenAnswer(this::createValueUsingMoreThanHalfTheJvmMemory);
|
||||
|
||||
inTest.get(A_KEY);
|
||||
|
||||
// force garbage collection of previously created value by creating an
|
||||
// object so large it can not coexist with the value
|
||||
createObjectUsingMoreThanHalfTheJvmMemory();
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeExceptionThrownInLoader.class)
|
||||
public void testCacheRethrowsRuntimeExceptionsFromLoader() {
|
||||
when(loader.apply(A_KEY)).thenThrow(new RuntimeExceptionThrownInLoader());
|
||||
|
||||
inTest.get(A_KEY);
|
||||
}
|
||||
|
||||
@Test(expected = ErrorThrownInLoader.class)
|
||||
public void testCacheRethrowsErrorsFromLoader() {
|
||||
when(loader.apply(A_KEY)).thenThrow(new ErrorThrownInLoader());
|
||||
|
||||
inTest.get(A_KEY);
|
||||
}
|
||||
|
||||
private Value createValueUsingMoreThanHalfTheJvmMemory(InvocationOnMock invocation) {
|
||||
Object data = createObjectUsingMoreThanHalfTheJvmMemory();
|
||||
Value value = new Value();
|
||||
value.setPayload(data);
|
||||
return value;
|
||||
}
|
||||
|
||||
private Object createObjectUsingMoreThanHalfTheJvmMemory() {
|
||||
long maxMemory = Runtime.getRuntime().maxMemory();
|
||||
long moreThanHalfTheJvmMemory = maxMemory / 2 + 1;
|
||||
return createObjectUsingAtLeast(moreThanHalfTheJvmMemory);
|
||||
}
|
||||
|
||||
private Object createObjectUsingAtLeast(long minMemory) {
|
||||
if (minMemory <= Integer.MAX_VALUE) {
|
||||
return new byte[(int) minMemory];
|
||||
} else if ((minMemory / Integer.MAX_VALUE) <= Integer.MAX_VALUE) {
|
||||
int numberOfArraysWithMaxIntSize = (int) (minMemory / Integer.MAX_VALUE);
|
||||
int numberOfRemainingBytes = (int) (minMemory - Integer.MAX_VALUE * numberOfArraysWithMaxIntSize);
|
||||
return new byte[][][] { //
|
||||
new byte[numberOfArraysWithMaxIntSize][Integer.MAX_VALUE], //
|
||||
new byte[1][numberOfRemainingBytes] //
|
||||
};
|
||||
} else {
|
||||
throw new IllegalArgumentException(format("Can not create object with more than 3.999999996 Exabyte"));
|
||||
}
|
||||
}
|
||||
|
||||
private static class RuntimeExceptionThrownInLoader extends RuntimeException {
|
||||
}
|
||||
|
||||
private static class ErrorThrownInLoader extends Error {
|
||||
}
|
||||
|
||||
private static class Value {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private Object payload;
|
||||
|
||||
public void setPayload(Object payload) {
|
||||
this.payload = payload;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2017 Skymatic UG (haftungsbeschränkt).
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the accompanying LICENSE file.
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.common.settings;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SettingsJsonAdapterTest {
|
||||
|
||||
private final SettingsJsonAdapter adapter = new SettingsJsonAdapter();
|
||||
|
||||
@Test
|
||||
public void testDeserialize() throws IOException {
|
||||
String vault1Json = "{\"id\": \"1\", \"path\": \"/vault1\", \"mountName\": \"vault1\", \"winDriveLetter\": \"X\"}";
|
||||
String vault2Json = "{\"id\": \"2\", \"path\": \"/vault2\", \"mountName\": \"vault2\", \"winDriveLetter\": \"Y\"}";
|
||||
String json = "{\"directories\": [" + vault1Json + "," + vault2Json + "]," //
|
||||
+ "\"checkForUpdatesEnabled\": true,"//
|
||||
+ "\"port\": 8080,"//
|
||||
+ "\"useIpv6\": true,"//
|
||||
+ "\"numTrayNotifications\": 42}";
|
||||
|
||||
Settings settings = adapter.fromJson(json);
|
||||
|
||||
Assert.assertTrue(settings.checkForUpdates().get());
|
||||
Assert.assertEquals(2, settings.getDirectories().size());
|
||||
Assert.assertEquals(8080, settings.port().get());
|
||||
// Assert.assertTrue(settings.useIpv6().get()); temporarily ignored
|
||||
Assert.assertEquals(42, settings.numTrayNotifications().get());
|
||||
Assert.assertEquals("dav", settings.preferredGvfsScheme().get());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package org.cryptomator.common.settings;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
public class SettingsTest {
|
||||
|
||||
@Test
|
||||
public void testAutoSave() throws IOException {
|
||||
@SuppressWarnings("unchecked")
|
||||
Consumer<Settings> changeListener = Mockito.mock(Consumer.class);
|
||||
Settings settings = new Settings();
|
||||
settings.setSaveCmd(changeListener);
|
||||
VaultSettings vaultSettings = VaultSettings.withRandomId();
|
||||
Mockito.verify(changeListener, Mockito.times(0)).accept(settings);
|
||||
|
||||
// first change (to property):
|
||||
settings.preferredGvfsScheme().set("asd");
|
||||
Mockito.verify(changeListener, Mockito.times(1)).accept(settings);
|
||||
|
||||
// second change (to list):
|
||||
settings.getDirectories().add(vaultSettings);
|
||||
Mockito.verify(changeListener, Mockito.times(2)).accept(settings);
|
||||
|
||||
// third change (to property of list item):
|
||||
vaultSettings.mountName().set("asd");
|
||||
Mockito.verify(changeListener, Mockito.times(3)).accept(settings);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2017 Skymatic UG (haftungsbeschränkt).
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the accompanying LICENSE file.
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.common.settings;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.gson.stream.JsonReader;
|
||||
|
||||
public class VaultSettingsJsonAdapterTest {
|
||||
|
||||
private final VaultSettingsJsonAdapter adapter = new VaultSettingsJsonAdapter();
|
||||
|
||||
@Test
|
||||
public void testDeserialize() throws IOException {
|
||||
String json = "{\"id\": \"foo\", \"path\": \"/foo/bar\", \"mountName\": \"test\", \"winDriveLetter\": \"X\", \"shouldBeIgnored\": true}";
|
||||
JsonReader jsonReader = new JsonReader(new StringReader(json));
|
||||
|
||||
VaultSettings vaultSettings = adapter.read(jsonReader);
|
||||
Assert.assertEquals("foo", vaultSettings.getId());
|
||||
Assert.assertEquals(Paths.get("/foo/bar"), vaultSettings.path().get());
|
||||
Assert.assertEquals("test", vaultSettings.mountName().get());
|
||||
Assert.assertEquals("X", vaultSettings.winDriveLetter().get());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,21 +6,21 @@
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.ui.model;
|
||||
package org.cryptomator.common.settings;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class VaultTest {
|
||||
public class VaultSettingsTest {
|
||||
|
||||
@Test
|
||||
public void testNormalize() throws Exception {
|
||||
assertEquals("_", Vault.normalize(" "));
|
||||
assertEquals("a", Vault.normalize("ä"));
|
||||
assertEquals("C", Vault.normalize("Ĉ"));
|
||||
assertEquals("_", Vault.normalize(":"));
|
||||
assertEquals("", Vault.normalize("汉语"));
|
||||
assertEquals("_", VaultSettings.normalizeMountName(" "));
|
||||
assertEquals("a", VaultSettings.normalizeMountName("ä"));
|
||||
assertEquals("C", VaultSettings.normalizeMountName("Ĉ"));
|
||||
assertEquals("_", VaultSettings.normalizeMountName(":"));
|
||||
assertEquals("_", VaultSettings.normalizeMountName("汉语"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,227 +0,0 @@
|
||||
package org.cryptomator.common.streams;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.anyOf;
|
||||
import static org.hamcrest.CoreMatchers.instanceOf;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.DoubleSummaryStatistics;
|
||||
import java.util.List;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.DoubleBinaryOperator;
|
||||
import java.util.function.DoubleConsumer;
|
||||
import java.util.function.DoubleFunction;
|
||||
import java.util.function.DoublePredicate;
|
||||
import java.util.function.DoubleToIntFunction;
|
||||
import java.util.function.DoubleToLongFunction;
|
||||
import java.util.function.DoubleUnaryOperator;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.ObjDoubleConsumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.BaseStream;
|
||||
import java.util.stream.DoubleStream;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.hamcrest.Matcher;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.experimental.theories.DataPoints;
|
||||
import org.junit.experimental.theories.FromDataPoints;
|
||||
import org.junit.experimental.theories.Theories;
|
||||
import org.junit.experimental.theories.Theory;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
@RunWith(Theories.class)
|
||||
public class AutoClosingDoubleStreamTest {
|
||||
|
||||
private static final DoublePredicate A_DOUBLE_PREDICATE = any -> true;
|
||||
private static final DoubleFunction A_DOUBLE_FUNCTION = i -> null;
|
||||
private static final BiConsumer A_BICONSUMER = (a, b) -> {
|
||||
};
|
||||
private static final Supplier A_SUPPLIER = () -> null;
|
||||
|
||||
@DataPoints("intermediateOperations")
|
||||
public static final List<DoubleermediateOperation<?>> INTERMEDIATE_OPERATIONS = new ArrayList<>();
|
||||
|
||||
@DataPoints("terminalOperations")
|
||||
public static final List<TerminalOperation<?>> TERMINAL_OPERATIONS = new ArrayList<>();
|
||||
private static final DoubleUnaryOperator A_DOUBLE_UNARY_OPERATOR = i -> 3;
|
||||
private static final DoubleToLongFunction A_DOUBLE_TO_LONG_FUNCTION = i -> 3L;
|
||||
private static final DoubleToIntFunction A_DOUBLE_TO_INT_FUNCTION = i -> 5;
|
||||
private static final DoubleConsumer A_DOUBLE_CONSUMER = i -> {
|
||||
};
|
||||
private static final ObjDoubleConsumer AN_OBJ_DOUBLE_CONSUMER = (a, b) -> {
|
||||
};
|
||||
private static final DoubleBinaryOperator A_DOUBLE_BINARY_OPERATOR = (a, b) -> a;
|
||||
|
||||
static {
|
||||
// define intermediate operations
|
||||
test(DoubleStream.class, DoubleStream::distinct);
|
||||
test(DoubleStream.class, stream -> stream.filter(A_DOUBLE_PREDICATE));
|
||||
test(DoubleStream.class, stream -> stream.flatMap(A_DOUBLE_FUNCTION));
|
||||
test(DoubleStream.class, stream -> stream.limit(5));
|
||||
test(DoubleStream.class, stream -> stream.map(A_DOUBLE_UNARY_OPERATOR));
|
||||
test(LongStream.class, stream -> stream.mapToLong(A_DOUBLE_TO_LONG_FUNCTION));
|
||||
test(Stream.class, stream -> stream.mapToObj(A_DOUBLE_FUNCTION));
|
||||
test(IntStream.class, stream -> stream.mapToInt(A_DOUBLE_TO_INT_FUNCTION));
|
||||
test(DoubleStream.class, DoubleStream::parallel);
|
||||
test(DoubleStream.class, stream -> stream.peek(A_DOUBLE_CONSUMER));
|
||||
test(DoubleStream.class, DoubleStream::sequential);
|
||||
test(DoubleStream.class, stream -> stream.skip(5));
|
||||
test(DoubleStream.class, DoubleStream::sorted);
|
||||
test(DoubleStream.class, DoubleStream::unordered);
|
||||
test(Stream.class, DoubleStream::boxed);
|
||||
|
||||
// define terminal operations
|
||||
test(stream -> stream.allMatch(A_DOUBLE_PREDICATE), true);
|
||||
test(stream -> stream.anyMatch(A_DOUBLE_PREDICATE), true);
|
||||
test(stream -> stream.collect(A_SUPPLIER, AN_OBJ_DOUBLE_CONSUMER, A_BICONSUMER), 7d);
|
||||
test(DoubleStream::count, 3L);
|
||||
test(DoubleStream::findAny, OptionalDouble.of(3));
|
||||
test(DoubleStream::findFirst, OptionalDouble.of(3));
|
||||
test(stream -> stream.forEach(A_DOUBLE_CONSUMER));
|
||||
test(stream -> stream.forEachOrdered(A_DOUBLE_CONSUMER));
|
||||
test(stream -> stream.max(), OptionalDouble.of(3));
|
||||
test(stream -> stream.min(), OptionalDouble.of(3));
|
||||
test(stream -> stream.noneMatch(A_DOUBLE_PREDICATE), true);
|
||||
test(stream -> stream.reduce(A_DOUBLE_BINARY_OPERATOR), OptionalDouble.of(3));
|
||||
test(stream -> stream.reduce(1, A_DOUBLE_BINARY_OPERATOR), 3d);
|
||||
test(DoubleStream::toArray, new double[1]);
|
||||
test(DoubleStream::sum, 1d);
|
||||
test(DoubleStream::average, OptionalDouble.of(3d));
|
||||
test(DoubleStream::summaryStatistics, new DoubleSummaryStatistics());
|
||||
}
|
||||
|
||||
private static <T> void test(Consumer<DoubleStream> consumer) {
|
||||
TERMINAL_OPERATIONS.add(new TerminalOperation<T>() {
|
||||
@Override
|
||||
public T result() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T apply(DoubleStream stream) {
|
||||
consumer.accept(stream);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static <T> void test(Function<DoubleStream, T> function, T result) {
|
||||
TERMINAL_OPERATIONS.add(new TerminalOperation<T>() {
|
||||
@Override
|
||||
public T result() {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T apply(DoubleStream stream) {
|
||||
return function.apply(stream);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static <T extends BaseStream> void test(Class<? extends T> type, Function<DoubleStream, T> function) {
|
||||
INTERMEDIATE_OPERATIONS.add(new DoubleermediateOperation<T>() {
|
||||
@Override
|
||||
public Class<? extends T> type() {
|
||||
return type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T apply(DoubleStream stream) {
|
||||
return function.apply(stream);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
private DoubleStream delegate;
|
||||
private DoubleStream inTest;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
delegate = mock(DoubleStream.class);
|
||||
inTest = AutoClosingDoubleStream.from(delegate);
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void testIntermediateOperationReturnsNewAutoClosingStream(@FromDataPoints("intermediateOperations") DoubleermediateOperation intermediateOperation) {
|
||||
BaseStream newDelegate = (BaseStream) mock(intermediateOperation.type());
|
||||
when(intermediateOperation.apply(delegate)).thenReturn(newDelegate);
|
||||
|
||||
BaseStream result = intermediateOperation.apply(inTest);
|
||||
|
||||
assertThat(result, isAutoClosing());
|
||||
verifyDelegate(result, newDelegate);
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void testTerminalOperationDelegatesToAndClosesDelegate(@FromDataPoints("terminalOperations") TerminalOperation terminalOperation) {
|
||||
Object expectedResult = terminalOperation.result();
|
||||
if (expectedResult != null) {
|
||||
when(terminalOperation.apply(delegate)).thenReturn(expectedResult);
|
||||
}
|
||||
|
||||
Object result = terminalOperation.apply(inTest);
|
||||
|
||||
InOrder inOrder = inOrder(delegate);
|
||||
assertThat(result, is(expectedResult));
|
||||
inOrder.verify(delegate).close();
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void testTerminalOperationClosesDelegateEvenOnException(@FromDataPoints("terminalOperations") TerminalOperation terminalOperation) {
|
||||
RuntimeException exception = new RuntimeException();
|
||||
terminalOperation.apply(doThrow(exception).when(delegate));
|
||||
|
||||
thrown.expect(is(exception));
|
||||
|
||||
try {
|
||||
terminalOperation.apply(inTest);
|
||||
} finally {
|
||||
verify(delegate).close();
|
||||
}
|
||||
}
|
||||
|
||||
private Matcher<BaseStream> isAutoClosing() {
|
||||
return is(anyOf(instanceOf(AutoClosingStream.class), instanceOf(AutoClosingDoubleStream.class), instanceOf(AutoClosingIntStream.class), instanceOf(AutoClosingLongStream.class)));
|
||||
}
|
||||
|
||||
private void verifyDelegate(BaseStream result, BaseStream newDelegate) {
|
||||
result.close();
|
||||
verify(newDelegate).close();
|
||||
}
|
||||
|
||||
private interface TerminalOperation<T> {
|
||||
|
||||
T result();
|
||||
|
||||
T apply(DoubleStream stream);
|
||||
|
||||
}
|
||||
|
||||
private interface DoubleermediateOperation<T extends BaseStream> {
|
||||
|
||||
Class<? extends T> type();
|
||||
|
||||
T apply(DoubleStream stream);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,228 +0,0 @@
|
||||
package org.cryptomator.common.streams;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.anyOf;
|
||||
import static org.hamcrest.CoreMatchers.instanceOf;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.IntSummaryStatistics;
|
||||
import java.util.List;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.IntBinaryOperator;
|
||||
import java.util.function.IntConsumer;
|
||||
import java.util.function.IntFunction;
|
||||
import java.util.function.IntPredicate;
|
||||
import java.util.function.IntToDoubleFunction;
|
||||
import java.util.function.IntToLongFunction;
|
||||
import java.util.function.IntUnaryOperator;
|
||||
import java.util.function.ObjIntConsumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.BaseStream;
|
||||
import java.util.stream.DoubleStream;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.hamcrest.Matcher;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.experimental.theories.DataPoints;
|
||||
import org.junit.experimental.theories.FromDataPoints;
|
||||
import org.junit.experimental.theories.Theories;
|
||||
import org.junit.experimental.theories.Theory;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
@RunWith(Theories.class)
|
||||
public class AutoClosingIntStreamTest {
|
||||
|
||||
private static final IntPredicate AN_INT_PREDICATE = any -> true;
|
||||
private static final IntFunction AN_INT_FUNCTION = i -> null;
|
||||
private static final BiConsumer A_BICONSUMER = (a, b) -> {
|
||||
};
|
||||
private static final Supplier A_SUPPLIER = () -> null;
|
||||
|
||||
@DataPoints("intermediateOperations")
|
||||
public static final List<IntermediateOperation<?>> INTERMEDIATE_OPERATIONS = new ArrayList<>();
|
||||
|
||||
@DataPoints("terminalOperations")
|
||||
public static final List<TerminalOperation<?>> TERMINAL_OPERATIONS = new ArrayList<>();
|
||||
private static final IntUnaryOperator AN_INT_UNARY_OPERATOR = i -> 3;
|
||||
private static final IntToDoubleFunction AN_INT_TO_DOUBLE_FUNCTION = i -> 3d;
|
||||
private static final IntToLongFunction AN_INT_TO_LONG_FUNCTION = i -> 5L;
|
||||
private static final IntConsumer AN_INT_CONSUMER = i -> {
|
||||
};
|
||||
private static final ObjIntConsumer AN_OBJ_INT_CONSUMER = (a, b) -> {
|
||||
};
|
||||
private static final IntBinaryOperator AN_INT_BINARY_OPERATOR = (a, b) -> a;
|
||||
|
||||
static {
|
||||
// define intermediate operations
|
||||
test(IntStream.class, IntStream::distinct);
|
||||
test(IntStream.class, stream -> stream.filter(AN_INT_PREDICATE));
|
||||
test(IntStream.class, stream -> stream.flatMap(AN_INT_FUNCTION));
|
||||
test(IntStream.class, stream -> stream.limit(5));
|
||||
test(IntStream.class, stream -> stream.map(AN_INT_UNARY_OPERATOR));
|
||||
test(DoubleStream.class, stream -> stream.mapToDouble(AN_INT_TO_DOUBLE_FUNCTION));
|
||||
test(Stream.class, stream -> stream.mapToObj(AN_INT_FUNCTION));
|
||||
test(LongStream.class, stream -> stream.mapToLong(AN_INT_TO_LONG_FUNCTION));
|
||||
test(IntStream.class, IntStream::parallel);
|
||||
test(IntStream.class, stream -> stream.peek(AN_INT_CONSUMER));
|
||||
test(IntStream.class, IntStream::sequential);
|
||||
test(IntStream.class, stream -> stream.skip(5));
|
||||
test(IntStream.class, IntStream::sorted);
|
||||
test(IntStream.class, IntStream::unordered);
|
||||
test(Stream.class, IntStream::boxed);
|
||||
|
||||
// define terminal operations
|
||||
test(stream -> stream.allMatch(AN_INT_PREDICATE), true);
|
||||
test(stream -> stream.anyMatch(AN_INT_PREDICATE), true);
|
||||
test(stream -> stream.collect(A_SUPPLIER, AN_OBJ_INT_CONSUMER, A_BICONSUMER), 7);
|
||||
test(IntStream::count, 3L);
|
||||
test(IntStream::findAny, OptionalInt.of(3));
|
||||
test(IntStream::findFirst, OptionalInt.of(3));
|
||||
test(stream -> stream.forEach(AN_INT_CONSUMER));
|
||||
test(stream -> stream.forEachOrdered(AN_INT_CONSUMER));
|
||||
test(stream -> stream.max(), OptionalInt.of(3));
|
||||
test(stream -> stream.min(), OptionalInt.of(3));
|
||||
test(stream -> stream.noneMatch(AN_INT_PREDICATE), true);
|
||||
test(stream -> stream.reduce(AN_INT_BINARY_OPERATOR), OptionalInt.of(3));
|
||||
test(stream -> stream.reduce(1, AN_INT_BINARY_OPERATOR), 3);
|
||||
test(IntStream::toArray, new int[1]);
|
||||
test(IntStream::sum, 1);
|
||||
test(IntStream::average, OptionalDouble.of(3d));
|
||||
test(IntStream::summaryStatistics, new IntSummaryStatistics());
|
||||
}
|
||||
|
||||
private static <T> void test(Consumer<IntStream> consumer) {
|
||||
TERMINAL_OPERATIONS.add(new TerminalOperation<T>() {
|
||||
@Override
|
||||
public T result() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T apply(IntStream stream) {
|
||||
consumer.accept(stream);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static <T> void test(Function<IntStream, T> function, T result) {
|
||||
TERMINAL_OPERATIONS.add(new TerminalOperation<T>() {
|
||||
@Override
|
||||
public T result() {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T apply(IntStream stream) {
|
||||
return function.apply(stream);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static <T extends BaseStream> void test(Class<? extends T> type, Function<IntStream, T> function) {
|
||||
INTERMEDIATE_OPERATIONS.add(new IntermediateOperation<T>() {
|
||||
@Override
|
||||
public Class<? extends T> type() {
|
||||
return type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T apply(IntStream stream) {
|
||||
return function.apply(stream);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
private IntStream delegate;
|
||||
private IntStream inTest;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
delegate = mock(IntStream.class);
|
||||
inTest = AutoClosingIntStream.from(delegate);
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void testIntermediateOperationReturnsNewAutoClosingStream(@FromDataPoints("intermediateOperations") IntermediateOperation intermediateOperation) {
|
||||
BaseStream newDelegate = (BaseStream) mock(intermediateOperation.type());
|
||||
when(intermediateOperation.apply(delegate)).thenReturn(newDelegate);
|
||||
|
||||
BaseStream result = intermediateOperation.apply(inTest);
|
||||
|
||||
assertThat(result, isAutoClosing());
|
||||
verifyDelegate(result, newDelegate);
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void testTerminalOperationDelegatesToAndClosesDelegate(@FromDataPoints("terminalOperations") TerminalOperation terminalOperation) {
|
||||
Object expectedResult = terminalOperation.result();
|
||||
if (expectedResult != null) {
|
||||
when(terminalOperation.apply(delegate)).thenReturn(expectedResult);
|
||||
}
|
||||
|
||||
Object result = terminalOperation.apply(inTest);
|
||||
|
||||
InOrder inOrder = inOrder(delegate);
|
||||
assertThat(result, is(expectedResult));
|
||||
inOrder.verify(delegate).close();
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void testTerminalOperationClosesDelegateEvenOnException(@FromDataPoints("terminalOperations") TerminalOperation terminalOperation) {
|
||||
RuntimeException exception = new RuntimeException();
|
||||
terminalOperation.apply(doThrow(exception).when(delegate));
|
||||
|
||||
thrown.expect(is(exception));
|
||||
|
||||
try {
|
||||
terminalOperation.apply(inTest);
|
||||
} finally {
|
||||
verify(delegate).close();
|
||||
}
|
||||
}
|
||||
|
||||
private Matcher<BaseStream> isAutoClosing() {
|
||||
return is(anyOf(instanceOf(AutoClosingStream.class), instanceOf(AutoClosingDoubleStream.class), instanceOf(AutoClosingIntStream.class), instanceOf(AutoClosingLongStream.class)));
|
||||
}
|
||||
|
||||
private void verifyDelegate(BaseStream result, BaseStream newDelegate) {
|
||||
result.close();
|
||||
verify(newDelegate).close();
|
||||
}
|
||||
|
||||
private interface TerminalOperation<T> {
|
||||
|
||||
T result();
|
||||
|
||||
T apply(IntStream stream);
|
||||
|
||||
}
|
||||
|
||||
private interface IntermediateOperation<T extends BaseStream> {
|
||||
|
||||
Class<? extends T> type();
|
||||
|
||||
T apply(IntStream stream);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,228 +0,0 @@
|
||||
package org.cryptomator.common.streams;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.anyOf;
|
||||
import static org.hamcrest.CoreMatchers.instanceOf;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.LongSummaryStatistics;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.OptionalLong;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.LongBinaryOperator;
|
||||
import java.util.function.LongConsumer;
|
||||
import java.util.function.LongFunction;
|
||||
import java.util.function.LongPredicate;
|
||||
import java.util.function.LongToDoubleFunction;
|
||||
import java.util.function.LongToIntFunction;
|
||||
import java.util.function.LongUnaryOperator;
|
||||
import java.util.function.ObjLongConsumer;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.BaseStream;
|
||||
import java.util.stream.DoubleStream;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.hamcrest.Matcher;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.experimental.theories.DataPoints;
|
||||
import org.junit.experimental.theories.FromDataPoints;
|
||||
import org.junit.experimental.theories.Theories;
|
||||
import org.junit.experimental.theories.Theory;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
@RunWith(Theories.class)
|
||||
public class AutoClosingLongStreamTest {
|
||||
|
||||
private static final LongPredicate AN_LONG_PREDICATE = any -> true;
|
||||
private static final LongFunction AN_LONG_FUNCTION = i -> null;
|
||||
private static final BiConsumer A_BICONSUMER = (a, b) -> {
|
||||
};
|
||||
private static final Supplier A_SUPPLIER = () -> null;
|
||||
|
||||
@DataPoints("intermediateOperations")
|
||||
public static final List<LongermediateOperation<?>> INTERMEDIATE_OPERATIONS = new ArrayList<>();
|
||||
|
||||
@DataPoints("terminalOperations")
|
||||
public static final List<TerminalOperation<?>> TERMINAL_OPERATIONS = new ArrayList<>();
|
||||
private static final LongUnaryOperator AN_LONG_UNARY_OPERATOR = i -> 3;
|
||||
private static final LongToDoubleFunction AN_LONG_TO_DOUBLE_FUNCTION = i -> 3d;
|
||||
private static final LongToIntFunction AN_LONG_TO_INT_FUNCTION = i -> 5;
|
||||
private static final LongConsumer AN_LONG_CONSUMER = i -> {
|
||||
};
|
||||
private static final ObjLongConsumer AN_OBJ_LONG_CONSUMER = (a, b) -> {
|
||||
};
|
||||
private static final LongBinaryOperator AN_LONG_BINARY_OPERATOR = (a, b) -> a;
|
||||
|
||||
static {
|
||||
// define intermediate operations
|
||||
test(LongStream.class, LongStream::distinct);
|
||||
test(LongStream.class, stream -> stream.filter(AN_LONG_PREDICATE));
|
||||
test(LongStream.class, stream -> stream.flatMap(AN_LONG_FUNCTION));
|
||||
test(LongStream.class, stream -> stream.limit(5));
|
||||
test(LongStream.class, stream -> stream.map(AN_LONG_UNARY_OPERATOR));
|
||||
test(DoubleStream.class, stream -> stream.mapToDouble(AN_LONG_TO_DOUBLE_FUNCTION));
|
||||
test(Stream.class, stream -> stream.mapToObj(AN_LONG_FUNCTION));
|
||||
test(IntStream.class, stream -> stream.mapToInt(AN_LONG_TO_INT_FUNCTION));
|
||||
test(LongStream.class, LongStream::parallel);
|
||||
test(LongStream.class, stream -> stream.peek(AN_LONG_CONSUMER));
|
||||
test(LongStream.class, LongStream::sequential);
|
||||
test(LongStream.class, stream -> stream.skip(5));
|
||||
test(LongStream.class, LongStream::sorted);
|
||||
test(LongStream.class, LongStream::unordered);
|
||||
test(Stream.class, LongStream::boxed);
|
||||
|
||||
// define terminal operations
|
||||
test(stream -> stream.allMatch(AN_LONG_PREDICATE), true);
|
||||
test(stream -> stream.anyMatch(AN_LONG_PREDICATE), true);
|
||||
test(stream -> stream.collect(A_SUPPLIER, AN_OBJ_LONG_CONSUMER, A_BICONSUMER), 7L);
|
||||
test(LongStream::count, 3L);
|
||||
test(LongStream::findAny, OptionalLong.of(3));
|
||||
test(LongStream::findFirst, OptionalLong.of(3));
|
||||
test(stream -> stream.forEach(AN_LONG_CONSUMER));
|
||||
test(stream -> stream.forEachOrdered(AN_LONG_CONSUMER));
|
||||
test(stream -> stream.max(), OptionalLong.of(3));
|
||||
test(stream -> stream.min(), OptionalLong.of(3));
|
||||
test(stream -> stream.noneMatch(AN_LONG_PREDICATE), true);
|
||||
test(stream -> stream.reduce(AN_LONG_BINARY_OPERATOR), OptionalLong.of(3));
|
||||
test(stream -> stream.reduce(1, AN_LONG_BINARY_OPERATOR), 3L);
|
||||
test(LongStream::toArray, new long[1]);
|
||||
test(LongStream::sum, 1L);
|
||||
test(LongStream::average, OptionalDouble.of(3d));
|
||||
test(LongStream::summaryStatistics, new LongSummaryStatistics());
|
||||
}
|
||||
|
||||
private static <T> void test(Consumer<LongStream> consumer) {
|
||||
TERMINAL_OPERATIONS.add(new TerminalOperation<T>() {
|
||||
@Override
|
||||
public T result() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T apply(LongStream stream) {
|
||||
consumer.accept(stream);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static <T> void test(Function<LongStream, T> function, T result) {
|
||||
TERMINAL_OPERATIONS.add(new TerminalOperation<T>() {
|
||||
@Override
|
||||
public T result() {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T apply(LongStream stream) {
|
||||
return function.apply(stream);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static <T extends BaseStream> void test(Class<? extends T> type, Function<LongStream, T> function) {
|
||||
INTERMEDIATE_OPERATIONS.add(new LongermediateOperation<T>() {
|
||||
@Override
|
||||
public Class<? extends T> type() {
|
||||
return type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T apply(LongStream stream) {
|
||||
return function.apply(stream);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
private LongStream delegate;
|
||||
private LongStream inTest;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
delegate = mock(LongStream.class);
|
||||
inTest = AutoClosingLongStream.from(delegate);
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void testIntermediateOperationReturnsNewAutoClosingStream(@FromDataPoints("intermediateOperations") LongermediateOperation intermediateOperation) {
|
||||
BaseStream newDelegate = (BaseStream) mock(intermediateOperation.type());
|
||||
when(intermediateOperation.apply(delegate)).thenReturn(newDelegate);
|
||||
|
||||
BaseStream result = intermediateOperation.apply(inTest);
|
||||
|
||||
assertThat(result, isAutoClosing());
|
||||
verifyDelegate(result, newDelegate);
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void testTerminalOperationDelegatesToAndClosesDelegate(@FromDataPoints("terminalOperations") TerminalOperation terminalOperation) {
|
||||
Object expectedResult = terminalOperation.result();
|
||||
if (expectedResult != null) {
|
||||
when(terminalOperation.apply(delegate)).thenReturn(expectedResult);
|
||||
}
|
||||
|
||||
Object result = terminalOperation.apply(inTest);
|
||||
|
||||
InOrder inOrder = inOrder(delegate);
|
||||
assertThat(result, is(expectedResult));
|
||||
inOrder.verify(delegate).close();
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void testTerminalOperationClosesDelegateEvenOnException(@FromDataPoints("terminalOperations") TerminalOperation terminalOperation) {
|
||||
RuntimeException exception = new RuntimeException();
|
||||
terminalOperation.apply(doThrow(exception).when(delegate));
|
||||
|
||||
thrown.expect(is(exception));
|
||||
|
||||
try {
|
||||
terminalOperation.apply(inTest);
|
||||
} finally {
|
||||
verify(delegate).close();
|
||||
}
|
||||
}
|
||||
|
||||
private Matcher<BaseStream> isAutoClosing() {
|
||||
return is(anyOf(instanceOf(AutoClosingStream.class), instanceOf(AutoClosingDoubleStream.class), instanceOf(AutoClosingIntStream.class), instanceOf(AutoClosingLongStream.class)));
|
||||
}
|
||||
|
||||
private void verifyDelegate(BaseStream result, BaseStream newDelegate) {
|
||||
result.close();
|
||||
verify(newDelegate).close();
|
||||
}
|
||||
|
||||
private interface TerminalOperation<T> {
|
||||
|
||||
T result();
|
||||
|
||||
T apply(LongStream stream);
|
||||
|
||||
}
|
||||
|
||||
private interface LongermediateOperation<T extends BaseStream> {
|
||||
|
||||
Class<? extends T> type();
|
||||
|
||||
T apply(LongStream stream);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,231 +0,0 @@
|
||||
package org.cryptomator.common.streams;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.anyOf;
|
||||
import static org.hamcrest.CoreMatchers.instanceOf;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BinaryOperator;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.IntFunction;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.function.ToDoubleFunction;
|
||||
import java.util.function.ToIntFunction;
|
||||
import java.util.function.ToLongFunction;
|
||||
import java.util.stream.BaseStream;
|
||||
import java.util.stream.Collector;
|
||||
import java.util.stream.DoubleStream;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.LongStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.hamcrest.Matcher;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.experimental.theories.DataPoints;
|
||||
import org.junit.experimental.theories.FromDataPoints;
|
||||
import org.junit.experimental.theories.Theories;
|
||||
import org.junit.experimental.theories.Theory;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
@RunWith(Theories.class)
|
||||
public class AutoClosingStreamTest {
|
||||
|
||||
private static final Predicate A_PREDICATE = any -> true;
|
||||
private static final Function A_FUNCTION = any -> null;
|
||||
private static final ToDoubleFunction A_TO_DOUBLE_FUNCTION = any -> 0d;
|
||||
private static final ToIntFunction A_TO_INT_FUNCTION = any -> 1;
|
||||
private static final ToLongFunction A_TO_LONG_FUNCTION = any -> 1L;
|
||||
private static final Consumer A_CONSUMER = any -> {
|
||||
};
|
||||
private static final Comparator A_COMPARATOR = (left, right) -> 0;
|
||||
private static final Collector A_COLLECTOR = mock(Collector.class);
|
||||
private static final BinaryOperator A_BINARY_OPERATOR = (left, right) -> null;
|
||||
private static final Object AN_OBJECT = new Object();
|
||||
private static final IntFunction AN_INT_FUNCTION = i -> null;
|
||||
private static final BiConsumer A_BICONSUMER = (a, b) -> {
|
||||
};
|
||||
private static final Supplier A_SUPPLIER = () -> null;
|
||||
|
||||
@DataPoints("intermediateOperations")
|
||||
public static final List<IntermediateOperation<?>> INTERMEDIATE_OPERATIONS = new ArrayList<>();
|
||||
|
||||
@DataPoints("terminalOperations")
|
||||
public static final List<TerminalOperation<?>> TERMINAL_OPERATIONS = new ArrayList<>();
|
||||
|
||||
static {
|
||||
// define intermediate operations
|
||||
test(Stream.class, Stream::distinct);
|
||||
test(Stream.class, stream -> stream.filter(A_PREDICATE));
|
||||
test(Stream.class, stream -> stream.flatMap(A_FUNCTION));
|
||||
test(DoubleStream.class, stream -> stream.flatMapToDouble(A_FUNCTION));
|
||||
test(IntStream.class, stream -> stream.flatMapToInt(A_FUNCTION));
|
||||
test(LongStream.class, stream -> stream.flatMapToLong(A_FUNCTION));
|
||||
test(Stream.class, stream -> stream.limit(5));
|
||||
test(Stream.class, stream -> stream.map(A_FUNCTION));
|
||||
test(DoubleStream.class, stream -> stream.mapToDouble(A_TO_DOUBLE_FUNCTION));
|
||||
test(IntStream.class, stream -> stream.mapToInt(A_TO_INT_FUNCTION));
|
||||
test(LongStream.class, stream -> stream.mapToLong(A_TO_LONG_FUNCTION));
|
||||
test(Stream.class, Stream::parallel);
|
||||
test(Stream.class, stream -> stream.peek(A_CONSUMER));
|
||||
test(Stream.class, Stream::sequential);
|
||||
test(Stream.class, stream -> stream.skip(5));
|
||||
test(Stream.class, Stream::sorted);
|
||||
test(Stream.class, stream -> stream.sorted(A_COMPARATOR));
|
||||
test(Stream.class, Stream::unordered);
|
||||
|
||||
// define terminal operations
|
||||
test(stream -> stream.allMatch(A_PREDICATE), true);
|
||||
test(stream -> stream.anyMatch(A_PREDICATE), true);
|
||||
test(stream -> stream.collect(A_COLLECTOR), new Object());
|
||||
test(stream -> stream.collect(A_SUPPLIER, A_BICONSUMER, A_BICONSUMER), new Object());
|
||||
test(Stream::count, 3L);
|
||||
test(Stream::findAny, Optional.of(new Object()));
|
||||
test(Stream::findFirst, Optional.of(new Object()));
|
||||
test(stream -> stream.forEach(A_CONSUMER));
|
||||
test(stream -> stream.forEachOrdered(A_CONSUMER));
|
||||
test(stream -> stream.max(A_COMPARATOR), Optional.of(new Object()));
|
||||
test(stream -> stream.min(A_COMPARATOR), Optional.of(new Object()));
|
||||
test(stream -> stream.noneMatch(A_PREDICATE), true);
|
||||
test(stream -> stream.reduce(A_BINARY_OPERATOR), Optional.of(new Object()));
|
||||
test(stream -> stream.reduce(AN_OBJECT, A_BINARY_OPERATOR), Optional.of(new Object()));
|
||||
test(stream -> stream.reduce(AN_OBJECT, A_BINARY_OPERATOR, A_BINARY_OPERATOR), Optional.of(new Object()));
|
||||
test(Stream::toArray, new Object[1]);
|
||||
test(stream -> stream.toArray(AN_INT_FUNCTION), new Object[1]);
|
||||
}
|
||||
|
||||
private static <T> void test(Consumer<Stream> consumer) {
|
||||
TERMINAL_OPERATIONS.add(new TerminalOperation<T>() {
|
||||
@Override
|
||||
public T result() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T apply(Stream stream) {
|
||||
consumer.accept(stream);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static <T> void test(Function<Stream, T> function, T result) {
|
||||
TERMINAL_OPERATIONS.add(new TerminalOperation<T>() {
|
||||
@Override
|
||||
public T result() {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T apply(Stream stream) {
|
||||
return function.apply(stream);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static <T extends BaseStream> void test(Class<? extends T> type, Function<Stream, T> function) {
|
||||
INTERMEDIATE_OPERATIONS.add(new IntermediateOperation<T>() {
|
||||
@Override
|
||||
public Class<? extends T> type() {
|
||||
return type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T apply(Stream stream) {
|
||||
return function.apply(stream);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
private Stream<Object> delegate;
|
||||
private Stream<Object> inTest;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
delegate = mock(Stream.class);
|
||||
inTest = AutoClosingStream.from(delegate);
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void testIntermediateOperationReturnsNewAutoClosingStream(@FromDataPoints("intermediateOperations") IntermediateOperation intermediateOperation) {
|
||||
BaseStream newDelegate = (BaseStream) mock(intermediateOperation.type());
|
||||
when(intermediateOperation.apply(delegate)).thenReturn(newDelegate);
|
||||
|
||||
BaseStream result = intermediateOperation.apply(inTest);
|
||||
|
||||
assertThat(result, isAutoClosing());
|
||||
verifyDelegate(result, newDelegate);
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void testTerminalOperationDelegatesToAndClosesDelegate(@FromDataPoints("terminalOperations") TerminalOperation terminalOperation) {
|
||||
Object expectedResult = terminalOperation.result();
|
||||
if (expectedResult != null) {
|
||||
when(terminalOperation.apply(delegate)).thenReturn(expectedResult);
|
||||
}
|
||||
|
||||
Object result = terminalOperation.apply(inTest);
|
||||
|
||||
InOrder inOrder = inOrder(delegate);
|
||||
assertThat(result, is(expectedResult));
|
||||
inOrder.verify(delegate).close();
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void testTerminalOperationClosesDelegateEvenOnException(@FromDataPoints("terminalOperations") TerminalOperation terminalOperation) {
|
||||
RuntimeException exception = new RuntimeException();
|
||||
terminalOperation.apply(doThrow(exception).when(delegate));
|
||||
|
||||
thrown.expect(is(exception));
|
||||
|
||||
try {
|
||||
terminalOperation.apply(inTest);
|
||||
} finally {
|
||||
verify(delegate).close();
|
||||
}
|
||||
}
|
||||
|
||||
private Matcher<BaseStream> isAutoClosing() {
|
||||
return is(anyOf(instanceOf(AutoClosingStream.class), instanceOf(AutoClosingDoubleStream.class), instanceOf(AutoClosingIntStream.class), instanceOf(AutoClosingLongStream.class)));
|
||||
}
|
||||
|
||||
private void verifyDelegate(BaseStream result, BaseStream newDelegate) {
|
||||
result.close();
|
||||
verify(newDelegate).close();
|
||||
}
|
||||
|
||||
private interface TerminalOperation<T> {
|
||||
|
||||
T result();
|
||||
|
||||
T apply(Stream stream);
|
||||
|
||||
}
|
||||
|
||||
private interface IntermediateOperation<T extends BaseStream> {
|
||||
|
||||
Class<? extends T> type();
|
||||
|
||||
T apply(Stream stream);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
2
main/filesystem-api/.gitignore
vendored
2
main/filesystem-api/.gitignore
vendored
@@ -1,2 +0,0 @@
|
||||
/target/
|
||||
/target/
|
||||
@@ -1,55 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
|
||||
import com.google.common.io.ByteStreams;
|
||||
|
||||
class Copier {
|
||||
|
||||
public static void copy(Folder source, Folder destination) {
|
||||
assertFoldersAreNotNested(source, destination);
|
||||
|
||||
destination.delete();
|
||||
destination.create();
|
||||
|
||||
source.files().forEach(sourceFile -> {
|
||||
File destinationFile = destination.file(sourceFile.name());
|
||||
sourceFile.copyTo(destinationFile);
|
||||
});
|
||||
|
||||
source.folders().forEach(sourceFolder -> {
|
||||
Folder destinationFolder = destination.folder(sourceFolder.name());
|
||||
sourceFolder.copyTo(destinationFolder);
|
||||
});
|
||||
}
|
||||
|
||||
public static void copy(File source, File destination) {
|
||||
try (OpenFiles openFiles = DeadlockSafeFileOpener.withReadable(source).andWritable(destination).open()) {
|
||||
ReadableFile readable = openFiles.readable(source);
|
||||
WritableFile writable = openFiles.writable(destination);
|
||||
writable.truncate();
|
||||
ByteStreams.copy(readable, writable);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertFoldersAreNotNested(Folder source, Folder destination) {
|
||||
if (source.isAncestorOf(destination)) {
|
||||
throw new IllegalArgumentException("Can not copy parent to child directory (src: " + source + ", dst: " + destination + ")");
|
||||
}
|
||||
if (destination.isAncestorOf(source)) {
|
||||
throw new IllegalArgumentException("Can not copy child to parent directory (src: " + source + ", dst: " + destination + ")");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.SortedMap;
|
||||
import java.util.TreeMap;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class DeadlockSafeFileOpener {
|
||||
|
||||
public static DeadlockSafeFileOpener withReadable(File file) {
|
||||
return new DeadlockSafeFileOpener().andReadable(file);
|
||||
}
|
||||
|
||||
public static DeadlockSafeFileOpener withWritable(File file) {
|
||||
return new DeadlockSafeFileOpener().andWritable(file);
|
||||
}
|
||||
|
||||
private final SortedMap<File, Consumer<File>> filesWithOperation = new TreeMap<>();
|
||||
|
||||
private final Map<File, ReadableFile> readableFiles = new HashMap<>();
|
||||
private final Map<File, WritableFile> writableFiles = new HashMap<>();
|
||||
|
||||
private DeadlockSafeFileOpener() {
|
||||
}
|
||||
|
||||
public DeadlockSafeFileOpener andReadable(File file) {
|
||||
if (filesWithOperation.put(file, this::openReadable) != null) {
|
||||
throw new IllegalArgumentException(format("File %s already marked for opening", file));
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public DeadlockSafeFileOpener andWritable(File file) {
|
||||
if (filesWithOperation.put(file, this::openWritable) != null) {
|
||||
throw new IllegalArgumentException(format("File %s already marked for opening", file));
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
private void openReadable(File file) {
|
||||
readableFiles.put(file, file.openReadable());
|
||||
}
|
||||
|
||||
private void openWritable(File file) {
|
||||
writableFiles.put(file, file.openWritable());
|
||||
}
|
||||
|
||||
public OpenFiles open() {
|
||||
try {
|
||||
filesWithOperation.forEach((file, openAction) -> openAction.accept(file));
|
||||
} catch (RuntimeException e) {
|
||||
OpenFiles.cleanup(readableFiles.values(), writableFiles.values());
|
||||
throw e;
|
||||
}
|
||||
return new OpenFiles(readableFiles, writableFiles);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package org.cryptomator.filesystem;
|
||||
|
||||
public class Deleter {
|
||||
|
||||
/**
|
||||
* Deletes all and only the content of a given {@link Folder} but <b>not</b> the folder itself.
|
||||
*/
|
||||
public static void deleteContent(Folder folder) {
|
||||
if (folder.exists()) {
|
||||
folder.folders().forEach(Folder::delete);
|
||||
folder.files().forEach(File::delete);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Markus Kreusch
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
******************************************************************************/
|
||||
package org.cryptomator.filesystem;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
|
||||
/**
|
||||
* A {@link File} in a {@link FileSystem}.
|
||||
*
|
||||
* @author Markus Kreusch
|
||||
*/
|
||||
public interface File extends Node, Comparable<File> {
|
||||
|
||||
static final int EOF = -1;
|
||||
|
||||
/**
|
||||
* @return The current size of the file. This value is a snapshot and might have been changed by concurrent modifications.
|
||||
* @throws UncheckedIOException
|
||||
* if an {@link IOException} occurs
|
||||
*/
|
||||
long size() throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Opens this file for reading.
|
||||
* <p>
|
||||
* An implementation guarantees, that per {@link FileSystem} and
|
||||
* {@code File} while a {@code ReadableFile} is open no {@link WritableFile}
|
||||
* can be open and vice versa. A {@link ReadableFile} is open when returned
|
||||
* from this method and not yet closed using {@link ReadableFile#close()}.
|
||||
* <br>
|
||||
* A limitation to the number of {@code ReadableFiles} is in general not
|
||||
* required but may be set by a specific implementation.
|
||||
* <p>
|
||||
* If a {@link WritableFile} for this {@code File} is open the invocation of
|
||||
* this method will block regarding the specified timeout.<br>
|
||||
* In addition implementations may block to lock the required IO resources
|
||||
* to read the file.
|
||||
*
|
||||
* @return a {@link ReadableFile} to work with
|
||||
* @throws UncheckedIOException
|
||||
* if an {@link IOException} occurs while opening the file, the
|
||||
* file does not exist or is a directory
|
||||
*/
|
||||
ReadableFile openReadable() throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Opens this file for writing.
|
||||
* <p>
|
||||
* If the file does not exist a new empty file is created.
|
||||
* <p>
|
||||
* An implementation guarantees, that per {@link FileSystem} and
|
||||
* {@code File} only one {@link WritableFile} is open at a time. A
|
||||
* {@code WritableFile} is open when returned from this method and not yet
|
||||
* closed using {@link WritableFile#close()} or
|
||||
* {@link WritableFile#delete()}.<br>
|
||||
* In addition while a {@code WritableFile} is open no {@link ReadableFile}
|
||||
* can be open and vice versa.
|
||||
* <p>
|
||||
* If a {@code Readable-} or {@code WritableFile} for this {@code File} is
|
||||
* open the invocation of this method will block regarding the specified
|
||||
* timeout.<br>
|
||||
* In addition implementations may block to lock the required IO resources
|
||||
* to read the file.
|
||||
*
|
||||
* @return a {@link WritableFile} to work with
|
||||
* @throws UncheckedIOException
|
||||
* if an {@link IOException} occurs while opening the file or
|
||||
* the file is a directory
|
||||
*/
|
||||
WritableFile openWritable() throws UncheckedIOException;
|
||||
|
||||
default void copyTo(File destination) {
|
||||
Copier.copy(this, destination);
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves this file including content to a new location specified by <code>destination</code>.
|
||||
*/
|
||||
void moveTo(File destination) throws UncheckedIOException;
|
||||
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Markus Kreusch
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
******************************************************************************/
|
||||
package org.cryptomator.filesystem;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* The root folder of a file system.
|
||||
*
|
||||
* @author Markus Kreusch
|
||||
*/
|
||||
public interface FileSystem extends Folder {
|
||||
|
||||
/**
|
||||
* @return an empty {@link Optional} because a {@link FileSystem} represents
|
||||
* the root {@link Folder} and thus does not have a parent
|
||||
*/
|
||||
@Override
|
||||
default Optional<? extends Folder> parent() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
Optional<Long> quotaUsedBytes();
|
||||
|
||||
Optional<Long> quotaAvailableBytes();
|
||||
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Markus Kreusch
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
******************************************************************************/
|
||||
package org.cryptomator.filesystem;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* A {@link Folder} in a {@link FileSystem}.
|
||||
*
|
||||
* @author Markus Kreusch
|
||||
*/
|
||||
public interface Folder extends Node {
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Creates a {@link Stream} over all child nodes of this {@code Folder}.
|
||||
* <p>
|
||||
* <b>Note:</b> The {@link Stream} may be lazily populated and thus
|
||||
* {@link IOException IOExceptions} may occurs after this method returned.
|
||||
* In this case implementors should throw a {@link UncheckedIOException}
|
||||
* from any method that produces an {@link IOException}. Thus users should
|
||||
* expect {@link UncheckedIOException UncheckedIOExceptions} when invoking
|
||||
* methods on the returned {@code Stream}.
|
||||
*
|
||||
* @return the created {@code Stream}
|
||||
* @throws UncheckedIOException
|
||||
* if an {@link IOException} occurs while initializing the
|
||||
* stream or the {@code Folder} does not exist
|
||||
*/
|
||||
Stream<? extends Node> children() throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns the child {@link Node} in this directory of type {@link File}
|
||||
* with the specified name.
|
||||
* <p>
|
||||
* This operation always returns a {@link File} without checking if the file
|
||||
* exists or is a {@link Folder} instead.
|
||||
*/
|
||||
File file(String name) throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* Returns a file by resolving a path relative to this folder.
|
||||
*
|
||||
* @param path A unix-style path, which is always relative to this folder, no matter if it starts with a slash or not. Path must not be empty.
|
||||
* @return File with the given path relative to this folder
|
||||
* @throws IllegalArgumentException
|
||||
* if relativePath is empty
|
||||
*/
|
||||
default File resolveFile(String relativePath) throws UncheckedIOException, IllegalArgumentException {
|
||||
return PathResolver.resolveFile(this, relativePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns the child {@link Node} in this directory of type {@link Folder}
|
||||
* with the specified name.
|
||||
* <p>
|
||||
* This operation always returns a {@link Folder} without checking if the
|
||||
* folder exists or is a {@link File} instead.
|
||||
*/
|
||||
Folder folder(String name) throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* Returns a folder by resolving a path relative to this folder.
|
||||
*
|
||||
* @param path A unix-style path, which is always relative to this folder, no matter if it starts with a slash or not. Path may be empty.
|
||||
* @return Folder with the given path relative to this folder. Returns <code>this</code> if path is empty.
|
||||
*/
|
||||
default Folder resolveFolder(String relativePath) throws UncheckedIOException {
|
||||
return PathResolver.resolveFolder(this, relativePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the directory including all parent directories, if it doesn't
|
||||
* exist yet. No effect, if folder already exists.
|
||||
*
|
||||
* @throws UncheckedIOException
|
||||
* if an {@link IOException} occurs while creating the folder or
|
||||
* one of its parents
|
||||
*/
|
||||
void create() throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* Recusively copies this directory and all its contents to (not into) the
|
||||
* given destination, creating nonexisting parent directories. If the target
|
||||
* exists it is deleted before performing the copy.
|
||||
*
|
||||
* @param target
|
||||
* Destination folder. Must not be a descendant of this folder.
|
||||
*/
|
||||
default void copyTo(Folder target) throws UncheckedIOException {
|
||||
Copier.copy(this, target);
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves this directory and its contents to the given destination. If the
|
||||
* target exists it is deleted before performing the move.
|
||||
*/
|
||||
void moveTo(Folder target);
|
||||
|
||||
/**
|
||||
* @return the result of {@link #children()} filtered to contain only
|
||||
* {@link File Files}
|
||||
*/
|
||||
default Stream<? extends File> files() throws UncheckedIOException {
|
||||
return children() //
|
||||
.filter(File.class::isInstance) //
|
||||
.map(File.class::cast);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the result of {@link #children()} filtered to contain only
|
||||
* {@link Folder Folders}
|
||||
*/
|
||||
default Stream<? extends Folder> folders() throws UncheckedIOException {
|
||||
return children() //
|
||||
.filter(Folder.class::isInstance) //
|
||||
.map(Folder.class::cast);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively checks whether this folder or any subfolder contains the
|
||||
* given node.
|
||||
*
|
||||
* @param node
|
||||
* Potential child, grandchild, ...
|
||||
* @return <code>true</code> if this folder is an ancestor of the node.
|
||||
*/
|
||||
default boolean isAncestorOf(Node node) {
|
||||
if (!node.parent().isPresent()) {
|
||||
return false;
|
||||
} else if (node.parent().get().equals(this)) {
|
||||
return true;
|
||||
} else {
|
||||
return this.isAncestorOf(node.parent().get());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class FolderVisitor {
|
||||
|
||||
private final Consumer<Folder> beforeFolderVisitor;
|
||||
private final Consumer<Folder> afterFolderVisitor;
|
||||
private final Consumer<File> fileVisitor;
|
||||
private final Consumer<Node> nodeVisitor;
|
||||
private final int maxDepth;
|
||||
|
||||
public FolderVisitor(FolderVisitorBuilder builder) {
|
||||
this.beforeFolderVisitor = builder.beforeFolderVisitor;
|
||||
this.afterFolderVisitor = builder.afterFolderVisitor;
|
||||
this.fileVisitor = builder.fileVisitor;
|
||||
this.nodeVisitor = builder.nodeVisitor;
|
||||
this.maxDepth = builder.maxDepth;
|
||||
}
|
||||
|
||||
public static FolderVisitorBuilder folderVisitor() {
|
||||
return new FolderVisitorBuilder();
|
||||
}
|
||||
|
||||
public FolderVisitor visit(Folder folder) {
|
||||
return visit(folder, 0);
|
||||
}
|
||||
|
||||
public FolderVisitor visit(File file) {
|
||||
return visit(file, 0);
|
||||
}
|
||||
|
||||
private FolderVisitor visit(Folder folder, int depth) {
|
||||
beforeFolderVisitor.accept(folder);
|
||||
nodeVisitor.accept(folder);
|
||||
final int childDepth = depth + 1;
|
||||
if (childDepth <= maxDepth) {
|
||||
folder.folders().forEach(childFolder -> visit(childFolder, childDepth));
|
||||
folder.files().forEach(childFile -> visit(childFile, childDepth));
|
||||
}
|
||||
afterFolderVisitor.accept(folder);
|
||||
return this;
|
||||
}
|
||||
|
||||
private FolderVisitor visit(File file, int depth) {
|
||||
nodeVisitor.accept(file);
|
||||
fileVisitor.accept(file);
|
||||
return this;
|
||||
}
|
||||
|
||||
public static class FolderVisitorBuilder {
|
||||
|
||||
private Consumer<Folder> beforeFolderVisitor = noOp();
|
||||
private Consumer<Folder> afterFolderVisitor = noOp();
|
||||
private Consumer<File> fileVisitor = noOp();
|
||||
private Consumer<Node> nodeVisitor = noOp();
|
||||
private int maxDepth = Integer.MAX_VALUE;
|
||||
|
||||
private FolderVisitorBuilder() {
|
||||
}
|
||||
|
||||
public FolderVisitorBuilder beforeFolder(Consumer<Folder> beforeFolderVisitor) {
|
||||
if (beforeFolderVisitor == null) {
|
||||
throw new IllegalArgumentException("Vistior may not be null");
|
||||
}
|
||||
this.beforeFolderVisitor = beforeFolderVisitor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public FolderVisitorBuilder afterFolder(Consumer<Folder> afterFolderVisitor) {
|
||||
if (afterFolderVisitor == null) {
|
||||
throw new IllegalArgumentException("Vistior may not be null");
|
||||
}
|
||||
this.afterFolderVisitor = afterFolderVisitor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public FolderVisitorBuilder forEachFile(Consumer<File> fileVisitor) {
|
||||
if (fileVisitor == null) {
|
||||
throw new IllegalArgumentException("Vistior may not be null");
|
||||
}
|
||||
this.fileVisitor = fileVisitor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public FolderVisitorBuilder forEachNode(Consumer<Node> nodeVisitor) {
|
||||
if (nodeVisitor == null) {
|
||||
throw new IllegalArgumentException("Vistior may not be null");
|
||||
}
|
||||
this.nodeVisitor = nodeVisitor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public FolderVisitorBuilder withMaxDepth(int maxDepth) {
|
||||
if (maxDepth < 0) {
|
||||
throw new IllegalArgumentException(format("maxDepth must not be smaller 0 but was %d", maxDepth));
|
||||
}
|
||||
this.maxDepth = maxDepth;
|
||||
return this;
|
||||
}
|
||||
|
||||
public FolderVisitor visit(Folder folder) {
|
||||
return build().visit(folder);
|
||||
}
|
||||
|
||||
public FolderVisitor visit(File file) {
|
||||
return build().visit(file);
|
||||
}
|
||||
|
||||
public FolderVisitor build() {
|
||||
return new FolderVisitor(this);
|
||||
}
|
||||
|
||||
private static <T> Consumer<T> noOp() {
|
||||
return ignoredParameter -> {
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Markus Kreusch
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
******************************************************************************/
|
||||
package org.cryptomator.filesystem;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Represents a node, namely a {@link File} or {@link Folder}, in a
|
||||
* {@link FileSystem}.
|
||||
* <p>
|
||||
* A node's identity (i.e. {@link #hashCode()} and {@link #equals(Object)}) depends on its parent node and its name (forming the node's path).
|
||||
* These properties are meant to be immutable. This means that e.g. moving a node doesn't modify the node's identity but rather transfers properties to the destination node.
|
||||
*
|
||||
* @author Markus Kreusch
|
||||
* @see Folder
|
||||
* @see File
|
||||
*/
|
||||
public interface Node {
|
||||
|
||||
String name() throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* @return Optional parent folder. No parent is present for the root node (see {@link FileSystem#parent()}).
|
||||
*/
|
||||
Optional<? extends Folder> parent() throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* @return <code>true</code> if the node exists.
|
||||
*/
|
||||
boolean exists() throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Deletes the node if it exists.
|
||||
* <p>
|
||||
* Does nothing if the node does not exist.
|
||||
*/
|
||||
void delete() throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Determines the last modified date of this node.
|
||||
*
|
||||
* @returns the last modified date of the file
|
||||
*/
|
||||
Instant lastModified() throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets the last modified date of the file.
|
||||
*
|
||||
* @param lastModified the time to set as creation time
|
||||
*/
|
||||
void setLastModified(Instant lastModified) throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Determines the creation time of this node.
|
||||
* <p>
|
||||
* Note: Getting the creation time may not be supported by all {@link FileSystem FileSystems}.
|
||||
*
|
||||
* @returns the creation time of the file or {@link Optional#empty()} if not supported
|
||||
*/
|
||||
default Optional<Instant> creationTime() throws UncheckedIOException {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets the creation time of this node.
|
||||
* <p>
|
||||
* Setting the creation time may not be supported by all {@link FileSystem FileSystems}. If the {@code FileSystem} this {@code Node} belongs to does not support the
|
||||
* setting the creation time the behavior of this method is unspecified.
|
||||
*
|
||||
* @param creationTime the time to set as creation time
|
||||
*/
|
||||
default void setCreationTime(Instant creationTime) throws UncheckedIOException {
|
||||
throw new UncheckedIOException(new IOException("CreationTime not supported"));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the {@link FileSystem} this Node belongs to
|
||||
*/
|
||||
default FileSystem fileSystem() {
|
||||
return parent() //
|
||||
.map(Node::fileSystem) //
|
||||
.orElseGet(() -> (FileSystem) this);
|
||||
}
|
||||
|
||||
default boolean belongsToSameFilesystem(Node other) {
|
||||
return fileSystem() == other.fileSystem();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem;
|
||||
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class OpenFiles implements AutoCloseable {
|
||||
|
||||
private final static Logger LOG = LoggerFactory.getLogger(OpenFiles.class);
|
||||
|
||||
private final Map<File, ReadableFile> readableFiles;
|
||||
private final Map<File, WritableFile> writableFiles;
|
||||
|
||||
public OpenFiles(Map<File, ReadableFile> readableFiles, Map<File, WritableFile> writableFiles) {
|
||||
this.readableFiles = readableFiles;
|
||||
this.writableFiles = writableFiles;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws UncheckedIOException {
|
||||
OpenFiles.cleanup(readableFiles.values(), writableFiles.values());
|
||||
}
|
||||
|
||||
public ReadableFile readable(File file) {
|
||||
return readableFiles.computeIfAbsent(file, fileNotOpenForReading -> {
|
||||
throw new IllegalArgumentException(String.format("File %s is not open for reading", fileNotOpenForReading));
|
||||
});
|
||||
}
|
||||
|
||||
public WritableFile writable(File file) {
|
||||
return writableFiles.computeIfAbsent(file, fileNotOpenForWriting -> {
|
||||
throw new IllegalArgumentException(String.format("File %s is not open for writing", fileNotOpenForWriting));
|
||||
});
|
||||
}
|
||||
|
||||
static void cleanup(Collection<ReadableFile> readableFiles, Collection<WritableFile> writableFiles) {
|
||||
Iterator<? extends AutoCloseable> iterator = Stream.concat(readableFiles.stream(), writableFiles.stream()).iterator();
|
||||
UncheckedIOException firstException = null;
|
||||
while (iterator.hasNext()) {
|
||||
AutoCloseable openFile = iterator.next();
|
||||
try {
|
||||
openFile.close();
|
||||
} catch (UncheckedIOException e) {
|
||||
if (firstException == null) {
|
||||
firstException = e;
|
||||
} else {
|
||||
firstException.addSuppressed(e);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.error("Unexpected exception during close on " + openFile.getClass().getSimpleName(), e);
|
||||
}
|
||||
}
|
||||
if (firstException != null) {
|
||||
throw firstException;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package org.cryptomator.filesystem;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
final class PathResolver {
|
||||
|
||||
private static final String DOT = ".";
|
||||
private static final String DOTDOT = "..";
|
||||
|
||||
private PathResolver() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a relative path (separated by '/') to a folder, e.g.
|
||||
* <!-- @formatter:off -->
|
||||
* <table>
|
||||
* <thead>
|
||||
* <tr>
|
||||
* <th>dir</th>
|
||||
* <th>path</th>
|
||||
* <th>result</th>
|
||||
* </tr>
|
||||
* </thead>
|
||||
* <tbody>
|
||||
* <tr>
|
||||
* <td>/foo/bar</td>
|
||||
* <td>foo/bar</td>
|
||||
* <td>/foo/bar/foo/bar</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>/foo/bar</td>
|
||||
* <td>../baz</td>
|
||||
* <td>/foo/baz</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>/foo/bar</td>
|
||||
* <td>./foo/..</td>
|
||||
* <td>/foo/bar</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>/foo/bar</td>
|
||||
* <td>/</td>
|
||||
* <td>/foo/bar</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>/foo/bar</td>
|
||||
* <td></td>
|
||||
* <td>/foo/bar</td>
|
||||
* </tr>
|
||||
* <tr>
|
||||
* <td>/foo/bar</td>
|
||||
* <td>../../..</td>
|
||||
* <td>Exception</td>
|
||||
* </tr>
|
||||
* </tbody>
|
||||
* </table>
|
||||
*
|
||||
* @param dir The directory from which to resolve the path.
|
||||
* @param relativePath The path relative to a given directory.
|
||||
* @return The folder with the given path relative to the given dir.
|
||||
*/
|
||||
public static Folder resolveFolder(Folder dir, String relativePath) {
|
||||
final String[] fragments = StringUtils.split(relativePath, '/');
|
||||
if (ArrayUtils.isEmpty(fragments)) {
|
||||
return dir;
|
||||
}
|
||||
return resolveFolder(dir, Arrays.stream(fragments).iterator());
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a relative path (separated by '/') to a file. Besides returning a File, this method is identical to {@link #resolveFile(Folder, String)}.
|
||||
*
|
||||
* @param dir The directory from which to resolve the path.
|
||||
* @param relativePath The path relative to a given directory.
|
||||
* @return The file with the given path relative to the given dir.
|
||||
* @throws IllegalArgumentException
|
||||
* if relativePath is empty, as this path would resolve to the directory itself, which obviously can't be a file.
|
||||
*/
|
||||
public static File resolveFile(Folder dir, String relativePath) {
|
||||
final String[] fragments = StringUtils.split(relativePath, '/');
|
||||
if (ArrayUtils.isEmpty(fragments)) {
|
||||
throw new IllegalArgumentException("Empty relativePath");
|
||||
}
|
||||
final Folder folder = resolveFolder(dir, Arrays.stream(fragments).limit(fragments.length - 1).iterator());
|
||||
final String filename = fragments[fragments.length - 1];
|
||||
return folder.file(filename);
|
||||
}
|
||||
|
||||
private static Folder resolveFolder(Folder dir, Iterator<String> remainingPathFragments) {
|
||||
if (!remainingPathFragments.hasNext()) {
|
||||
return dir;
|
||||
}
|
||||
final String fragment = remainingPathFragments.next();
|
||||
assert fragment.length() > 0 : "iterator must not contain empty fragments";
|
||||
if (DOT.equals(fragment)) {
|
||||
return resolveFolder(dir, remainingPathFragments);
|
||||
} else if (DOTDOT.equals(fragment) && dir.parent().isPresent()) {
|
||||
return resolveFolder(dir.parent().get(), remainingPathFragments);
|
||||
} else if (DOTDOT.equals(fragment) && !dir.parent().isPresent()) {
|
||||
throw new UncheckedIOException(new FileNotFoundException("Unresolvable path"));
|
||||
} else {
|
||||
return resolveFolder(dir.folder(fragment), remainingPathFragments);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Markus Kreusch
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
******************************************************************************/
|
||||
package org.cryptomator.filesystem;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.ReadableByteChannel;
|
||||
|
||||
public interface ReadableFile extends ReadableByteChannel {
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Tries to fill the remaining space in the given byte buffer with data from
|
||||
* this readable bytes from the current position.
|
||||
* <p>
|
||||
* May read less bytes if the end of this readable bytes has been reached.
|
||||
*
|
||||
* @param target
|
||||
* the byte buffer to fill
|
||||
* @return the number of bytes actually read, or {@code -1} if the end of
|
||||
* file has been reached
|
||||
* @throws UncheckedIOException
|
||||
* if an {@link IOException} occurs while reading from this
|
||||
* {@code ReadableBytes}
|
||||
*/
|
||||
@Override
|
||||
int read(ByteBuffer target) throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Fast-forwards or rewinds the file to the specified position.
|
||||
* <p>
|
||||
* Consecutive reads on the file will begin at the new position.
|
||||
*
|
||||
* @param position
|
||||
* the position to set the file to
|
||||
* @throws UncheckedIOException
|
||||
* if an {@link IOException} occurs
|
||||
*
|
||||
*/
|
||||
void position(long position) throws UncheckedIOException;
|
||||
|
||||
@Override
|
||||
void close() throws UncheckedIOException;
|
||||
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Markus Kreusch
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
******************************************************************************/
|
||||
package org.cryptomator.filesystem;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.WritableByteChannel;
|
||||
|
||||
public interface WritableFile extends WritableByteChannel {
|
||||
|
||||
void truncate() throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* Writes the data in the given byte buffer to this readable bytes at the
|
||||
* current position.
|
||||
*
|
||||
* @param source
|
||||
* the byte buffer to use
|
||||
* @return the number of bytes written, always equal to
|
||||
* {@code source.remaining()}
|
||||
* @throws UncheckedIOException
|
||||
* if an {@link IOException} occurs while writing
|
||||
*/
|
||||
@Override
|
||||
int write(ByteBuffer source) throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Fast-forwards or rewinds the file to the specified position.
|
||||
* <p>
|
||||
* Consecutive writes on the file will begin at the new position.
|
||||
* <p>
|
||||
* If the position is set to a value greater than the current end of file
|
||||
* consecutive writes will write data to the given position. The value of
|
||||
* all bytes between this position and the previous end of file will be
|
||||
* unspecified.
|
||||
*
|
||||
* @param position
|
||||
* the position to set the file to
|
||||
* @throws UncheckedIOException
|
||||
* if an {@link IOException} occurs
|
||||
*/
|
||||
void position(long position) throws UncheckedIOException;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Closes this {@code WritableFile} which finally commits all operations
|
||||
* performed on it to the underlying file system.
|
||||
* <p>
|
||||
* After a {@code WritableFile} has been closed all other operations will
|
||||
* throw an {@link UncheckedIOException}.
|
||||
* <p>
|
||||
* Invoking this method on a {@link WritableFile} which has already been
|
||||
* closed does nothing.
|
||||
*/
|
||||
@Override
|
||||
void close() throws UncheckedIOException;
|
||||
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.delegating;
|
||||
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.cryptomator.filesystem.File;
|
||||
import org.cryptomator.filesystem.ReadableFile;
|
||||
import org.cryptomator.filesystem.WritableFile;
|
||||
|
||||
public abstract class DelegatingFile<D extends DelegatingFolder<D, ?>> extends DelegatingNode<File> implements File {
|
||||
|
||||
private final D parent;
|
||||
|
||||
public DelegatingFile(D parent, File delegate) {
|
||||
super(delegate);
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<D> parent() throws UncheckedIOException {
|
||||
return Optional.of(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long size() throws UncheckedIOException {
|
||||
return delegate.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ReadableFile openReadable() throws UncheckedIOException {
|
||||
return delegate.openReadable();
|
||||
}
|
||||
|
||||
@Override
|
||||
public WritableFile openWritable() throws UncheckedIOException {
|
||||
return delegate.openWritable();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void copyTo(File destination) {
|
||||
if (getClass().equals(destination.getClass())) {
|
||||
final File delegateDest = ((DelegatingFile<?>) destination).delegate;
|
||||
delegate.copyTo(delegateDest);
|
||||
} else {
|
||||
delegate.copyTo(destination);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void moveTo(File destination) {
|
||||
if (getClass().equals(destination.getClass())) {
|
||||
final File delegateDest = ((DelegatingFile<?>) destination).delegate;
|
||||
delegate.moveTo(delegateDest);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Can only move DelegatingFile to other DelegatingFile.");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete() throws UncheckedIOException {
|
||||
delegate.delete();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(File o) {
|
||||
if (getClass().equals(o.getClass())) {
|
||||
final File delegateOther = ((DelegatingFile<?>) o).delegate;
|
||||
return delegate.compareTo(delegateOther);
|
||||
} else {
|
||||
return delegate.compareTo(o);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package org.cryptomator.filesystem.delegating;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.cryptomator.filesystem.FileSystem;
|
||||
import org.cryptomator.filesystem.Folder;
|
||||
|
||||
public interface DelegatingFileSystem extends FileSystem {
|
||||
|
||||
Folder getDelegate();
|
||||
|
||||
@Override
|
||||
default Optional<Long> quotaUsedBytes() {
|
||||
return getDelegate().fileSystem().quotaUsedBytes();
|
||||
}
|
||||
|
||||
@Override
|
||||
default Optional<Long> quotaAvailableBytes() {
|
||||
return getDelegate().fileSystem().quotaAvailableBytes();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.delegating;
|
||||
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.cryptomator.common.WeakValuedCache;
|
||||
import org.cryptomator.common.streams.AutoClosingStream;
|
||||
import org.cryptomator.filesystem.File;
|
||||
import org.cryptomator.filesystem.Folder;
|
||||
import org.cryptomator.filesystem.Node;
|
||||
|
||||
public abstract class DelegatingFolder<D extends DelegatingFolder<D, F>, F extends DelegatingFile<D>> extends DelegatingNode<Folder>implements Folder {
|
||||
|
||||
private final D parent;
|
||||
private final WeakValuedCache<Folder, D> folders = WeakValuedCache.usingLoader(this::newFolder);
|
||||
private final WeakValuedCache<File, F> files = WeakValuedCache.usingLoader(this::newFile);
|
||||
|
||||
public DelegatingFolder(D parent, Folder delegate) {
|
||||
super(delegate);
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<D> parent() throws UncheckedIOException {
|
||||
return Optional.ofNullable(parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Stream<? extends Node> children() throws UncheckedIOException {
|
||||
return AutoClosingStream.from(Stream.concat(folders(), files()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Stream<D> folders() {
|
||||
return delegate.folders().map(folders::get);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Stream<F> files() throws UncheckedIOException {
|
||||
return delegate.files().map(files::get);
|
||||
}
|
||||
|
||||
@Override
|
||||
public F file(String name) throws UncheckedIOException {
|
||||
return files.get(delegate.file(name));
|
||||
}
|
||||
|
||||
protected abstract F newFile(File delegate);
|
||||
|
||||
@Override
|
||||
public D folder(String name) throws UncheckedIOException {
|
||||
return folders.get(delegate.folder(name));
|
||||
}
|
||||
|
||||
protected abstract D newFolder(Folder delegate);
|
||||
|
||||
@Override
|
||||
public void create() throws UncheckedIOException {
|
||||
if (exists()) {
|
||||
return;
|
||||
}
|
||||
parent().ifPresent(p -> p.create());
|
||||
delegate.create();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete() {
|
||||
delegate.delete();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void copyTo(Folder destination) throws UncheckedIOException {
|
||||
if (destination instanceof DelegatingFolder) {
|
||||
final Folder delegateDest = ((DelegatingFolder<?, ?>) destination).delegate;
|
||||
delegate.copyTo(delegateDest);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Can only copy DelegatingFolder to other DelegatingFolder.");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void moveTo(Folder destination) {
|
||||
if (getClass().equals(destination.getClass())) {
|
||||
final Folder delegateDest = ((DelegatingFolder<?, ?>) destination).delegate;
|
||||
delegate.moveTo(delegateDest);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Can only move DelegatingFolder to other DelegatingFolder.");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.delegating;
|
||||
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.cryptomator.filesystem.Node;
|
||||
|
||||
public abstract class DelegatingNode<T extends Node> implements Node {
|
||||
|
||||
protected final T delegate;
|
||||
|
||||
public DelegatingNode(T delegate) {
|
||||
if (delegate == null) {
|
||||
throw new IllegalArgumentException("Delegate must not be null");
|
||||
}
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() throws UncheckedIOException {
|
||||
return delegate.name();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean exists() throws UncheckedIOException {
|
||||
return delegate.exists();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instant lastModified() throws UncheckedIOException {
|
||||
return delegate.lastModified();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLastModified(Instant instant) throws UncheckedIOException {
|
||||
delegate.setLastModified(instant);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Instant> creationTime() throws UncheckedIOException {
|
||||
return delegate.creationTime();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCreationTime(Instant instant) throws UncheckedIOException {
|
||||
delegate.setCreationTime(instant);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return delegate.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof DelegatingNode) {
|
||||
DelegatingNode<?> other = (DelegatingNode<?>) obj;
|
||||
return this.delegate.equals(other.delegate);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Delegate[" + delegate + "]";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.delegating;
|
||||
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import org.cryptomator.filesystem.ReadableFile;
|
||||
|
||||
public class DelegatingReadableFile implements ReadableFile {
|
||||
|
||||
private final ReadableFile delegate;
|
||||
|
||||
public DelegatingReadableFile(ReadableFile delegate) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOpen() {
|
||||
return delegate.isOpen();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(ByteBuffer target) throws UncheckedIOException {
|
||||
return delegate.read(target);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void position(long position) throws UncheckedIOException {
|
||||
delegate.position(position);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws UncheckedIOException {
|
||||
delegate.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.delegating;
|
||||
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import org.cryptomator.filesystem.WritableFile;
|
||||
|
||||
public class DelegatingWritableFile implements WritableFile {
|
||||
|
||||
final WritableFile delegate;
|
||||
|
||||
public DelegatingWritableFile(WritableFile delegate) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOpen() {
|
||||
return delegate.isOpen();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void truncate() throws UncheckedIOException {
|
||||
delegate.truncate();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int write(ByteBuffer source) throws UncheckedIOException {
|
||||
return delegate.write(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void position(long position) throws UncheckedIOException {
|
||||
delegate.position(position);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws UncheckedIOException {
|
||||
delegate.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
/**
|
||||
* Defines a file system abstraction to allow access to real and virtual file
|
||||
* systems through a common API.
|
||||
*/
|
||||
package org.cryptomator.filesystem;
|
||||
@@ -1,35 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.io;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
public final class ByteBuffers {
|
||||
|
||||
private ByteBuffers() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies as many bytes as possible from the given source to the destination buffer.
|
||||
* The position of both buffers will be incremented by as many bytes as have been copied.
|
||||
*
|
||||
* @param source ByteBuffer from which bytes are read
|
||||
* @param destination ByteBuffer into which bytes are written
|
||||
* @return number of bytes copied, i.e. {@link ByteBuffer#remaining() source.remaining()} or {@link ByteBuffer#remaining() destination.remaining()}, whatever is less.
|
||||
*/
|
||||
public static int copy(ByteBuffer source, ByteBuffer destination) {
|
||||
final int numBytes = Math.min(source.remaining(), destination.remaining());
|
||||
final ByteBuffer tmp = source.asReadOnlyBuffer();
|
||||
tmp.limit(tmp.position() + numBytes);
|
||||
destination.put(tmp);
|
||||
source.position(tmp.position()); // until now only tmp pos has been incremented, so we need to adjust the position
|
||||
return numBytes;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package org.cryptomator.io;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.channels.Channels;
|
||||
import java.nio.channels.ReadableByteChannel;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.cryptomator.filesystem.File;
|
||||
import org.cryptomator.filesystem.WritableFile;
|
||||
|
||||
public final class FileContents {
|
||||
|
||||
public static final FileContents UTF_8 = FileContents.withCharset(StandardCharsets.UTF_8);
|
||||
|
||||
private final Charset charset;
|
||||
|
||||
private FileContents(Charset charset) {
|
||||
this.charset = charset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the whole content from the given file.
|
||||
*
|
||||
* @param file File whose content should be read.
|
||||
* @return The file's content interpreted in this FileContents' charset.
|
||||
*/
|
||||
public String readContents(File file) {
|
||||
try ( //
|
||||
ReadableByteChannel channel = file.openReadable(); //
|
||||
Reader reader = Channels.newReader(channel, charset.newDecoder(), -1)) {
|
||||
return IOUtils.toString(reader);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the string into the file encoded with this FileContents' charset.
|
||||
* This methods replaces any previously existing content, i.e. the string will be the sole content.
|
||||
*
|
||||
* @param file File whose content should be written.
|
||||
* @param content The new content.
|
||||
*/
|
||||
public void writeContents(File file, String content) {
|
||||
try (WritableFile writable = file.openWritable()) {
|
||||
writable.truncate();
|
||||
writable.write(charset.encode(content));
|
||||
}
|
||||
}
|
||||
|
||||
public static FileContents withCharset(Charset charset) {
|
||||
return new FileContents(charset);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package org.cryptomator.filesystem;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import org.hamcrest.Description;
|
||||
import org.hamcrest.Matcher;
|
||||
import org.hamcrest.TypeSafeDiagnosingMatcher;
|
||||
|
||||
public class ByteBufferMatcher {
|
||||
|
||||
public static Matcher<ByteBuffer> byteBufferFilledWith(int value) {
|
||||
if (((byte) value) != value) {
|
||||
throw new IllegalArgumentException("Invalid byte value");
|
||||
}
|
||||
return new TypeSafeDiagnosingMatcher<ByteBuffer>(ByteBuffer.class) {
|
||||
|
||||
@Override
|
||||
public void describeTo(Description description) {
|
||||
description.appendText("a byte buffer filled with " + value);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean matchesSafely(ByteBuffer item, Description mismatchDescription) {
|
||||
while (item.hasRemaining()) {
|
||||
byte currentValue = item.get();
|
||||
if (currentValue != value) {
|
||||
mismatchDescription.appendText("a byte buffer containing also " + currentValue);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,227 +0,0 @@
|
||||
package org.cryptomator.filesystem;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.cryptomator.common.test.matcher.ContainsMatcher.contains;
|
||||
import static org.cryptomator.common.test.mockito.Answers.collectParameters;
|
||||
import static org.cryptomator.common.test.mockito.Answers.consecutiveAnswers;
|
||||
import static org.cryptomator.common.test.mockito.Answers.value;
|
||||
import static org.cryptomator.filesystem.File.EOF;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InOrder;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.junit.MockitoJUnit;
|
||||
import org.mockito.junit.MockitoRule;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
import de.bechte.junit.runners.context.HierarchicalContextRunner;
|
||||
|
||||
@RunWith(HierarchicalContextRunner.class)
|
||||
public class CopierTest {
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
@Rule
|
||||
public MockitoRule mockitoRule = MockitoJUnit.rule();
|
||||
|
||||
public class CopyFiles {
|
||||
|
||||
@Mock
|
||||
private File source;
|
||||
|
||||
@Mock
|
||||
private File destination;
|
||||
|
||||
@Mock
|
||||
private ReadableFile readable;
|
||||
|
||||
@Mock
|
||||
private WritableFile writable;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
when(source.openReadable()).thenReturn(readable);
|
||||
when(destination.openWritable()).thenReturn(writable);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCopyFileOpensFilesInSortedOrderIfSourceIsSmallerDestination() {
|
||||
mockCompareToWithOrder(source, destination);
|
||||
when(readable.read(any())).thenReturn(EOF);
|
||||
|
||||
Copier.copy(source, destination);
|
||||
|
||||
InOrder inOrder = inOrder(source, destination);
|
||||
inOrder.verify(source).openReadable();
|
||||
inOrder.verify(destination).openWritable();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCopyFileOpensFilesInSortedOrderIfDestinationIsSmallerSource() {
|
||||
mockCompareToWithOrder(destination, source);
|
||||
when(readable.read(any())).thenReturn(EOF);
|
||||
|
||||
Copier.copy(source, destination);
|
||||
|
||||
InOrder inOrder = inOrder(source, destination);
|
||||
inOrder.verify(destination).openWritable();
|
||||
inOrder.verify(source).openReadable();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCopyFileReadsAndWritesReadableSourceAndWritableDestintationUntilEof() {
|
||||
int irrelevantValue = 0;
|
||||
Collection<byte[]> written = new ArrayList<>();
|
||||
mockCompareToWithOrder(source, destination);
|
||||
byte[] read1 = {1, 48, 32, 33, 22};
|
||||
byte[] read2 = {4, 3, 1, -2, -8};
|
||||
when(readable.read(any())).then(consecutiveAnswers(fillBufferWith(read1), fillBufferWith(read2), value(EOF)));
|
||||
when(writable.write(any())).then(collectParameters(value(irrelevantValue), (ByteBuffer buffer) -> {
|
||||
byte[] data = new byte[buffer.remaining()];
|
||||
buffer.get(data);
|
||||
written.add(data);
|
||||
}));
|
||||
|
||||
Copier.copy(source, destination);
|
||||
|
||||
InOrder inOrder = inOrder(readable, writable);
|
||||
inOrder.verify(writable).truncate();
|
||||
inOrder.verify(readable).read(any());
|
||||
inOrder.verify(writable).write(any());
|
||||
inOrder.verify(readable).read(any());
|
||||
inOrder.verify(writable).write(any());
|
||||
inOrder.verify(readable).read(any());
|
||||
inOrder.verify(readable).close();
|
||||
inOrder.verify(writable).close();
|
||||
|
||||
assertThat(written, contains(is(read1), is(read2)));
|
||||
}
|
||||
|
||||
private Answer<Integer> fillBufferWith(byte[] data) {
|
||||
return new Answer<Integer>() {
|
||||
@Override
|
||||
public Integer answer(InvocationOnMock invocation) throws Throwable {
|
||||
ByteBuffer buffer = invocation.getArgumentAt(0, ByteBuffer.class);
|
||||
for (byte value : data) {
|
||||
buffer.put(value);
|
||||
}
|
||||
return data.length;
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
private void mockCompareToWithOrder(File first, File last) {
|
||||
when(first.compareTo(last)).thenReturn(-1);
|
||||
when(last.compareTo(first)).thenReturn(1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public class CopyFolders {
|
||||
|
||||
@Mock
|
||||
private Folder source;
|
||||
|
||||
@Mock
|
||||
private Folder destination;
|
||||
|
||||
@Test
|
||||
public void testCopyFolderDeletesAndCreatesDestinationBeforeIteratingOverTheFilesAndFoldersInSource() {
|
||||
when(source.files()).thenReturn(Stream.empty());
|
||||
when(source.folders()).thenReturn(Stream.empty());
|
||||
|
||||
Copier.copy(source, destination);
|
||||
|
||||
InOrder inOrder = inOrder(source, destination);
|
||||
inOrder.verify(destination).delete();
|
||||
inOrder.verify(destination).create();
|
||||
inOrder.verify(source).files();
|
||||
inOrder.verify(source).folders();
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
public void testCopyFolderInvokesCopyToOnAllFilesInSourceWithFileWithSameNameFromDestination() {
|
||||
String filename1 = "nameOfFile1";
|
||||
String filename2 = "nameOfFile2";
|
||||
File file1 = mock(File.class);
|
||||
File file2 = mock(File.class);
|
||||
File destinationFile1 = mock(File.class);
|
||||
File destinationFile2 = mock(File.class);
|
||||
when(source.files()).thenReturn((Stream) asList(file1, file2).stream());
|
||||
when(source.folders()).thenReturn(Stream.empty());
|
||||
when(destination.file(filename1)).thenReturn(destinationFile1);
|
||||
when(destination.file(filename2)).thenReturn(destinationFile2);
|
||||
when(file1.name()).thenReturn(filename1);
|
||||
when(file2.name()).thenReturn(filename2);
|
||||
|
||||
Copier.copy(source, destination);
|
||||
|
||||
verify(file1).copyTo(destinationFile1);
|
||||
verify(file2).copyTo(destinationFile2);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
public void testCopyFolderInvokesCopyToOnAllFoldersInSourceWithFolderWithSameNameFromDestination() {
|
||||
String folderName1 = "nameOfFolder1";
|
||||
String folderName2 = "nameOfFolder2";
|
||||
Folder folder1 = mock(Folder.class);
|
||||
Folder folder2 = mock(Folder.class);
|
||||
Folder destinationfolder1 = mock(Folder.class);
|
||||
Folder destinationfolder2 = mock(Folder.class);
|
||||
when(source.folders()).thenReturn((Stream) asList(folder1, folder2).stream());
|
||||
when(source.files()).thenReturn(Stream.empty());
|
||||
when(destination.folder(folderName1)).thenReturn(destinationfolder1);
|
||||
when(destination.folder(folderName2)).thenReturn(destinationfolder2);
|
||||
when(folder1.name()).thenReturn(folderName1);
|
||||
when(folder2.name()).thenReturn(folderName2);
|
||||
|
||||
Copier.copy(source, destination);
|
||||
|
||||
verify(folder1).copyTo(destinationfolder1);
|
||||
verify(folder2).copyTo(destinationfolder2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCopyFolderFailsWithIllegalArgumentExceptionIfSourceIsNestedInDestination() {
|
||||
when(source.isAncestorOf(destination)).thenReturn(false);
|
||||
when(destination.isAncestorOf(source)).thenReturn(true);
|
||||
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
|
||||
Copier.copy(source, destination);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCopyFolderFailsWithIllegalArgumentExceptionIfDestinationIsNestedInSource() {
|
||||
when(source.isAncestorOf(destination)).thenReturn(true);
|
||||
when(destination.isAncestorOf(source)).thenReturn(false);
|
||||
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
|
||||
Copier.copy(source, destination);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package org.cryptomator.filesystem;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
public class PathResolverTest {
|
||||
|
||||
private final Folder root = Mockito.mock(Folder.class);
|
||||
private final Folder foo = Mockito.mock(Folder.class);
|
||||
private final Folder bar = Mockito.mock(Folder.class);
|
||||
private final File baz = Mockito.mock(File.class);
|
||||
|
||||
@Before
|
||||
public void configureMocks() throws IOException {
|
||||
Mockito.doReturn(Optional.empty()).when(root).parent();
|
||||
Mockito.doReturn(Optional.of(root)).when(foo).parent();
|
||||
Mockito.doReturn(Optional.of(foo)).when(bar).parent();
|
||||
|
||||
Mockito.doReturn(foo).when(root).folder("foo");
|
||||
Mockito.doReturn(bar).when(foo).folder("bar");
|
||||
Mockito.doReturn(baz).when(bar).file("baz");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResolveSameFolder() {
|
||||
Assert.assertEquals(foo, PathResolver.resolveFolder(foo, ""));
|
||||
Assert.assertEquals(foo, PathResolver.resolveFolder(foo, "/"));
|
||||
Assert.assertEquals(foo, PathResolver.resolveFolder(foo, "///"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResolveChildFolder() {
|
||||
Assert.assertEquals(bar, PathResolver.resolveFolder(root, "foo/bar"));
|
||||
Assert.assertEquals(bar, PathResolver.resolveFolder(root, "foo/./bar"));
|
||||
Assert.assertEquals(bar, PathResolver.resolveFolder(root, "./foo/././bar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResolveParentFolder() {
|
||||
Assert.assertEquals(foo, PathResolver.resolveFolder(bar, ".."));
|
||||
Assert.assertEquals(root, PathResolver.resolveFolder(bar, "../.."));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResolveSiblingFolder() {
|
||||
Assert.assertEquals(foo, PathResolver.resolveFolder(bar, "../../foo"));
|
||||
}
|
||||
|
||||
@Test(expected = UncheckedIOException.class)
|
||||
public void testResolveUnresolvableFolder() {
|
||||
PathResolver.resolveFolder(root, "..");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testResolveFileWithEmptyPath() {
|
||||
PathResolver.resolveFile(root, "");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResolveFile() {
|
||||
Assert.assertEquals(baz, PathResolver.resolveFile(foo, "../foo/bar/./baz"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package org.cryptomator.filesystem.delegating;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.cryptomator.filesystem.FileSystem;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
public class DelegatingFileSystemTest {
|
||||
|
||||
@Test
|
||||
public void testQuotaAvailableBytes() {
|
||||
FileSystem mockFs = Mockito.mock(FileSystem.class);
|
||||
Mockito.when(mockFs.fileSystem()).thenReturn(mockFs);
|
||||
Mockito.when(mockFs.quotaAvailableBytes()).thenReturn(Optional.of(42l));
|
||||
|
||||
DelegatingFileSystem delegatingFs = TestDelegatingFileSystem.withRoot(mockFs);
|
||||
Assert.assertEquals(mockFs.quotaAvailableBytes(), delegatingFs.quotaAvailableBytes());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQuotaUsedBytes() {
|
||||
FileSystem mockFs = Mockito.mock(FileSystem.class);
|
||||
Mockito.when(mockFs.fileSystem()).thenReturn(mockFs);
|
||||
Mockito.when(mockFs.quotaUsedBytes()).thenReturn(Optional.of(23l));
|
||||
|
||||
DelegatingFileSystem delegatingFs = TestDelegatingFileSystem.withRoot(mockFs);
|
||||
Assert.assertEquals(mockFs.quotaUsedBytes(), delegatingFs.quotaUsedBytes());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.delegating;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.cryptomator.filesystem.File;
|
||||
import org.cryptomator.filesystem.Folder;
|
||||
import org.cryptomator.filesystem.ReadableFile;
|
||||
import org.cryptomator.filesystem.WritableFile;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
public class DelegatingFileTest {
|
||||
|
||||
@Test
|
||||
public void testName() {
|
||||
File mockFile = Mockito.mock(File.class);
|
||||
DelegatingFile<?> delegatingFile = new TestDelegatingFile(null, mockFile);
|
||||
|
||||
Mockito.when(mockFile.name()).thenReturn("Test");
|
||||
Assert.assertEquals(mockFile.name(), delegatingFile.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSize() {
|
||||
File mockFile = Mockito.mock(File.class);
|
||||
DelegatingFile<?> delegatingFile = new TestDelegatingFile(null, mockFile);
|
||||
|
||||
Mockito.when(mockFile.size()).thenReturn(42l);
|
||||
Assert.assertEquals(42l, delegatingFile.size());
|
||||
Mockito.verify(mockFile).size();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParent() {
|
||||
Folder mockFolder = Mockito.mock(Folder.class);
|
||||
File mockFile = Mockito.mock(File.class);
|
||||
|
||||
TestDelegatingFileSystem delegatingParent = TestDelegatingFileSystem.withRoot(mockFolder);
|
||||
DelegatingFile<?> delegatingFile = new TestDelegatingFile(delegatingParent, mockFile);
|
||||
Assert.assertEquals(delegatingParent, delegatingFile.parent().get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExists() {
|
||||
File mockFile = Mockito.mock(File.class);
|
||||
DelegatingFile<?> delegatingFile = new TestDelegatingFile(null, mockFile);
|
||||
|
||||
Mockito.when(mockFile.exists()).thenReturn(true);
|
||||
Assert.assertTrue(delegatingFile.exists());
|
||||
|
||||
Mockito.when(mockFile.exists()).thenReturn(false);
|
||||
Assert.assertFalse(delegatingFile.exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLastModified() {
|
||||
File mockFile = Mockito.mock(File.class);
|
||||
DelegatingFile<?> delegatingFile = new TestDelegatingFile(null, mockFile);
|
||||
|
||||
Instant now = Instant.now();
|
||||
Mockito.when(mockFile.lastModified()).thenReturn(now);
|
||||
Assert.assertEquals(now, delegatingFile.lastModified());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetLastModified() {
|
||||
File mockFile = Mockito.mock(File.class);
|
||||
DelegatingFile<?> delegatingFile = new TestDelegatingFile(null, mockFile);
|
||||
|
||||
Instant now = Instant.now();
|
||||
delegatingFile.setLastModified(now);
|
||||
Mockito.verify(mockFile).setLastModified(now);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreationTime() {
|
||||
File mockFile = Mockito.mock(File.class);
|
||||
DelegatingFile<?> delegatingFile = new TestDelegatingFile(null, mockFile);
|
||||
|
||||
Instant now = Instant.now();
|
||||
Mockito.when(mockFile.creationTime()).thenReturn(Optional.of(now));
|
||||
Assert.assertEquals(now, delegatingFile.creationTime().get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetCreationTime() {
|
||||
File mockFile = Mockito.mock(File.class);
|
||||
DelegatingFile<?> delegatingFile = new TestDelegatingFile(null, mockFile);
|
||||
|
||||
Instant now = Instant.now();
|
||||
delegatingFile.setCreationTime(now);
|
||||
Mockito.verify(mockFile).setCreationTime(now);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOpenReadable() {
|
||||
File mockFile = Mockito.mock(File.class);
|
||||
ReadableFile mockReadableFile = Mockito.mock(ReadableFile.class);
|
||||
|
||||
Mockito.when(mockFile.openReadable()).thenReturn(mockReadableFile);
|
||||
DelegatingFile<?> delegatingFile = new TestDelegatingFile(null, mockFile);
|
||||
Assert.assertNotNull(delegatingFile.openReadable());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOpenWritable() {
|
||||
File mockFile = Mockito.mock(File.class);
|
||||
WritableFile mockWritableFile = Mockito.mock(WritableFile.class);
|
||||
|
||||
Mockito.when(mockFile.openWritable()).thenReturn(mockWritableFile);
|
||||
DelegatingFile<?> delegatingFile = new TestDelegatingFile(null, mockFile);
|
||||
Assert.assertNotNull(delegatingFile.openWritable());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMoveTo() {
|
||||
File mockFile1 = Mockito.mock(File.class);
|
||||
File mockFile2 = Mockito.mock(File.class);
|
||||
DelegatingFile<?> delegatingFile1 = new TestDelegatingFile(null, mockFile1);
|
||||
DelegatingFile<?> delegatingFile2 = new TestDelegatingFile(null, mockFile2);
|
||||
|
||||
delegatingFile1.moveTo(delegatingFile2);
|
||||
Mockito.verify(mockFile1).moveTo(mockFile2);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testMoveToDestinationFromDifferentLayer() {
|
||||
File mockFile1 = Mockito.mock(File.class);
|
||||
File mockFile2 = Mockito.mock(File.class);
|
||||
DelegatingFile<?> delegatingFile1 = new TestDelegatingFile(null, mockFile1);
|
||||
|
||||
delegatingFile1.moveTo(mockFile2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCopyTo() {
|
||||
File mockFile1 = Mockito.mock(File.class);
|
||||
File mockFile2 = Mockito.mock(File.class);
|
||||
DelegatingFile<?> delegatingFile1 = new TestDelegatingFile(null, mockFile1);
|
||||
DelegatingFile<?> delegatingFile2 = new TestDelegatingFile(null, mockFile2);
|
||||
|
||||
delegatingFile1.copyTo(delegatingFile2);
|
||||
Mockito.verify(mockFile1).copyTo(mockFile2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCopyToDestinationFromDifferentLayer() {
|
||||
File mockFile1 = Mockito.mock(File.class);
|
||||
File mockFile2 = Mockito.mock(File.class);
|
||||
DelegatingFile<?> delegatingFile1 = new TestDelegatingFile(null, mockFile1);
|
||||
|
||||
delegatingFile1.copyTo(mockFile2);
|
||||
Mockito.verify(mockFile1).copyTo(mockFile2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDelete() {
|
||||
File mockFile = Mockito.mock(File.class);
|
||||
DelegatingFile<?> delegatingFile = new TestDelegatingFile(null, mockFile);
|
||||
|
||||
delegatingFile.delete();
|
||||
Mockito.verify(mockFile).delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCompareTo() {
|
||||
File mockFile1 = Mockito.mock(File.class);
|
||||
File mockFile2 = Mockito.mock(File.class);
|
||||
|
||||
Mockito.when(mockFile1.compareTo(mockFile2)).thenReturn(-1);
|
||||
DelegatingFile<?> delegatingFile1 = new TestDelegatingFile(null, mockFile1);
|
||||
DelegatingFile<?> delegatingFile2 = new TestDelegatingFile(null, mockFile2);
|
||||
Assert.assertEquals(-1, delegatingFile1.compareTo(delegatingFile2));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.delegating;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.cryptomator.filesystem.File;
|
||||
import org.cryptomator.filesystem.Folder;
|
||||
import org.cryptomator.filesystem.Node;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
public class DelegatingFolderTest {
|
||||
|
||||
@Test
|
||||
public void testName() {
|
||||
Folder mockFolder = Mockito.mock(Folder.class);
|
||||
DelegatingFolder<?, ?> delegatingFolder = new TestDelegatingFolder(null, mockFolder);
|
||||
|
||||
Mockito.when(mockFolder.name()).thenReturn("Test");
|
||||
Assert.assertEquals(mockFolder.name(), delegatingFolder.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParent() {
|
||||
Folder mockFolder1 = Mockito.mock(Folder.class);
|
||||
Folder mockFolder2 = Mockito.mock(Folder.class);
|
||||
|
||||
TestDelegatingFileSystem delegatingParent = TestDelegatingFileSystem.withRoot(mockFolder1);
|
||||
DelegatingFolder<?, ?> delegatingFolder = new TestDelegatingFolder(delegatingParent, mockFolder2);
|
||||
Assert.assertEquals(delegatingParent, delegatingFolder.parent().get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExists() {
|
||||
Folder mockFolder = Mockito.mock(Folder.class);
|
||||
DelegatingFolder<?, ?> delegatingFolder = new TestDelegatingFolder(null, mockFolder);
|
||||
|
||||
Mockito.when(mockFolder.exists()).thenReturn(true);
|
||||
Assert.assertTrue(delegatingFolder.exists());
|
||||
|
||||
Mockito.when(mockFolder.exists()).thenReturn(false);
|
||||
Assert.assertFalse(delegatingFolder.exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLastModified() {
|
||||
Folder mockFolder = Mockito.mock(Folder.class);
|
||||
DelegatingFolder<?, ?> delegatingFolder = new TestDelegatingFolder(null, mockFolder);
|
||||
|
||||
Instant now = Instant.now();
|
||||
Mockito.when(mockFolder.lastModified()).thenReturn(now);
|
||||
Assert.assertEquals(now, delegatingFolder.lastModified());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetLastModified() {
|
||||
Folder mockFolder = Mockito.mock(Folder.class);
|
||||
DelegatingFolder<?, ?> delegatingFolder = new TestDelegatingFolder(null, mockFolder);
|
||||
|
||||
Instant now = Instant.now();
|
||||
delegatingFolder.setLastModified(now);
|
||||
Mockito.verify(mockFolder).setLastModified(now);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreationTime() {
|
||||
Folder mockFolder = Mockito.mock(Folder.class);
|
||||
DelegatingFolder<?, ?> delegatingFolder = new TestDelegatingFolder(null, mockFolder);
|
||||
|
||||
Instant now = Instant.now();
|
||||
Mockito.when(mockFolder.creationTime()).thenReturn(Optional.of(now));
|
||||
Assert.assertEquals(now, delegatingFolder.creationTime().get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetCreationTime() {
|
||||
Folder mockFolder = Mockito.mock(Folder.class);
|
||||
DelegatingFolder<?, ?> delegatingFolder = new TestDelegatingFolder(null, mockFolder);
|
||||
|
||||
Instant now = Instant.now();
|
||||
delegatingFolder.setCreationTime(now);
|
||||
Mockito.verify(mockFolder).setCreationTime(now);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testChildren() {
|
||||
Folder mockFolder = Mockito.mock(Folder.class);
|
||||
TestDelegatingFileSystem delegatingFolder = TestDelegatingFileSystem.withRoot(mockFolder);
|
||||
|
||||
Folder subFolder1 = Mockito.mock(Folder.class);
|
||||
TestDelegatingFolder delegatingSubFolder1 = new TestDelegatingFolder(delegatingFolder, subFolder1);
|
||||
File subFile1 = Mockito.mock(File.class);
|
||||
TestDelegatingFile delegatingSubFile1 = new TestDelegatingFile(delegatingFolder, subFile1);
|
||||
|
||||
/* folders */
|
||||
Mockito.when(mockFolder.folder("subFolder1")).thenReturn(subFolder1);
|
||||
Assert.assertEquals(delegatingSubFolder1, delegatingFolder.folder("subFolder1"));
|
||||
|
||||
Mockito.<Stream<? extends Folder>>when(mockFolder.folders()).thenAnswer((invocation) -> {
|
||||
return Arrays.stream(new Folder[] {subFolder1});
|
||||
});
|
||||
List<TestDelegatingFolder> subFolders = delegatingFolder.folders().collect(Collectors.toList());
|
||||
Assert.assertThat(subFolders, Matchers.containsInAnyOrder(delegatingSubFolder1));
|
||||
|
||||
/* files */
|
||||
Mockito.when(mockFolder.file("subFile1")).thenReturn(subFile1);
|
||||
Assert.assertEquals(delegatingSubFile1, delegatingFolder.file("subFile1"));
|
||||
|
||||
Mockito.<Stream<? extends File>>when(mockFolder.files()).thenAnswer((invocation) -> {
|
||||
return Arrays.stream(new File[] {subFile1});
|
||||
});
|
||||
List<TestDelegatingFile> subFiles = delegatingFolder.files().collect(Collectors.toList());
|
||||
Assert.assertThat(subFiles, Matchers.containsInAnyOrder(delegatingSubFile1));
|
||||
|
||||
/* files and folders */
|
||||
List<Node> children = delegatingFolder.children().collect(Collectors.toList());
|
||||
DelegatingNode<?>[] expectedChildren = new DelegatingNode[] {delegatingSubFolder1, delegatingSubFile1};
|
||||
Assert.assertThat(children, Matchers.containsInAnyOrder(expectedChildren));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMoveTo() {
|
||||
Folder mockFolder1 = Mockito.mock(Folder.class);
|
||||
Folder mockFolder2 = Mockito.mock(Folder.class);
|
||||
DelegatingFolder<?, ?> delegatingFolder1 = new TestDelegatingFolder(null, mockFolder1);
|
||||
DelegatingFolder<?, ?> delegatingFolder2 = new TestDelegatingFolder(null, mockFolder2);
|
||||
|
||||
delegatingFolder1.moveTo(delegatingFolder2);
|
||||
Mockito.verify(mockFolder1).moveTo(mockFolder2);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testMoveToDestinationFromDifferentLayer() {
|
||||
Folder mockFolder1 = Mockito.mock(Folder.class);
|
||||
Folder mockFolder2 = Mockito.mock(Folder.class);
|
||||
DelegatingFolder<?, ?> delegatingFolder1 = new TestDelegatingFolder(null, mockFolder1);
|
||||
|
||||
delegatingFolder1.moveTo(mockFolder2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCopyTo() {
|
||||
Folder mockFolder1 = Mockito.mock(Folder.class);
|
||||
Folder mockFolder2 = Mockito.mock(Folder.class);
|
||||
DelegatingFolder<?, ?> delegatingFolder1 = new TestDelegatingFolder(null, mockFolder1);
|
||||
DelegatingFolder<?, ?> delegatingFolder2 = new TestDelegatingFolder(null, mockFolder2);
|
||||
|
||||
delegatingFolder1.copyTo(delegatingFolder2);
|
||||
Mockito.verify(mockFolder1).copyTo(mockFolder2);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testCopyToDestinationFromDifferentLayer() {
|
||||
Folder mockFolder1 = Mockito.mock(Folder.class);
|
||||
Folder mockFolder2 = Mockito.mock(Folder.class);
|
||||
DelegatingFolder<?, ?> delegatingFolder1 = new TestDelegatingFolder(null, mockFolder1);
|
||||
|
||||
delegatingFolder1.copyTo(mockFolder2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreate() {
|
||||
Folder mockFolder = Mockito.mock(Folder.class);
|
||||
DelegatingFolder<?, ?> delegatingFolder = new TestDelegatingFolder(null, mockFolder);
|
||||
|
||||
delegatingFolder.create();
|
||||
Mockito.verify(mockFolder).create();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDelete() {
|
||||
Folder mockFolder = Mockito.mock(Folder.class);
|
||||
DelegatingFolder<?, ?> delegatingFolder = new TestDelegatingFolder(null, mockFolder);
|
||||
|
||||
delegatingFolder.delete();
|
||||
Mockito.verify(mockFolder).delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSubresourcesAreSameInstance() {
|
||||
Folder mockFolder = Mockito.mock(Folder.class);
|
||||
Folder mockSubFolder = Mockito.mock(Folder.class);
|
||||
File mockSubFile = Mockito.mock(File.class);
|
||||
Mockito.when(mockFolder.folder("mockSubFolder")).thenReturn(mockSubFolder);
|
||||
Mockito.when(mockFolder.file("mockSubFile")).thenReturn(mockSubFile);
|
||||
|
||||
DelegatingFolder<?, ?> delegatingFolder = new TestDelegatingFolder(null, mockFolder);
|
||||
Assert.assertSame(delegatingFolder.folder("mockSubFolder"), delegatingFolder.folder("mockSubFolder"));
|
||||
Assert.assertSame(delegatingFolder.file("mockSubFile"), delegatingFolder.file("mockSubFile"));
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.delegating;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import org.cryptomator.filesystem.ReadableFile;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
public class DelegatingReadableFileTest {
|
||||
|
||||
@Test
|
||||
public void testIsOpen() {
|
||||
ReadableFile mockReadableFile = Mockito.mock(ReadableFile.class);
|
||||
@SuppressWarnings("resource")
|
||||
DelegatingReadableFile delegatingReadableFile = new DelegatingReadableFile(mockReadableFile);
|
||||
|
||||
Mockito.when(mockReadableFile.isOpen()).thenReturn(true);
|
||||
Assert.assertTrue(delegatingReadableFile.isOpen());
|
||||
|
||||
Mockito.when(mockReadableFile.isOpen()).thenReturn(false);
|
||||
Assert.assertFalse(delegatingReadableFile.isOpen());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRead() {
|
||||
ReadableFile mockReadableFile = Mockito.mock(ReadableFile.class);
|
||||
@SuppressWarnings("resource")
|
||||
DelegatingReadableFile delegatingReadableFile = new DelegatingReadableFile(mockReadableFile);
|
||||
|
||||
ByteBuffer buf = ByteBuffer.allocate(4);
|
||||
Mockito.when(mockReadableFile.read(buf)).thenReturn(4);
|
||||
Assert.assertEquals(4, delegatingReadableFile.read(buf));
|
||||
Mockito.verify(mockReadableFile).read(buf);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPosition() {
|
||||
ReadableFile mockReadableFile = Mockito.mock(ReadableFile.class);
|
||||
@SuppressWarnings("resource")
|
||||
DelegatingReadableFile delegatingReadableFile = new DelegatingReadableFile(mockReadableFile);
|
||||
|
||||
delegatingReadableFile.position(42);
|
||||
Mockito.verify(mockReadableFile).position(42);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClose() {
|
||||
ReadableFile mockReadableFile = Mockito.mock(ReadableFile.class);
|
||||
DelegatingReadableFile delegatingReadableFile = new DelegatingReadableFile(mockReadableFile);
|
||||
|
||||
delegatingReadableFile.close();
|
||||
Mockito.verify(mockReadableFile).close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.delegating;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import org.cryptomator.filesystem.WritableFile;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
public class DelegatingWritableFileTest {
|
||||
|
||||
@Test
|
||||
public void testIsOpen() {
|
||||
WritableFile mockWritableFile = Mockito.mock(WritableFile.class);
|
||||
@SuppressWarnings("resource")
|
||||
DelegatingWritableFile delegatingWritableFile = new DelegatingWritableFile(mockWritableFile);
|
||||
|
||||
Mockito.when(mockWritableFile.isOpen()).thenReturn(true);
|
||||
Assert.assertTrue(delegatingWritableFile.isOpen());
|
||||
|
||||
Mockito.when(mockWritableFile.isOpen()).thenReturn(false);
|
||||
Assert.assertFalse(delegatingWritableFile.isOpen());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTruncate() {
|
||||
WritableFile mockWritableFile = Mockito.mock(WritableFile.class);
|
||||
@SuppressWarnings("resource")
|
||||
DelegatingWritableFile delegatingWritableFile = new DelegatingWritableFile(mockWritableFile);
|
||||
|
||||
delegatingWritableFile.truncate();
|
||||
Mockito.verify(mockWritableFile).truncate();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrite() {
|
||||
WritableFile mockWritableFile = Mockito.mock(WritableFile.class);
|
||||
@SuppressWarnings("resource")
|
||||
DelegatingWritableFile delegatingWritableFile = new DelegatingWritableFile(mockWritableFile);
|
||||
|
||||
ByteBuffer buf = ByteBuffer.allocate(4);
|
||||
Mockito.when(mockWritableFile.write(buf)).thenReturn(4);
|
||||
Assert.assertEquals(4, delegatingWritableFile.write(buf));
|
||||
Mockito.verify(mockWritableFile).write(buf);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPosition() {
|
||||
WritableFile mockWritableFile = Mockito.mock(WritableFile.class);
|
||||
@SuppressWarnings("resource")
|
||||
DelegatingWritableFile delegatingWritableFile = new DelegatingWritableFile(mockWritableFile);
|
||||
|
||||
delegatingWritableFile.position(42);
|
||||
Mockito.verify(mockWritableFile).position(42);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClose() {
|
||||
WritableFile mockWritableFile = Mockito.mock(WritableFile.class);
|
||||
DelegatingWritableFile delegatingWritableFile = new DelegatingWritableFile(mockWritableFile);
|
||||
|
||||
delegatingWritableFile.close();
|
||||
Mockito.verify(mockWritableFile).close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package org.cryptomator.filesystem.delegating;
|
||||
|
||||
import org.cryptomator.filesystem.File;
|
||||
|
||||
class TestDelegatingFile extends DelegatingFile<TestDelegatingFolder> {
|
||||
|
||||
public TestDelegatingFile(TestDelegatingFolder parent, File delegate) {
|
||||
super(parent, delegate);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package org.cryptomator.filesystem.delegating;
|
||||
|
||||
import org.cryptomator.filesystem.Folder;
|
||||
|
||||
class TestDelegatingFileSystem extends TestDelegatingFolder implements DelegatingFileSystem {
|
||||
|
||||
private TestDelegatingFileSystem(Folder delegate) {
|
||||
super(null, delegate);
|
||||
}
|
||||
|
||||
public static TestDelegatingFileSystem withRoot(Folder delegate) {
|
||||
return new TestDelegatingFileSystem(delegate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Folder getDelegate() {
|
||||
return delegate;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package org.cryptomator.filesystem.delegating;
|
||||
|
||||
import org.cryptomator.filesystem.File;
|
||||
import org.cryptomator.filesystem.Folder;
|
||||
|
||||
class TestDelegatingFolder extends DelegatingFolder<TestDelegatingFolder, TestDelegatingFile> {
|
||||
|
||||
public TestDelegatingFolder(TestDelegatingFolder parent, Folder delegate) {
|
||||
super(parent, delegate);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected TestDelegatingFile newFile(File delegate) {
|
||||
return new TestDelegatingFile(this, delegate);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected TestDelegatingFolder newFolder(Folder delegate) {
|
||||
return new TestDelegatingFolder(this, delegate);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2015 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.io;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ByteBuffersTest {
|
||||
|
||||
@Test
|
||||
public void testCopyOfEmptySource() {
|
||||
final ByteBuffer src = ByteBuffer.allocate(0);
|
||||
final ByteBuffer dst = ByteBuffer.allocate(5);
|
||||
dst.put(new byte[3]);
|
||||
Assert.assertEquals(0, src.position());
|
||||
Assert.assertEquals(0, src.remaining());
|
||||
Assert.assertEquals(3, dst.position());
|
||||
Assert.assertEquals(2, dst.remaining());
|
||||
ByteBuffers.copy(src, dst);
|
||||
Assert.assertEquals(0, src.position());
|
||||
Assert.assertEquals(0, src.remaining());
|
||||
Assert.assertEquals(3, dst.position());
|
||||
Assert.assertEquals(2, dst.remaining());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCopyToEmptyDestination() {
|
||||
final ByteBuffer src = ByteBuffer.wrap(new byte[4]);
|
||||
final ByteBuffer dst = ByteBuffer.allocate(0);
|
||||
src.put(new byte[2]);
|
||||
Assert.assertEquals(2, src.position());
|
||||
Assert.assertEquals(2, src.remaining());
|
||||
Assert.assertEquals(0, dst.position());
|
||||
Assert.assertEquals(0, dst.remaining());
|
||||
ByteBuffers.copy(src, dst);
|
||||
Assert.assertEquals(2, src.position());
|
||||
Assert.assertEquals(2, src.remaining());
|
||||
Assert.assertEquals(0, dst.position());
|
||||
Assert.assertEquals(0, dst.remaining());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCopyToBiggerDestination() {
|
||||
final ByteBuffer src = ByteBuffer.wrap(new byte[2]);
|
||||
final ByteBuffer dst = ByteBuffer.allocate(10);
|
||||
dst.put(new byte[3]);
|
||||
Assert.assertEquals(0, src.position());
|
||||
Assert.assertEquals(2, src.remaining());
|
||||
Assert.assertEquals(3, dst.position());
|
||||
Assert.assertEquals(7, dst.remaining());
|
||||
ByteBuffers.copy(src, dst);
|
||||
Assert.assertEquals(2, src.position());
|
||||
Assert.assertEquals(0, src.remaining());
|
||||
Assert.assertEquals(5, dst.position());
|
||||
Assert.assertEquals(5, dst.remaining());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCopyToSmallerDestination() {
|
||||
final ByteBuffer src = ByteBuffer.wrap(new byte[5]);
|
||||
final ByteBuffer dst = ByteBuffer.allocate(2);
|
||||
Assert.assertEquals(0, src.position());
|
||||
Assert.assertEquals(5, src.remaining());
|
||||
Assert.assertEquals(0, dst.position());
|
||||
Assert.assertEquals(2, dst.remaining());
|
||||
ByteBuffers.copy(src, dst);
|
||||
Assert.assertEquals(2, src.position());
|
||||
Assert.assertEquals(3, src.remaining());
|
||||
Assert.assertEquals(2, dst.position());
|
||||
Assert.assertEquals(0, dst.remaining());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
package org.cryptomator.io;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.cryptomator.filesystem.File;
|
||||
import org.cryptomator.filesystem.ReadableFile;
|
||||
import org.cryptomator.filesystem.WritableFile;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Assume;
|
||||
import org.junit.Test;
|
||||
import org.junit.experimental.theories.DataPoints;
|
||||
import org.junit.experimental.theories.Theories;
|
||||
import org.junit.experimental.theories.Theory;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
@RunWith(Theories.class)
|
||||
public class FileContentsTest {
|
||||
|
||||
@DataPoints
|
||||
public static final Iterable<Charset> CHARSETS = Arrays.asList(StandardCharsets.UTF_8, StandardCharsets.US_ASCII, StandardCharsets.UTF_16);
|
||||
|
||||
@DataPoints
|
||||
public static final Iterable<String> TEST_CONTENTS = Arrays.asList("hello world", "hellö wörld", "");
|
||||
|
||||
@Theory
|
||||
public void testReadAll(Charset charset, String testString) {
|
||||
Assume.assumeTrue(charset.newEncoder().canEncode(testString));
|
||||
|
||||
ByteBuffer testContent = ByteBuffer.wrap(testString.getBytes(charset));
|
||||
File file = Mockito.mock(File.class);
|
||||
ReadableFile readable = Mockito.mock(ReadableFile.class);
|
||||
Mockito.when(file.openReadable()).thenReturn(readable);
|
||||
Mockito.when(readable.read(Mockito.any(ByteBuffer.class))).then(invocation -> {
|
||||
ByteBuffer target = invocation.getArgumentAt(0, ByteBuffer.class);
|
||||
if (testContent.hasRemaining()) {
|
||||
return ByteBuffers.copy(testContent, target);
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
});
|
||||
|
||||
String contentsRead = FileContents.withCharset(charset).readContents(file);
|
||||
Assert.assertEquals(testString, contentsRead);
|
||||
}
|
||||
|
||||
@Theory
|
||||
public void testWriteAll(Charset charset, String testString) {
|
||||
Assume.assumeTrue(charset.newEncoder().canEncode(testString));
|
||||
|
||||
ByteBuffer testContent = ByteBuffer.allocate(100);
|
||||
File file = Mockito.mock(File.class);
|
||||
WritableFile writable = Mockito.mock(WritableFile.class);
|
||||
Mockito.when(file.openWritable()).thenReturn(writable);
|
||||
Mockito.doAnswer(invocation -> {
|
||||
testContent.clear();
|
||||
return null;
|
||||
}).when(writable).truncate();
|
||||
Mockito.when(writable.write(Mockito.any(ByteBuffer.class))).then(invocation -> {
|
||||
ByteBuffer source = invocation.getArgumentAt(0, ByteBuffer.class);
|
||||
if (testContent.hasRemaining()) {
|
||||
return ByteBuffers.copy(source, testContent);
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
});
|
||||
|
||||
FileContents.withCharset(charset).writeContents(file, testString);
|
||||
Assert.assertArrayEquals(testString.getBytes(charset), Arrays.copyOf(testContent.array(), testContent.position()));
|
||||
}
|
||||
|
||||
@Test(expected = UncheckedIOException.class)
|
||||
public void testIOExceptionDuringRead() {
|
||||
File file = Mockito.mock(File.class);
|
||||
Mockito.when(file.openReadable()).thenAnswer(invocation -> {
|
||||
throw new IOException("failed");
|
||||
});
|
||||
|
||||
FileContents.UTF_8.readContents(file);
|
||||
}
|
||||
|
||||
@Test(expected = UncheckedIOException.class)
|
||||
public void testUncheckedIOExceptionDuringRead() {
|
||||
File file = Mockito.mock(File.class);
|
||||
Mockito.when(file.openReadable()).thenThrow(new UncheckedIOException(new IOException("failed")));
|
||||
|
||||
FileContents.UTF_8.readContents(file);
|
||||
}
|
||||
|
||||
@Test(expected = UncheckedIOException.class)
|
||||
public void testUncheckedIOExceptionDuringWrite() {
|
||||
File file = Mockito.mock(File.class);
|
||||
Mockito.when(file.openWritable()).thenThrow(new UncheckedIOException(new IOException("failed")));
|
||||
|
||||
FileContents.UTF_8.writeContents(file, "hello world");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<Configuration status="WARN">
|
||||
|
||||
<Appenders>
|
||||
<Console name="Console" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="%16d %-5p [%c{1}:%L] %m%n" />
|
||||
<ThresholdFilter level="WARN" onMatch="DENY" onMismatch="ACCEPT" />
|
||||
</Console>
|
||||
<Console name="StdErr" target="SYSTEM_ERR">
|
||||
<PatternLayout pattern="%16d %-5p [%c{1}:%L] %m%n" />
|
||||
<ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY" />
|
||||
</Console>
|
||||
</Appenders>
|
||||
|
||||
<Loggers>
|
||||
<Root level="DEBUG">
|
||||
<AppenderRef ref="Console" />
|
||||
<AppenderRef ref="StdErr" />
|
||||
</Root>
|
||||
</Loggers>
|
||||
|
||||
</Configuration>
|
||||
@@ -1,45 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
Copyright (c) 2015 Sebastian Stenzel
|
||||
This file is licensed under the terms of the MIT license.
|
||||
See the LICENSE.txt file for more info.
|
||||
|
||||
Contributors:
|
||||
Sebastian Stenzel - initial API and implementation
|
||||
-->
|
||||
<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>
|
||||
<parent>
|
||||
<groupId>org.cryptomator</groupId>
|
||||
<artifactId>main</artifactId>
|
||||
<version>1.2.3</version>
|
||||
</parent>
|
||||
<artifactId>filesystem-charsets</artifactId>
|
||||
<name>Cryptomator filesystem: Charset compatibility layer</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.cryptomator</groupId>
|
||||
<artifactId>filesystem-api</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Tests -->
|
||||
<dependency>
|
||||
<groupId>org.cryptomator</groupId>
|
||||
<artifactId>commons-test</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.cryptomator</groupId>
|
||||
<artifactId>filesystem-inmemory</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -1,32 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2016 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.charsets;
|
||||
|
||||
import java.io.UncheckedIOException;
|
||||
import java.text.Normalizer;
|
||||
import java.text.Normalizer.Form;
|
||||
|
||||
import org.cryptomator.filesystem.File;
|
||||
import org.cryptomator.filesystem.delegating.DelegatingFile;
|
||||
|
||||
class NormalizedNameFile extends DelegatingFile<NormalizedNameFolder> {
|
||||
|
||||
private final Form displayForm;
|
||||
|
||||
public NormalizedNameFile(NormalizedNameFolder parent, File delegate, Form displayForm) {
|
||||
super(parent, delegate);
|
||||
this.displayForm = displayForm;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() throws UncheckedIOException {
|
||||
return Normalizer.normalize(super.name(), displayForm);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2016 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.charsets;
|
||||
|
||||
import java.text.Normalizer.Form;
|
||||
|
||||
import org.cryptomator.filesystem.Folder;
|
||||
import org.cryptomator.filesystem.delegating.DelegatingFileSystem;
|
||||
|
||||
public class NormalizedNameFileSystem extends NormalizedNameFolder implements DelegatingFileSystem {
|
||||
|
||||
public NormalizedNameFileSystem(Folder delegate, Form displayForm) {
|
||||
super(null, delegate, displayForm);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Folder getDelegate() {
|
||||
return delegate;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2016 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.charsets;
|
||||
|
||||
import java.io.UncheckedIOException;
|
||||
import java.text.Normalizer;
|
||||
import java.text.Normalizer.Form;
|
||||
|
||||
import org.cryptomator.filesystem.File;
|
||||
import org.cryptomator.filesystem.Folder;
|
||||
import org.cryptomator.filesystem.delegating.DelegatingFolder;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
class NormalizedNameFolder extends DelegatingFolder<NormalizedNameFolder, NormalizedNameFile> {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(NormalizedNameFolder.class);
|
||||
private final Form displayForm;
|
||||
|
||||
public NormalizedNameFolder(NormalizedNameFolder parent, Folder delegate, Form displayForm) {
|
||||
super(parent, delegate);
|
||||
this.displayForm = displayForm;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() throws UncheckedIOException {
|
||||
return Normalizer.normalize(super.name(), displayForm);
|
||||
}
|
||||
|
||||
@Override
|
||||
public NormalizedNameFile file(String name) throws UncheckedIOException {
|
||||
String nfcName = Normalizer.normalize(name, Form.NFC);
|
||||
String nfdName = Normalizer.normalize(name, Form.NFD);
|
||||
NormalizedNameFile nfcFile = super.file(nfcName);
|
||||
NormalizedNameFile nfdFile = super.file(nfdName);
|
||||
if (!nfcName.equals(nfdName) && nfcFile.exists() && nfdFile.exists()) {
|
||||
LOG.debug("Ambiguous file names \"" + nfcName + "\" (NFC) vs. \"" + nfdName + "\" (NFD). Both files exist. Using \"" + nfcName + "\" (NFC).");
|
||||
} else if (!nfcName.equals(nfdName) && !nfcFile.exists() && nfdFile.exists()) {
|
||||
LOG.debug("Moving file from \"" + nfcName + "\" (NFD) to \"" + nfdName + "\" (NFC).");
|
||||
nfdFile.moveTo(nfcFile);
|
||||
}
|
||||
return nfcFile;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected NormalizedNameFile newFile(File delegate) {
|
||||
return new NormalizedNameFile(this, delegate, displayForm);
|
||||
}
|
||||
|
||||
@Override
|
||||
public NormalizedNameFolder folder(String name) throws UncheckedIOException {
|
||||
String nfcName = Normalizer.normalize(name, Form.NFC);
|
||||
String nfdName = Normalizer.normalize(name, Form.NFD);
|
||||
NormalizedNameFolder nfcFolder = super.folder(nfcName);
|
||||
NormalizedNameFolder nfdFolder = super.folder(nfdName);
|
||||
if (!nfcName.equals(nfdName) && nfcFolder.exists() && nfdFolder.exists()) {
|
||||
LOG.debug("Ambiguous folder names \"" + nfcName + "\" (NFC) vs. \"" + nfdName + "\" (NFD). Both files exist. Using \"" + nfcName + "\" (NFC).");
|
||||
} else if (!nfcName.equals(nfdName) && !nfcFolder.exists() && nfdFolder.exists()) {
|
||||
LOG.debug("Moving folder from \"" + nfcName + "\" (NFD) to \"" + nfdName + "\" (NFC).");
|
||||
nfdFolder.moveTo(nfcFolder);
|
||||
}
|
||||
return nfcFolder;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected NormalizedNameFolder newFolder(Folder delegate) {
|
||||
return new NormalizedNameFolder(this, delegate, displayForm);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2016 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
/**
|
||||
* Makes sure, the filesystems wrapped by this filesystem work only on UTF-8 encoded file paths using Normalization Form C.
|
||||
* Filesystems wrapping this file system, on the other hand, will get filenames reported in a specified Normalization Form.
|
||||
* It is recommended to use NFD for OS X and NFC for other operating systems.
|
||||
* When looking for a file or folder with a name given in either form, both possibilities are considered
|
||||
* and files/folders stored in NFD are automatically migrated to NFC.
|
||||
*/
|
||||
package org.cryptomator.filesystem.charsets;
|
||||
@@ -1,90 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2016 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.charsets;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.text.Normalizer.Form;
|
||||
|
||||
import org.cryptomator.filesystem.FileSystem;
|
||||
import org.cryptomator.filesystem.WritableFile;
|
||||
import org.cryptomator.filesystem.inmem.InMemoryFileSystem;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NormalizedNameFileSystemTest {
|
||||
|
||||
@Test
|
||||
public void testFileMigration() {
|
||||
FileSystem inMemoryFs = new InMemoryFileSystem();
|
||||
try (WritableFile writable = inMemoryFs.file("\u006F\u0302").openWritable()) {
|
||||
writable.write(ByteBuffer.allocate(0));
|
||||
}
|
||||
FileSystem normalizationFs = new NormalizedNameFileSystem(inMemoryFs, Form.NFC);
|
||||
Assert.assertTrue(normalizationFs.file("\u00F4").exists());
|
||||
Assert.assertTrue(normalizationFs.file("\u006F\u0302").exists());
|
||||
Assert.assertFalse(inMemoryFs.file("\u006F\u0302").exists());
|
||||
Assert.assertTrue(inMemoryFs.file("\u00F4").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoFileMigration() {
|
||||
FileSystem inMemoryFs = new InMemoryFileSystem();
|
||||
try (WritableFile writable = inMemoryFs.file("\u00F4").openWritable()) {
|
||||
writable.write(ByteBuffer.allocate(0));
|
||||
}
|
||||
FileSystem normalizationFs = new NormalizedNameFileSystem(inMemoryFs, Form.NFC);
|
||||
Assert.assertTrue(normalizationFs.file("\u00F4").exists());
|
||||
Assert.assertTrue(normalizationFs.file("\u006F\u0302").exists());
|
||||
Assert.assertFalse(inMemoryFs.file("\u006F\u0302").exists());
|
||||
Assert.assertTrue(inMemoryFs.file("\u00F4").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFolderMigration() {
|
||||
FileSystem inMemoryFs = new InMemoryFileSystem();
|
||||
inMemoryFs.folder("\u006F\u0302").create();
|
||||
FileSystem normalizationFs = new NormalizedNameFileSystem(inMemoryFs, Form.NFC);
|
||||
Assert.assertTrue(normalizationFs.folder("\u00F4").exists());
|
||||
Assert.assertTrue(normalizationFs.folder("\u006F\u0302").exists());
|
||||
Assert.assertFalse(inMemoryFs.folder("\u006F\u0302").exists());
|
||||
Assert.assertTrue(inMemoryFs.folder("\u00F4").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoFolderMigration() {
|
||||
FileSystem inMemoryFs = new InMemoryFileSystem();
|
||||
inMemoryFs.folder("\u00F4").create();
|
||||
FileSystem normalizationFs = new NormalizedNameFileSystem(inMemoryFs, Form.NFC);
|
||||
Assert.assertTrue(normalizationFs.folder("\u00F4").exists());
|
||||
Assert.assertTrue(normalizationFs.folder("\u006F\u0302").exists());
|
||||
Assert.assertFalse(inMemoryFs.folder("\u006F\u0302").exists());
|
||||
Assert.assertTrue(inMemoryFs.folder("\u00F4").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNfcDisplayNames() {
|
||||
FileSystem inMemoryFs = new InMemoryFileSystem();
|
||||
inMemoryFs.folder("a\u00F4").create();
|
||||
inMemoryFs.folder("b\u006F\u0302").create();
|
||||
FileSystem normalizationFs = new NormalizedNameFileSystem(inMemoryFs, Form.NFC);
|
||||
Assert.assertEquals("a\u00F4", normalizationFs.folder("a\u00F4").name());
|
||||
Assert.assertEquals("b\u00F4", normalizationFs.folder("b\u006F\u0302").name());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNfdDisplayNames() {
|
||||
FileSystem inMemoryFs = new InMemoryFileSystem();
|
||||
inMemoryFs.folder("a\u00F4").create();
|
||||
inMemoryFs.folder("b\u006F\u0302").create();
|
||||
FileSystem normalizationFs = new NormalizedNameFileSystem(inMemoryFs, Form.NFD);
|
||||
Assert.assertEquals("a\u006F\u0302", normalizationFs.folder("a\u00F4").name());
|
||||
Assert.assertEquals("b\u006F\u0302", normalizationFs.folder("b\u006F\u0302").name());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2016 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.charsets;
|
||||
|
||||
import java.text.Normalizer.Form;
|
||||
|
||||
import org.cryptomator.filesystem.File;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
public class NormalizedNameFileTest {
|
||||
|
||||
private File delegateNfc;
|
||||
private File delegateNfd;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
delegateNfc = Mockito.mock(File.class);
|
||||
delegateNfd = Mockito.mock(File.class);
|
||||
Mockito.when(delegateNfc.name()).thenReturn("\u00C5");
|
||||
Mockito.when(delegateNfd.name()).thenReturn("\u0041\u030A");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDisplayNameInNfc() {
|
||||
File file1 = new NormalizedNameFile(null, delegateNfc, Form.NFC);
|
||||
File file2 = new NormalizedNameFile(null, delegateNfd, Form.NFC);
|
||||
Assert.assertEquals("\u00C5", file1.name());
|
||||
Assert.assertEquals("\u00C5", file2.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDisplayNameInNfd() {
|
||||
File file1 = new NormalizedNameFile(null, delegateNfc, Form.NFD);
|
||||
File file2 = new NormalizedNameFile(null, delegateNfd, Form.NFD);
|
||||
Assert.assertEquals("\u0041\u030A", file1.name());
|
||||
Assert.assertEquals("\u0041\u030A", file2.name());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2016 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.charsets;
|
||||
|
||||
import java.text.Normalizer.Form;
|
||||
|
||||
import org.cryptomator.filesystem.File;
|
||||
import org.cryptomator.filesystem.Folder;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
public class NormalizedNameFolderTest {
|
||||
|
||||
private Folder delegate;
|
||||
private File delegateSubFileNfc;
|
||||
private File delegateSubFileNfd;
|
||||
private Folder delegateSubFolderNfc;
|
||||
private Folder delegateSubFolderNfd;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
delegate = Mockito.mock(Folder.class);
|
||||
delegateSubFileNfc = Mockito.mock(File.class);
|
||||
delegateSubFileNfd = Mockito.mock(File.class);
|
||||
Mockito.when(delegate.file("\u00C5")).thenReturn(delegateSubFileNfc);
|
||||
Mockito.when(delegateSubFileNfc.name()).thenReturn("\u00C5");
|
||||
Mockito.when(delegate.file("\u0041\u030A")).thenReturn(delegateSubFileNfd);
|
||||
Mockito.when(delegateSubFileNfd.name()).thenReturn("\u0041\u030A");
|
||||
delegateSubFolderNfc = Mockito.mock(Folder.class);
|
||||
delegateSubFolderNfd = Mockito.mock(Folder.class);
|
||||
Mockito.when(delegate.folder("\u00F4")).thenReturn(delegateSubFolderNfc);
|
||||
Mockito.when(delegateSubFolderNfc.name()).thenReturn("\u00F4");
|
||||
Mockito.when(delegate.folder("\u006F\u0302")).thenReturn(delegateSubFolderNfd);
|
||||
Mockito.when(delegateSubFolderNfd.name()).thenReturn("\u006F\u0302");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDisplayNameInNfc() {
|
||||
Folder folder1 = new NormalizedNameFolder(null, delegateSubFolderNfc, Form.NFC);
|
||||
Folder folder2 = new NormalizedNameFolder(null, delegateSubFolderNfd, Form.NFC);
|
||||
Assert.assertEquals("\u00F4", folder1.name());
|
||||
Assert.assertEquals("\u00F4", folder2.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDisplayNameInNfd() {
|
||||
Folder folder1 = new NormalizedNameFolder(null, delegateSubFolderNfc, Form.NFD);
|
||||
Folder folder2 = new NormalizedNameFolder(null, delegateSubFolderNfd, Form.NFD);
|
||||
Assert.assertEquals("\u006F\u0302", folder1.name());
|
||||
Assert.assertEquals("\u006F\u0302", folder2.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoFolderMigration1() {
|
||||
Mockito.when(delegateSubFolderNfc.exists()).thenReturn(true);
|
||||
Mockito.when(delegateSubFolderNfd.exists()).thenReturn(false);
|
||||
Folder folder = new NormalizedNameFolder(null, delegate, Form.NFC);
|
||||
Folder sub1 = folder.folder("\u00F4");
|
||||
Folder sub2 = folder.folder("\u006F\u0302");
|
||||
Mockito.verify(delegateSubFolderNfd, Mockito.never()).moveTo(Mockito.any());
|
||||
Assert.assertSame(sub1, sub2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoFolderMigration2() {
|
||||
Mockito.when(delegateSubFolderNfc.exists()).thenReturn(true);
|
||||
Mockito.when(delegateSubFolderNfd.exists()).thenReturn(true);
|
||||
Folder folder = new NormalizedNameFolder(null, delegate, Form.NFC);
|
||||
Folder sub1 = folder.folder("\u00F4");
|
||||
Folder sub2 = folder.folder("\u006F\u0302");
|
||||
Mockito.verify(delegateSubFolderNfd, Mockito.never()).moveTo(Mockito.any());
|
||||
Assert.assertSame(sub1, sub2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoFolderMigration3() {
|
||||
Mockito.when(delegateSubFolderNfc.exists()).thenReturn(false);
|
||||
Mockito.when(delegateSubFolderNfd.exists()).thenReturn(false);
|
||||
Folder folder = new NormalizedNameFolder(null, delegate, Form.NFC);
|
||||
Folder sub1 = folder.folder("\u00F4");
|
||||
Folder sub2 = folder.folder("\u006F\u0302");
|
||||
Mockito.verify(delegateSubFolderNfd, Mockito.never()).moveTo(Mockito.any());
|
||||
Assert.assertSame(sub1, sub2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFolderMigration() {
|
||||
Mockito.when(delegateSubFolderNfc.exists()).thenReturn(false);
|
||||
Mockito.when(delegateSubFolderNfd.exists()).thenReturn(true);
|
||||
Folder folder = new NormalizedNameFolder(null, delegate, Form.NFC);
|
||||
Folder sub1 = folder.folder("\u00F4");
|
||||
Mockito.verify(delegateSubFolderNfd).moveTo(delegateSubFolderNfc);
|
||||
Folder sub2 = folder.folder("\u006F\u0302");
|
||||
Assert.assertSame(sub1, sub2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoFileMigration1() {
|
||||
Mockito.when(delegateSubFileNfc.exists()).thenReturn(true);
|
||||
Mockito.when(delegateSubFileNfd.exists()).thenReturn(false);
|
||||
Folder folder = new NormalizedNameFolder(null, delegate, Form.NFC);
|
||||
File sub1 = folder.file("\u00C5");
|
||||
File sub2 = folder.file("\u0041\u030A");
|
||||
Mockito.verify(delegateSubFileNfd, Mockito.never()).moveTo(Mockito.any());
|
||||
Assert.assertSame(sub1, sub2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoFileMigration2() {
|
||||
Mockito.when(delegateSubFileNfc.exists()).thenReturn(true);
|
||||
Mockito.when(delegateSubFileNfd.exists()).thenReturn(true);
|
||||
Folder folder = new NormalizedNameFolder(null, delegate, Form.NFC);
|
||||
File sub1 = folder.file("\u00C5");
|
||||
File sub2 = folder.file("\u0041\u030A");
|
||||
Mockito.verify(delegateSubFileNfd, Mockito.never()).moveTo(Mockito.any());
|
||||
Assert.assertSame(sub1, sub2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoFileMigration3() {
|
||||
Mockito.when(delegateSubFileNfc.exists()).thenReturn(false);
|
||||
Mockito.when(delegateSubFileNfd.exists()).thenReturn(false);
|
||||
Folder folder = new NormalizedNameFolder(null, delegate, Form.NFC);
|
||||
File sub1 = folder.file("\u00C5");
|
||||
File sub2 = folder.file("\u0041\u030A");
|
||||
Mockito.verify(delegateSubFileNfd, Mockito.never()).moveTo(Mockito.any());
|
||||
Assert.assertSame(sub1, sub2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFileMigration() {
|
||||
Mockito.when(delegateSubFileNfc.exists()).thenReturn(false);
|
||||
Mockito.when(delegateSubFileNfd.exists()).thenReturn(true);
|
||||
Folder folder = new NormalizedNameFolder(null, delegate, Form.NFC);
|
||||
File sub1 = folder.file("\u00C5");
|
||||
Mockito.verify(delegateSubFileNfd).moveTo(delegateSubFileNfc);
|
||||
File sub2 = folder.file("\u0041\u030A");
|
||||
Assert.assertSame(sub1, sub2);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<Configuration status="WARN">
|
||||
|
||||
<Appenders>
|
||||
<Console name="Console" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="%16d %-5p [%c{1}:%L] %m%n" />
|
||||
<ThresholdFilter level="WARN" onMatch="DENY" onMismatch="ACCEPT" />
|
||||
</Console>
|
||||
<Console name="StdErr" target="SYSTEM_ERR">
|
||||
<PatternLayout pattern="%16d %-5p [%c{1}:%L] %m%n" />
|
||||
<ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY" />
|
||||
</Console>
|
||||
</Appenders>
|
||||
|
||||
<Loggers>
|
||||
<Root level="DEBUG">
|
||||
<AppenderRef ref="Console" />
|
||||
<AppenderRef ref="StdErr" />
|
||||
</Root>
|
||||
</Loggers>
|
||||
|
||||
</Configuration>
|
||||
@@ -1 +0,0 @@
|
||||
/target/
|
||||
@@ -1,64 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
Copyright (c) 2016 Sebastian Stenzel
|
||||
This file is licensed under the terms of the MIT license.
|
||||
See the LICENSE.txt file for more info.
|
||||
|
||||
Contributors:
|
||||
Sebastian Stenzel - initial API and implementation
|
||||
-->
|
||||
<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>
|
||||
<parent>
|
||||
<groupId>org.cryptomator</groupId>
|
||||
<artifactId>main</artifactId>
|
||||
<version>1.2.3</version>
|
||||
</parent>
|
||||
<artifactId>filesystem-crypto-integration-tests</artifactId>
|
||||
<name>Cryptomator filesystem: Encryption layer tests</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.cryptomator</groupId>
|
||||
<artifactId>filesystem-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.cryptomator</groupId>
|
||||
<artifactId>filesystem-crypto</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.cryptomator</groupId>
|
||||
<artifactId>filesystem-nameshortening</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- DI -->
|
||||
<dependency>
|
||||
<groupId>com.google.dagger</groupId>
|
||||
<artifactId>dagger</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.dagger</groupId>
|
||||
<artifactId>dagger-compiler</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Tests -->
|
||||
<dependency>
|
||||
<groupId>org.cryptomator</groupId>
|
||||
<artifactId>commons-test</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.cryptomator</groupId>
|
||||
<artifactId>filesystem-inmemory</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -1,33 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2016 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.crypto;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.cryptomator.crypto.engine.impl.CryptoEngineModule;
|
||||
|
||||
/**
|
||||
* Used as drop-in-replacement for {@link CryptoEngineModule} during unit tests.
|
||||
*/
|
||||
public class CryptoEngineTestModule extends CryptoEngineModule {
|
||||
|
||||
@Override
|
||||
public SecureRandom provideSecureRandom() {
|
||||
return new SecureRandom() {
|
||||
|
||||
@Override
|
||||
public void nextBytes(byte[] bytes) {
|
||||
Arrays.fill(bytes, (byte) 0x00);
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2016 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.crypto;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.cryptomator.crypto.engine.impl.CryptoEngineModule;
|
||||
import org.cryptomator.filesystem.shortening.ShorteningFileSystemFactory;
|
||||
|
||||
import dagger.Component;
|
||||
|
||||
/**
|
||||
* To be used in integration tests, where a {@link CryptoFileSystem} is needed in conjunction with {@link CryptoEngineTestModule} (which mocks the CSPRNG) as follows:
|
||||
* <code>
|
||||
* DaggerCryptoFileSystemTestComponent.builder().cryptoEngineModule(new CryptoEngineTestModule()).build()
|
||||
* </code>
|
||||
*/
|
||||
@Singleton
|
||||
@Component(modules = CryptoEngineModule.class)
|
||||
public interface CryptoFileSystemTestComponent {
|
||||
|
||||
CryptoFileSystemFactory cryptoFileSystemFactory();
|
||||
|
||||
ShorteningFileSystemFactory shorteningFileSystemFactory();
|
||||
|
||||
}
|
||||
@@ -1,298 +0,0 @@
|
||||
/*******************************************************************************
|
||||
* Copyright (c) 2016 Sebastian Stenzel and others.
|
||||
* This file is licensed under the terms of the MIT license.
|
||||
* See the LICENSE.txt file for more info.
|
||||
*
|
||||
* Contributors:
|
||||
* Sebastian Stenzel - initial API and implementation
|
||||
*******************************************************************************/
|
||||
package org.cryptomator.filesystem.crypto;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
import java.util.concurrent.ForkJoinTask;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import org.cryptomator.filesystem.File;
|
||||
import org.cryptomator.filesystem.FileSystem;
|
||||
import org.cryptomator.filesystem.Folder;
|
||||
import org.cryptomator.filesystem.Node;
|
||||
import org.cryptomator.filesystem.ReadableFile;
|
||||
import org.cryptomator.filesystem.WritableFile;
|
||||
import org.cryptomator.filesystem.inmem.InMemoryFileSystem;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class CryptoFileSystemIntegrationTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(CryptoFileSystemIntegrationTest.class);
|
||||
|
||||
private final CryptoFileSystemTestComponent cryptoFsComp = DaggerCryptoFileSystemTestComponent.builder().cryptoEngineModule(new CryptoEngineTestModule()).build();
|
||||
|
||||
private CryptoFileSystemDelegate cryptoDelegate;
|
||||
private FileSystem ciphertextFs;
|
||||
private FileSystem cleartextFs;
|
||||
|
||||
@Before
|
||||
public void setupFileSystems() {
|
||||
cryptoDelegate = Mockito.mock(CryptoFileSystemDelegate.class);
|
||||
ciphertextFs = new InMemoryFileSystem();
|
||||
FileSystem shorteningFs = cryptoFsComp.shorteningFileSystemFactory().get(ciphertextFs);
|
||||
cryptoFsComp.cryptoFileSystemFactory().initializeNew(shorteningFs, "TopSecret");
|
||||
cleartextFs = cryptoFsComp.cryptoFileSystemFactory().unlockExisting(shorteningFs, "TopSecret", cryptoDelegate);
|
||||
}
|
||||
|
||||
@Test(timeout = 1000)
|
||||
public void testVaultStructureInitializationAndBackupBehaviour() throws UncheckedIOException, IOException {
|
||||
final FileSystem physicalFs = new InMemoryFileSystem();
|
||||
final File masterkeyFile = physicalFs.file("masterkey.cryptomator");
|
||||
final File masterkeyBkupFile = physicalFs.file("masterkey.cryptomator.bkup");
|
||||
final Folder physicalDataRoot = physicalFs.folder("d");
|
||||
Assert.assertFalse(masterkeyFile.exists());
|
||||
Assert.assertFalse(masterkeyBkupFile.exists());
|
||||
Assert.assertFalse(physicalDataRoot.exists());
|
||||
|
||||
cryptoFsComp.cryptoFileSystemFactory().initializeNew(physicalFs, "asd");
|
||||
Assert.assertTrue(masterkeyFile.exists());
|
||||
Assert.assertFalse(masterkeyBkupFile.exists());
|
||||
Assert.assertFalse(physicalDataRoot.exists());
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
final FileSystem cryptoFs = cryptoFsComp.cryptoFileSystemFactory().unlockExisting(physicalFs, "asd", cryptoDelegate);
|
||||
Assert.assertTrue(masterkeyBkupFile.exists());
|
||||
Assert.assertTrue(physicalDataRoot.exists());
|
||||
Assert.assertEquals(3, physicalFs.children().count()); // d + masterkey.cryptomator + masterkey.cryptomator.bkup
|
||||
Assert.assertEquals(1, physicalDataRoot.folders().count()); // ROOT directory
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEncryptionOfLongFolderNames() {
|
||||
final String shortName = "normal folder name";
|
||||
final String longName = "this will be a long filename after encryption, because its encrypted name is longer than onehundredandeighty characters";
|
||||
|
||||
final Folder shortFolder = cleartextFs.folder(shortName);
|
||||
final Folder longFolder = cleartextFs.folder(longName);
|
||||
|
||||
shortFolder.create();
|
||||
longFolder.create();
|
||||
|
||||
// because of the long file, a metadata folder should exist on the physical layer:
|
||||
Assert.assertEquals(1, ciphertextFs.folder("m").folders().count());
|
||||
Assert.assertTrue(ciphertextFs.folder("m").exists());
|
||||
|
||||
// but the shortened filenames must not be visible on the cleartext layer:
|
||||
Assert.assertArrayEquals(new String[] {shortName, longName}, cleartextFs.folders().map(Node::name).sorted().toArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEncryptionAndDecryptionOfFiles() {
|
||||
// write test content to encrypted file
|
||||
try (WritableFile writable = cleartextFs.file("test1.txt").openWritable()) {
|
||||
writable.write(ByteBuffer.wrap("Hello ".getBytes()));
|
||||
writable.write(ByteBuffer.wrap("World".getBytes()));
|
||||
}
|
||||
|
||||
File physicalFile = ciphertextFs.folder("d").folders().findAny().get().folders().findAny().get().files().findAny().get();
|
||||
Assert.assertTrue(physicalFile.exists());
|
||||
|
||||
// read test content from decrypted file
|
||||
try (ReadableFile readable = cleartextFs.file("test1.txt").openReadable()) {
|
||||
ByteBuffer buf1 = ByteBuffer.allocate(5);
|
||||
readable.read(buf1);
|
||||
buf1.flip();
|
||||
Assert.assertEquals("Hello", new String(buf1.array(), 0, buf1.remaining()));
|
||||
ByteBuffer buf2 = ByteBuffer.allocate(10);
|
||||
readable.read(buf2);
|
||||
buf2.flip();
|
||||
Assert.assertArrayEquals(" World".getBytes(), Arrays.copyOfRange(buf2.array(), 0, buf2.remaining()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testForcedDecryptionOfManipulatedFile() {
|
||||
// write test content to encrypted file
|
||||
try (WritableFile writable = cleartextFs.file("test1.txt").openWritable()) {
|
||||
writable.write(ByteBuffer.wrap("Hello World".getBytes()));
|
||||
}
|
||||
|
||||
File physicalFile = ciphertextFs.folder("d").folders().findAny().get().folders().findAny().get().files().findAny().get();
|
||||
Assert.assertTrue(physicalFile.exists());
|
||||
|
||||
// toggle last bit
|
||||
try (WritableFile writable = physicalFile.openWritable(); ReadableFile readable = physicalFile.openReadable()) {
|
||||
ByteBuffer buf = ByteBuffer.allocate((int) physicalFile.size());
|
||||
readable.read(buf);
|
||||
buf.array()[buf.limit() - 1] ^= 0x01;
|
||||
buf.flip();
|
||||
writable.write(buf);
|
||||
}
|
||||
|
||||
// whitelist
|
||||
Mockito.when(cryptoDelegate.shouldSkipAuthentication("/test1.txt")).thenReturn(true);
|
||||
|
||||
// read test content from decrypted file
|
||||
try (ReadableFile readable = cleartextFs.file("test1.txt").openReadable()) {
|
||||
ByteBuffer buf = ByteBuffer.allocate(11);
|
||||
readable.read(buf);
|
||||
buf.flip();
|
||||
Assert.assertArrayEquals("Hello World".getBytes(), buf.array());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(timeout = 20000) // assuming a minimum speed of 10mb/s during encryption and decryption 20s should be enough
|
||||
public void testEncryptionAndDecryptionSpeed() throws InterruptedException, IOException {
|
||||
File file = cleartextFs.file("benchmark.test");
|
||||
|
||||
final long encStart = System.nanoTime();
|
||||
try (WritableFile writable = file.openWritable()) {
|
||||
final ByteBuffer cleartext = ByteBuffer.allocate(100000); // 100k
|
||||
for (int i = 0; i < 1000; i++) { // 100M total
|
||||
cleartext.rewind();
|
||||
writable.write(cleartext);
|
||||
}
|
||||
}
|
||||
final long encEnd = System.nanoTime();
|
||||
LOG.debug("Encryption of 100M took {}ms", (encEnd - encStart) / 1000 / 1000);
|
||||
|
||||
final long decStart = System.nanoTime();
|
||||
try (ReadableFile readable = file.openReadable()) {
|
||||
final ByteBuffer cleartext = ByteBuffer.allocate(100000); // 100k
|
||||
for (int i = 0; i < 1000; i++) { // 100M total
|
||||
cleartext.clear();
|
||||
readable.read(cleartext);
|
||||
cleartext.flip();
|
||||
Assert.assertEquals(cleartext.get(), 0x00);
|
||||
}
|
||||
}
|
||||
final long decEnd = System.nanoTime();
|
||||
LOG.debug("Decryption of 100M took {}ms", (decEnd - decStart) / 1000 / 1000);
|
||||
|
||||
file.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRandomAccessOnLastBlock() {
|
||||
// prepare test data:
|
||||
ByteBuffer testData = ByteBuffer.allocate(16000 * Integer.BYTES); // < 64kb
|
||||
for (int i = 0; i < 16000; i++) {
|
||||
testData.putInt(i);
|
||||
}
|
||||
|
||||
// write test data to file:
|
||||
File cleartextFile = cleartextFs.file("test");
|
||||
try (WritableFile writable = cleartextFile.openWritable()) {
|
||||
testData.flip();
|
||||
writable.write(testData);
|
||||
}
|
||||
|
||||
// read last block:
|
||||
try (ReadableFile readable = cleartextFile.openReadable()) {
|
||||
ByteBuffer buf = ByteBuffer.allocate(Integer.BYTES);
|
||||
buf.clear();
|
||||
readable.position(15999 * Integer.BYTES);
|
||||
readable.read(buf);
|
||||
buf.flip();
|
||||
Assert.assertEquals(15999, buf.getInt());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSequentialRandomAccess() {
|
||||
// prepare test data:
|
||||
ByteBuffer testData = ByteBuffer.allocate(1_000_000 * Integer.BYTES); // = 4MB
|
||||
for (int i = 0; i < 1000000; i++) {
|
||||
testData.putInt(i);
|
||||
}
|
||||
|
||||
// write test data to file:
|
||||
File cleartextFile = cleartextFs.file("test");
|
||||
try (WritableFile writable = cleartextFile.openWritable()) {
|
||||
testData.flip();
|
||||
writable.write(testData);
|
||||
}
|
||||
|
||||
// shuffle our test positions:
|
||||
List<Integer> nums = new ArrayList<>();
|
||||
for (int i = 0; i < 1_000_000; i++) {
|
||||
nums.add(i);
|
||||
}
|
||||
Collections.shuffle(nums);
|
||||
|
||||
// read parts from positions:
|
||||
try (ReadableFile readable = cleartextFile.openReadable()) {
|
||||
ByteBuffer buf = ByteBuffer.allocate(Integer.BYTES);
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
int num = nums.get(i);
|
||||
buf.clear();
|
||||
readable.position(num * Integer.BYTES);
|
||||
readable.read(buf);
|
||||
buf.flip();
|
||||
Assert.assertEquals(num, buf.getInt());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParallelRandomAccess() {
|
||||
// prepare test data:
|
||||
ByteBuffer testData = ByteBuffer.allocate(1_000_000 * Integer.BYTES); // = 4MB
|
||||
for (int i = 0; i < 1000000; i++) {
|
||||
testData.putInt(i);
|
||||
}
|
||||
|
||||
// write test data to file:
|
||||
final File cleartextFile = cleartextFs.file("test");
|
||||
try (WritableFile writable = cleartextFile.openWritable()) {
|
||||
testData.flip();
|
||||
writable.write(testData);
|
||||
}
|
||||
|
||||
// shuffle our test positions:
|
||||
List<Integer> nums = new ArrayList<>();
|
||||
for (int i = 0; i < 1_000_000; i++) {
|
||||
nums.add(i);
|
||||
}
|
||||
Collections.shuffle(nums);
|
||||
|
||||
// read parts from positions in parallel:
|
||||
final ForkJoinPool pool = new ForkJoinPool(10);
|
||||
final List<Future<Boolean>> tasks = new ArrayList<>();
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
final int num = nums.get(i);
|
||||
final ForkJoinTask<Boolean> task = ForkJoinTask.adapt(() -> {
|
||||
try (ReadableFile readable = cleartextFile.openReadable()) {
|
||||
ByteBuffer buf = ByteBuffer.allocate(Integer.BYTES);
|
||||
buf.clear();
|
||||
readable.position(num * Integer.BYTES);
|
||||
readable.read(buf);
|
||||
buf.flip();
|
||||
int numRead = buf.getInt();
|
||||
return num == numRead;
|
||||
}
|
||||
});
|
||||
pool.execute(task);
|
||||
tasks.add(task);
|
||||
}
|
||||
|
||||
// Wait for tasks to finish and check results
|
||||
Assert.assertTrue(tasks.stream().allMatch(task -> {
|
||||
try {
|
||||
return task.get();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user