[BAEL-19088] - Move articles out of core-java-io part 3
This commit is contained in:
@@ -1,64 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.Files;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
|
||||
public class FileCopy {
|
||||
|
||||
public static void copyFileUsingStream(File source, File dest) throws IOException {
|
||||
InputStream is = null;
|
||||
OutputStream os = null;
|
||||
is = new FileInputStream(source);
|
||||
os = new FileOutputStream(dest);
|
||||
byte[] buffer = new byte[1024];
|
||||
int length;
|
||||
while ((length = is.read(buffer)) > 0) {
|
||||
os.write(buffer, 0, length);
|
||||
}
|
||||
is.close();
|
||||
os.close();
|
||||
}
|
||||
|
||||
public static void copyFileUsingChannel(File source, File dest) throws IOException {
|
||||
FileChannel sourceChannel = null;
|
||||
FileChannel destChannel = null;
|
||||
sourceChannel = new FileInputStream(source).getChannel();
|
||||
destChannel = new FileOutputStream(dest).getChannel();
|
||||
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
|
||||
sourceChannel.close();
|
||||
destChannel.close();
|
||||
}
|
||||
|
||||
public static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
|
||||
FileUtils.copyFile(source, dest);
|
||||
}
|
||||
|
||||
public static void copyFileUsingJavaFiles(File source, File dest) throws IOException {
|
||||
Files.copy(source.toPath(), dest.toPath());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.StringWriter;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
public class StreamUtils {
|
||||
|
||||
public static String getStringFromInputStream(InputStream input) throws IOException {
|
||||
StringWriter writer = new StringWriter();
|
||||
IOUtils.copy(input, writer, "UTF-8");
|
||||
return writer.toString();
|
||||
}
|
||||
}
|
||||
@@ -1,453 +0,0 @@
|
||||
#
|
||||
# OWASP Enterprise Security API (ESAPI) Properties file -- PRODUCTION Version
|
||||
#
|
||||
# This file is part of the Open Web Application Security Project (OWASP)
|
||||
# Enterprise Security API (ESAPI) project. For details, please see
|
||||
# http://www.owasp.org/index.php/ESAPI.
|
||||
#
|
||||
# Copyright (c) 2008,2009 - The OWASP Foundation
|
||||
#
|
||||
# DISCUSS: This may cause a major backwards compatibility issue, etc. but
|
||||
# from a name space perspective, we probably should have prefaced
|
||||
# all the property names with ESAPI or at least OWASP. Otherwise
|
||||
# there could be problems is someone loads this properties file into
|
||||
# the System properties. We could also put this file into the
|
||||
# esapi.jar file (perhaps as a ResourceBundle) and then allow an external
|
||||
# ESAPI properties be defined that would overwrite these defaults.
|
||||
# That keeps the application's properties relatively simple as usually
|
||||
# they will only want to override a few properties. If looks like we
|
||||
# already support multiple override levels of this in the
|
||||
# DefaultSecurityConfiguration class, but I'm suggesting placing the
|
||||
# defaults in the esapi.jar itself. That way, if the jar is signed,
|
||||
# we could detect if those properties had been tampered with. (The
|
||||
# code to check the jar signatures is pretty simple... maybe 70-90 LOC,
|
||||
# but off course there is an execution penalty (similar to the way
|
||||
# that the separate sunjce.jar used to be when a class from it was
|
||||
# first loaded). Thoughts?
|
||||
###############################################################################
|
||||
#
|
||||
# WARNING: Operating system protection should be used to lock down the .esapi
|
||||
# resources directory and all the files inside and all the directories all the
|
||||
# way up to the root directory of the file system. Note that if you are using
|
||||
# file-based implementations, that some files may need to be read-write as they
|
||||
# get updated dynamically.
|
||||
#
|
||||
# Before using, be sure to update the MasterKey and MasterSalt as described below.
|
||||
# N.B.: If you had stored data that you have previously encrypted with ESAPI 1.4,
|
||||
# you *must* FIRST decrypt it using ESAPI 1.4 and then (if so desired)
|
||||
# re-encrypt it with ESAPI 2.0. If you fail to do this, you will NOT be
|
||||
# able to decrypt your data with ESAPI 2.0.
|
||||
#
|
||||
# YOU HAVE BEEN WARNED!!! More details are in the ESAPI 2.0 Release Notes.
|
||||
#
|
||||
#===========================================================================
|
||||
# ESAPI Configuration
|
||||
#
|
||||
# If true, then print all the ESAPI properties set here when they are loaded.
|
||||
# If false, they are not printed. Useful to reduce output when running JUnit tests.
|
||||
# If you need to troubleshoot a properties related problem, turning this on may help.
|
||||
# This is 'false' in the src/test/resources/.esapi version. It is 'true' by
|
||||
# default for reasons of backward compatibility with earlier ESAPI versions.
|
||||
ESAPI.printProperties=true
|
||||
|
||||
# ESAPI is designed to be easily extensible. You can use the reference implementation
|
||||
# or implement your own providers to take advantage of your enterprise's security
|
||||
# infrastructure. The functions in ESAPI are referenced using the ESAPI locator, like:
|
||||
#
|
||||
# String ciphertext =
|
||||
# ESAPI.encryptor().encrypt("Secret message"); // Deprecated in 2.0
|
||||
# CipherText cipherText =
|
||||
# ESAPI.encryptor().encrypt(new PlainText("Secret message")); // Preferred
|
||||
#
|
||||
# Below you can specify the classname for the provider that you wish to use in your
|
||||
# application. The only requirement is that it implement the appropriate ESAPI interface.
|
||||
# This allows you to switch security implementations in the future without rewriting the
|
||||
# entire application.
|
||||
#
|
||||
# ExperimentalAccessController requires ESAPI-AccessControlPolicy.xml in .esapi directory
|
||||
ESAPI.AccessControl=org.owasp.esapi.reference.DefaultAccessController
|
||||
# FileBasedAuthenticator requires users.txt file in .esapi directory
|
||||
ESAPI.Authenticator=org.owasp.esapi.reference.FileBasedAuthenticator
|
||||
ESAPI.Encoder=org.owasp.esapi.reference.DefaultEncoder
|
||||
ESAPI.Encryptor=org.owasp.esapi.reference.crypto.JavaEncryptor
|
||||
|
||||
ESAPI.Executor=org.owasp.esapi.reference.DefaultExecutor
|
||||
ESAPI.HTTPUtilities=org.owasp.esapi.reference.DefaultHTTPUtilities
|
||||
ESAPI.IntrusionDetector=org.owasp.esapi.reference.DefaultIntrusionDetector
|
||||
# Log4JFactory Requires log4j.xml or log4j.properties in classpath - http://www.laliluna.de/log4j-tutorial.html
|
||||
ESAPI.Logger=org.owasp.esapi.reference.Log4JLogFactory
|
||||
#ESAPI.Logger=org.owasp.esapi.reference.JavaLogFactory
|
||||
ESAPI.Randomizer=org.owasp.esapi.reference.DefaultRandomizer
|
||||
ESAPI.Validator=org.owasp.esapi.reference.DefaultValidator
|
||||
|
||||
#===========================================================================
|
||||
# ESAPI Authenticator
|
||||
#
|
||||
Authenticator.AllowedLoginAttempts=3
|
||||
Authenticator.MaxOldPasswordHashes=13
|
||||
Authenticator.UsernameParameterName=username
|
||||
Authenticator.PasswordParameterName=password
|
||||
# RememberTokenDuration (in days)
|
||||
Authenticator.RememberTokenDuration=14
|
||||
# Session Timeouts (in minutes)
|
||||
Authenticator.IdleTimeoutDuration=20
|
||||
Authenticator.AbsoluteTimeoutDuration=120
|
||||
|
||||
#===========================================================================
|
||||
# ESAPI Encoder
|
||||
#
|
||||
# ESAPI canonicalizes input before validation to prevent bypassing filters with encoded attacks.
|
||||
# Failure to canonicalize input is a very common mistake when implementing validation schemes.
|
||||
# Canonicalization is automatic when using the ESAPI Validator, but you can also use the
|
||||
# following code to canonicalize data.
|
||||
#
|
||||
# ESAPI.Encoder().canonicalize( "%22hello world"" );
|
||||
#
|
||||
# Multiple encoding is when a single encoding format is applied multiple times. Allowing
|
||||
# multiple encoding is strongly discouraged.
|
||||
Encoder.AllowMultipleEncoding=false
|
||||
|
||||
# Mixed encoding is when multiple different encoding formats are applied, or when
|
||||
# multiple formats are nested. Allowing multiple encoding is strongly discouraged.
|
||||
Encoder.AllowMixedEncoding=false
|
||||
|
||||
# The default list of codecs to apply when canonicalizing untrusted data. The list should include the codecs
|
||||
# for all downstream interpreters or decoders. For example, if the data is likely to end up in a URL, HTML, or
|
||||
# inside JavaScript, then the list of codecs below is appropriate. The order of the list is not terribly important.
|
||||
Encoder.DefaultCodecList=HTMLEntityCodec,PercentCodec,JavaScriptCodec
|
||||
|
||||
|
||||
#===========================================================================
|
||||
# ESAPI Encryption
|
||||
#
|
||||
# The ESAPI Encryptor provides basic cryptographic functions with a simplified API.
|
||||
# To get started, generate a new key using java -classpath esapi.jar org.owasp.esapi.reference.crypto.JavaEncryptor
|
||||
# There is not currently any support for key rotation, so be careful when changing your key and salt as it
|
||||
# will invalidate all signed, encrypted, and hashed data.
|
||||
#
|
||||
# WARNING: Not all combinations of algorithms and key lengths are supported.
|
||||
# If you choose to use a key length greater than 128, you MUST download the
|
||||
# unlimited strength policy files and install in the lib directory of your JRE/JDK.
|
||||
# See http://java.sun.com/javase/downloads/index.jsp for more information.
|
||||
#
|
||||
# Backward compatibility with ESAPI Java 1.4 is supported by the two deprecated API
|
||||
# methods, Encryptor.encrypt(String) and Encryptor.decrypt(String). However, whenever
|
||||
# possible, these methods should be avoided as they use ECB cipher mode, which in almost
|
||||
# all circumstances a poor choice because of it's weakness. CBC cipher mode is the default
|
||||
# for the new Encryptor encrypt / decrypt methods for ESAPI Java 2.0. In general, you
|
||||
# should only use this compatibility setting if you have persistent data encrypted with
|
||||
# version 1.4 and even then, you should ONLY set this compatibility mode UNTIL
|
||||
# you have decrypted all of your old encrypted data and then re-encrypted it with
|
||||
# ESAPI 2.0 using CBC mode. If you have some reason to mix the deprecated 1.4 mode
|
||||
# with the new 2.0 methods, make sure that you use the same cipher algorithm for both
|
||||
# (256-bit AES was the default for 1.4; 128-bit is the default for 2.0; see below for
|
||||
# more details.) Otherwise, you will have to use the new 2.0 encrypt / decrypt methods
|
||||
# where you can specify a SecretKey. (Note that if you are using the 256-bit AES,
|
||||
# that requires downloading the special jurisdiction policy files mentioned above.)
|
||||
#
|
||||
# ***** IMPORTANT: Do NOT forget to replace these with your own values! *****
|
||||
# To calculate these values, you can run:
|
||||
# java -classpath esapi.jar org.owasp.esapi.reference.crypto.JavaEncryptor
|
||||
#
|
||||
Encryptor.MasterKey=tzfztf56ftv
|
||||
Encryptor.MasterSalt=123456ztrewq
|
||||
|
||||
# Provides the default JCE provider that ESAPI will "prefer" for its symmetric
|
||||
# encryption and hashing. (That is it will look to this provider first, but it
|
||||
# will defer to other providers if the requested algorithm is not implemented
|
||||
# by this provider.) If left unset, ESAPI will just use your Java VM's current
|
||||
# preferred JCE provider, which is generally set in the file
|
||||
# "$JAVA_HOME/jre/lib/security/java.security".
|
||||
#
|
||||
# The main intent of this is to allow ESAPI symmetric encryption to be
|
||||
# used with a FIPS 140-2 compliant crypto-module. For details, see the section
|
||||
# "Using ESAPI Symmetric Encryption with FIPS 140-2 Cryptographic Modules" in
|
||||
# the ESAPI 2.0 Symmetric Encryption User Guide, at:
|
||||
# http://owasp-esapi-java.googlecode.com/svn/trunk/documentation/esapi4java-core-2.0-symmetric-crypto-user-guide.html
|
||||
# However, this property also allows you to easily use an alternate JCE provider
|
||||
# such as "Bouncy Castle" without having to make changes to "java.security".
|
||||
# See Javadoc for SecurityProviderLoader for further details. If you wish to use
|
||||
# a provider that is not known to SecurityProviderLoader, you may specify the
|
||||
# fully-qualified class name of the JCE provider class that implements
|
||||
# java.security.Provider. If the name contains a '.', this is interpreted as
|
||||
# a fully-qualified class name that implements java.security.Provider.
|
||||
#
|
||||
# NOTE: Setting this property has the side-effect of changing it in your application
|
||||
# as well, so if you are using JCE in your application directly rather than
|
||||
# through ESAPI (you wouldn't do that, would you? ;-), it will change the
|
||||
# preferred JCE provider there as well.
|
||||
#
|
||||
# Default: Keeps the JCE provider set to whatever JVM sets it to.
|
||||
Encryptor.PreferredJCEProvider=
|
||||
|
||||
# AES is the most widely used and strongest encryption algorithm. This
|
||||
# should agree with your Encryptor.CipherTransformation property.
|
||||
# By default, ESAPI Java 1.4 uses "PBEWithMD5AndDES" and which is
|
||||
# very weak. It is essentially a password-based encryption key, hashed
|
||||
# with MD5 around 1K times and then encrypted with the weak DES algorithm
|
||||
# (56-bits) using ECB mode and an unspecified padding (it is
|
||||
# JCE provider specific, but most likely "NoPadding"). However, 2.0 uses
|
||||
# "AES/CBC/PKCSPadding". If you want to change these, change them here.
|
||||
# Warning: This property does not control the default reference implementation for
|
||||
# ESAPI 2.0 using JavaEncryptor. Also, this property will be dropped
|
||||
# in the future.
|
||||
# @deprecated
|
||||
Encryptor.EncryptionAlgorithm=AES
|
||||
# For ESAPI Java 2.0 - New encrypt / decrypt methods use this.
|
||||
Encryptor.CipherTransformation=AES/CBC/PKCS5Padding
|
||||
|
||||
# Applies to ESAPI 2.0 and later only!
|
||||
# Comma-separated list of cipher modes that provide *BOTH*
|
||||
# confidentiality *AND* message authenticity. (NIST refers to such cipher
|
||||
# modes as "combined modes" so that's what we shall call them.) If any of these
|
||||
# cipher modes are used then no MAC is calculated and stored
|
||||
# in the CipherText upon encryption. Likewise, if one of these
|
||||
# cipher modes is used with decryption, no attempt will be made
|
||||
# to validate the MAC contained in the CipherText object regardless
|
||||
# of whether it contains one or not. Since the expectation is that
|
||||
# these cipher modes support support message authenticity already,
|
||||
# injecting a MAC in the CipherText object would be at best redundant.
|
||||
#
|
||||
# Note that as of JDK 1.5, the SunJCE provider does not support *any*
|
||||
# of these cipher modes. Of these listed, only GCM and CCM are currently
|
||||
# NIST approved. YMMV for other JCE providers. E.g., Bouncy Castle supports
|
||||
# GCM and CCM with "NoPadding" mode, but not with "PKCS5Padding" or other
|
||||
# padding modes.
|
||||
Encryptor.cipher_modes.combined_modes=GCM,CCM,IAPM,EAX,OCB,CWC
|
||||
|
||||
# Applies to ESAPI 2.0 and later only!
|
||||
# Additional cipher modes allowed for ESAPI 2.0 encryption. These
|
||||
# cipher modes are in _addition_ to those specified by the property
|
||||
# 'Encryptor.cipher_modes.combined_modes'.
|
||||
# Note: We will add support for streaming modes like CFB & OFB once
|
||||
# we add support for 'specified' to the property 'Encryptor.ChooseIVMethod'
|
||||
# (probably in ESAPI 2.1).
|
||||
# DISCUSS: Better name?
|
||||
Encryptor.cipher_modes.additional_allowed=CBC
|
||||
|
||||
# 128-bit is almost always sufficient and appears to be more resistant to
|
||||
# related key attacks than is 256-bit AES. Use '_' to use default key size
|
||||
# for cipher algorithms (where it makes sense because the algorithm supports
|
||||
# a variable key size). Key length must agree to what's provided as the
|
||||
# cipher transformation, otherwise this will be ignored after logging a
|
||||
# warning.
|
||||
#
|
||||
# NOTE: This is what applies BOTH ESAPI 1.4 and 2.0. See warning above about mixing!
|
||||
Encryptor.EncryptionKeyLength=128
|
||||
|
||||
# Because 2.0 uses CBC mode by default, it requires an initialization vector (IV).
|
||||
# (All cipher modes except ECB require an IV.) There are two choices: we can either
|
||||
# use a fixed IV known to both parties or allow ESAPI to choose a random IV. While
|
||||
# the IV does not need to be hidden from adversaries, it is important that the
|
||||
# adversary not be allowed to choose it. Also, random IVs are generally much more
|
||||
# secure than fixed IVs. (In fact, it is essential that feed-back cipher modes
|
||||
# such as CFB and OFB use a different IV for each encryption with a given key so
|
||||
# in such cases, random IVs are much preferred. By default, ESAPI 2.0 uses random
|
||||
# IVs. If you wish to use 'fixed' IVs, set 'Encryptor.ChooseIVMethod=fixed' and
|
||||
# uncomment the Encryptor.fixedIV.
|
||||
#
|
||||
# Valid values: random|fixed|specified 'specified' not yet implemented; planned for 2.1
|
||||
Encryptor.ChooseIVMethod=random
|
||||
# If you choose to use a fixed IV, then you must place a fixed IV here that
|
||||
# is known to all others who are sharing your secret key. The format should
|
||||
# be a hex string that is the same length as the cipher block size for the
|
||||
# cipher algorithm that you are using. The following is an *example* for AES
|
||||
# from an AES test vector for AES-128/CBC as described in:
|
||||
# NIST Special Publication 800-38A (2001 Edition)
|
||||
# "Recommendation for Block Cipher Modes of Operation".
|
||||
# (Note that the block size for AES is 16 bytes == 128 bits.)
|
||||
#
|
||||
Encryptor.fixedIV=0x000102030405060708090a0b0c0d0e0f
|
||||
|
||||
# Whether or not CipherText should use a message authentication code (MAC) with it.
|
||||
# This prevents an adversary from altering the IV as well as allowing a more
|
||||
# fool-proof way of determining the decryption failed because of an incorrect
|
||||
# key being supplied. This refers to the "separate" MAC calculated and stored
|
||||
# in CipherText, not part of any MAC that is calculated as a result of a
|
||||
# "combined mode" cipher mode.
|
||||
#
|
||||
# If you are using ESAPI with a FIPS 140-2 cryptographic module, you *must* also
|
||||
# set this property to false.
|
||||
Encryptor.CipherText.useMAC=true
|
||||
|
||||
# Whether or not the PlainText object may be overwritten and then marked
|
||||
# eligible for garbage collection. If not set, this is still treated as 'true'.
|
||||
Encryptor.PlainText.overwrite=true
|
||||
|
||||
# Do not use DES except in a legacy situations. 56-bit is way too small key size.
|
||||
#Encryptor.EncryptionKeyLength=56
|
||||
#Encryptor.EncryptionAlgorithm=DES
|
||||
|
||||
# TripleDES is considered strong enough for most purposes.
|
||||
# Note: There is also a 112-bit version of DESede. Using the 168-bit version
|
||||
# requires downloading the special jurisdiction policy from Sun.
|
||||
#Encryptor.EncryptionKeyLength=168
|
||||
#Encryptor.EncryptionAlgorithm=DESede
|
||||
|
||||
Encryptor.HashAlgorithm=SHA-512
|
||||
Encryptor.HashIterations=1024
|
||||
Encryptor.DigitalSignatureAlgorithm=SHA1withDSA
|
||||
Encryptor.DigitalSignatureKeyLength=1024
|
||||
Encryptor.RandomAlgorithm=SHA1PRNG
|
||||
Encryptor.CharacterEncoding=UTF-8
|
||||
|
||||
# This is the Pseudo Random Function (PRF) that ESAPI's Key Derivation Function
|
||||
# (KDF) normally uses. Note this is *only* the PRF used for ESAPI's KDF and
|
||||
# *not* what is used for ESAPI's MAC. (Currently, HmacSHA1 is always used for
|
||||
# the MAC, mostly to keep the overall size at a minimum.)
|
||||
#
|
||||
# Currently supported choices for JDK 1.5 and 1.6 are:
|
||||
# HmacSHA1 (160 bits), HmacSHA256 (256 bits), HmacSHA384 (384 bits), and
|
||||
# HmacSHA512 (512 bits).
|
||||
# Note that HmacMD5 is *not* supported for the PRF used by the KDF even though
|
||||
# the JDKs support it. See the ESAPI 2.0 Symmetric Encryption User Guide
|
||||
# further details.
|
||||
Encryptor.KDF.PRF=HmacSHA256
|
||||
#===========================================================================
|
||||
# ESAPI HttpUtilties
|
||||
#
|
||||
# The HttpUtilities provide basic protections to HTTP requests and responses. Primarily these methods
|
||||
# protect against malicious data from attackers, such as unprintable characters, escaped characters,
|
||||
# and other simple attacks. The HttpUtilities also provides utility methods for dealing with cookies,
|
||||
# headers, and CSRF tokens.
|
||||
#
|
||||
# Default file upload location (remember to escape backslashes with \\)
|
||||
HttpUtilities.UploadDir=C:\\ESAPI\\testUpload
|
||||
HttpUtilities.UploadTempDir=C:\\temp
|
||||
# Force flags on cookies, if you use HttpUtilities to set cookies
|
||||
HttpUtilities.ForceHttpOnlySession=false
|
||||
HttpUtilities.ForceSecureSession=false
|
||||
HttpUtilities.ForceHttpOnlyCookies=true
|
||||
HttpUtilities.ForceSecureCookies=true
|
||||
# Maximum size of HTTP headers
|
||||
HttpUtilities.MaxHeaderSize=4096
|
||||
# File upload configuration
|
||||
HttpUtilities.ApprovedUploadExtensions=.zip,.pdf,.doc,.docx,.ppt,.pptx,.tar,.gz,.tgz,.rar,.war,.jar,.ear,.xls,.rtf,.properties,.java,.class,.txt,.xml,.jsp,.jsf,.exe,.dll
|
||||
HttpUtilities.MaxUploadFileBytes=500000000
|
||||
# Using UTF-8 throughout your stack is highly recommended. That includes your database driver,
|
||||
# container, and any other technologies you may be using. Failure to do this may expose you
|
||||
# to Unicode transcoding injection attacks. Use of UTF-8 does not hinder internationalization.
|
||||
HttpUtilities.ResponseContentType=text/html; charset=UTF-8
|
||||
# This is the name of the cookie used to represent the HTTP session
|
||||
# Typically this will be the default "JSESSIONID"
|
||||
HttpUtilities.HttpSessionIdName=JSESSIONID
|
||||
|
||||
|
||||
|
||||
#===========================================================================
|
||||
# ESAPI Executor
|
||||
# CHECKME - Not sure what this is used for, but surely it should be made OS independent.
|
||||
Executor.WorkingDirectory=C:\\Windows\\Temp
|
||||
Executor.ApprovedExecutables=C:\\Windows\\System32\\cmd.exe,C:\\Windows\\System32\\runas.exe
|
||||
|
||||
|
||||
#===========================================================================
|
||||
# ESAPI Logging
|
||||
# Set the application name if these logs are combined with other applications
|
||||
Logger.ApplicationName=ExampleApplication
|
||||
# If you use an HTML log viewer that does not properly HTML escape log data, you can set LogEncodingRequired to true
|
||||
Logger.LogEncodingRequired=false
|
||||
# Determines whether ESAPI should log the application name. This might be clutter in some single-server/single-app environments.
|
||||
Logger.LogApplicationName=true
|
||||
# Determines whether ESAPI should log the server IP and port. This might be clutter in some single-server environments.
|
||||
Logger.LogServerIP=true
|
||||
# LogFileName, the name of the logging file. Provide a full directory path (e.g., C:\\ESAPI\\ESAPI_logging_file) if you
|
||||
# want to place it in a specific directory.
|
||||
Logger.LogFileName=ESAPI_logging_file
|
||||
# MaxLogFileSize, the max size (in bytes) of a single log file before it cuts over to a new one (default is 10,000,000)
|
||||
Logger.MaxLogFileSize=10000000
|
||||
|
||||
|
||||
#===========================================================================
|
||||
# ESAPI Intrusion Detection
|
||||
#
|
||||
# Each event has a base to which .count, .interval, and .action are added
|
||||
# The IntrusionException will fire if we receive "count" events within "interval" seconds
|
||||
# The IntrusionDetector is configurable to take the following actions: log, logout, and disable
|
||||
# (multiple actions separated by commas are allowed e.g. event.test.actions=log,disable
|
||||
#
|
||||
# Custom Events
|
||||
# Names must start with "event." as the base
|
||||
# Use IntrusionDetector.addEvent( "test" ) in your code to trigger "event.test" here
|
||||
# You can also disable intrusion detection completely by changing
|
||||
# the following parameter to true
|
||||
#
|
||||
IntrusionDetector.Disable=false
|
||||
#
|
||||
IntrusionDetector.event.test.count=2
|
||||
IntrusionDetector.event.test.interval=10
|
||||
IntrusionDetector.event.test.actions=disable,log
|
||||
|
||||
# Exception Events
|
||||
# All EnterpriseSecurityExceptions are registered automatically
|
||||
# Call IntrusionDetector.getInstance().addException(e) for Exceptions that do not extend EnterpriseSecurityException
|
||||
# Use the fully qualified classname of the exception as the base
|
||||
|
||||
# any intrusion is an attack
|
||||
IntrusionDetector.org.owasp.esapi.errors.IntrusionException.count=1
|
||||
IntrusionDetector.org.owasp.esapi.errors.IntrusionException.interval=1
|
||||
IntrusionDetector.org.owasp.esapi.errors.IntrusionException.actions=log,disable,logout
|
||||
|
||||
# for test purposes
|
||||
# CHECKME: Shouldn't there be something in the property name itself that designates
|
||||
# that these are for testing???
|
||||
IntrusionDetector.org.owasp.esapi.errors.IntegrityException.count=10
|
||||
IntrusionDetector.org.owasp.esapi.errors.IntegrityException.interval=5
|
||||
IntrusionDetector.org.owasp.esapi.errors.IntegrityException.actions=log,disable,logout
|
||||
|
||||
# rapid validation errors indicate scans or attacks in progress
|
||||
# org.owasp.esapi.errors.ValidationException.count=10
|
||||
# org.owasp.esapi.errors.ValidationException.interval=10
|
||||
# org.owasp.esapi.errors.ValidationException.actions=log,logout
|
||||
|
||||
# sessions jumping between hosts indicates session hijacking
|
||||
IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.count=2
|
||||
IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.interval=10
|
||||
IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.actions=log,logout
|
||||
|
||||
|
||||
#===========================================================================
|
||||
# ESAPI Validation
|
||||
#
|
||||
# The ESAPI Validator works on regular expressions with defined names. You can define names
|
||||
# either here, or you may define application specific patterns in a separate file defined below.
|
||||
# This allows enterprises to specify both organizational standards as well as application specific
|
||||
# validation rules.
|
||||
#
|
||||
Validator.ConfigurationFile=validation.properties
|
||||
|
||||
# Validators used by ESAPI
|
||||
Validator.AccountName=^[a-zA-Z0-9]{3,20}$
|
||||
Validator.SystemCommand=^[a-zA-Z\\-\\/]{1,64}$
|
||||
Validator.RoleName=^[a-z]{1,20}$
|
||||
|
||||
#the word TEST below should be changed to your application
|
||||
#name - only relative URL's are supported
|
||||
Validator.Redirect=^\\/test.*$
|
||||
|
||||
# Global HTTP Validation Rules
|
||||
# Values with Base64 encoded data (e.g. encrypted state) will need at least [a-zA-Z0-9\/+=]
|
||||
Validator.HTTPScheme=^(http|https)$
|
||||
Validator.HTTPServerName=^[a-zA-Z0-9_.\\-]*$
|
||||
Validator.HTTPParameterName=^[a-zA-Z0-9_]{1,32}$
|
||||
Validator.HTTPParameterValue=^[a-zA-Z0-9.\\-\\/+=@_ ]*$
|
||||
Validator.HTTPCookieName=^[a-zA-Z0-9\\-_]{1,32}$
|
||||
Validator.HTTPCookieValue=^[a-zA-Z0-9\\-\\/+=_ ]*$
|
||||
Validator.HTTPHeaderName=^[a-zA-Z0-9\\-_]{1,32}$
|
||||
Validator.HTTPHeaderValue=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ ]*$
|
||||
Validator.HTTPContextPath=^\\/?[a-zA-Z0-9.\\-\\/_]*$
|
||||
Validator.HTTPServletPath=^[a-zA-Z0-9.\\-\\/_]*$
|
||||
Validator.HTTPPath=^[a-zA-Z0-9.\\-_]*$
|
||||
Validator.HTTPQueryString=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ %]*$
|
||||
Validator.HTTPURI=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ ]*$
|
||||
Validator.HTTPURL=^.*$
|
||||
Validator.HTTPJSESSIONID=^[A-Z0-9]{10,30}$
|
||||
|
||||
# Validation of file related input
|
||||
Validator.FileName=^[a-zA-Z0-9!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$
|
||||
Validator.DirectoryName=^[a-zA-Z0-9:/\\\\!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$
|
||||
|
||||
# Validation of dates. Controls whether or not 'lenient' dates are accepted.
|
||||
# See DataFormat.setLenient(boolean flag) for further details.
|
||||
Validator.AcceptLenientDates=false
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
<?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>
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
com.baeldung.javac.SampleJavacPlugin
|
||||
@@ -1,3 +0,0 @@
|
||||
UK
|
||||
US
|
||||
Germany
|
||||
@@ -1,3 +0,0 @@
|
||||
1|IND|India
|
||||
2|MY|Malaysia
|
||||
3|AU|Australia
|
||||
|
@@ -1,6 +0,0 @@
|
||||
dataSourceClassName=//TBD
|
||||
dataSource.user=//TBD
|
||||
dataSource.password=//TBD
|
||||
dataSource.databaseName=//TBD
|
||||
dataSource.portNumber=//TBD
|
||||
dataSource.serverName=//TBD
|
||||
@@ -1,15 +0,0 @@
|
||||
var first = {
|
||||
name: "Whiskey",
|
||||
age: 5
|
||||
};
|
||||
|
||||
var second = {
|
||||
volume: 100
|
||||
};
|
||||
|
||||
Object.bindProperties(first, second);
|
||||
|
||||
print(first.volume);
|
||||
|
||||
second.volume = 1000;
|
||||
print(first.volume);
|
||||
@@ -1 +0,0 @@
|
||||
print(__FILE__, __LINE__, __DIR__);
|
||||
@@ -1,19 +0,0 @@
|
||||
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;
|
||||
@@ -1,11 +0,0 @@
|
||||
var demo = {
|
||||
__noSuchProperty__: function (propName) {
|
||||
print("Accessed non-existing property: " + propName);
|
||||
},
|
||||
|
||||
__noSuchMethod__: function (methodName) {
|
||||
print("Invoked non-existing method: " + methodName);
|
||||
}
|
||||
};
|
||||
|
||||
demo;
|
||||
@@ -1 +0,0 @@
|
||||
function increment(num) ++num;
|
||||
@@ -1,2 +0,0 @@
|
||||
print(" hello world".trimLeft());
|
||||
print("hello world ".trimRight());
|
||||
@@ -1,9 +0,0 @@
|
||||
function arrays(arr) {
|
||||
|
||||
var javaIntArray = Java.to(arr, "int[]");
|
||||
print(javaIntArray[0]);
|
||||
print(javaIntArray[1]);
|
||||
print(javaIntArray[2]);
|
||||
}
|
||||
|
||||
arrays([100, "1654", true]);
|
||||
@@ -1,69 +0,0 @@
|
||||
package com.baeldung.copyfiles;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class 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())));
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
package com.baeldung.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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
package com.baeldung.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.baeldung.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());
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package com.baeldung.file;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.io.CharSink;
|
||||
import com.google.common.io.FileWriteMode;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.util.StreamUtils;
|
||||
|
||||
public class 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");
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package com.baeldung.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.baeldung.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));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.filesystem.jndi.test;
|
||||
package com.baeldung.filesystem.jndi;
|
||||
|
||||
import com.baeldung.filesystem.jndi.LookupFSJNDI;
|
||||
import org.junit.Test;
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java.mimetype;
|
||||
package com.baeldung.mimetype;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.baeldung.java.io;
|
||||
package com.baeldung.readfile;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Ignore;
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java8;
|
||||
package com.baeldung.size;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@@ -18,7 +18,7 @@ public class JavaFileSizeUnitTest {
|
||||
@Before
|
||||
public void init() {
|
||||
final String separator = File.separator;
|
||||
filePath = String.join(separator, new String[] { "src", "test", "resources", "testFolder", "sample_file_1.in" });
|
||||
filePath = String.join(separator, new String[] { "src", "test", "resources", "size", "sample_file_1.in" });
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.java8;
|
||||
package com.baeldung.size;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@@ -25,7 +25,7 @@ public class JavaFolderSizeUnitTest {
|
||||
@Before
|
||||
public void init() {
|
||||
final String separator = File.separator;
|
||||
path = String.format("src%stest%sresources%stestFolder", separator, separator, separator);
|
||||
path = String.format("src%stest%sresources%ssize", separator, separator, separator);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1,52 +0,0 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileCopyUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingStream_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_stream.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_stream.txt");
|
||||
FileCopy.copyFileUsingStream(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFiles_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_files.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_files.txt");
|
||||
FileCopy.copyFileUsingJavaFiles(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingChannel_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_channel.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_channel.txt");
|
||||
FileCopy.copyFileUsingChannel(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingApache_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_apache.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_apache.txt");
|
||||
FileCopy.copyFileUsingApacheCommonsIO(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package org.baeldung.core.exceptions;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
public class FileNotFoundExceptionUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(FileNotFoundExceptionUnitTest.class);
|
||||
|
||||
private String fileName = Double.toString(Math.random());
|
||||
|
||||
@Test(expected = BusinessException.class)
|
||||
public void raiseBusinessSpecificException() throws IOException {
|
||||
try {
|
||||
readFailingFile();
|
||||
} catch (FileNotFoundException ex) {
|
||||
throw new BusinessException("BusinessException: necessary file was not present.");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createFile() throws IOException {
|
||||
try {
|
||||
readFailingFile();
|
||||
} catch (FileNotFoundException ex) {
|
||||
try {
|
||||
new File(fileName).createNewFile();
|
||||
readFailingFile();
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException("BusinessException: even creation is not possible.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void logError() throws IOException {
|
||||
try {
|
||||
readFailingFile();
|
||||
} catch (FileNotFoundException ex) {
|
||||
LOG.error("Optional file " + fileName + " was not found.");
|
||||
}
|
||||
}
|
||||
|
||||
private void readFailingFile() throws IOException {
|
||||
BufferedReader rd = new BufferedReader(new FileReader(new File(fileName)));
|
||||
rd.readLine();
|
||||
// no need to close file
|
||||
}
|
||||
|
||||
private class BusinessException extends RuntimeException {
|
||||
BusinessException(String string) {
|
||||
super(string);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,258 +0,0 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.Reader;
|
||||
import java.io.StringReader;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.commons.io.input.CharSequenceReader;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.io.CharSink;
|
||||
import com.google.common.io.CharSource;
|
||||
import com.google.common.io.CharStreams;
|
||||
import com.google.common.io.FileWriteMode;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public class JavaReaderToXUnitTest {
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
private static final int DEFAULT_SIZE = 1500000;
|
||||
|
||||
// tests - sandbox
|
||||
|
||||
// tests - Reader to String
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingReaderIntoStringV1_thenCorrect() throws IOException {
|
||||
final Reader reader = new StringReader("With Java 1");
|
||||
int intValueOfChar;
|
||||
String targetString = "";
|
||||
while ((intValueOfChar = reader.read()) != -1) {
|
||||
targetString += (char) intValueOfChar;
|
||||
}
|
||||
reader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingReaderIntoStringV2_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Java 1");
|
||||
final char[] arr = new char[8 * 1024];
|
||||
final StringBuilder buffer = new StringBuilder();
|
||||
int numCharsRead;
|
||||
while ((numCharsRead = initialReader.read(arr, 0, arr.length)) != -1) {
|
||||
buffer.append(arr, 0, numCharsRead);
|
||||
}
|
||||
initialReader.close();
|
||||
final String targetString = buffer.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingReaderIntoString_thenCorrect() throws IOException {
|
||||
final Reader initialReader = CharSource.wrap("With Google Guava").openStream();
|
||||
final String targetString = CharStreams.toString(initialReader);
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoString_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Apache Commons");
|
||||
final String targetString = IOUtils.toString(initialReader);
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
// tests - Reader WRITE TO File
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenWritingReaderContentsToFile_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("Some text");
|
||||
|
||||
int intValueOfChar;
|
||||
final StringBuilder buffer = new StringBuilder();
|
||||
while ((intValueOfChar = initialReader.read()) != -1) {
|
||||
buffer.append((char) intValueOfChar);
|
||||
}
|
||||
initialReader.close();
|
||||
|
||||
final File targetFile = new File("src/test/resources/targetFile.txt");
|
||||
targetFile.createNewFile();
|
||||
|
||||
final Writer targetFileWriter = new FileWriter(targetFile);
|
||||
targetFileWriter.write(buffer.toString());
|
||||
targetFileWriter.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenWritingReaderContentsToFile_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("Some text");
|
||||
|
||||
final File targetFile = new File("src/test/resources/targetFile.txt");
|
||||
com.google.common.io.Files.touch(targetFile);
|
||||
final CharSink charSink = com.google.common.io.Files.asCharSink(targetFile, Charset.defaultCharset(), FileWriteMode.APPEND);
|
||||
charSink.writeFrom(initialReader);
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenWritingReaderContentsToFile_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new CharSequenceReader("CharSequenceReader extends Reader");
|
||||
|
||||
final File targetFile = new File("src/test/resources/targetFile.txt");
|
||||
FileUtils.touch(targetFile);
|
||||
final byte[] buffer = IOUtils.toByteArray(initialReader);
|
||||
FileUtils.writeByteArrayToFile(targetFile, buffer);
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
// tests - Reader to byte[]
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingReaderIntoByteArray_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Java");
|
||||
|
||||
final char[] charArray = new char[8 * 1024];
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
int numCharsRead;
|
||||
while ((numCharsRead = initialReader.read(charArray, 0, charArray.length)) != -1) {
|
||||
builder.append(charArray, 0, numCharsRead);
|
||||
}
|
||||
final byte[] targetArray = builder.toString().getBytes();
|
||||
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingReaderIntoByteArray_thenCorrect() throws IOException {
|
||||
final Reader initialReader = CharSource.wrap("With Google Guava").openStream();
|
||||
|
||||
final byte[] targetArray = CharStreams.toString(initialReader).getBytes();
|
||||
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoByteArray_thenCorrect() throws IOException {
|
||||
final StringReader initialReader = new StringReader("With Commons IO");
|
||||
|
||||
final byte[] targetArray = IOUtils.toByteArray(initialReader);
|
||||
|
||||
initialReader.close();
|
||||
}
|
||||
|
||||
// tests - Reader to InputStream
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Java");
|
||||
|
||||
final char[] charBuffer = new char[8 * 1024];
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
int numCharsRead;
|
||||
while ((numCharsRead = initialReader.read(charBuffer, 0, charBuffer.length)) != -1) {
|
||||
builder.append(charBuffer, 0, numCharsRead);
|
||||
}
|
||||
final InputStream targetStream = new ByteArrayInputStream(builder.toString().getBytes());
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Guava");
|
||||
|
||||
final InputStream targetStream = new ByteArrayInputStream(CharStreams.toString(initialReader).getBytes());
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Commons IO");
|
||||
|
||||
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader));
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStream_thenCorrect() throws IOException {
|
||||
String initialString = "With Commons IO";
|
||||
final Reader initialReader = new StringReader(initialString);
|
||||
|
||||
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader));
|
||||
|
||||
final String finalString = IOUtils.toString(targetStream);
|
||||
assertThat(finalString, equalTo(initialString));
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
// tests - Reader to InputStream with encoding
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingReaderIntoInputStreamWithCharset() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Java");
|
||||
|
||||
final char[] charBuffer = new char[8 * 1024];
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
int numCharsRead;
|
||||
while ((numCharsRead = initialReader.read(charBuffer, 0, charBuffer.length)) != -1) {
|
||||
builder.append(charBuffer, 0, numCharsRead);
|
||||
}
|
||||
final InputStream targetStream = new ByteArrayInputStream(builder.toString().getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingReaderIntoInputStreamWithCharset_thenCorrect() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Guava");
|
||||
|
||||
final InputStream targetStream = new ByteArrayInputStream(CharStreams.toString(initialReader).getBytes(Charsets.UTF_8));
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding() throws IOException {
|
||||
final Reader initialReader = new StringReader("With Commons IO");
|
||||
|
||||
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8);
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingReaderIntoInputStreamWithEncoding_thenCorrect() throws IOException {
|
||||
String initialString = "With Commons IO";
|
||||
final Reader initialReader = new StringReader(initialString);
|
||||
final InputStream targetStream = IOUtils.toInputStream(IOUtils.toString(initialReader), Charsets.UTF_8);
|
||||
|
||||
String finalString = IOUtils.toString(targetStream, Charsets.UTF_8);
|
||||
assertThat(finalString, equalTo(initialString));
|
||||
|
||||
initialReader.close();
|
||||
targetStream.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class JavaXToByteArrayUnitTest {
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
// tests - X to Byte Array
|
||||
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
package org.baeldung.java.io;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.io.StringReader;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.commons.io.input.CharSequenceReader;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.io.ByteSource;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.google.common.io.CharSource;
|
||||
|
||||
public class JavaXToReaderUnitTest {
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
// tests - String to Reader
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingStringIntoReader_thenCorrect() throws IOException {
|
||||
final String initialString = "With Plain Java";
|
||||
final Reader targetReader = new StringReader(initialString);
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingStringIntoReader_thenCorrect() throws IOException {
|
||||
final String initialString = "With Google Guava";
|
||||
final Reader targetReader = CharSource.wrap(initialString).openStream();
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingStringIntoReader_thenCorrect() throws IOException {
|
||||
final String initialString = "With Apache Commons IO";
|
||||
final Reader targetReader = new CharSequenceReader(initialString);
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
// tests - byte array to Reader
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = "Hello world!".getBytes();
|
||||
final Reader targetReader = new StringReader(new String(initialArray));
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava2_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = "Hello world!".getBytes();
|
||||
final Reader targetReader = new InputStreamReader(new ByteArrayInputStream(initialArray));
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = "With Guava".getBytes();
|
||||
final String bufferString = new String(initialArray);
|
||||
final Reader targetReader = CharSource.wrap(bufferString).openStream();
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingByteArrayIntoReader_thenCorrect() throws IOException {
|
||||
final byte[] initialArray = "With Commons IO".getBytes();
|
||||
final Reader targetReader = new CharSequenceReader(new String(initialArray));
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
// tests - File to Reader
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingFileIntoReader_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/test/resources/initialFile.txt");
|
||||
initialFile.createNewFile();
|
||||
final Reader targetReader = new FileReader(initialFile);
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingFileIntoReader_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/test/resources/initialFile.txt");
|
||||
com.google.common.io.Files.touch(initialFile);
|
||||
final Reader targetReader = com.google.common.io.Files.newReader(initialFile, Charset.defaultCharset());
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingFileIntoReader_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/test/resources/initialFile.txt");
|
||||
FileUtils.touch(initialFile);
|
||||
FileUtils.write(initialFile, "With Commons IO");
|
||||
final byte[] buffer = FileUtils.readFileToByteArray(initialFile);
|
||||
final Reader targetReader = new CharSequenceReader(new String(buffer));
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
// tests - InputStream to Reader
|
||||
|
||||
@Test
|
||||
public void givenUsingPlainJava_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = new ByteArrayInputStream("With Java".getBytes());
|
||||
final Reader targetReader = new InputStreamReader(initialStream);
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingGuava_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = ByteSource.wrap("With Guava".getBytes()).openStream();
|
||||
final byte[] buffer = ByteStreams.toByteArray(initialStream);
|
||||
final Reader targetReader = CharSource.wrap(new String(buffer)).openStream();
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingCommonsIO_whenConvertingInputStreamIntoReader_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = IOUtils.toInputStream("With Commons IO");
|
||||
final byte[] buffer = IOUtils.toByteArray(initialStream);
|
||||
final Reader targetReader = new CharSequenceReader(new String(buffer));
|
||||
|
||||
targetReader.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
package org.baeldung.writetofile;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileLock;
|
||||
import java.nio.channels.OverlappingFileLockException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaWriteToFileUnitTest {
|
||||
|
||||
private String fileName = "src/test/resources/test_write.txt";
|
||||
private String fileName1 = "src/test/resources/test_write_1.txt";
|
||||
private String fileName2 = "src/test/resources/test_write_2.txt";
|
||||
private String fileName3 = "src/test/resources/test_write_3.txt";
|
||||
private String fileName4 = "src/test/resources/test_write_4.txt";
|
||||
private String fileName5 = "src/test/resources/test_write_5.txt";
|
||||
|
||||
@Test
|
||||
public void whenWriteStringUsingBufferedWritter_thenCorrect() throws IOException {
|
||||
final String str = "Hello";
|
||||
final BufferedWriter writer = new BufferedWriter(new FileWriter(fileName3));
|
||||
writer.write(str);
|
||||
writer.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendStringUsingBufferedWritter_thenOldContentShouldExistToo() throws IOException {
|
||||
final String str = "World";
|
||||
final BufferedWriter writer = new BufferedWriter(new FileWriter(fileName3, true));
|
||||
writer.append(' ');
|
||||
writer.append(str);
|
||||
writer.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWritingStringToFile_whenUsingPrintWriter_thenCorrect() throws IOException {
|
||||
final FileWriter fileWriter = new FileWriter(fileName);
|
||||
final PrintWriter printWriter = new PrintWriter(fileWriter);
|
||||
printWriter.print("Some String");
|
||||
printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
|
||||
printWriter.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWritingStringToFile_whenUsingFileOutputStream_thenCorrect() throws IOException {
|
||||
final String str = "Hello";
|
||||
final FileOutputStream outputStream = new FileOutputStream(fileName3);
|
||||
final byte[] strToBytes = str.getBytes();
|
||||
outputStream.write(strToBytes);
|
||||
outputStream.close();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void givenWritingToFile_whenUsingDataOutputStream_thenCorrect() throws IOException {
|
||||
final String value = "Hello";
|
||||
final FileOutputStream fos = new FileOutputStream(fileName1);
|
||||
final DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
|
||||
outStream.writeUTF(value);
|
||||
outStream.close();
|
||||
|
||||
String result;
|
||||
final FileInputStream fis = new FileInputStream(fileName1);
|
||||
final DataInputStream reader = new DataInputStream(fis);
|
||||
result = reader.readUTF();
|
||||
reader.close();
|
||||
|
||||
assertEquals(value, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWritingToSpecificPositionInFile_thenCorrect() throws IOException {
|
||||
final int data1 = 2014;
|
||||
final int data2 = 1500;
|
||||
writeToPosition(fileName2, data1, 4);
|
||||
assertEquals(data1, readFromPosition(fileName2, 4));
|
||||
writeToPosition(fileName2, data2, 4);
|
||||
assertEquals(data2, readFromPosition(fileName2, 4));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTryToLockFile_thenItShouldBeLocked() throws IOException {
|
||||
final RandomAccessFile stream = new RandomAccessFile(fileName4, "rw");
|
||||
final FileChannel channel = stream.getChannel();
|
||||
|
||||
FileLock lock = null;
|
||||
try {
|
||||
lock = channel.tryLock();
|
||||
} catch (final OverlappingFileLockException e) {
|
||||
stream.close();
|
||||
channel.close();
|
||||
}
|
||||
stream.writeChars("test lock");
|
||||
lock.release();
|
||||
|
||||
stream.close();
|
||||
channel.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWritingToFile_whenUsingFileChannel_thenCorrect() throws IOException {
|
||||
final RandomAccessFile stream = new RandomAccessFile(fileName5, "rw");
|
||||
final FileChannel channel = stream.getChannel();
|
||||
final String value = "Hello";
|
||||
final byte[] strBytes = value.getBytes();
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
|
||||
buffer.put(strBytes);
|
||||
buffer.flip();
|
||||
channel.write(buffer);
|
||||
stream.close();
|
||||
channel.close();
|
||||
|
||||
final RandomAccessFile reader = new RandomAccessFile(fileName5, "r");
|
||||
assertEquals(value, reader.readLine());
|
||||
reader.close();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWriteToTmpFile_thenCorrect() throws IOException {
|
||||
final String toWrite = "Hello";
|
||||
final File tmpFile = File.createTempFile("test", ".tmp");
|
||||
final FileWriter writer = new FileWriter(tmpFile);
|
||||
writer.write(toWrite);
|
||||
writer.close();
|
||||
|
||||
final BufferedReader reader = new BufferedReader(new FileReader(tmpFile));
|
||||
assertEquals(toWrite, reader.readLine());
|
||||
reader.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingJava7_whenWritingToFile_thenCorrect() throws IOException {
|
||||
final String str = "Hello";
|
||||
|
||||
final Path path = Paths.get(fileName3);
|
||||
final byte[] strToBytes = str.getBytes();
|
||||
|
||||
Files.write(path, strToBytes);
|
||||
|
||||
final String read = Files.readAllLines(path, Charset.defaultCharset()).get(0);
|
||||
assertEquals(str, read);
|
||||
}
|
||||
|
||||
// UTIL
|
||||
|
||||
// use RandomAccessFile to write data at specific position in the file
|
||||
private void writeToPosition(final String filename, final int data, final long position) throws IOException {
|
||||
final RandomAccessFile writer = new RandomAccessFile(filename, "rw");
|
||||
writer.seek(position);
|
||||
writer.writeInt(data);
|
||||
writer.close();
|
||||
}
|
||||
|
||||
// use RandomAccessFile to read data from specific position in the file
|
||||
private int readFromPosition(final String filename, final long position) throws IOException {
|
||||
int result = 0;
|
||||
final RandomAccessFile reader = new RandomAccessFile(filename, "r");
|
||||
reader.seek(position);
|
||||
result = reader.readInt();
|
||||
reader.close();
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
@@ -1,2 +0,0 @@
|
||||
files will be copied here and then deleted
|
||||
remove `file.delete()` to see the files here
|
||||
@@ -1 +0,0 @@
|
||||
apache
|
||||
@@ -1 +0,0 @@
|
||||
channel
|
||||
@@ -1 +0,0 @@
|
||||
files
|
||||
@@ -1 +0,0 @@
|
||||
stream
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1 +0,0 @@
|
||||
This example shows how we can delete the file contents without deleting the file
|
||||
@@ -1 +0,0 @@
|
||||
With Commons IO
|
||||
@@ -1 +0,0 @@
|
||||
This is a sample txt file for unit test ListFilesUnitTest
|
||||
@@ -1 +0,0 @@
|
||||
{}
|
||||
@@ -1 +0,0 @@
|
||||
{}
|
||||
@@ -1 +0,0 @@
|
||||
<xml></xml>
|
||||
@@ -1 +0,0 @@
|
||||
Hello World
|
||||
@@ -1 +0,0 @@
|
||||
Some textSome text
|
||||
@@ -1 +0,0 @@
|
||||
Some StringProduct name is iPhone and its price is 1000 $
|
||||
Binary file not shown.
Binary file not shown.
@@ -1 +0,0 @@
|
||||
Hello World
|
||||
Binary file not shown.
@@ -1 +0,0 @@
|
||||
Hello
|
||||
Reference in New Issue
Block a user