Merge branch 'RB' into current

# Conflicts:
#	.gitignore
#	pom.xml
#	src/main/java/com/ossez/lang/tutorial/overview/HelloWorld.java
This commit is contained in:
YuCheng Hu 2021-04-12 22:24:27 -04:00
commit 93bd3048b7
No known key found for this signature in database
GPG Key ID: 1E5CBEF8B550FB7D
555 changed files with 224166 additions and 0 deletions

244
.gitignore vendored
View File

@ -1,3 +1,243 @@
<<<<<<< HEAD
=======
<<<<<<< HEAD
### Gradle ###
.gradle
build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Cache of project
.gradletasknamecache
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
# gradle/wrapper/gradle-wrapper.properties
### Gradle Patch ###
**/build/
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
.idea/sonarlint
### Intellij+iml ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij+iml Patch ###
# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023
*.iml
modules.xml
.idea/misc.xml
*.ipr
### Maven ###
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
.mvn/wrapper/maven-wrapper.jar
.flattened-pom.xml
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
.idea/sonarlint
=======
>>>>>>> RB
# Binaries
*.7z
*.dmg
@ -86,3 +326,7 @@ Network Trash Folder
Temporary Items
.apdisk
<<<<<<< HEAD
=======
>>>>>>> 361e407d91e00158295aadeaca0a91d84a534820
>>>>>>> RB

9
.travis.yml Normal file
View File

@ -0,0 +1,9 @@
sudo: false
language: java
jdk:
- oraclejdk8
script:
- test/run.sh
notifications:
slack:
secure: wjhq7HXbbe3Tdu9UI+3BVNRjW/QMhjhbhoXypMBS+A6MC58rU4oT7VPRiG4xi+sCjUfjP3ZmWmmy/t5RH89T/Vs9DuZlqxT4j28y5N5GZvlBTn3/nvMTFJ8hnW3E9xTiFEgMjXvuEbtrMpXicTTu+NyuZTDEHHfcgwnJJrGdOSY=

2
CONTRIBUTING.adoc Normal file
View File

@ -0,0 +1,2 @@
If you have not previously done so, please fill out and
submit the https://cla.pivotal.io/sign/spring[Contributor License Agreement].

16
LICENSE.code.txt Normal file
View File

@ -0,0 +1,16 @@
All code in this repository is:
=======================================================================
Copyright (c) 2013 GoPivotal, Inc. All Rights Reserved
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

1
LICENSE.writing.txt Normal file
View File

@ -0,0 +1 @@
Except where otherwise noted, this work is licensed under https://creativecommons.org/licenses/by-nd/3.0/

12
README.md Normal file
View File

@ -0,0 +1,12 @@
<p align="center">
<a href="https://www.hackerrank.com/huyuchengus">
<img height=85 src="https://avatars1.githubusercontent.com/u/45009982?s=200&v=4">
</a>
<br>提供 CWIKI.US 项目中使用的代码
</p>
所有的 Java 代码使用的是 JDK 8。
你可以通过单击下面连接后访问我们网站,并且访问我们提供的最新有关 Java 的开发资料。
* [概述](https://www.cwiki.us/pages/viewpage.action?pageId=37492282)

75
build.gradle Normal file
View File

@ -0,0 +1,75 @@
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.1.4.RELEASE")
}
}
plugins {
id 'io.spring.dependency-management' version '1.0.8.RELEASE' apply false
id 'org.jetbrains.kotlin.jvm' version '1.3.50' apply false
id 'org.jetbrains.dokka' version '0.9.18' apply false
id 'org.asciidoctor.convert' version '1.5.8'
id 'io.spring.nohttp' version '0.0.3.RELEASE'
id 'de.undercouch.download' version '4.0.0'
id 'com.gradle.build-scan' version '2.4.2'
id "com.jfrog.artifactory" version '4.9.8' apply false
id "io.freefair.aspectj" version "4.1.1" apply false
id "com.github.ben-manes.versions" version "0.24.0"
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
bootJar {
baseName = 'cwiki-us-spring-batch-processing'
version = '0.1.0'
}
repositories {
maven { url "https://maven.ossez.com/repository/internal" }
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
configure(allprojects) { project ->
apply plugin: 'java'
dependencies {
// LOG
compile 'ch.qos.logback:logback-classic:1.2.3'
compile 'org.hsqldb:hsqldb:2.5.0'
testCompile("junit:junit:4.12")
}
repositories {
maven { url "https://maven.ossez.com/repository/internal" }
mavenCentral()
}
}
configure(rootProject) {
description = "Spring Framework"
apply plugin: "groovy"
apply plugin: "kotlin"
apply plugin: "io.spring.nohttp"
dependencies {
asciidoctor("io.spring.asciidoctor:spring-asciidoctor-extensions:0.1.3.RELEASE")
}
}

View File

@ -0,0 +1,10 @@
## Core Java Modules
This module contains modules about core Java
## Relevant articles:
- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms)
- [Guide to Java FileChannel](https://www.baeldung.com/java-filechannel)
- [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception)
- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch)

View File

@ -0,0 +1,235 @@
### Gradle ###
.gradle
build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Cache of project
.gradletasknamecache
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
# gradle/wrapper/gradle-wrapper.properties
### Gradle Patch ###
**/build/
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
.idea/sonarlint
### Intellij+iml ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij+iml Patch ###
# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023
*.iml
modules.xml
.idea/misc.xml
*.ipr
### Maven ###
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
.mvn/wrapper/maven-wrapper.jar
.flattened-pom.xml
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
.idea/sonarlint

View File

@ -0,0 +1,11 @@
=========
## Core Java Cookbooks and Examples
### 相关的文章:
- [Java @Override Annotation](https://www.baeldung.com/java-override)
- [Java @SuppressWarnings Annotation](https://www.baeldung.com/java-suppresswarnings)
- [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs)
- [Java @Deprecated Annotation注解](https://www.cwiki.us/display/JAVAZH/Java+@Deprecated+Annotation)
- [Overview of Java Built-in Annotations](https://www.baeldung.com/java-default-annotations)
- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation)

View File

@ -0,0 +1,83 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ossez</groupId>
<artifactId>core-java-annotations</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-annotations</name>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-bytecode</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-annotations</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<asspectj.version>1.8.9</asspectj.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator.version>1.19</jmh-generator.version>
<!-- plugins -->
<maven-surefire-plugin.version>2.22.1</maven-surefire-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,5 @@
package com.ossez.annotations;
@Deprecated
class ClassWithAnnotation {
}

View File

@ -0,0 +1,23 @@
package com.ossez.annotations;
public class ClassWithDeprecatedMethod {
/**
* Calculate period between versions
* * @deprecated
* * This method is no longer acceptable to compute time between versions.
* * <p> Use {@link ClassWithDeprecatedMethod#updatedMethod()} instead.
*/
@Deprecated
public static void deprecatedMethod() {
}
/**
* Updated Method instead of deprecatedMethod.
*/
public static void updatedMethod() {
}
}

View File

@ -0,0 +1,11 @@
package com.ossez.annotations;
class ClassWithSafeVarargs<T> {
@SafeVarargs
final void iterateOverVarargs(T... args) {
for (T x : args) {
// do stuff with x
}
}
}

View File

@ -0,0 +1,9 @@
package com.ossez.annotations;
class ClassWithSuppressWarnings {
@SuppressWarnings("deprecation")
void useDeprecatedMethod() {
ClassWithDeprecatedMethod.deprecatedMethod(); // no warning is generated here
}
}

View File

@ -0,0 +1,8 @@
package com.ossez.annotations;
@FunctionalInterface
interface IntConsumer {
void accept(Integer number);
}

View File

@ -0,0 +1,8 @@
package com.ossez.annotations;
import java.lang.annotation.Repeatable;
@Repeatable(Intervals.class)
@interface Interval {
int hour() default 1;
}

View File

@ -0,0 +1,9 @@
package com.ossez.annotations;
public class IntervalUsage {
@Interval(hour = 17)
@Interval(hour = 13)
void doPeriodicCleanup() {
}
}

View File

@ -0,0 +1,5 @@
package com.ossez.annotations;
@interface Intervals {
Interval[] value();
}

View File

@ -0,0 +1,11 @@
package com.ossez.annotations;
import java.lang.annotation.*;
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.LOCAL_VARIABLE, ElementType.FIELD})
@interface MyAnnotation {
}

View File

@ -0,0 +1,16 @@
package com.ossez.annotations;
class MyAnnotationTarget {
// this is OK
@MyAnnotation
String someField;
// @MyAnnotation <- this is invalid usage!
void doSomething() {
// this also works
@MyAnnotation
String localVariable;
}
}

View File

@ -0,0 +1,6 @@
package com.ossez.annotations;
interface MyOperation {
void perform();
}

View File

@ -0,0 +1,9 @@
package com.ossez.annotations;
class MyOperationImpl implements MyOperation {
@Override
public void perform() {
}
}

View File

@ -0,0 +1,13 @@
package com.ossez.customannotations;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(METHOD)
public @interface Init {
}

View File

@ -0,0 +1,13 @@
package com.ossez.customannotations;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target({ FIELD })
public @interface JsonElement {
public String key() default "";
}

View File

@ -0,0 +1,13 @@
package com.ossez.customannotations;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(TYPE)
public @interface JsonSerializable {
}

View File

@ -0,0 +1,10 @@
package com.ossez.customannotations;
public class JsonSerializationException extends RuntimeException {
private static final long serialVersionUID = 1L;
public JsonSerializationException(String message) {
super(message);
}
}

View File

@ -0,0 +1,67 @@
package com.ossez.customannotations;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
public class ObjectToJsonConverter {
public String convertToJson(Object object) throws JsonSerializationException {
try {
checkIfSerializable(object);
initializeObject(object);
return getJsonString(object);
} catch (Exception e) {
throw new JsonSerializationException(e.getMessage());
}
}
private void checkIfSerializable(Object object) {
if (Objects.isNull(object)) {
throw new JsonSerializationException("Can't serialize a null object");
}
Class<?> clazz = object.getClass();
if (!clazz.isAnnotationPresent(JsonSerializable.class)) {
throw new JsonSerializationException("The class " + clazz.getSimpleName() + " is not annotated with JsonSerializable");
}
}
private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> clazz = object.getClass();
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(Init.class)) {
method.setAccessible(true);
method.invoke(object);
}
}
}
private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException {
Class<?> clazz = object.getClass();
Map<String, String> jsonElementsMap = new HashMap<>();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
if (field.isAnnotationPresent(JsonElement.class)) {
jsonElementsMap.put(getKey(field), (String) field.get(object));
}
}
String jsonString = jsonElementsMap.entrySet()
.stream()
.map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"")
.collect(Collectors.joining(","));
return "{" + jsonString + "}";
}
private String getKey(Field field) {
String value = field.getAnnotation(JsonElement.class)
.key();
return value.isEmpty() ? field.getName() : value;
}
}

View File

@ -0,0 +1,66 @@
package com.ossez.customannotations;
@JsonSerializable
public class Person {
@JsonElement
private String firstName;
@JsonElement
private String lastName;
@JsonElement(key = "personAge")
private String age;
private String address;
public Person(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public Person(String firstName, String lastName, String age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
@Init
private void initNames() {
this.firstName = this.firstName.substring(0, 1)
.toUpperCase() + this.firstName.substring(1);
this.lastName = this.lastName.substring(0, 1)
.toUpperCase() + this.lastName.substring(1);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<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>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
package com.ossez.annotations;
import org.junit.jupiter.api.Test;
public class DeprecatedTest {
@Test
public void testStrikesWarning() {
ClassWithDeprecatedMethod.deprecatedMethod();
}
}

View File

@ -0,0 +1,26 @@
package com.ossez.customannotations;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class JsonSerializerUnitTest {
@Test
public void givenObjectNotSerializedThenExceptionThrown() throws JsonSerializationException {
Object object = new Object();
ObjectToJsonConverter serializer = new ObjectToJsonConverter();
assertThrows(JsonSerializationException.class, () -> {
serializer.convertToJson(object);
});
}
@Test
public void givenObjectSerializedThenTrueReturned() throws JsonSerializationException {
Person person = new Person("soufiane", "cheouati", "34");
ObjectToJsonConverter serializer = new ObjectToJsonConverter();
String jsonString = serializer.convertToJson(person);
assertEquals("{\"personAge\":\"34\",\"firstName\":\"Soufiane\",\"lastName\":\"Cheouati\"}", jsonString);
}
}

View File

@ -0,0 +1,5 @@
0.*
# Files generated by integration tests
# *.txt
/temp

View File

@ -0,0 +1,44 @@
## Core Java IO
This module contains articles about core Java input and output (IO)
### Relevant Articles:
- [How to Read a Large File Efficiently with Java](http://www.baeldung.com/java-read-lines-large-file)
- [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string)
- [Java Write to File](http://www.baeldung.com/java-write-to-file)
- [Java Convert File to InputStream](http://www.baeldung.com/convert-file-to-input-stream)
- [Java Scanner](http://www.baeldung.com/java-scanner)
- [Java Byte Array to Writer](http://www.baeldung.com/java-convert-byte-array-to-writer)
- [Java Directory Size](http://www.baeldung.com/java-folder-size)
- [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](http://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library)
- [File Size in Java](http://www.baeldung.com/java-file-size)
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path)
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer)
- [How to Copy a File with Java](http://www.baeldung.com/java-copy-file)
- [Java Append Data to a File](http://www.baeldung.com/java-append-to-file)
- [FileNotFoundException in Java](http://www.baeldung.com/java-filenotfound-exception)
- [How to Read a File in Java](http://www.baeldung.com/reading-file-in-java)
- [A Guide To NIO2 Asynchronous File Channel](http://www.baeldung.com/java-nio2-async-file-channel)
- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor)
- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute)
- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api)
- [Zipping and Unzipping in Java](http://www.baeldung.com/java-compress-and-uncompress)
- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path)
- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice)
- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels)
- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel)
- [Download a File From an URL in Java](http://www.baeldung.com/java-download-file)
- [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink)
- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter)
- [Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist)
- [Guide to Java OutputStream](https://www.baeldung.com/java-outputstream)
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension)
- [Getting a Files Mime Type in Java](http://www.baeldung.com/java-file-mime-type)
- [Create a Directory in Java](https://www.baeldung.com/java-create-directory)
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
- [List Files in a Directory in Java](https://www.baeldung.com/java-list-directory-files)
- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes)
- [Introduction to the Java NIO Selector](https://www.baeldung.com/java-nio-selector)
- [[More -->]](/core-java-modules/core-java-io-2)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,301 @@
<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>
<artifactId>core-java-io</artifactId>
<version>0.0.1</version>
<name>core-java-io</name>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<!-- utils -->
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>${collections-generic.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>org.decimal4j</groupId>
<artifactId>decimal4j</artifactId>
<version>${decimal4j.version}</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>${unix4j.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
<!-- web -->
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>${moneta.version}</version>
</dependency>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>${esapi.version}</version>
</dependency>
<dependency>
<groupId>com.sun.messaging.mq</groupId>
<artifactId>fscontext</artifactId>
<version>${fscontext.version}</version>
</dependency>
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
<version>${protonpack.version}</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator-annprocess.version}</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client -->
<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId>
<version>${async-http-client.version}</version>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>${opencsv.version}</version>
<scope>test</scope>
</dependency>
<!-- Mime Type Resolution Libraries -->
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>${tika.version}</version>
</dependency>
<dependency>
<groupId>net.sf.jmimemagic</groupId>
<artifactId>jmimemagic</artifactId>
<version>${jmime-magic.version}</version>
</dependency>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>9.0.1</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-io</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<configuration>
<executable>java</executable>
<mainClass>com.ossez.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
<arguments>
<argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument>
<classpath />
<argument>com.ossez.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.ossez.resource.MyResourceLoader</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase> -->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath />
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- util -->
<bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version>
<commons-math3.version>3.6.1</commons-math3.version>
<decimal4j.version>1.0.3</decimal4j.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<fscontext.version>4.6-b01</fscontext.version>
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
<opencsv.version>4.1</opencsv.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
<!-- maven plugins -->
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<hsqldb.version>2.4.0</hsqldb.version>
<esapi.version>2.1.0.1</esapi.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
<async-http-client.version>2.4.5</async-http-client.version>
<!-- Mime Type Libraries -->
<tika.version>1.18</tika.version>
<jmime-magic.version>0.1.5</jmime-magic.version>
<maven-jar-plugin.version>3.1.0</maven-jar-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,84 @@
package com.ossez.bufferedreader;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.stream.Collectors;
public class BufferedReaderExample {
public String readAllLines(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
return content.toString();
}
public String readAllLinesWithStream(BufferedReader reader) {
return reader
.lines()
.collect(Collectors.joining(System.lineSeparator()));
}
public String readAllCharsOneByOne(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
int value;
while ((value = reader.read()) != -1) {
content.append((char) value);
}
return content.toString();
}
public String readMultipleChars(BufferedReader reader) throws IOException {
int length = 5;
char[] chars = new char[length];
int charsRead = reader.read(chars, 0, length);
String result;
if (charsRead != -1) {
result = new String(chars, 0, charsRead);
} else {
result = "";
}
return result;
}
public String readFile() {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("src/main/resources/input.txt"));
String content = readAllLines(reader);
return content;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String readFileTryWithResources() {
try (BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/input.txt"))) {
String content = readAllLines(reader);
return content;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -0,0 +1,22 @@
package com.ossez.csv;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class WriteCsvFileExample {
public String convertToCSV(String[] data) {
return Stream.of(data)
.map(this::escapeSpecialCharacters)
.collect(Collectors.joining(","));
}
public String escapeSpecialCharacters(String data) {
String escapedData = data.replaceAll("\\R", " ");
if (data.contains(",") || data.contains("\"") || data.contains("'")) {
data = data.replace("\"", "\"\"");
escapedData = "\"" + data + "\"";
}
return escapedData;
}
}

View File

@ -0,0 +1,42 @@
package com.ossez.dirmonitoring;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
public class DirectoryMonitoringExample {
private static final Logger LOG = LoggerFactory.getLogger(DirectoryMonitoringExample.class);
private static final int POLL_INTERVAL = 500;
public static void main(String[] args) throws Exception {
FileAlterationObserver observer = new FileAlterationObserver(System.getProperty("user.home"));
FileAlterationMonitor monitor = new FileAlterationMonitor(POLL_INTERVAL);
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
LOG.debug("File: " + file.getName() + " created");
}
@Override
public void onFileDelete(File file) {
LOG.debug("File: " + file.getName() + " deleted");
}
@Override
public void onFileChange(File file) {
LOG.debug("File: " + file.getName() + " changed");
}
};
observer.addListener(listener);
monitor.addObserver(observer);
monitor.start();
}
}

View File

@ -0,0 +1,90 @@
package com.ossez.download;
import org.apache.commons.io.FileUtils;
import org.asynchttpclient.*;
import java.io.*;
import java.net.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.ExecutionException;
public class FileDownload {
public static void downloadWithJavaIO(String url, String localFilename) {
try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(localFilename)) {
byte dataBuffer[] = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void downloadWithJava7IO(String url, String localFilename) {
try (InputStream in = new URL(url).openStream()) {
Files.copy(in, Paths.get(localFilename), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void downloadWithJavaNIO(String fileURL, String localFilename) throws IOException {
URL url = new URL(fileURL);
try (ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(localFilename); FileChannel fileChannel = fileOutputStream.getChannel()) {
fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
fileOutputStream.close();
}
}
public static void downloadWithApacheCommons(String url, String localFilename) {
int CONNECT_TIMEOUT = 10000;
int READ_TIMEOUT = 10000;
try {
FileUtils.copyURLToFile(new URL(url), new File(localFilename), CONNECT_TIMEOUT, READ_TIMEOUT);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void downloadWithAHC(String url, String localFilename) throws ExecutionException, InterruptedException, IOException {
FileOutputStream stream = new FileOutputStream(localFilename);
AsyncHttpClient client = Dsl.asyncHttpClient();
client.prepareGet(url)
.execute(new AsyncCompletionHandler<FileOutputStream>() {
@Override
public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
stream.getChannel()
.write(bodyPart.getBodyByteBuffer());
return State.CONTINUE;
}
@Override
public FileOutputStream onCompleted(Response response) throws Exception {
return stream;
}
})
.get();
stream.getChannel().close();
client.close();
}
}

View File

@ -0,0 +1,62 @@
package com.ossez.download;
import java.io.*;
import java.net.*;
public class ResumableDownload {
public static long downloadFile(String downloadUrl, String saveAsFileName) throws IOException, URISyntaxException {
File outputFile = new File(saveAsFileName);
URLConnection downloadFileConnection = new URI(downloadUrl).toURL()
.openConnection();
return transferDataAndGetBytesDownloaded(downloadFileConnection, outputFile);
}
private static long transferDataAndGetBytesDownloaded(URLConnection downloadFileConnection, File outputFile) throws IOException {
long bytesDownloaded = 0;
try (InputStream is = downloadFileConnection.getInputStream(); OutputStream os = new FileOutputStream(outputFile, true)) {
byte[] buffer = new byte[1024];
int bytesCount;
while ((bytesCount = is.read(buffer)) > 0) {
os.write(buffer, 0, bytesCount);
bytesDownloaded += bytesCount;
}
}
return bytesDownloaded;
}
public static long downloadFileWithResume(String downloadUrl, String saveAsFileName) throws IOException, URISyntaxException {
File outputFile = new File(saveAsFileName);
URLConnection downloadFileConnection = addFileResumeFunctionality(downloadUrl, outputFile);
return transferDataAndGetBytesDownloaded(downloadFileConnection, outputFile);
}
private static URLConnection addFileResumeFunctionality(String downloadUrl, File outputFile) throws IOException, URISyntaxException, ProtocolException, ProtocolException {
long existingFileSize = 0L;
URLConnection downloadFileConnection = new URI(downloadUrl).toURL()
.openConnection();
if (outputFile.exists() && downloadFileConnection instanceof HttpURLConnection) {
HttpURLConnection httpFileConnection = (HttpURLConnection) downloadFileConnection;
HttpURLConnection tmpFileConn = (HttpURLConnection) new URI(downloadUrl).toURL()
.openConnection();
tmpFileConn.setRequestMethod("HEAD");
long fileLength = tmpFileConn.getContentLengthLong();
existingFileSize = outputFile.length();
if (existingFileSize < fileLength) {
httpFileConnection.setRequestProperty("Range", "bytes=" + existingFileSize + "-" + fileLength);
} else {
throw new IOException("File Download already completed.");
}
}
return downloadFileConnection;
}
}

View File

@ -0,0 +1,23 @@
package com.ossez.extension;
import com.google.common.io.Files;
import org.apache.commons.io.FilenameUtils;
import java.util.Optional;
public class Extension {
//Instead of file name we can also specify full path of a file eg. /baeldung/com/demo/abc.java
public String getExtensionByApacheCommonLib(String filename) {
return FilenameUtils.getExtension(filename);
}
public Optional<String> getExtensionByStringHandling(String filename) {
return Optional.ofNullable(filename)
.filter(f -> f.contains("."))
.map(f -> f.substring(filename.lastIndexOf(".") + 1));
}
public String getExtensionByGuava(String filename) {
return Files.getFileExtension(filename);
}
}

View File

@ -0,0 +1,24 @@
package com.ossez.fileparser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class BufferedReaderExample {
protected static ArrayList<String> generateArrayListFromFile(String filename) throws IOException {
ArrayList<String> result = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
while (br.ready()) {
result.add(br.readLine());
}
return result;
}
}
}

View File

@ -0,0 +1,31 @@
package com.ossez.fileparser;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class FileReaderExample {
protected static ArrayList<String> generateArrayListFromFile(String filename) throws IOException {
ArrayList<String> result = new ArrayList<>();
try (FileReader f = new FileReader(filename)) {
StringBuffer sb = new StringBuffer();
while (f.ready()) {
char c = (char) f.read();
if (c == '\n') {
result.add(sb.toString());
sb = new StringBuffer();
} else {
sb.append(c);
}
}
if (sb.length() > 0) {
result.add(sb.toString());
}
}
return result;
}
}

View File

@ -0,0 +1,18 @@
package com.ossez.fileparser;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class FilesReadLinesExample {
protected static ArrayList<String> generateArrayListFromFile(String filename) throws IOException {
List<String> result = Files.readAllLines(Paths.get(filename));
return (ArrayList<String>) result;
}
}

View File

@ -0,0 +1,24 @@
package com.ossez.fileparser;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class ScannerIntExample {
protected static ArrayList<Integer> generateArrayListFromFile(String filename) throws IOException {
ArrayList<Integer> result = new ArrayList<>();
try (Scanner s = new Scanner(new FileReader(filename))) {
while (s.hasNext()) {
result.add(s.nextInt());
}
return result;
}
}
}

View File

@ -0,0 +1,24 @@
package com.ossez.fileparser;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class ScannerStringExample {
protected static ArrayList<String> generateArrayListFromFile(String filename) throws IOException {
ArrayList<String> result = new ArrayList<>();
try (Scanner s = new Scanner(new FileReader(filename))) {
while (s.hasNext()) {
result.add(s.nextLine());
}
return result;
}
}
}

View File

@ -0,0 +1,64 @@
package com.ossez.files;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ListFiles {
public static final int DEPTH = 1;
public Set<String> listFilesUsingJavaIO(String dir) {
return Stream.of(new File(dir).listFiles())
.filter(file -> !file.isDirectory())
.map(File::getName)
.collect(Collectors.toSet());
}
public Set<String> listFilesUsingFileWalk(String dir, int depth) throws IOException {
try (Stream<Path> stream = Files.walk(Paths.get(dir), depth)) {
return stream.filter(file -> !Files.isDirectory(file))
.map(Path::getFileName)
.map(Path::toString)
.collect(Collectors.toSet());
}
}
public Set<String> listFilesUsingFileWalkAndVisitor(String dir) throws IOException {
Set<String> fileList = new HashSet<>();
Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!Files.isDirectory(file)) {
fileList.add(file.getFileName()
.toString());
}
return FileVisitResult.CONTINUE;
}
});
return fileList;
}
public Set<String> listFilesUsingDirectoryStream(String dir) throws IOException {
Set<String> fileList = new HashSet<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(dir))) {
for (Path path : stream) {
if (!Files.isDirectory(path)) {
fileList.add(path.getFileName()
.toString());
}
}
}
return fileList;
}
}

View File

@ -0,0 +1,42 @@
package com.ossez.filesystem.jndi;
import java.io.File;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class LookupFSJNDI {
private InitialContext ctx = null;
public LookupFSJNDI() throws NamingException {
super();
init();
}
private void init() throws NamingException {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
// URI to namespace (actual directory)
env.put(Context.PROVIDER_URL, "file:./src/test/resources");
ctx = new InitialContext(env);
}
public InitialContext getCtx() {
return ctx;
}
public File getFile(String fileName) {
File file;
try {
file = (File) getCtx().lookup(fileName);
} catch (NamingException e) {
file = null;
}
return file;
}
}

View File

@ -0,0 +1,50 @@
package com.ossez.java.nio.selector;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class EchoClient {
private static SocketChannel client;
private static ByteBuffer buffer;
private static EchoClient instance;
public static EchoClient start() {
if (instance == null)
instance = new EchoClient();
return instance;
}
public static void stop() throws IOException {
client.close();
buffer = null;
}
private EchoClient() {
try {
client = SocketChannel.open(new InetSocketAddress("localhost", 5454));
buffer = ByteBuffer.allocate(256);
} catch (IOException e) {
e.printStackTrace();
}
}
public String sendMessage(String msg) {
buffer = ByteBuffer.wrap(msg.getBytes());
String response = null;
try {
client.write(buffer);
buffer.clear();
client.read(buffer);
response = new String(buffer.array()).trim();
System.out.println("response=" + response);
buffer.clear();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}

View File

@ -0,0 +1,75 @@
package com.ossez.java.nio.selector;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class EchoServer {
private static final String POISON_PILL = "POISON_PILL";
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
ServerSocketChannel serverSocket = ServerSocketChannel.open();
serverSocket.bind(new InetSocketAddress("localhost", 5454));
serverSocket.configureBlocking(false);
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
ByteBuffer buffer = ByteBuffer.allocate(256);
while (true) {
selector.select();
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> iter = selectedKeys.iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
if (key.isAcceptable()) {
register(selector, serverSocket);
}
if (key.isReadable()) {
answerWithEcho(buffer, key);
}
iter.remove();
}
}
}
private static void answerWithEcho(ByteBuffer buffer, SelectionKey key) throws IOException {
SocketChannel client = (SocketChannel) key.channel();
client.read(buffer);
if (new String(buffer.array()).trim().equals(POISON_PILL)) {
client.close();
System.out.println("Not accepting client messages anymore");
}
buffer.flip();
client.write(buffer);
buffer.clear();
}
private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException {
SocketChannel client = serverSocket.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
}
public static Process start() throws IOException, InterruptedException {
String javaHome = System.getProperty("java.home");
String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = EchoServer.class.getCanonicalName();
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
return builder.start();
}
}

View File

@ -0,0 +1,2 @@
###Relevant Articles:
- [Introduction to the Java NIO Selector](http://www.baeldung.com/java-nio-selector)

View File

@ -0,0 +1,56 @@
package com.ossez.java.nio2.visitor;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import static java.nio.file.FileVisitResult.CONTINUE;
import static java.nio.file.FileVisitResult.TERMINATE;
public class FileSearchExample implements FileVisitor<Path> {
private final String fileName;
private final Path startDir;
public FileSearchExample(String fileName, Path startingDir) {
this.fileName = fileName;
startDir = startingDir;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String fileName = file.getFileName().toString();
if (this.fileName.equals(fileName)) {
System.out.println("File found: " + file.toString());
return TERMINATE;
}
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
System.out.println("Failed to access file: " + file.toString());
return CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
boolean finishedSearch = Files.isSameFile(dir, startDir);
if (finishedSearch) {
System.out.println("File:" + fileName + " not found");
return TERMINATE;
}
return CONTINUE;
}
public static void main(String[] args) throws IOException {
Path startingDir = Paths.get("C:/Users/new/Desktop");
FileSearchExample crawler = new FileSearchExample("hibernate.txt", startingDir);
Files.walkFileTree(startingDir, crawler);
}
}

View File

@ -0,0 +1,30 @@
package com.ossez.java.nio2.visitor;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
public class FileVisitorImpl implements FileVisitor<Path> {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
return null;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
return null;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
return null;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
return null;
}
}

View File

@ -0,0 +1,29 @@
package com.ossez.java.nio2.watcher;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class DirectoryWatcherExample {
public static void main(String[] args) throws IOException, InterruptedException {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get(System.getProperty("user.home"));
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
}
key.reset();
}
watchService.close();
}
}

View File

@ -0,0 +1,42 @@
package com.ossez.resource;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
public class MyResourceLoader {
private void loadFileWithReader() throws IOException {
try (FileReader fileReader = new FileReader("src/main/resources/input.txt");
BufferedReader reader = new BufferedReader(fileReader)) {
String contents = reader.lines()
.collect(Collectors.joining(System.lineSeparator()));
System.out.println(contents);
}
}
private void loadFileAsResource() throws IOException {
try (InputStream inputStream = getClass().getResourceAsStream("/input.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String contents = reader.lines()
.collect(Collectors.joining(System.lineSeparator()));
System.out.println(contents);
}
}
public static void main(String[] args) throws IOException {
MyResourceLoader resourceLoader = new MyResourceLoader();
resourceLoader.loadFileAsResource();
resourceLoader.loadFileWithReader();
}
}

View File

@ -0,0 +1,48 @@
package com.ossez.stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import org.apache.commons.io.FileUtils;
public class FileCopy {
public static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
is.close();
os.close();
}
public static void copyFileUsingChannel(File source, File dest) throws IOException {
FileChannel sourceChannel = null;
FileChannel destChannel = null;
sourceChannel = new FileInputStream(source).getChannel();
destChannel = new FileOutputStream(dest).getChannel();
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
sourceChannel.close();
destChannel.close();
}
public static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
FileUtils.copyFile(source, dest);
}
public static void copyFileUsingJavaFiles(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
}

View File

@ -0,0 +1,48 @@
package com.ossez.stream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class OutputStreamExamples {
public void fileOutputStreamByteSequence(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) {
out.write(bytes);
}
}
public void fileOutputStreamByteSubSequence(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) {
out.write(bytes, 6, 5);
}
}
public void fileOutputStreamByteSingle(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) {
out.write(bytes[6]);
}
}
public void bufferedOutputStream(String file, String... data) throws IOException {
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
for (String s : data) {
out.write(s.getBytes());
out.write(" ".getBytes());
}
}
}
public void outputStreamWriter(String file, String data) throws IOException {
try (OutputStream out = new FileOutputStream(file); Writer writer = new OutputStreamWriter(out, "UTF-8")) {
writer.write(data);
}
}
}

View File

@ -0,0 +1,54 @@
package com.ossez.symlink;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardOpenOption.*;
import java.util.stream.IntStream;
public class SymLinkExample {
public void createSymbolicLink(Path link, Path target) throws IOException {
if (Files.exists(link)) {
Files.delete(link);
}
Files.createSymbolicLink(link, target);
}
public void createHardLink(Path link, Path target) throws IOException {
if (Files.exists(link)) {
Files.delete(link);
}
Files.createLink(link, target);
}
public Path createTextFile() throws IOException {
byte[] content = IntStream.range(0, 10000)
.mapToObj(i -> i + System.lineSeparator())
.reduce("", String::concat)
.getBytes(StandardCharsets.UTF_8);
Path filePath = Paths.get(".", "target_link.txt");
Files.write(filePath, content, CREATE, TRUNCATE_EXISTING);
return filePath;
}
public void printLinkFiles(Path path) throws IOException {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
for (Path file : stream) {
if (Files.isDirectory(file)) {
printLinkFiles(file);
} else if (Files.isSymbolicLink(file)) {
System.out.format("File link '%s' with target '%s'%n", file, Files.readSymbolicLink(file));
}
}
}
}
public static void main(String[] args) throws IOException {
new SymLinkExample().printLinkFiles(Paths.get("."));
}
}

View File

@ -0,0 +1,46 @@
package com.ossez.unzip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipFile {
public static void main(final String[] args) throws IOException {
final String fileZip = "src/main/resources/unzipTest/compressed.zip";
final File destDir = new File("src/main/resources/unzipTest");
final byte[] buffer = new byte[1024];
final ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
final File newFile = newFile(destDir, zipEntry);
final FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
/**
* @see https://snyk.io/research/zip-slip-vulnerability
*/
public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
File destFile = new File(destinationDir, zipEntry.getName());
String destDirPath = destinationDir.getCanonicalPath();
String destFilePath = destFile.getCanonicalPath();
if (!destFilePath.startsWith(destDirPath + File.separator)) {
throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
}
return destFile;
}
}

View File

@ -0,0 +1,16 @@
package com.ossez.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import org.apache.commons.io.IOUtils;
public class StreamUtils {
public static String getStringFromInputStream(InputStream input) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "UTF-8");
return writer.toString();
}
}

View File

@ -0,0 +1,50 @@
package com.ossez.zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipDirectory {
public static void main(final String[] args) throws IOException {
final String sourceFile = "src/main/resources/zipTest";
final FileOutputStream fos = new FileOutputStream("src/main/resources/dirCompressed.zip");
final ZipOutputStream zipOut = new ZipOutputStream(fos);
final File fileToZip = new File(sourceFile);
zipFile(fileToZip, fileToZip.getName(), zipOut);
zipOut.close();
fos.close();
}
private static void zipFile(final File fileToZip, final String fileName, final ZipOutputStream zipOut) throws IOException {
if (fileToZip.isHidden()) {
return;
}
if (fileToZip.isDirectory()) {
if (fileName.endsWith("/")) {
zipOut.putNextEntry(new ZipEntry(fileName));
zipOut.closeEntry();
} else {
zipOut.putNextEntry(new ZipEntry(fileName + "/"));
zipOut.closeEntry();
}
final File[] children = fileToZip.listFiles();
for (final File childFile : children) {
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
}
return;
}
final FileInputStream fis = new FileInputStream(fileToZip);
final ZipEntry zipEntry = new ZipEntry(fileName);
zipOut.putNextEntry(zipEntry);
final byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
}

View File

@ -0,0 +1,28 @@
package com.ossez.zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFile {
public static void main(final String[] args) throws IOException {
final String sourceFile = "src/main/resources/zipTest/test1.txt";
final FileOutputStream fos = new FileOutputStream("src/main/resources/compressed.zip");
final ZipOutputStream zipOut = new ZipOutputStream(fos);
final File fileToZip = new File(sourceFile);
final FileInputStream fis = new FileInputStream(fileToZip);
final ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zipOut.putNextEntry(zipEntry);
final byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
zipOut.close();
fis.close();
fos.close();
}
}

View File

@ -0,0 +1,33 @@
package com.ossez.zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipMultipleFiles {
public static void main(final String[] args) throws IOException {
final List<String> srcFiles = Arrays.asList("src/main/resources/zipTest/test1.txt", "src/main/resources/zipTest/test2.txt");
final FileOutputStream fos = new FileOutputStream("src/main/resources/multiCompressed.zip");
final ZipOutputStream zipOut = new ZipOutputStream(fos);
for (final String srcFile : srcFiles) {
final File fileToZip = new File(srcFile);
final FileInputStream fis = new FileInputStream(fileToZip);
final ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zipOut.putNextEntry(zipEntry);
final byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
zipOut.close();
fos.close();
}
}

View File

@ -0,0 +1,453 @@
#
# OWASP Enterprise Security API (ESAPI) Properties file -- PRODUCTION Version
#
# This file is part of the Open Web Application Security Project (OWASP)
# Enterprise Security API (ESAPI) project. For details, please see
# http://www.owasp.org/index.php/ESAPI.
#
# Copyright (c) 2008,2009 - The OWASP Foundation
#
# DISCUSS: This may cause a major backwards compatibility issue, etc. but
# from a name space perspective, we probably should have prefaced
# all the property names with ESAPI or at least OWASP. Otherwise
# there could be problems is someone loads this properties file into
# the System properties. We could also put this file into the
# esapi.jar file (perhaps as a ResourceBundle) and then allow an external
# ESAPI properties be defined that would overwrite these defaults.
# That keeps the application's properties relatively simple as usually
# they will only want to override a few properties. If looks like we
# already support multiple override levels of this in the
# DefaultSecurityConfiguration class, but I'm suggesting placing the
# defaults in the esapi.jar itself. That way, if the jar is signed,
# we could detect if those properties had been tampered with. (The
# code to check the jar signatures is pretty simple... maybe 70-90 LOC,
# but off course there is an execution penalty (similar to the way
# that the separate sunjce.jar used to be when a class from it was
# first loaded). Thoughts?
###############################################################################
#
# WARNING: Operating system protection should be used to lock down the .esapi
# resources directory and all the files inside and all the directories all the
# way up to the root directory of the file system. Note that if you are using
# file-based implementations, that some files may need to be read-write as they
# get updated dynamically.
#
# Before using, be sure to update the MasterKey and MasterSalt as described below.
# N.B.: If you had stored data that you have previously encrypted with ESAPI 1.4,
# you *must* FIRST decrypt it using ESAPI 1.4 and then (if so desired)
# re-encrypt it with ESAPI 2.0. If you fail to do this, you will NOT be
# able to decrypt your data with ESAPI 2.0.
#
# YOU HAVE BEEN WARNED!!! More details are in the ESAPI 2.0 Release Notes.
#
#===========================================================================
# ESAPI Configuration
#
# If true, then print all the ESAPI properties set here when they are loaded.
# If false, they are not printed. Useful to reduce output when running JUnit tests.
# If you need to troubleshoot a properties related problem, turning this on may help.
# This is 'false' in the src/test/resources/.esapi version. It is 'true' by
# default for reasons of backward compatibility with earlier ESAPI versions.
ESAPI.printProperties=true
# ESAPI is designed to be easily extensible. You can use the reference implementation
# or implement your own providers to take advantage of your enterprise's security
# infrastructure. The functions in ESAPI are referenced using the ESAPI locator, like:
#
# String ciphertext =
# ESAPI.encryptor().encrypt("Secret message"); // Deprecated in 2.0
# CipherText cipherText =
# ESAPI.encryptor().encrypt(new PlainText("Secret message")); // Preferred
#
# Below you can specify the classname for the provider that you wish to use in your
# application. The only requirement is that it implement the appropriate ESAPI interface.
# This allows you to switch security implementations in the future without rewriting the
# entire application.
#
# ExperimentalAccessController requires ESAPI-AccessControlPolicy.xml in .esapi directory
ESAPI.AccessControl=org.owasp.esapi.reference.DefaultAccessController
# FileBasedAuthenticator requires users.txt file in .esapi directory
ESAPI.Authenticator=org.owasp.esapi.reference.FileBasedAuthenticator
ESAPI.Encoder=org.owasp.esapi.reference.DefaultEncoder
ESAPI.Encryptor=org.owasp.esapi.reference.crypto.JavaEncryptor
ESAPI.Executor=org.owasp.esapi.reference.DefaultExecutor
ESAPI.HTTPUtilities=org.owasp.esapi.reference.DefaultHTTPUtilities
ESAPI.IntrusionDetector=org.owasp.esapi.reference.DefaultIntrusionDetector
# Log4JFactory Requires log4j.xml or log4j.properties in classpath - http://www.laliluna.de/log4j-tutorial.html
ESAPI.Logger=org.owasp.esapi.reference.Log4JLogFactory
#ESAPI.Logger=org.owasp.esapi.reference.JavaLogFactory
ESAPI.Randomizer=org.owasp.esapi.reference.DefaultRandomizer
ESAPI.Validator=org.owasp.esapi.reference.DefaultValidator
#===========================================================================
# ESAPI Authenticator
#
Authenticator.AllowedLoginAttempts=3
Authenticator.MaxOldPasswordHashes=13
Authenticator.UsernameParameterName=username
Authenticator.PasswordParameterName=password
# RememberTokenDuration (in days)
Authenticator.RememberTokenDuration=14
# Session Timeouts (in minutes)
Authenticator.IdleTimeoutDuration=20
Authenticator.AbsoluteTimeoutDuration=120
#===========================================================================
# ESAPI Encoder
#
# ESAPI canonicalizes input before validation to prevent bypassing filters with encoded attacks.
# Failure to canonicalize input is a very common mistake when implementing validation schemes.
# Canonicalization is automatic when using the ESAPI Validator, but you can also use the
# following code to canonicalize data.
#
# ESAPI.Encoder().canonicalize( "%22hello world&#x22;" );
#
# Multiple encoding is when a single encoding format is applied multiple times. Allowing
# multiple encoding is strongly discouraged.
Encoder.AllowMultipleEncoding=false
# Mixed encoding is when multiple different encoding formats are applied, or when
# multiple formats are nested. Allowing multiple encoding is strongly discouraged.
Encoder.AllowMixedEncoding=false
# The default list of codecs to apply when canonicalizing untrusted data. The list should include the codecs
# for all downstream interpreters or decoders. For example, if the data is likely to end up in a URL, HTML, or
# inside JavaScript, then the list of codecs below is appropriate. The order of the list is not terribly important.
Encoder.DefaultCodecList=HTMLEntityCodec,PercentCodec,JavaScriptCodec
#===========================================================================
# ESAPI Encryption
#
# The ESAPI Encryptor provides basic cryptographic functions with a simplified API.
# To get started, generate a new key using java -classpath esapi.jar org.owasp.esapi.reference.crypto.JavaEncryptor
# There is not currently any support for key rotation, so be careful when changing your key and salt as it
# will invalidate all signed, encrypted, and hashed data.
#
# WARNING: Not all combinations of algorithms and key lengths are supported.
# If you choose to use a key length greater than 128, you MUST download the
# unlimited strength policy files and install in the lib directory of your JRE/JDK.
# See http://java.sun.com/javase/downloads/index.jsp for more information.
#
# Backward compatibility with ESAPI Java 1.4 is supported by the two deprecated API
# methods, Encryptor.encrypt(String) and Encryptor.decrypt(String). However, whenever
# possible, these methods should be avoided as they use ECB cipher mode, which in almost
# all circumstances a poor choice because of it's weakness. CBC cipher mode is the default
# for the new Encryptor encrypt / decrypt methods for ESAPI Java 2.0. In general, you
# should only use this compatibility setting if you have persistent data encrypted with
# version 1.4 and even then, you should ONLY set this compatibility mode UNTIL
# you have decrypted all of your old encrypted data and then re-encrypted it with
# ESAPI 2.0 using CBC mode. If you have some reason to mix the deprecated 1.4 mode
# with the new 2.0 methods, make sure that you use the same cipher algorithm for both
# (256-bit AES was the default for 1.4; 128-bit is the default for 2.0; see below for
# more details.) Otherwise, you will have to use the new 2.0 encrypt / decrypt methods
# where you can specify a SecretKey. (Note that if you are using the 256-bit AES,
# that requires downloading the special jurisdiction policy files mentioned above.)
#
# ***** IMPORTANT: Do NOT forget to replace these with your own values! *****
# To calculate these values, you can run:
# java -classpath esapi.jar org.owasp.esapi.reference.crypto.JavaEncryptor
#
Encryptor.MasterKey=tzfztf56ftv
Encryptor.MasterSalt=123456ztrewq
# Provides the default JCE provider that ESAPI will "prefer" for its symmetric
# encryption and hashing. (That is it will look to this provider first, but it
# will defer to other providers if the requested algorithm is not implemented
# by this provider.) If left unset, ESAPI will just use your Java VM's current
# preferred JCE provider, which is generally set in the file
# "$JAVA_HOME/jre/lib/security/java.security".
#
# The main intent of this is to allow ESAPI symmetric encryption to be
# used with a FIPS 140-2 compliant crypto-module. For details, see the section
# "Using ESAPI Symmetric Encryption with FIPS 140-2 Cryptographic Modules" in
# the ESAPI 2.0 Symmetric Encryption User Guide, at:
# http://owasp-esapi-java.googlecode.com/svn/trunk/documentation/esapi4java-core-2.0-symmetric-crypto-user-guide.html
# However, this property also allows you to easily use an alternate JCE provider
# such as "Bouncy Castle" without having to make changes to "java.security".
# See Javadoc for SecurityProviderLoader for further details. If you wish to use
# a provider that is not known to SecurityProviderLoader, you may specify the
# fully-qualified class name of the JCE provider class that implements
# java.security.Provider. If the name contains a '.', this is interpreted as
# a fully-qualified class name that implements java.security.Provider.
#
# NOTE: Setting this property has the side-effect of changing it in your application
# as well, so if you are using JCE in your application directly rather than
# through ESAPI (you wouldn't do that, would you? ;-), it will change the
# preferred JCE provider there as well.
#
# Default: Keeps the JCE provider set to whatever JVM sets it to.
Encryptor.PreferredJCEProvider=
# AES is the most widely used and strongest encryption algorithm. This
# should agree with your Encryptor.CipherTransformation property.
# By default, ESAPI Java 1.4 uses "PBEWithMD5AndDES" and which is
# very weak. It is essentially a password-based encryption key, hashed
# with MD5 around 1K times and then encrypted with the weak DES algorithm
# (56-bits) using ECB mode and an unspecified padding (it is
# JCE provider specific, but most likely "NoPadding"). However, 2.0 uses
# "AES/CBC/PKCSPadding". If you want to change these, change them here.
# Warning: This property does not control the default reference implementation for
# ESAPI 2.0 using JavaEncryptor. Also, this property will be dropped
# in the future.
# @deprecated
Encryptor.EncryptionAlgorithm=AES
# For ESAPI Java 2.0 - New encrypt / decrypt methods use this.
Encryptor.CipherTransformation=AES/CBC/PKCS5Padding
# Applies to ESAPI 2.0 and later only!
# Comma-separated list of cipher modes that provide *BOTH*
# confidentiality *AND* message authenticity. (NIST refers to such cipher
# modes as "combined modes" so that's what we shall call them.) If any of these
# cipher modes are used then no MAC is calculated and stored
# in the CipherText upon encryption. Likewise, if one of these
# cipher modes is used with decryption, no attempt will be made
# to validate the MAC contained in the CipherText object regardless
# of whether it contains one or not. Since the expectation is that
# these cipher modes support support message authenticity already,
# injecting a MAC in the CipherText object would be at best redundant.
#
# Note that as of JDK 1.5, the SunJCE provider does not support *any*
# of these cipher modes. Of these listed, only GCM and CCM are currently
# NIST approved. YMMV for other JCE providers. E.g., Bouncy Castle supports
# GCM and CCM with "NoPadding" mode, but not with "PKCS5Padding" or other
# padding modes.
Encryptor.cipher_modes.combined_modes=GCM,CCM,IAPM,EAX,OCB,CWC
# Applies to ESAPI 2.0 and later only!
# Additional cipher modes allowed for ESAPI 2.0 encryption. These
# cipher modes are in _addition_ to those specified by the property
# 'Encryptor.cipher_modes.combined_modes'.
# Note: We will add support for streaming modes like CFB & OFB once
# we add support for 'specified' to the property 'Encryptor.ChooseIVMethod'
# (probably in ESAPI 2.1).
# DISCUSS: Better name?
Encryptor.cipher_modes.additional_allowed=CBC
# 128-bit is almost always sufficient and appears to be more resistant to
# related key attacks than is 256-bit AES. Use '_' to use default key size
# for cipher algorithms (where it makes sense because the algorithm supports
# a variable key size). Key length must agree to what's provided as the
# cipher transformation, otherwise this will be ignored after logging a
# warning.
#
# NOTE: This is what applies BOTH ESAPI 1.4 and 2.0. See warning above about mixing!
Encryptor.EncryptionKeyLength=128
# Because 2.0 uses CBC mode by default, it requires an initialization vector (IV).
# (All cipher modes except ECB require an IV.) There are two choices: we can either
# use a fixed IV known to both parties or allow ESAPI to choose a random IV. While
# the IV does not need to be hidden from adversaries, it is important that the
# adversary not be allowed to choose it. Also, random IVs are generally much more
# secure than fixed IVs. (In fact, it is essential that feed-back cipher modes
# such as CFB and OFB use a different IV for each encryption with a given key so
# in such cases, random IVs are much preferred. By default, ESAPI 2.0 uses random
# IVs. If you wish to use 'fixed' IVs, set 'Encryptor.ChooseIVMethod=fixed' and
# uncomment the Encryptor.fixedIV.
#
# Valid values: random|fixed|specified 'specified' not yet implemented; planned for 2.1
Encryptor.ChooseIVMethod=random
# If you choose to use a fixed IV, then you must place a fixed IV here that
# is known to all others who are sharing your secret key. The format should
# be a hex string that is the same length as the cipher block size for the
# cipher algorithm that you are using. The following is an *example* for AES
# from an AES test vector for AES-128/CBC as described in:
# NIST Special Publication 800-38A (2001 Edition)
# "Recommendation for Block Cipher Modes of Operation".
# (Note that the block size for AES is 16 bytes == 128 bits.)
#
Encryptor.fixedIV=0x000102030405060708090a0b0c0d0e0f
# Whether or not CipherText should use a message authentication code (MAC) with it.
# This prevents an adversary from altering the IV as well as allowing a more
# fool-proof way of determining the decryption failed because of an incorrect
# key being supplied. This refers to the "separate" MAC calculated and stored
# in CipherText, not part of any MAC that is calculated as a result of a
# "combined mode" cipher mode.
#
# If you are using ESAPI with a FIPS 140-2 cryptographic module, you *must* also
# set this property to false.
Encryptor.CipherText.useMAC=true
# Whether or not the PlainText object may be overwritten and then marked
# eligible for garbage collection. If not set, this is still treated as 'true'.
Encryptor.PlainText.overwrite=true
# Do not use DES except in a legacy situations. 56-bit is way too small key size.
#Encryptor.EncryptionKeyLength=56
#Encryptor.EncryptionAlgorithm=DES
# TripleDES is considered strong enough for most purposes.
# Note: There is also a 112-bit version of DESede. Using the 168-bit version
# requires downloading the special jurisdiction policy from Sun.
#Encryptor.EncryptionKeyLength=168
#Encryptor.EncryptionAlgorithm=DESede
Encryptor.HashAlgorithm=SHA-512
Encryptor.HashIterations=1024
Encryptor.DigitalSignatureAlgorithm=SHA1withDSA
Encryptor.DigitalSignatureKeyLength=1024
Encryptor.RandomAlgorithm=SHA1PRNG
Encryptor.CharacterEncoding=UTF-8
# This is the Pseudo Random Function (PRF) that ESAPI's Key Derivation Function
# (KDF) normally uses. Note this is *only* the PRF used for ESAPI's KDF and
# *not* what is used for ESAPI's MAC. (Currently, HmacSHA1 is always used for
# the MAC, mostly to keep the overall size at a minimum.)
#
# Currently supported choices for JDK 1.5 and 1.6 are:
# HmacSHA1 (160 bits), HmacSHA256 (256 bits), HmacSHA384 (384 bits), and
# HmacSHA512 (512 bits).
# Note that HmacMD5 is *not* supported for the PRF used by the KDF even though
# the JDKs support it. See the ESAPI 2.0 Symmetric Encryption User Guide
# further details.
Encryptor.KDF.PRF=HmacSHA256
#===========================================================================
# ESAPI HttpUtilties
#
# The HttpUtilities provide basic protections to HTTP requests and responses. Primarily these methods
# protect against malicious data from attackers, such as unprintable characters, escaped characters,
# and other simple attacks. The HttpUtilities also provides utility methods for dealing with cookies,
# headers, and CSRF tokens.
#
# Default file upload location (remember to escape backslashes with \\)
HttpUtilities.UploadDir=C:\\ESAPI\\testUpload
HttpUtilities.UploadTempDir=C:\\temp
# Force flags on cookies, if you use HttpUtilities to set cookies
HttpUtilities.ForceHttpOnlySession=false
HttpUtilities.ForceSecureSession=false
HttpUtilities.ForceHttpOnlyCookies=true
HttpUtilities.ForceSecureCookies=true
# Maximum size of HTTP headers
HttpUtilities.MaxHeaderSize=4096
# File upload configuration
HttpUtilities.ApprovedUploadExtensions=.zip,.pdf,.doc,.docx,.ppt,.pptx,.tar,.gz,.tgz,.rar,.war,.jar,.ear,.xls,.rtf,.properties,.java,.class,.txt,.xml,.jsp,.jsf,.exe,.dll
HttpUtilities.MaxUploadFileBytes=500000000
# Using UTF-8 throughout your stack is highly recommended. That includes your database driver,
# container, and any other technologies you may be using. Failure to do this may expose you
# to Unicode transcoding injection attacks. Use of UTF-8 does not hinder internationalization.
HttpUtilities.ResponseContentType=text/html; charset=UTF-8
# This is the name of the cookie used to represent the HTTP session
# Typically this will be the default "JSESSIONID"
HttpUtilities.HttpSessionIdName=JSESSIONID
#===========================================================================
# ESAPI Executor
# CHECKME - Not sure what this is used for, but surely it should be made OS independent.
Executor.WorkingDirectory=C:\\Windows\\Temp
Executor.ApprovedExecutables=C:\\Windows\\System32\\cmd.exe,C:\\Windows\\System32\\runas.exe
#===========================================================================
# ESAPI Logging
# Set the application name if these logs are combined with other applications
Logger.ApplicationName=ExampleApplication
# If you use an HTML log viewer that does not properly HTML escape log data, you can set LogEncodingRequired to true
Logger.LogEncodingRequired=false
# Determines whether ESAPI should log the application name. This might be clutter in some single-server/single-app environments.
Logger.LogApplicationName=true
# Determines whether ESAPI should log the server IP and port. This might be clutter in some single-server environments.
Logger.LogServerIP=true
# LogFileName, the name of the logging file. Provide a full directory path (e.g., C:\\ESAPI\\ESAPI_logging_file) if you
# want to place it in a specific directory.
Logger.LogFileName=ESAPI_logging_file
# MaxLogFileSize, the max size (in bytes) of a single log file before it cuts over to a new one (default is 10,000,000)
Logger.MaxLogFileSize=10000000
#===========================================================================
# ESAPI Intrusion Detection
#
# Each event has a base to which .count, .interval, and .action are added
# The IntrusionException will fire if we receive "count" events within "interval" seconds
# The IntrusionDetector is configurable to take the following actions: log, logout, and disable
# (multiple actions separated by commas are allowed e.g. event.test.actions=log,disable
#
# Custom Events
# Names must start with "event." as the base
# Use IntrusionDetector.addEvent( "test" ) in your code to trigger "event.test" here
# You can also disable intrusion detection completely by changing
# the following parameter to true
#
IntrusionDetector.Disable=false
#
IntrusionDetector.event.test.count=2
IntrusionDetector.event.test.interval=10
IntrusionDetector.event.test.actions=disable,log
# Exception Events
# All EnterpriseSecurityExceptions are registered automatically
# Call IntrusionDetector.getInstance().addException(e) for Exceptions that do not extend EnterpriseSecurityException
# Use the fully qualified classname of the exception as the base
# any intrusion is an attack
IntrusionDetector.org.owasp.esapi.errors.IntrusionException.count=1
IntrusionDetector.org.owasp.esapi.errors.IntrusionException.interval=1
IntrusionDetector.org.owasp.esapi.errors.IntrusionException.actions=log,disable,logout
# for test purposes
# CHECKME: Shouldn't there be something in the property name itself that designates
# that these are for testing???
IntrusionDetector.org.owasp.esapi.errors.IntegrityException.count=10
IntrusionDetector.org.owasp.esapi.errors.IntegrityException.interval=5
IntrusionDetector.org.owasp.esapi.errors.IntegrityException.actions=log,disable,logout
# rapid validation errors indicate scans or attacks in progress
# org.owasp.esapi.errors.ValidationException.count=10
# org.owasp.esapi.errors.ValidationException.interval=10
# org.owasp.esapi.errors.ValidationException.actions=log,logout
# sessions jumping between hosts indicates session hijacking
IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.count=2
IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.interval=10
IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.actions=log,logout
#===========================================================================
# ESAPI Validation
#
# The ESAPI Validator works on regular expressions with defined names. You can define names
# either here, or you may define application specific patterns in a separate file defined below.
# This allows enterprises to specify both organizational standards as well as application specific
# validation rules.
#
Validator.ConfigurationFile=validation.properties
# Validators used by ESAPI
Validator.AccountName=^[a-zA-Z0-9]{3,20}$
Validator.SystemCommand=^[a-zA-Z\\-\\/]{1,64}$
Validator.RoleName=^[a-z]{1,20}$
#the word TEST below should be changed to your application
#name - only relative URL's are supported
Validator.Redirect=^\\/test.*$
# Global HTTP Validation Rules
# Values with Base64 encoded data (e.g. encrypted state) will need at least [a-zA-Z0-9\/+=]
Validator.HTTPScheme=^(http|https)$
Validator.HTTPServerName=^[a-zA-Z0-9_.\\-]*$
Validator.HTTPParameterName=^[a-zA-Z0-9_]{1,32}$
Validator.HTTPParameterValue=^[a-zA-Z0-9.\\-\\/+=@_ ]*$
Validator.HTTPCookieName=^[a-zA-Z0-9\\-_]{1,32}$
Validator.HTTPCookieValue=^[a-zA-Z0-9\\-\\/+=_ ]*$
Validator.HTTPHeaderName=^[a-zA-Z0-9\\-_]{1,32}$
Validator.HTTPHeaderValue=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ ]*$
Validator.HTTPContextPath=^\\/?[a-zA-Z0-9.\\-\\/_]*$
Validator.HTTPServletPath=^[a-zA-Z0-9.\\-\\/_]*$
Validator.HTTPPath=^[a-zA-Z0-9.\\-_]*$
Validator.HTTPQueryString=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ %]*$
Validator.HTTPURI=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ ]*$
Validator.HTTPURL=^.*$
Validator.HTTPJSESSIONID=^[A-Z0-9]{10,30}$
# Validation of file related input
Validator.FileName=^[a-zA-Z0-9!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$
Validator.DirectoryName=^[a-zA-Z0-9:/\\\\!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$
# Validation of dates. Controls whether or not 'lenient' dates are accepted.
# See DataFormat.setLenient(boolean flag) for further details.
Validator.AcceptLenientDates=false

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1">
<!-- JDO tutorial "unit" -->
<persistence-unit name="Tutorial">
<exclude-unlisted-classes/>
<properties>
<property name="javax.jdo.PersistenceManagerFactoryClass" value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory"/>
<property name="javax.jdo.option.ConnectionURL" value="jdbc:h2:mem:mypersistence"/>
<property name="javax.jdo.option.ConnectionDriverName" value="org.h2.Driver"/>
<property name="javax.jdo.option.ConnectionUserName" value="sa"/>
<property name="javax.jdo.option.ConnectionPassword" value=""/>
<property name="datanucleus.schema.autoCreateAll" value="true"/>
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1 @@
com.ossez.javac.SampleJavacPlugin

View File

@ -0,0 +1,3 @@
UK
US
Germany

View File

@ -0,0 +1,3 @@
1|IND|India
2|MY|Malaysia
3|AU|Australia
1 1 IND India
2 2 MY Malaysia
3 3 AU Australia

View File

@ -0,0 +1,6 @@
dataSourceClassName=//TBD
dataSource.user=//TBD
dataSource.password=//TBD
dataSource.databaseName=//TBD
dataSource.portNumber=//TBD
dataSource.serverName=//TBD

View File

@ -0,0 +1,45 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit. In lacus enim, scelerisque id sapien ut, semper euismod quam. Nunc ullamcorper semper blandit. Praesent quis quam mollis, iaculis lectus a, fringilla leo. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis vitae auctor mauris. Pellentesque eu pellentesque lorem, vel ultricies libero. Pellentesque vestibulum sagittis eros. In vestibulum lacus elit. Interdum et malesuada fames ac ante ipsum primis in faucibus.
Vivamus pharetra lacus fringilla nisl molestie eleifend. Donec et dolor non quam mattis mattis. Proin malesuada maximus elit id semper. Donec facilisis dolor ut feugiat auctor. Proin accumsan semper consectetur. Vivamus facilisis odio vel bibendum imperdiet. Sed rutrum nisi nec nisi interdum fringilla. Aliquam laoreet velit ullamcorper egestas ultrices. Aliquam ultricies sem sed orci interdum, eu porta purus malesuada. Sed accumsan, nunc ut maximus rhoncus, arcu ante pretium ex, non ultrices magna nisi et velit. Pellentesque tempor mi quis lacus consectetur, quis imperdiet enim efficitur. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
Nunc sed maximus erat. Aenean imperdiet finibus massa ac aliquam. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis dignissim cursus purus, eu tempus urna. Nunc sed mauris scelerisque, luctus eros ut, viverra nisi. Maecenas congue sed ligula in eleifend. Praesent nec dignissim enim, dictum efficitur massa. Nullam eros dui, rutrum quis aliquam accumsan, sollicitudin cursus eros. Phasellus euismod, lorem vitae vehicula ullamcorper, leo lorem vestibulum magna, vitae malesuada libero ipsum id lorem. Aenean finibus turpis facilisis tortor bibendum, vitae dignissim dolor dictum. Ut quis ornare nisi, non rutrum sapien.
Etiam placerat, est eget placerat imperdiet, neque urna tristique est, a dictum nisl dolor vitae leo. Vivamus porttitor mi vitae volutpat ultrices. Quisque at ante porta mauris ultricies iaculis. Phasellus iaculis sollicitudin urna nec facilisis. Suspendisse dapibus vulputate scelerisque. Fusce felis diam, eleifend in tristique in, malesuada a purus. Suspendisse euismod ipsum sed urna imperdiet, quis venenatis lacus dapibus. Maecenas vitae est vel sem fringilla ornare at ut mi. Quisque porta, nulla at rutrum fringilla, mi ligula egestas libero, ac convallis elit diam et sapien. Vestibulum purus tortor, ornare ut enim sed, mattis lobortis erat. Maecenas ac ante tincidunt, euismod mauris a, fermentum diam. Nullam arcu est, consequat sed enim in, bibendum aliquet velit. Donec bibendum magna ac augue sagittis vehicula. Curabitur nec mauris eu augue bibendum volutpat. Fusce fringilla varius fringilla.
Aliquam faucibus massa non orci accumsan, porta consectetur diam vulputate. Nullam nec erat mollis, imperdiet libero nec, tincidunt neque. Aenean varius purus nec est auctor, sed vulputate libero varius. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vel neque elit. Donec vulputate fermentum nulla, ut aliquam neque tempor in. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec vel venenatis est. Suspendisse luctus elit quis dui dapibus, id sodales dolor cursus. Curabitur ut vehicula dui. Fusce aliquet est et ante feugiat, et tempus ex congue. Nunc eget dapibus leo. Nunc eu accumsan diam. Suspendisse risus eros, rutrum et volutpat in, consequat in nulla. Suspendisse id felis a orci accumsan iaculis.
Duis tincidunt diam eget tortor aliquet sodales. Etiam sodales purus ac urna mollis, et cursus enim porttitor. Nulla viverra ligula nunc, ornare condimentum felis posuere sed. Fusce aliquet pretium sagittis. Sed ac mi elementum massa dictum ornare. Integer quis dapibus lectus. Curabitur in rhoncus justo, et vulputate justo. Integer eget efficitur felis.
Sed finibus vel tortor ac egestas. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas vestibulum nulla mi, blandit efficitur sapien fermentum eu. Integer sed turpis eros. Phasellus sed aliquam ligula. Etiam dictum quam in dapibus mattis. Donec et tristique quam. Pellentesque gravida luctus dolor, eu ornare sapien. Donec justo ante, lacinia non sem et, ultricies dignissim nibh. Vivamus eu nisl et magna pulvinar efficitur. Sed at vehicula lectus, sit amet luctus sem. Morbi vehicula sapien nisi, nec sagittis orci vestibulum et.
Praesent non finibus diam. Quisque sit amet nisl vitae augue lobortis commodo. Morbi ullamcorper, tortor id ornare maximus, erat ipsum ullamcorper ipsum, in imperdiet diam sem vel erat. Sed pellentesque quis ex sed volutpat. Vestibulum volutpat diam ac dignissim sollicitudin. Praesent at luctus ex, at volutpat dui. Nunc nulla dui, lobortis et pharetra quis, efficitur in turpis. Donec sodales auctor purus id mollis. Sed auctor eu erat eget bibendum. Mauris tincidunt ornare neque id consequat. Suspendisse non massa ante. Quisque velit enim, rhoncus at erat eget, scelerisque placerat elit. Donec finibus luctus dolor. In sed eleifend lorem. Sed tempor ullamcorper lorem nec tristique. Fusce nec volutpat neque, id elementum est.
Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum mattis elementum tellus, vitae maximus nulla eleifend ut. Vestibulum eu nibh vulputate, posuere felis eget, aliquet ex. Nullam leo ex, lacinia a ante ac, accumsan efficitur ligula. Vestibulum ornare gravida tempus. Proin rhoncus felis sit amet dolor commodo facilisis. Integer aliquet, diam sed pharetra feugiat, sem massa mollis orci, eget pretium libero nunc at quam. Ut rhoncus quam vitae massa hendrerit, ornare condimentum odio varius. Donec odio sapien, tristique eget libero ac, interdum facilisis odio. Phasellus nec mauris vel dolor semper mattis et quis ligula. Donec nec porttitor nunc. Integer maximus quam vitae sem gravida, ut commodo ex porttitor.
Sed cursus nisi turpis, vel laoreet massa blandit ut. Cras posuere velit nulla, nec pellentesque ipsum dignissim eget. Donec pharetra, ex et commodo viverra, leo dolor dapibus tellus, vel dignissim est sem ac lectus. Quisque a arcu dapibus, aliquet magna sed, rhoncus neque. Integer suscipit, nulla ac varius lacinia, orci metus scelerisque neque, a laoreet nibh risus vitae dolor. Pellentesque felis metus, pulvinar vel cursus id, ultrices non purus. Donec mi lectus, faucibus sit amet nunc at, sagittis pretium lectus. Fusce nec purus arcu. Mauris neque neque, blandit eget mi at, auctor tempus orci. Mauris sapien lorem, luctus nec tellus non, porttitor aliquam dui.
Mauris non ex risus. Aliquam imperdiet in eros eget placerat. Sed congue sed sapien porta sollicitudin. Phasellus tempor hendrerit metus vitae tincidunt. Suspendisse congue nisi sed augue dapibus, at pretium ante mollis. Cras non posuere nulla. Proin malesuada finibus magna vel iaculis. Cras in dapibus lorem. Pellentesque volutpat dolor sit amet magna tincidunt mollis. Nunc et lectus sodales, accumsan est vitae, ornare augue. Maecenas malesuada arcu leo, eget blandit lectus porttitor et. Nam aliquam sapien sit amet purus consequat lobortis. Aenean varius, augue porta dignissim efficitur, felis velit dapibus leo, tincidunt ultricies magna felis id ligula. Duis hendrerit, lectus eu elementum euismod, elit lectus consequat mi, sit amet egestas justo massa ut urna. Proin eleifend interdum ultrices.
Donec lacinia orci pharetra ornare tincidunt. Nulla facilisi. Maecenas malesuada dui ac elit sagittis tincidunt id dictum dolor. Quisque lobortis purus ac metus volutpat viverra. Proin finibus sapien ut odio semper consectetur. Sed gravida luctus egestas. Mauris pretium volutpat elit, at commodo arcu sagittis nec. Ut condimentum fringilla urna ac dignissim. Cras aliquam metus pulvinar, pulvinar nibh at, placerat arcu. Nulla ornare tortor sed lectus mollis, vitae fringilla tellus egestas. Vivamus efficitur tincidunt sapien, sed finibus mi congue eu. Nullam magna velit, lacinia vitae ligula eget, molestie consectetur felis. Suspendisse varius turpis orci, ac laoreet arcu accumsan sed. Fusce quis fermentum lacus, nec varius libero. Pellentesque ac odio ut justo lobortis elementum sit amet vehicula lorem. Nulla interdum nulla eget mi tristique, vitae egestas nunc egestas.
Curabitur commodo libero eu elit tincidunt, quis placerat risus vehicula. Vestibulum vehicula id nunc iaculis fermentum. Aenean semper, tellus ac semper rutrum, justo lorem feugiat leo, quis vulputate neque dui non ligula. Etiam egestas, enim eget tempor porta, nunc est tristique ante, vel suscipit massa lorem vel diam. Donec faucibus ante id turpis rhoncus congue. Nullam laoreet, diam efficitur scelerisque consequat, ligula leo ultrices est, non fermentum elit mauris ut dolor. Morbi non porttitor lorem. Sed volutpat sapien et lorem porttitor, ultricies ultricies tellus congue. Mauris sodales, tortor nec sagittis finibus, dui odio aliquet nibh, in luctus sapien massa eu risus. Nulla in est sed ante molestie vehicula vel nec lectus. Fusce maximus a quam eget aliquam. Vivamus pulvinar quis nisi a maximus. Proin cursus lacus sapien, et hendrerit elit pretium a. Donec tellus lectus, consectetur id dolor a, luctus rutrum libero. Suspendisse auctor scelerisque dui, nec pellentesque felis viverra nec. Cras elit ex, varius sed pulvinar sed, suscipit ultrices lacus.
Vivamus eu luctus lectus. Maecenas congue magna orci, quis semper nulla blandit vel. Phasellus dignissim risus placerat lacinia sagittis. Praesent at gravida nisi, at pulvinar diam. Nulla egestas lectus sed felis facilisis egestas. Curabitur posuere gravida urna eu vestibulum. Pellentesque at dolor gravida, placerat quam sit amet, fermentum ligula. Morbi fringilla, mi eget mollis dictum, neque dolor ullamcorper leo, a rutrum libero ipsum eget orci. Curabitur consectetur iaculis vestibulum. Suspendisse ultricies ligula et neque lacinia luctus. Sed dignissim neque id eros sollicitudin pellentesque.
Donec et magna quis lectus pharetra finibus a fringilla sapien. Phasellus accumsan, erat eu sodales cursus, tortor elit dapibus risus, ut ornare neque arcu in tellus. Nam ac vehicula diam, at aliquam nisl. Cras in sem eget nisi ultrices rutrum sit amet eu velit. Sed molestie tellus eget ante scelerisque, sit amet pulvinar neque fringilla. Nunc volutpat facilisis egestas. Cras sodales dui ac massa egestas, in mattis leo rhoncus. Pellentesque vitae urna vehicula ipsum sodales suscipit. Sed commodo tempus fringilla.
Etiam egestas elit vitae mi maximus fringilla quis eget libero. Fusce finibus ultrices tellus at molestie. Pellentesque posuere blandit elementum. Etiam eu erat eu urna hendrerit euismod. Nulla quis lectus rhoncus, ultricies urna eget, pretium neque. Cras sit amet ipsum sit amet purus rutrum ultricies nec vitae tortor. Sed tempor dapibus augue in pulvinar. Ut pretium sapien in malesuada accumsan. Donec eget ultrices erat, ut efficitur ligula. Sed posuere mauris est, nec convallis ipsum tempus non.
Duis a ullamcorper ante. Quisque eu ultricies metus, at aliquet odio. Nullam tempus molestie augue ut varius. Fusce purus eros, dictum nec finibus sed, sodales et diam. Suspendisse sed mi purus. Donec eleifend ipsum diam, nec fringilla enim laoreet non. Phasellus condimentum, magna sit amet porttitor suscipit, arcu risus lobortis dolor, ac fringilla nibh nisl vel purus. Phasellus facilisis posuere orci sit amet tempus. Nam nec enim maximus, rhoncus felis a, rutrum diam.
Suspendisse potenti. Donec vel tempor neque. In aliquet nulla in eleifend bibendum. Sed sapien sem, finibus in sodales vitae, euismod in sem. Phasellus nec elit a erat pulvinar semper. Aliquam luctus nisl in libero molestie aliquam. Nunc ac ornare felis. Ut non mauris ut ipsum rhoncus pretium. Curabitur tristique lacus a sagittis aliquam. Morbi vel volutpat tellus. Maecenas volutpat, lacus sed tempus imperdiet, eros tellus volutpat nisi, a egestas augue nulla quis arcu. In sollicitudin imperdiet efficitur. Suspendisse viverra aliquet nisi, congue ultrices arcu hendrerit in.
Maecenas vitae vestibulum nunc. Nullam semper faucibus tincidunt. Etiam sed hendrerit risus. Proin gravida, urna nec tincidunt tempus, nulla sapien porttitor nibh, porttitor lobortis nunc quam et tortor. Praesent ut varius lacus, ut hendrerit enim. Ut nec turpis ac felis imperdiet bibendum. Phasellus porttitor enim odio, et vehicula mi convallis vel. Quisque porta scelerisque sagittis. Praesent dignissim sagittis vulputate. Aenean non justo ac est volutpat bibendum. Aliquam mattis, sapien dapibus pellentesque semper, velit urna malesuada diam, nec varius nibh eros at erat. Proin leo ante, ultricies id velit ut, faucibus porta nibh. Sed nec fermentum urna, sed mollis leo. Aliquam erat volutpat.
Donec condimentum, urna sed hendrerit vestibulum, ante nibh lacinia dui, in tincidunt odio sem eget orci. In hac habitasse platea dictumst. Mauris id ex id ante tempus finibus eu sagittis erat. Quisque interdum urna risus, vel varius nibh euismod non. Nulla eget pellentesque quam. Aliquam vestibulum ac tortor non lobortis. Sed vitae erat sed libero dignissim dictum nec in turpis. Vivamus id ornare elit, ut facilisis lectus. Morbi dictum purus eget ipsum dignissim porttitor. Sed at vehicula purus, nec rhoncus quam. Nunc a nisl quis arcu blandit fermentum vel quis odio. Vivamus rhoncus, sapien sed lacinia hendrerit, velit urna fermentum dolor, id feugiat magna ligula sed urna. Proin euismod efficitur libero, eget porttitor lacus tempus quis. Duis tincidunt quis est a laoreet. Nam sit amet tristique nisl, sit amet mattis mi.
Aenean id dictum nulla, sed laoreet magna. Morbi consectetur in turpis at aliquam. Maecenas rutrum feugiat metus, at ullamcorper augue fermentum ut. Vivamus in magna pretium nibh dictum rhoncus luctus at orci. In hac habitasse platea dictumst. Fusce convallis, nulla nec hendrerit suscipit, ipsum diam lobortis sem, vitae elementum lectus erat sit amet magna. Quisque sollicitudin fringilla purus, ac molestie justo congue vitae. Nulla sapien leo, ullamcorper ac tellus in, cursus rhoncus enim. Suspendisse rutrum magna non ex elementum elementum id vitae enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse ornare libero eu molestie pulvinar. Phasellus faucibus, magna eget rutrum porta, lorem turpis blandit lectus, eu viverra massa risus et ex.
Ut consectetur eros lacus, ac ullamcorper lacus mattis a. Cras congue justo ut erat interdum, et scelerisque nisi malesuada. Quisque sed sapien sollicitudin purus tincidunt finibus vestibulum vel dolor. Cras iaculis bibendum erat, a dictum urna viverra et. Integer non neque vulputate, tincidunt purus nec, rutrum arcu. Aliquam nec magna non sem semper laoreet quis at quam. Mauris dui lectus, convallis eu efficitur at, facilisis nec lorem. Cras felis sem, egestas ac rutrum vel, mollis et ex. Aenean semper egestas libero, nec commodo mi blandit efficitur. Duis nec quam in massa dignissim sagittis vel vitae leo. Nam molestie hendrerit auctor.
Sed suscipit egestas tellus sed cursus. Donec vel massa sit amet dui condimentum accumsan. Phasellus libero eros, lobortis a nisi id, porttitor maximus lectus. Praesent consectetur diam urna, id viverra turpis elementum in. Vivamus vitae pretium justo, nec tempor felis. Vivamus volutpat ultricies magna. Suspendisse vulputate lectus ac orci volutpat ullamcorper. Nulla eu leo pretium, commodo arcu accumsan, tempor nisl. Fusce sit amet tellus a ipsum vehicula laoreet sed vitae mauris. Duis porttitor massa mattis nibh placerat consequat. Fusce rutrum commodo tortor eget pellentesque. Suspendisse tempor enim libero, consequat dictum nibh dictum varius. Pellentesque feugiat sit amet urna sed facilisis. Curabitur a sagittis augue.

View File

@ -0,0 +1,15 @@
var first = {
name: "Whiskey",
age: 5
};
var second = {
volume: 100
};
Object.bindProperties(first, second);
print(first.volume);
second.volume = 1000;
print(first.volume);

View File

@ -0,0 +1 @@
print(__FILE__, __LINE__, __DIR__);

View File

@ -0,0 +1,19 @@
var math = {
increment: function (num) {
return ++num;
},
failFunc: function () {
try {
throw "BOOM";
} catch (e if typeof e === 'string') {
print("String thrown: " + e);
}
catch (e) {
print("this shouldn't happen!");
}
}
};
math;

View File

@ -0,0 +1,11 @@
var demo = {
__noSuchProperty__: function (propName) {
print("Accessed non-existing property: " + propName);
},
__noSuchMethod__: function (methodName) {
print("Invoked non-existing method: " + methodName);
}
};
demo;

View File

@ -0,0 +1 @@
function increment(num) ++num;

View File

@ -0,0 +1,2 @@
print(" hello world".trimLeft());
print("hello world ".trimRight());

View File

@ -0,0 +1,9 @@
function arrays(arr) {
var javaIntArray = Java.to(arr, "int[]");
print(javaIntArray[0]);
print(javaIntArray[1]);
print(javaIntArray[2]);
}
arrays([100, "1654", true]);

View File

@ -0,0 +1,6 @@
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

View File

@ -0,0 +1,9 @@
# Root logger
log4j.rootLogger=INFO, file, stdout
# Write to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<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>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1 @@
Test1

View File

@ -0,0 +1 @@
Test2

View File

@ -0,0 +1,75 @@
package com.ossez.bufferedreader;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
public class BufferedReaderExampleUnitTest {
private static final String FILE_PATH = "src/main/resources/input.txt";
@Test
public void givenBufferedReader_whenReadAllLines_thenReturnsContent() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
BufferedReaderExample bre = new BufferedReaderExample();
String content = bre.readAllLines(reader);
assertThat(content).isNotEmpty();
assertThat(content).contains("Lorem ipsum");
}
@Test
public void givenBufferedReader_whenReadAllLinesWithStream_thenReturnsContent() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
BufferedReaderExample bre = new BufferedReaderExample();
String content = bre.readAllLinesWithStream(reader);
assertThat(content).isNotEmpty();
assertThat(content).contains("Lorem ipsum");
}
@Test
public void whenReadFile_thenReturnsContent() {
BufferedReaderExample bre = new BufferedReaderExample();
String content = bre.readFile();
assertThat(content.toString()).contains("Lorem ipsum");
}
@Test
public void givenBufferedReader_whenReadAllCharsOneByOne_thenReturnsContent() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
BufferedReaderExample bre = new BufferedReaderExample();
String content = bre.readAllCharsOneByOne(reader);
assertThat(content).isNotEmpty();
assertThat(content).contains("Lorem ipsum");
}
@Test
public void givenBufferedReader_whenReadMultipleChars_thenReturnsContent() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
BufferedReaderExample bre = new BufferedReaderExample();
String content = bre.readMultipleChars(reader);
assertThat(content).isNotEmpty();
assertThat(content).isEqualTo("Lorem");
}
@Test
public void whenReadFileTryWithResources_thenReturnsContent() {
BufferedReaderExample bre = new BufferedReaderExample();
String content = bre.readFileTryWithResources();
assertThat(content.toString()).contains("Lorem ipsum");
}
}

View File

@ -0,0 +1,58 @@
package com.ossez.bufferedreader;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class BufferedReaderUnitTest {
private static final String FILE_PATH = "src/main/resources/input.txt";
@Test
public void givenBufferedReader_whenSkipUnderscores_thenOk() throws IOException {
StringBuilder result = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new StringReader("1__2__3__4__5"))) {
int value;
while((value = reader.read()) != -1) {
result.append((char) value);
reader.skip(2L);
}
}
assertEquals("12345", result.toString());
}
@Test
public void givenBufferedReader_whenSkipsWhitespacesAtBeginning_thenOk() throws IOException {
String result;
try (BufferedReader reader = new BufferedReader(new StringReader(" Lorem ipsum dolor sit amet."))) {
do {
reader.mark(1);
} while(Character.isWhitespace(reader.read()));
reader.reset();
result = reader.readLine();
}
assertEquals("Lorem ipsum dolor sit amet.", result);
}
@Test
public void whenCreatesNewBufferedReader_thenOk() throws IOException {
try(BufferedReader reader = Files.newBufferedReader(Paths.get(FILE_PATH))) {
assertNotNull(reader);
assertTrue(reader.ready());
}
}
}

View File

@ -0,0 +1,69 @@
package com.ossez.copyfiles;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class FileCopierIntegrationTest {
File original = new File("src/test/resources/original.txt");
@Before
public void init() throws IOException {
if (!original.exists())
Files.createFile(original.toPath());
}
@Test
public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithIo.txt");
try (InputStream in = new BufferedInputStream(new FileInputStream(original)); OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) {
byte[] buffer = new byte[1024];
int lengthRead;
while ((lengthRead = in.read(buffer)) > 0) {
out.write(buffer, 0, lengthRead);
out.flush();
}
}
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
}
@Test
public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
FileUtils.copyFile(original, copied);
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
}
@Test
public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException {
Path copied = Paths.get("src/test/resources/copiedWithNio.txt");
Path originalPath = original.toPath();
Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING);
assertThat(copied).exists();
assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied)));
}
@Test
public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
com.google.common.io.Files.copy(original, copied);
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
}
}

View File

@ -0,0 +1,58 @@
package com.ossez.core.exceptions;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class FileNotFoundExceptionUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(FileNotFoundExceptionUnitTest.class);
private String fileName = Double.toString(Math.random());
@Test(expected = BusinessException.class)
public void raiseBusinessSpecificException() throws IOException {
try {
readFailingFile();
} catch (FileNotFoundException ex) {
throw new BusinessException("BusinessException: necessary file was not present.");
}
}
@Test
public void createFile() throws IOException {
try {
readFailingFile();
} catch (FileNotFoundException ex) {
try {
new File(fileName).createNewFile();
readFailingFile();
} catch (IOException ioe) {
throw new RuntimeException("BusinessException: even creation is not possible.");
}
}
}
@Test
public void logError() throws IOException {
try {
readFailingFile();
} catch (FileNotFoundException ex) {
LOG.error("Optional file " + fileName + " was not found.");
}
}
private void readFailingFile() throws IOException {
BufferedReader rd = new BufferedReader(new FileReader(new File(fileName)));
rd.readLine();
// no need to close file
}
private class BusinessException extends RuntimeException {
BusinessException(String string) {
super(string);
}
}
}

View File

@ -0,0 +1,106 @@
package com.ossez.csv;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import org.junit.Assert;
import org.junit.Test;
import com.opencsv.CSVReader;
public class ReadCSVInArrayUnitTest {
public static final String COMMA_DELIMITER = ",";
public static final String CSV_FILE = "src/test/resources/book.csv";
public static final List<List<String>> EXPECTED_ARRAY = Collections.unmodifiableList(new ArrayList<List<String>>() {
{
add(new ArrayList<String>() {
{
add("Mary Kom");
add("Unbreakable");
}
});
add(new ArrayList<String>() {
{
add("Kapil Isapuari");
add("Farishta");
}
});
}
});
@Test
public void givenCSVFile_whenBufferedReader_thenContentsAsExpected() throws IOException {
List<List<String>> records = new ArrayList<List<String>>();
try (BufferedReader br = new BufferedReader(new FileReader(CSV_FILE))) {
String line = "";
while ((line = br.readLine()) != null) {
String[] values = line.split(COMMA_DELIMITER);
records.add(Arrays.asList(values));
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < EXPECTED_ARRAY.size(); i++) {
Assert.assertArrayEquals(EXPECTED_ARRAY.get(i)
.toArray(),
records.get(i)
.toArray());
}
}
@Test
public void givenCSVFile_whenScanner_thenContentsAsExpected() throws IOException {
List<List<String>> records = new ArrayList<List<String>>();
try (Scanner scanner = new Scanner(new File(CSV_FILE));) {
while (scanner.hasNextLine()) {
records.add(getRecordFromLine(scanner.nextLine()));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i < EXPECTED_ARRAY.size(); i++) {
Assert.assertArrayEquals(EXPECTED_ARRAY.get(i)
.toArray(),
records.get(i)
.toArray());
}
}
private List<String> getRecordFromLine(String line) {
List<String> values = new ArrayList<String>();
try (Scanner rowScanner = new Scanner(line)) {
rowScanner.useDelimiter(COMMA_DELIMITER);
while (rowScanner.hasNext()) {
values.add(rowScanner.next());
}
}
return values;
}
@Test
public void givenCSVFile_whenOpencsv_thenContentsAsExpected() throws IOException {
List<List<String>> records = new ArrayList<List<String>>();
try (CSVReader csvReader = new CSVReader(new FileReader(CSV_FILE));) {
String[] values = null;
while ((values = csvReader.readNext()) != null) {
records.add(Arrays.asList(values));
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < EXPECTED_ARRAY.size(); i++) {
Assert.assertArrayEquals(EXPECTED_ARRAY.get(i)
.toArray(),
records.get(i)
.toArray());
}
}
}

View File

@ -0,0 +1,85 @@
package com.ossez.csv;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WriteCsvFileExampleUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(WriteCsvFileExampleUnitTest.class);
private WriteCsvFileExample csvExample;
@Before
public void setupClass() {
csvExample = new WriteCsvFileExample();
}
@Test
public void givenCommaContainingData_whenEscapeSpecialCharacters_stringReturnedInQuotes() {
String data = "three,two,one";
String escapedData = csvExample.escapeSpecialCharacters(data);
String expectedData = "\"three,two,one\"";
assertEquals(expectedData, escapedData);
}
@Test
public void givenQuoteContainingData_whenEscapeSpecialCharacters_stringReturnedFormatted() {
String data = "She said \"Hello\"";
String escapedData = csvExample.escapeSpecialCharacters(data);
String expectedData = "\"She said \"\"Hello\"\"\"";
assertEquals(expectedData, escapedData);
}
@Test
public void givenNewlineContainingData_whenEscapeSpecialCharacters_stringReturnedInQuotes() {
String dataNewline = "This contains\na newline";
String dataCarriageReturn = "This contains\r\na newline and carriage return";
String escapedDataNl = csvExample.escapeSpecialCharacters(dataNewline);
String escapedDataCr = csvExample.escapeSpecialCharacters(dataCarriageReturn);
String expectedData = "This contains a newline";
assertEquals(expectedData, escapedDataNl);
String expectedDataCr = "This contains a newline and carriage return";
assertEquals(expectedDataCr, escapedDataCr);
}
@Test
public void givenNonSpecialData_whenEscapeSpecialCharacters_stringReturnedUnchanged() {
String data = "This is nothing special";
String returnedData = csvExample.escapeSpecialCharacters(data);
assertEquals(data, returnedData);
}
@Test
public void givenDataArray_whenConvertToCSV_thenOutputCreated() throws IOException {
List<String[]> dataLines = new ArrayList<String[]>();
dataLines.add(new String[] { "John", "Doe", "38", "Comment Data\nAnother line of comment data" });
dataLines.add(new String[] { "Jane", "Doe, Jr.", "19", "She said \"I'm being quoted\"" });
File csvOutputFile = File.createTempFile("exampleOutput", ".csv");
try (PrintWriter pw = new PrintWriter(csvOutputFile)) {
dataLines.stream()
.map(csvExample::convertToCSV)
.forEach(pw::println);
} catch (FileNotFoundException e) {
LOG.error("IOException " + e.getMessage());
}
assertTrue(csvOutputFile.exists());
csvOutputFile.deleteOnExit();
}
}

View File

@ -0,0 +1,100 @@
package com.ossez.directories;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class NewDirectoryUnitTest {
private static final File TEMP_DIRECTORY = new File(System.getProperty("java.io.tmpdir"));
@Before
public void beforeEach() {
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
File nestedInNewDirectory = new File(newDirectory, "nested_directory");
File existingDirectory = new File(TEMP_DIRECTORY, "existing_directory");
File existingNestedDirectory = new File(existingDirectory, "existing_nested_directory");
File nestedInExistingDirectory = new File(existingDirectory, "nested_directory");
nestedInNewDirectory.delete();
newDirectory.delete();
nestedInExistingDirectory.delete();
existingDirectory.mkdir();
existingNestedDirectory.mkdir();
}
@Test
public void givenUnexistingDirectory_whenMkdir_thenTrue() {
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
assertFalse(newDirectory.exists());
boolean directoryCreated = newDirectory.mkdir();
assertTrue(directoryCreated);
}
@Test
public void givenExistingDirectory_whenMkdir_thenFalse() {
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
newDirectory.mkdir();
assertTrue(newDirectory.exists());
boolean directoryCreated = newDirectory.mkdir();
assertFalse(directoryCreated);
}
@Test
public void givenUnexistingNestedDirectories_whenMkdir_thenFalse() {
File newDirectory = new File(TEMP_DIRECTORY, "new_directory");
File nestedDirectory = new File(newDirectory, "nested_directory");
assertFalse(newDirectory.exists());
assertFalse(nestedDirectory.exists());
boolean directoriesCreated = nestedDirectory.mkdir();
assertFalse(directoriesCreated);
}
@Test
public void givenUnexistingNestedDirectories_whenMkdirs_thenTrue() {
File newDirectory = new File(System.getProperty("java.io.tmpdir") + File.separator + "new_directory");
File nestedDirectory = new File(newDirectory, "nested_directory");
assertFalse(newDirectory.exists());
assertFalse(nestedDirectory.exists());
boolean directoriesCreated = nestedDirectory.mkdirs();
assertTrue(directoriesCreated);
}
@Test
public void givenExistingParentDirectories_whenMkdirs_thenTrue() {
File newDirectory = new File(TEMP_DIRECTORY, "existing_directory");
newDirectory.mkdir();
File nestedDirectory = new File(newDirectory, "nested_directory");
assertTrue(newDirectory.exists());
assertFalse(nestedDirectory.exists());
boolean directoriesCreated = nestedDirectory.mkdirs();
assertTrue(directoriesCreated);
}
@Test
public void givenExistingNestedDirectories_whenMkdirs_thenFalse() {
File existingDirectory = new File(TEMP_DIRECTORY, "existing_directory");
File existingNestedDirectory = new File(existingDirectory, "existing_nested_directory");
assertTrue(existingDirectory.exists());
assertTrue(existingNestedDirectory.exists());
boolean directoriesCreated = existingNestedDirectory.mkdirs();
assertFalse(directoriesCreated);
}
}

View File

@ -0,0 +1,91 @@
package com.ossez.download;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ExecutionException;
import javax.xml.bind.DatatypeConverter;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
public class FileDownloadIntegrationTest {
static String FILE_URL = "http://ovh.net/files/1Mio.dat";
static String FILE_NAME = "file.dat";
static String FILE_MD5_HASH = "6cb91af4ed4c60c11613b75cd1fc6116";
@Test
public void givenJavaIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
FileDownload.downloadWithJavaIO(FILE_URL, FILE_NAME);
assertTrue(checkMd5Hash(FILE_NAME));
}
@Test
public void givenJavaNIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
FileDownload.downloadWithJavaNIO(FILE_URL, FILE_NAME);
assertTrue(checkMd5Hash(FILE_NAME));
}
@Test
public void givenJava7IO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
FileDownload.downloadWithJava7IO(FILE_URL, FILE_NAME);
assertTrue(checkMd5Hash(FILE_NAME));
}
@Test
public void givenAHCLibrary_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException, ExecutionException, InterruptedException {
FileDownload.downloadWithAHC(FILE_URL, FILE_NAME);
assertTrue(checkMd5Hash(FILE_NAME));
}
@Test
public void givenApacheCommonsIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
FileDownload.downloadWithApacheCommons(FILE_URL, FILE_NAME);
assertTrue(checkMd5Hash(FILE_NAME));
}
@Test
public void givenJavaIO_whenDownloadingFileStops_thenDownloadShouldBeResumedCorrectly() throws NoSuchAlgorithmException, IOException, URISyntaxException {
ResumableDownload.downloadFileWithResume(FILE_URL, FILE_NAME);
assertTrue(checkMd5Hash(FILE_NAME));
}
private boolean checkMd5Hash(String filename) throws IOException, NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(Files.readAllBytes(Paths.get(filename)));
byte[] digest = md.digest();
String myChecksum = DatatypeConverter.printHexBinary(digest);
return myChecksum.equalsIgnoreCase(FILE_MD5_HASH);
}
@BeforeClass
public static void setup() throws IOException {
if (Files.exists(Paths.get(FILE_NAME))) {
Files.delete(Paths.get(FILE_NAME));
}
}
@After
public void cleanup() throws IOException {
if (Files.exists(Paths.get(FILE_NAME))) {
Files.delete(Paths.get(FILE_NAME));
}
}
}

View File

@ -0,0 +1,31 @@
package com.ossez.extension;
import org.junit.Assert;
import org.junit.Test;
import java.util.Optional;
public class ExtensionUnitTest {
private Extension extension = new Extension();
@Test
public void getExtension_whenApacheCommonIO_thenExtensionIsTrue() {
String expectedExtension = "txt";
String actualExtension = extension.getExtensionByApacheCommonLib("jarvis.txt");
Assert.assertEquals(expectedExtension, actualExtension);
}
@Test
public void getExtension_whenStringHandle_thenExtensionIsTrue() {
String expectedExtension = "java";
Optional<String> actualExtension = extension.getExtensionByStringHandling("Demo.java");
Assert.assertEquals(expectedExtension, actualExtension.get());
}
@Test
public void getExtension_whenGuava_thenExtensionIsTrue() {
String expectedExtension = "class";
String actualExtension = extension.getExtensionByGuava("baeldung/Demo.class");
Assert.assertEquals(expectedExtension, actualExtension);
}
}

View File

@ -0,0 +1,48 @@
package com.ossez.file;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class FilenameFilterManualTest {
private static File directory;
@BeforeClass
public static void setupClass() {
directory = new File(FilenameFilterManualTest.class.getClassLoader()
.getResource("fileNameFilterManualTestFolder")
.getFile());
}
@Test
public void whenFilteringFilesEndingWithJson_thenEqualExpectedFiles() {
FilenameFilter filter = (dir, name) -> name.endsWith(".json");
String[] expectedFiles = { "people.json", "students.json" };
String[] actualFiles = directory.list(filter);
Assert.assertArrayEquals(expectedFiles, actualFiles);
}
@Test
public void whenFilteringFilesEndingWithXml_thenEqualExpectedFiles() {
Predicate<String> predicate = (name) -> name.endsWith(".xml");
String[] expectedFiles = { "teachers.xml", "workers.xml" };
List<String> files = Arrays.stream(directory.list())
.filter(predicate)
.collect(Collectors.toList());
String[] actualFiles = files.toArray(new String[files.size()]);
Assert.assertArrayEquals(expectedFiles, actualFiles);
}
}

View File

@ -0,0 +1,96 @@
package com.ossez.file;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.ossez.util.StreamUtils;
public class FilesClearDataUnitTest {
public static final String FILE_PATH = "src/test/resources/fileexample.txt";
@Before
@After
public void setup() throws IOException {
PrintWriter writer = new PrintWriter(FILE_PATH);
writer.print("This example shows how we can delete the file contents without deleting the file");
writer.close();
}
@Test
public void givenExistingFile_whenDeleteContentUsingPrintWritter_thenEmptyFile() throws IOException {
PrintWriter writer = new PrintWriter(FILE_PATH);
writer.print("");
writer.close();
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
@Test
public void givenExistingFile_whenDeleteContentUsingPrintWritterWithougObject_thenEmptyFile() throws IOException {
new PrintWriter(FILE_PATH).close();
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
@Test
public void givenExistingFile_whenDeleteContentUsingFileWriter_thenEmptyFile() throws IOException {
new FileWriter(FILE_PATH, false).close();
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
@Test
public void givenExistingFile_whenDeleteContentUsingFileOutputStream_thenEmptyFile() throws IOException {
new FileOutputStream(FILE_PATH).close();
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
@Test
public void givenExistingFile_whenDeleteContentUsingFileUtils_thenEmptyFile() throws IOException {
FileUtils.write(new File(FILE_PATH), "", Charset.defaultCharset());
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
@Test
public void givenExistingFile_whenDeleteContentUsingNIOFiles_thenEmptyFile() throws IOException {
BufferedWriter writer = Files.newBufferedWriter(Paths.get(FILE_PATH));
writer.write("");
writer.flush();
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
@Test
public void givenExistingFile_whenDeleteContentUsingNIOFileChannel_thenEmptyFile() throws IOException {
FileChannel.open(Paths.get(FILE_PATH), StandardOpenOption.WRITE).truncate(0).close();
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
@Test
public void givenExistingFile_whenDeleteContentUsingGuava_thenEmptyFile() throws IOException {
File file = new File(FILE_PATH);
byte[] empty = new byte[0];
com.google.common.io.Files.write(empty, file);
assertEquals(0, StreamUtils.getStringFromInputStream(new FileInputStream(FILE_PATH)).length());
}
}

View File

@ -0,0 +1,82 @@
package com.ossez.file;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import com.google.common.base.Charsets;
import com.google.common.io.CharSink;
import com.google.common.io.FileWriteMode;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.ossez.util.StreamUtils;
public class FilesManualTest {
public static final String fileName = "src/main/resources/countries.properties";
@Before
@After
public void setup() throws Exception {
PrintWriter writer = new PrintWriter(fileName);
writer.print("UK\r\n" + "US\r\n" + "Germany\r\n");
writer.close();
}
@Test
public void whenAppendToFileUsingGuava_thenCorrect() throws IOException {
File file = new File(fileName);
CharSink chs = com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);
chs.write("Spain\r\n");
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
public void whenAppendToFileUsingFiles_thenCorrect() throws IOException {
Files.write(Paths.get(fileName), "Spain\r\n".getBytes(), StandardOpenOption.APPEND);
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
public void whenAppendToFileUsingFileUtils_thenCorrect() throws IOException {
File file = new File(fileName);
FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true);
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
public void whenAppendToFileUsingFileOutputStream_thenCorrect() throws Exception {
FileOutputStream fos = new FileOutputStream(fileName, true);
fos.write("Spain\r\n".getBytes());
fos.close();
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
public void whenAppendToFileUsingFileWriter_thenCorrect() throws IOException {
FileWriter fw = new FileWriter(fileName, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Spain");
bw.newLine();
bw.close();
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
}

View File

@ -0,0 +1,46 @@
package com.ossez.file;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import com.ossez.files.ListFiles;
public class ListFilesUnitTest {
private ListFiles listFiles = new ListFiles();
private String DIRECTORY = "src/test/resources/listFilesUnitTestFolder";
private static final int DEPTH = 1;
private Set<String> EXPECTED_FILE_LIST = new HashSet<String>() {
{
add("test.xml");
add("employee.json");
add("students.json");
add("country.txt");
}
};
@Test
public void givenDir_whenUsingJAVAIO_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingJavaIO(DIRECTORY));
}
@Test
public void givenDir_whenWalkingTree_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFileWalk(DIRECTORY,DEPTH));
}
@Test
public void givenDir_whenWalkingTreeWithVisitor_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingFileWalkAndVisitor(DIRECTORY));
}
@Test
public void givenDir_whenUsingDirectoryStream_thenListAllFiles() throws IOException {
assertEquals(EXPECTED_FILE_LIST, listFiles.listFilesUsingDirectoryStream(DIRECTORY));
}
}

Some files were not shown because too many files have changed in this diff Show More