This commit is contained in:
orrym 2018-03-05 20:02:25 +02:00
commit 0a40f30578
339 changed files with 2707 additions and 3459 deletions

View File

@ -41,3 +41,5 @@
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)

View File

@ -1,26 +1,5 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
*.txt
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml
# *.txt
/temp

View File

@ -1,5 +1,4 @@
<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">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-io</artifactId>
@ -211,16 +210,6 @@
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.5.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
@ -264,99 +253,6 @@
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<executions>
<execution>
<configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
@ -384,19 +280,19 @@
<argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument>
<classpath/>
<classpath />
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.0.0-M1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<target>1.8</target>
</configuration>
</plugin>
@ -442,7 +338,7 @@
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase>-->
<!-- <phase>integration-test</phase> -->
<phase>none</phase>
<goals>
<goal>exec</goal>
@ -452,7 +348,7 @@
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath/>
<classpath />
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
@ -490,7 +386,7 @@
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>

View File

@ -10,7 +10,7 @@ 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"));
@ -25,5 +25,5 @@ public class DirectoryWatcherExample {
watchService.close();
}
}

View File

@ -1,2 +0,0 @@
line 1
a second line

View File

@ -19,52 +19,51 @@ import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class FileCopierTest {
File original = new File("src/test/resources/original.txt");
File original = new File("src/test/resources/original.txt");
@Before
public void init() throws IOException {
if (!original.exists())
Files.createFile(original.toPath());
}
@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 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 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 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())));
}
@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

@ -3,7 +3,6 @@ package com.baeldung.file;
import org.apache.commons.io.FileUtils;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import java.io.BufferedReader;

View File

@ -42,19 +42,14 @@ public class FilesTest {
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");
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");
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
@ -62,9 +57,7 @@ public class FilesTest {
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");
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
@ -73,9 +66,7 @@ public class FilesTest {
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");
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
@ -86,9 +77,6 @@ public class FilesTest {
bw.newLine();
bw.close();
assertThat(
StreamUtils.getStringFromInputStream(
new FileInputStream(fileName)))
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n");
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n");
}
}

View File

@ -35,7 +35,7 @@ public class LookupFSJNDIIntegrationTest {
@Test
public void givenInitialContext_whenLokupFileExists_thenSuccess() {
File file = fsjndi.getFile(FILENAME);
assertNotNull("File exists", file);
File file = fsjndi.getFile(FILENAME);
assertNotNull("File exists", file);
}
}

View File

@ -9,7 +9,6 @@ import java.net.URI;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import org.junit.Test;

View File

@ -17,18 +17,19 @@ import java.util.concurrent.Future;
import static org.junit.Assert.assertEquals;
public class AsyncFileIntegrationTest {
@Test
public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
final Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
final ByteBuffer buffer = ByteBuffer.allocate(1024);
Future<Integer> operation = fileChannel.read(buffer, 0);
final Future<Integer> operation = fileChannel.read(buffer, 0);
operation.get();
String fileContent = new String(buffer.array()).trim();
final String fileContent = new String(buffer.array()).trim();
buffer.clear();
assertEquals(fileContent, "baeldung.com");
@ -36,18 +37,16 @@ public class AsyncFileIntegrationTest {
@Test
public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException {
Path path = Paths.get(URI.create(AsyncFileIntegrationTest.class.getResource("/file.txt").toString()));
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
final Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
final ByteBuffer buffer = ByteBuffer.allocate(1024);
fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
// result is number of bytes read
// attachment is the buffer
}
@Override
@ -59,42 +58,40 @@ public class AsyncFileIntegrationTest {
@Test
public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
String fileName = "temp";
Path path = Paths.get(fileName);
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
final String fileName = "temp";
final Path path = Paths.get(fileName);
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
ByteBuffer buffer = ByteBuffer.allocate(1024);
long position = 0;
final ByteBuffer buffer = ByteBuffer.allocate(1024);
final long position = 0;
buffer.put("hello world".getBytes());
buffer.flip();
Future<Integer> operation = fileChannel.write(buffer, position);
final Future<Integer> operation = fileChannel.write(buffer, position);
buffer.clear();
operation.get();
String content = readContent(path);
final String content = readContent(path);
assertEquals("hello world", content);
}
@Test
public void givenPathAndContent_whenWritesToFileWithHandler_thenCorrect() throws IOException {
String fileName = UUID.randomUUID().toString();
Path path = Paths.get(fileName);
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
final String fileName = UUID.randomUUID().toString();
final Path path = Paths.get(fileName);
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
ByteBuffer buffer = ByteBuffer.allocate(1024);
final ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("hello world".getBytes());
buffer.flip();
fileChannel.write(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
// result is number of bytes written
// attachment is the buffer
}
@Override
@ -104,23 +101,25 @@ public class AsyncFileIntegrationTest {
});
}
public static String readContent(Path file) throws ExecutionException, InterruptedException {
//
private String readContent(Path file) throws ExecutionException, InterruptedException {
AsynchronousFileChannel fileChannel = null;
try {
fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteBuffer buffer = ByteBuffer.allocate(1024);
final ByteBuffer buffer = ByteBuffer.allocate(1024);
Future<Integer> operation = fileChannel.read(buffer, 0);
final Future<Integer> operation = fileChannel.read(buffer, 0);
operation.get();
String fileContent = new String(buffer.array()).trim();
final String fileContent = new String(buffer.array()).trim();
buffer.clear();
return fileContent;
}
}

View File

@ -20,7 +20,6 @@ public class BasicAttribsIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(BasicAttribsIntegrationTest.class);
private static final String HOME = System.getProperty("user.home");
private static BasicFileAttributes basicAttribs;

View File

@ -55,12 +55,7 @@ public class JavaFolderSizeUnitTest {
@Test
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
final Path folder = Paths.get(path);
final long size = Files.walk(folder)
.filter(p -> p.toFile()
.isFile())
.mapToLong(p -> p.toFile()
.length())
.sum();
final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum();
assertEquals(EXPECTED_SIZE, size);
}
@ -77,12 +72,8 @@ public class JavaFolderSizeUnitTest {
public void whenGetFolderSizeUsingGuava_thenCorrect() {
final File folder = new File(path);
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser()
.breadthFirstTraversal(folder);
final long size = StreamSupport.stream(files.spliterator(), false)
.filter(File::isFile)
.mapToLong(File::length)
.sum();
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum();
assertEquals(EXPECTED_SIZE, size);
}

View File

@ -18,14 +18,13 @@ import static org.junit.Assert.assertNotNull;
public class MappedByteBufferUnitTest {
@Test
public void givenFileChannel_whenReadToTheMappedByteBuffer_thenShouldSuccess() throws Exception {
//given
// given
CharBuffer charBuffer = null;
Path pathToRead = getFileURIFromResources("fileToRead.txt");
//when
// when
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToRead, EnumSet.of(StandardOpenOption.READ))) {
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
@ -34,20 +33,19 @@ public class MappedByteBufferUnitTest {
}
}
//then
// then
assertNotNull(charBuffer);
assertEquals(charBuffer.toString(), "This is a content of the file");
}
@Test
public void givenPath_whenWriteToItUsingMappedByteBuffer_thenShouldSuccessfullyWrite() throws Exception {
//given
CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file");
Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt");
// given
final CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file");
final Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt");
//when
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite,
EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
// when
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite, EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length());
if (mappedByteBuffer != null) {
@ -55,14 +53,16 @@ public class MappedByteBufferUnitTest {
}
}
//then
List<String> fileContent = Files.readAllLines(pathToWrite);
// then
final List<String> fileContent = Files.readAllLines(pathToWrite);
assertEquals(fileContent.get(0), "This will be written to the file");
}
private Path getFileURIFromResources(String fileName) throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
//
private final Path getFileURIFromResources(String fileName) throws Exception {
final ClassLoader classLoader = getClass().getClassLoader();
return Paths.get(classLoader.getResource(fileName).toURI());
}
}

View File

@ -1,47 +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 FileCopyTest {
@Test
public void whenUsingStream_thenCopyFile() throws IOException {
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_stream.txt");
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_stream.txt");
FileCopy.copyFileUsingStream(src, dest);
assertTrue(dest.exists());
dest.delete();
}
@Test
public void whenUsingFiles_thenCopyFile() throws IOException {
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_files.txt");
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_files.txt");
FileCopy.copyFileUsingJavaFiles(src, dest);
assertTrue(dest.exists());
dest.delete();
}
@Test
public void whenUsingChannel_thenCopyFile() throws IOException {
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_channel.txt");
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_channel.txt");
FileCopy.copyFileUsingChannel(src, dest);
assertTrue(dest.exists());
dest.delete();
}
@Test
public void whenUsingApache_thenCopyFile() throws IOException {
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_apache.txt");
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_apache.txt");
FileCopy.copyFileUsingApacheCommonsIO(src, dest);
assertTrue(dest.exists());
dest.delete();
}
}

View File

@ -0,0 +1,52 @@
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();
}
}

View File

@ -152,11 +152,11 @@ public class JavaInputStreamToXUnitTest {
@Test
public final void whenConvertingToFile_thenCorrect() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
final byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
final File targetFile = new File("src/main/resources/targetFile.tmp");
final File targetFile = new File("src/test/resources/targetFile.tmp");
final OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
@ -166,8 +166,8 @@ public class JavaInputStreamToXUnitTest {
@Test
public final void whenConvertingInProgressToFile_thenCorrect() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
final File targetFile = new File("src/main/resources/targetFile.tmp");
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
final File targetFile = new File("src/test/resources/targetFile.tmp");
final OutputStream outStream = new FileOutputStream(targetFile);
final byte[] buffer = new byte[8 * 1024];
@ -182,8 +182,8 @@ public class JavaInputStreamToXUnitTest {
@Test
public final void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
final File targetFile = new File("src/main/resources/targetFile.tmp");
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
final File targetFile = new File("src/test/resources/targetFile.tmp");
java.nio.file.Files.copy(initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
@ -192,11 +192,11 @@ public class JavaInputStreamToXUnitTest {
@Test
public final void whenConvertingInputStreamToFile_thenCorrect3() throws IOException {
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
final byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
final File targetFile = new File("src/main/resources/targetFile.tmp");
final File targetFile = new File("src/test/resources/targetFile.tmp");
Files.write(buffer, targetFile);
IOUtils.closeQuietly(initialStream);
@ -204,13 +204,13 @@ public class JavaInputStreamToXUnitTest {
@Test
public final void whenConvertingInputStreamToFile_thenCorrect4() throws IOException {
final InputStream initialStream = FileUtils.openInputStream(new File("src/main/resources/sample.txt"));
final InputStream initialStream = FileUtils.openInputStream(new File("src/test/resources/sample.txt"));
final File targetFile = new File("src/main/resources/targetFile.tmp");
final File targetFile = new File("src/test/resources/targetFile.tmp");
FileUtils.copyInputStreamToFile(initialStream, targetFile);
}
@Test
public final void givenUsingPlainJava_whenConvertingAnInputStreamToString_thenCorrect() throws IOException {
String originalString = randomAlphabetic(8);
@ -225,7 +225,7 @@ public class JavaInputStreamToXUnitTest {
buffer.flush();
byte[] byteArray = buffer.toByteArray();
String text = new String(byteArray, StandardCharsets.UTF_8);
assertThat(text, equalTo(originalString));
}

View File

@ -18,7 +18,6 @@ import static org.junit.Assert.assertTrue;
public class JavaReadFromFileUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaReadFromFileUnitTest.class);
@Test
@ -107,11 +106,12 @@ public class JavaReadFromFileUnitTest {
@Test
public void whenReadUTFEncodedFile_thenCorrect() throws IOException {
final String expected_value = "青空";
final String expected_value = "é<EFBFBD>空";
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));
final String currentLine = reader.readLine();
reader.close();
LOG.debug(currentLine);
assertEquals(expected_value, currentLine);
}

View File

@ -68,7 +68,7 @@ public class JavaXToInputStreamUnitTest {
@Test
public final void givenUsingPlainJava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
final File initialFile = new File("src/main/resources/sample.txt");
final File initialFile = new File("src/test/resources/sample.txt");
final InputStream targetStream = new FileInputStream(initialFile);
IOUtils.closeQuietly(targetStream);
@ -76,7 +76,7 @@ public class JavaXToInputStreamUnitTest {
@Test
public final void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
final File initialFile = new File("src/main/resources/sample.txt");
final File initialFile = new File("src/test/resources/sample.txt");
final InputStream targetStream = Files.asByteSource(initialFile).openStream();
IOUtils.closeQuietly(targetStream);
@ -84,7 +84,7 @@ public class JavaXToInputStreamUnitTest {
@Test
public final void givenUsingCommonsIO_whenConvertingFileToInputStream_thenCorrect() throws IOException {
final File initialFile = new File("src/main/resources/sample.txt");
final File initialFile = new File("src/test/resources/sample.txt");
final InputStream targetStream = FileUtils.openInputStream(initialFile);
IOUtils.closeQuietly(targetStream);

View File

@ -0,0 +1 @@
With Commons IO

View File

@ -0,0 +1 @@
Hello World

View File

@ -0,0 +1 @@
Hello World

View File

@ -0,0 +1 @@
Some textSome text

View File

@ -0,0 +1 @@
Some StringProduct name is iPhone and its price is 1000 $

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1 @@
Hello World

Binary file not shown.

View File

@ -0,0 +1 @@
Hello

View File

@ -129,3 +129,11 @@
- [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize)
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
- [Method Overloading and Overriding in Java](http://www.baeldung.com/java-method-overload-override)
- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set)
- [Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
- [Java TreeMap vs HashMap](http://www.baeldung.com/java-treemap-vs-hashmap)
- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator)
- [The Trie Data Structure in Java](http://www.baeldung.com/trie-java)
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
- [How to TDD a List Implementation](http://jira.baeldung.com/browse/BAEL-1537)

View File

@ -0,0 +1,62 @@
package com.baeldung.asciiart;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
public class AsciiArt {
public AsciiArt() {
}
public void drawString(String text, String artChar, Settings settings) {
BufferedImage image = getImageIntegerMode(settings.width, settings.height);
Graphics2D graphics2D = getGraphics2D(image.getGraphics(), settings);
graphics2D.drawString(text, 6, ((int) (settings.height * 0.67)));
for (int y = 0; y < settings.height; y++) {
StringBuilder stringBuilder = new StringBuilder();
for (int x = 0; x < settings.width; x++) {
stringBuilder.append(image.getRGB(x, y) == -16777216 ? " " : artChar);
}
if (stringBuilder.toString()
.trim()
.isEmpty()) {
continue;
}
System.out.println(stringBuilder);
}
}
private BufferedImage getImageIntegerMode(int width, int height) {
return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}
private Graphics2D getGraphics2D(Graphics graphics, Settings settings) {
graphics.setFont(settings.font);
Graphics2D graphics2D = (Graphics2D) graphics;
graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
return graphics2D;
}
public class Settings {
public Font font;
public int width;
public int height;
public Settings(Font font, int width, int height) {
this.font = font;
this.width = width;
this.height = height;
}
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.casting;
import java.util.ArrayList;
import java.util.List;
public class AnimalFeederGeneric<T> {
private Class<T> type;
public AnimalFeederGeneric(Class<T> type) {
this.type = type;
}
public List<T> feed(List<Animal> animals) {
List<T> list = new ArrayList<T>();
animals.forEach(animal -> {
if (type.isInstance(animal)) {
T objAsType = type.cast(animal);
list.add(objAsType);
}
});
return list;
}
}

View File

@ -1,2 +0,0 @@
line 1
a second line

View File

@ -0,0 +1,20 @@
package com.baeldung.asciiart;
import java.awt.Font;
import org.junit.Test;
import com.baeldung.asciiart.AsciiArt.Settings;
public class AsciiArtTest {
@Test
public void givenTextWithAsciiCharacterAndSettings_shouldPrintAsciiArt() {
AsciiArt asciiArt = new AsciiArt();
String text = "BAELDUNG";
Settings settings = asciiArt.new Settings(new Font("SansSerif", Font.BOLD, 24), text.length() * 30, 30); // 30 pixel width per character
asciiArt.drawString(text, "*", settings);
}
}

View File

@ -11,6 +11,7 @@ public class CastingTest {
public void whenPrimitiveConverted_thenValueChanged() {
double myDouble = 1.1;
int myInt = (int) myDouble;
assertNotEquals(myDouble, myInt);
}
@ -55,4 +56,25 @@ public class CastingTest {
animals.add(new Dog());
new AnimalFeeder().uncheckedFeed(animals);
}
@Test
public void whenDowncastToCatWithCastMethod_thenMeowIsCalled() {
Animal animal = new Cat();
if (Cat.class.isInstance(animal)) {
Cat cat = Cat.class.cast(animal);
cat.meow();
}
}
@Test
public void whenParameterCat_thenOnlyCatsFed() {
List<Animal> animals = new ArrayList<>();
animals.add(new Cat());
animals.add(new Dog());
AnimalFeederGeneric<Cat> catFeeder = new AnimalFeederGeneric<Cat>(Cat.class);
List<Cat> fedAnimals = catFeeder.feed(animals);
assertTrue(fedAnimals.size() == 1);
assertTrue(fedAnimals.get(0) instanceof Cat);
}
}

View File

@ -1 +0,0 @@
Hello world

View File

@ -1 +0,0 @@
Hello world !

View File

@ -18,3 +18,5 @@
- [JUnit 5 for Kotlin Developers](http://www.baeldung.com/junit-5-kotlin)
- [Extension Methods in Kotlin](http://www.baeldung.com/kotlin-extension-methods)
- [Infix Functions in Kotlin](http://www.baeldung.com/kotlin-infix-functions)
- [Try-with-resources in Kotlin](http://www.baeldung.com/kotlin-try-with-resources)
- [HTTP Requests with Kotlin and khttp](http://www.baeldung.com/kotlin-khttp)

View File

@ -3,7 +3,6 @@ package com.baeldung.geotools;
import static org.junit.Assert.assertNotNull;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.junit.Test;
import org.opengis.feature.simple.SimpleFeatureType;
@ -19,4 +18,5 @@ public class GeoToolsUnitTest {
assertNotNull(collection);
}
}

View File

@ -1,2 +1,3 @@
### Relevant Articles:
- [RESTFul CRUD application with JavaLite] ()
- [A Guide to JavaLite Building a RESTful CRUD application](http://www.baeldung.com/javalite-rest)

3
java-rmi/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant articles
- [Getting Started with Java RMI](http://www.baeldung.com/java-rmi)

View File

@ -0,0 +1,14 @@
<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>exchange-rate-api</artifactId>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>java-spi</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
</project>

View File

@ -0,0 +1,42 @@
package com.baeldung.rate;
import com.baeldung.rate.exception.ProviderNotFoundException;
import com.baeldung.rate.spi.ExchangeRateProvider;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;
public final class ExchangeRate {
private static final String DEFAULT_PROVIDER = "com.baeldung.rate.spi.YahooFinanceExchangeRateProvider";
//All providers
public static List<ExchangeRateProvider> providers() {
List<ExchangeRateProvider> services = new ArrayList<>();
ServiceLoader<ExchangeRateProvider> loader = ServiceLoader.load(ExchangeRateProvider.class);
loader.forEach(exchangeRateProvider -> {
services.add(exchangeRateProvider);
});
return services;
}
//Default provider
public static ExchangeRateProvider provider() {
return provider(DEFAULT_PROVIDER);
}
//provider by name
public static ExchangeRateProvider provider(String providerName) {
ServiceLoader<ExchangeRateProvider> loader = ServiceLoader.load(ExchangeRateProvider.class);
Iterator<ExchangeRateProvider> it = loader.iterator();
while (it.hasNext()) {
ExchangeRateProvider provider = it.next();
if (providerName.equals(provider.getClass().getName())) {
return provider;
}
}
throw new ProviderNotFoundException("Exchange Rate provider " + providerName + " not found");
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.rate.api;
import java.math.BigDecimal;
import java.time.LocalDate;
public class Quote {
private String currency;
private BigDecimal ask;
private BigDecimal bid;
private LocalDate date;
//...
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public BigDecimal getAsk() {
return ask;
}
public void setAsk(BigDecimal ask) {
this.ask = ask;
}
public BigDecimal getBid() {
return bid;
}
public void setBid(BigDecimal bid) {
this.bid = bid;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.rate.api;
import java.time.LocalDate;
import java.util.List;
public interface QuoteManager {
List<Quote> getQuotes(String baseCurrency, LocalDate date);
}

View File

@ -0,0 +1,13 @@
package com.baeldung.rate.exception;
public class ProviderNotFoundException extends RuntimeException {
public ProviderNotFoundException() {
super();
}
public ProviderNotFoundException(String message) {
super(message);
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.rate.spi;
import com.baeldung.rate.api.QuoteManager;
public interface ExchangeRateProvider {
QuoteManager create();
}

View File

@ -0,0 +1,27 @@
<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>exchange-rate-app</artifactId>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>java-spi</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>exchange-rate-api</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>exchange-rate-impl</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,21 @@
package com.baeldung.rate.app;
import com.baeldung.rate.ExchangeRate;
import com.baeldung.rate.api.Quote;
import java.time.LocalDate;
import java.util.List;
public class MainApp {
public static void main(String... args) {
ExchangeRate.providers().forEach(provider -> {
System.out.println("Retreiving USD quotes from provider :" + provider);
List<Quote> quotes = provider.create().getQuotes("USD", LocalDate.now());
System.out.println(String.format("%14s%12s|%12s", "","Ask", "Bid"));
System.out.println("----------------------------------------");
quotes.forEach(quote -> {
System.out.println("USD --> " + quote.getCurrency() + " : " + String.format("%12f|%12f", quote.getAsk(), quote.getBid()));
});
});
}
}

View File

@ -0,0 +1,42 @@
<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>exchange-rate-impl</artifactId>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>java-spi</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>exchange-rate-api</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.10.0</version>
</dependency>
<dependency>
<groupId>javax.json.bind</groupId>
<artifactId>javax.json.bind-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>yasson</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,26 @@
package com.baeldung.rate.impl;
import com.baeldung.rate.api.Quote;
import java.util.List;
public class QuoteResponse {
private List<Quote> result;
private String error;
public List<Quote> getResult() {
return result;
}
public void setResult(List<Quote> result) {
this.result = result;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.rate.impl;
public class QuoteResponseWrapper {
private QuoteResponse quoteResponse;
public QuoteResponse getQuoteResponse() {
return quoteResponse;
}
public void setQuoteResponse(QuoteResponse quoteResponse) {
this.quoteResponse = quoteResponse;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.rate.impl;
import com.baeldung.rate.api.QuoteManager;
import com.baeldung.rate.spi.ExchangeRateProvider;
public class YahooFinanceExchangeRateProvider implements ExchangeRateProvider {
@Override
public QuoteManager create() {
return new YahooQuoteManagerImpl();
}
}

View File

@ -0,0 +1,65 @@
package com.baeldung.rate.impl;
import com.baeldung.rate.api.Quote;
import com.baeldung.rate.api.QuoteManager;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import javax.json.bind.JsonbBuilder;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.Currency;
import java.util.List;
public class YahooQuoteManagerImpl implements QuoteManager {
static final String URL_PROVIDER = "https://query1.finance.yahoo.com/v7/finance/quote";
OkHttpClient client = new OkHttpClient();
@Override
public List<Quote> getQuotes(String baseCurrency, LocalDate date) {
StringBuilder sb = new StringBuilder();
Currency.getAvailableCurrencies().forEach(currency -> {
if (!currency.equals(currency.getCurrencyCode())) {
sb.append(baseCurrency).append(currency.getCurrencyCode()).append("=X").append(",");
}
});
String value = "";
try {
value = URLEncoder.encode(sb.toString().substring(0, sb.toString().length() - 1), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String queryString = String.format("%s=%s", "symbols", value);
String response = doGetRequest(queryString);
System.out.println(response);
return map(response);
}
private List<Quote> map(String response) {
QuoteResponseWrapper qrw = JsonbBuilder.create().fromJson(response, QuoteResponseWrapper.class);
return qrw.getQuoteResponse().getResult();
}
String doGetRequest(String queryString) {
String fullUrl = URL_PROVIDER + "?" + queryString;
System.out.println(fullUrl);
Request request = new Request.Builder()
.url(fullUrl)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -0,0 +1 @@
com.baeldung.rate.impl.YahooFinanceExchangeRateProvider

20
java-spi/pom.xml Normal file
View File

@ -0,0 +1,20 @@
<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>java-spi</artifactId>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<module>exchange-rate-api</module>
<module>exchange-rate-impl</module>
<module>exchange-rate-app</module>
</modules>
</project>

3
jenkins/README.md Normal file
View File

@ -0,0 +1,3 @@
## Relevant articles:
- [Writing a Jenkins Plugin](http://www.baeldung.com/jenkins-custom-plugin)

View File

@ -60,6 +60,9 @@
- [Guide to google-http-client](http://www.baeldung.com/google-http-client)
- [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client)
- [Programatically Create, Configure, and Run a Tomcat Server] (http://www.baeldung.com/tomcat-programmatic-setup)
- [A Docker Guide for Java](http://www.baeldung.com/docker-java-api)
- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling)
- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic)

Binary file not shown.

View File

@ -0,0 +1 @@
log4j.rootLogger=INFO, stdout

View File

@ -1,122 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<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">
<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>libraries</artifactId>
<name>libraries</name>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>libraries</artifactId>
<name>libraries</name>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>3.3.0</version>
<type>maven-plugin</type>
</dependency>
</dependencies>
<extensions>true</extensions>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.20</version>
<configuration>
<systemProperties>
<webdriver.chrome.driver>chromedriver</webdriver.chrome.driver>
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>net.serenity-bdd.maven.plugins</groupId>
<artifactId>serenity-maven-plugin</artifactId>
<version>${serenity.plugin.version}</version>
<executions>
<execution>
<id>serenity-reports</id>
<phase>post-integration-test</phase>
<goals>
<goal>aggregate</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- JDO Plugin -->
<plugin>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-maven-plugin</artifactId>
<version>5.0.2</version>
<configuration>
<api>JDO</api>
<props>${basedir}/datanucleus.properties</props>
<log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration>
<verbose>true</verbose>
<fork>false</fork>
<!-- Solve windows line too long error -->
</configuration>
<executions>
<execution>
<phase>process-classes</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Neuroph -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<excludes>
<exclude>**/log4j.properties</exclude>
</excludes>
<archive>
<manifest>
<mainClass>com.baeldung.neuroph.NeurophXOR</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<executions>
<execution>
<id>test</id>
<phase>test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<includes>
<include>test/java/com/baeldung/neuroph/XORTest.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
<!-- /Neuroph -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client -->
<!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client -->
<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId>
@ -200,11 +95,11 @@
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>rome</groupId>
<artifactId>rome</artifactId>
@ -640,14 +535,14 @@
<version>${googleclient.version}</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson2</artifactId>
<version>${googleclient.version}</version>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson2</artifactId>
<version>${googleclient.version}</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-gson</artifactId>
<version>${googleclient.version}</version>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-gson</artifactId>
<version>${googleclient.version}</version>
</dependency>
<dependency>
<groupId>org.infinispan</groupId>
@ -655,7 +550,7 @@
<version>${infinispan.version}</version>
</dependency>
<!--Java Docker API Client-->
<!--Java Docker API Client -->
<dependency>
<groupId>com.github.docker-java</groupId>
<artifactId>docker-java</artifactId>
@ -680,23 +575,23 @@
<artifactId>jersey-client</artifactId>
<version>1.19.4</version>
</dependency>
<!--Java Docker API Client-->
<!--Java Docker API Client -->
<!-- google api -->
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>${google-api.version}</version>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>${google-api.version}</version>
</dependency>
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>${google-api.version}</version>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>${google-api.version}</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-sheets</artifactId>
<version>${google-sheets.version}</version>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-sheets</artifactId>
<version>${google-sheets.version}</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
@ -753,6 +648,108 @@
<url>https://repository.apache.org/content/groups/staging</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>3.3.0</version>
<type>maven-plugin</type>
</dependency>
</dependencies>
<extensions>true</extensions>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.20</version>
<configuration>
<systemProperties>
<webdriver.chrome.driver>chromedriver</webdriver.chrome.driver>
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>net.serenity-bdd.maven.plugins</groupId>
<artifactId>serenity-maven-plugin</artifactId>
<version>${serenity.plugin.version}</version>
<executions>
<execution>
<id>serenity-reports</id>
<phase>post-integration-test</phase>
<goals>
<goal>aggregate</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- JDO Plugin -->
<plugin>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-maven-plugin</artifactId>
<version>5.0.2</version>
<configuration>
<api>JDO</api>
<props>${basedir}/datanucleus.properties</props>
<log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration>
<verbose>true</verbose>
<fork>false</fork>
<!-- Solve windows line too long error -->
</configuration>
<executions>
<execution>
<phase>process-classes</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Neuroph -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<excludes>
<exclude>**/log4j.properties</exclude>
</excludes>
<archive>
<manifest>
<mainClass>com.baeldung.neuroph.NeurophXOR</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
<!-- /Neuroph -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<googleclient.version>1.23.0</googleclient.version>
<crdt.version>0.1.0</crdt.version>
@ -818,4 +815,5 @@
<async.http.client.version>2.2.0</async.http.client.version>
<infinispan.version>9.1.5.Final</infinispan.version>
</properties>
</project>

View File

@ -42,8 +42,7 @@ import org.bouncycastle.util.Store;
public class BouncyCastleCrypto {
public static byte[] signData(byte[] data, final X509Certificate signingCertificate, final PrivateKey signingKey)
throws CertificateEncodingException, OperatorCreationException, CMSException, IOException {
public static byte[] signData(byte[] data, final X509Certificate signingCertificate, final PrivateKey signingKey) throws CertificateEncodingException, OperatorCreationException, CMSException, IOException {
byte[] signedMessage = null;
List<X509Certificate> certList = new ArrayList<X509Certificate>();
CMSTypedData cmsData = new CMSProcessableByteArray(data);
@ -51,17 +50,14 @@ public class BouncyCastleCrypto {
Store certs = new JcaCertStore(certList);
CMSSignedDataGenerator cmsGenerator = new CMSSignedDataGenerator();
ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(signingKey);
cmsGenerator.addSignerInfoGenerator(
new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build())
.build(contentSigner, signingCertificate));
cmsGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(contentSigner, signingCertificate));
cmsGenerator.addCertificates(certs);
CMSSignedData cms = cmsGenerator.generate(cmsData, true);
signedMessage = cms.getEncoded();
return signedMessage;
}
public static boolean verifSignData(final byte[] signedData)
throws CMSException, IOException, OperatorCreationException, CertificateException {
public static boolean verifSignData(final byte[] signedData) throws CMSException, IOException, OperatorCreationException, CertificateException {
ByteArrayInputStream bIn = new ByteArrayInputStream(signedData);
ASN1InputStream aIn = new ASN1InputStream(bIn);
CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject()));
@ -81,16 +77,14 @@ public class BouncyCastleCrypto {
return true;
}
public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate)
throws CertificateEncodingException, CMSException, IOException {
public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate) throws CertificateEncodingException, CMSException, IOException {
byte[] encryptedData = null;
if (null != data && null != encryptionCertificate) {
CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator();
JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate);
cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey);
CMSTypedData msg = new CMSProcessableByteArray(data);
OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC")
.build();
OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC").build();
CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(msg, encryptor);
encryptedData = cmsEnvelopedData.getEncoded();
}

View File

@ -5,12 +5,17 @@ import net.bytebuddy.implementation.bind.annotation.BindingPriority;
public class Bar {
@BindingPriority(3)
public static String sayHelloBar() { return "Holla in Bar!"; }
public static String sayHelloBar() {
return "Holla in Bar!";
}
@BindingPriority(2)
public static String sayBar() { return "bar"; }
public String bar() { return Bar.class.getSimpleName() + " - Bar"; }
public static String sayBar() {
return "bar";
}
public String bar() {
return Bar.class.getSimpleName() + " - Bar";
}
}

View File

@ -2,6 +2,8 @@ package com.baeldung.bytebuddy;
public class Foo {
public String sayHelloFoo() { return "Hello in Foo!"; }
public String sayHelloFoo() {
return "Hello in Foo!";
}
}

View File

@ -19,9 +19,7 @@ final class DataObject {
@Override
public String toString() {
return "DataObject{" +
"data='" + data + '\'' +
'}';
return "DataObject{" + "data='" + data + '\'' + '}';
}
public static DataObject get(String data) {

View File

@ -7,9 +7,7 @@ import net.openhft.chronicle.ExcerptAppender;
public class ChronicleQueue {
static void writeToQueue(
Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue)
throws IOException {
static void writeToQueue(Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue) throws IOException {
ExcerptAppender appender = chronicle.createAppender();
appender.startExcerpt();
appender.writeUTF(stringValue);

View File

@ -24,7 +24,7 @@ public class CourseEntity {
public void setCodes(List<String> codes) {
this.codes = codes;
}
public void setStudent(String id, Student student) {
students.put(id, student);
}

View File

@ -8,33 +8,27 @@ import org.apache.commons.beanutils.PropertyUtils;
public class CourseService {
public static void setValues(Course course, String name, List<String> codes)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
public static void setValues(Course course, String name, List<String> codes) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
// Setting the simple properties
PropertyUtils.setSimpleProperty(course, "name", name);
PropertyUtils.setSimpleProperty(course, "codes", codes);
}
public static void setIndexedValue(Course course, int codeIndex, String code)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
public static void setIndexedValue(Course course, int codeIndex, String code) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
// Setting the indexed properties
PropertyUtils.setIndexedProperty(course, "codes[" + codeIndex + "]", code);
}
public static void setMappedValue(Course course, String enrollId, Student student)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
public static void setMappedValue(Course course, String enrollId, Student student) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
// Setting the mapped properties
PropertyUtils.setMappedProperty(course, "enrolledStudent(" + enrollId + ")", student);
}
public static String getNestedValue(Course course, String enrollId, String nestedPropertyName)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return (String) PropertyUtils.getNestedProperty(
course, "enrolledStudent(" + enrollId + ")." + nestedPropertyName);
public static String getNestedValue(Course course, String enrollId, String nestedPropertyName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return (String) PropertyUtils.getNestedProperty(course, "enrolledStudent(" + enrollId + ")." + nestedPropertyName);
}
public static void copyProperties(Course course, CourseEntity courseEntity)
throws IllegalAccessException, InvocationTargetException {
public static void copyProperties(Course course, CourseEntity courseEntity) throws IllegalAccessException, InvocationTargetException {
BeanUtils.copyProperties(course, courseEntity);
}
}

View File

@ -7,7 +7,7 @@ public class AuditFilter implements Filter {
@Override
public boolean postprocess(Context context, Exception exception) {
// Send notification to customer & bank.
// Send notification to customer & bank.
return false;
}

View File

@ -73,7 +73,7 @@ public class Customer implements Comparable<Customer> {
this.name = name;
this.phone = phone;
}
public Customer(String name) {
super();
this.name = name;

View File

@ -20,7 +20,6 @@ public class Email {
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
public String getAddress() {
return address;

View File

@ -26,9 +26,7 @@ public class BuilderMethods {
@Override
public int hashCode() {
return new HashCodeBuilder().append(this.intValue)
.append(this.strSample)
.toHashCode();
return new HashCodeBuilder().append(this.intValue).append(this.strSample).toHashCode();
}
@Override
@ -41,16 +39,12 @@ public class BuilderMethods {
}
final BuilderMethods otherObject = (BuilderMethods) obj;
return new EqualsBuilder().append(this.intValue, otherObject.intValue)
.append(this.strSample, otherObject.strSample)
.isEquals();
return new EqualsBuilder().append(this.intValue, otherObject.intValue).append(this.strSample, otherObject.strSample).isEquals();
}
@Override
public String toString() {
return new ToStringBuilder(this).append("INTVALUE", this.intValue)
.append("STRINGVALUE", this.strSample)
.toString();
return new ToStringBuilder(this).append("INTVALUE", this.intValue).append("STRINGVALUE", this.strSample).toString();
}
public static void main(final String[] arguments) {
@ -58,21 +52,21 @@ public class BuilderMethods {
System.out.println(simple1.getName());
System.out.println(simple1.hashCode());
System.out.println(simple1.toString());
SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer();
try {
sampleLazyInitializer.get();
} catch (ConcurrentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
SampleBackgroundInitializer sampleBackgroundInitializer = new SampleBackgroundInitializer();
sampleBackgroundInitializer.start();
// Proceed with other tasks instead of waiting for the SampleBackgroundInitializer task to finish.
try {
Object result = sampleBackgroundInitializer.get();
} catch (ConcurrentException e) {
@ -81,13 +75,13 @@ public class BuilderMethods {
}
}
class SampleBackgroundInitializer extends BackgroundInitializer<String>{
class SampleBackgroundInitializer extends BackgroundInitializer<String> {
@Override
protected String initialize() throws Exception {
return null;
}
// Any complex task that takes some time
}

View File

@ -3,7 +3,7 @@ package com.baeldung.commons.lang3;
import org.apache.commons.lang3.concurrent.LazyInitializer;
public class SampleLazyInitializer extends LazyInitializer<SampleObject> {
@Override
protected SampleObject initialize() {
return new SampleObject();

View File

@ -1,7 +1,7 @@
package com.baeldung.commons.lang3;
public class SampleObject {
//Ignored
// Ignored
}

View File

@ -53,16 +53,12 @@ class Docx4jExample {
File image = new File(imagePath);
byte[] fileContent = Files.readAllBytes(image.toPath());
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage
.createImagePart(wordPackage, fileContent);
Inline inline = imagePart.createImageInline(
"Baeldung Image", "Alt Text", 1, 2, false);
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordPackage, fileContent);
Inline inline = imagePart.createImageInline("Baeldung Image", "Alt Text", 1, 2, false);
P Imageparagraph = addImageToParagraph(inline);
mainDocumentPart.getContent().add(Imageparagraph);
int writableWidthTwips = wordPackage.getDocumentModel()
.getSections().get(0).getPageDimensions()
.getWritableWidthTwips();
int writableWidthTwips = wordPackage.getDocumentModel().getSections().get(0).getPageDimensions().getWritableWidthTwips();
int columnNumber = 3;
Tbl tbl = TblFactory.createTable(3, 3, writableWidthTwips / columnNumber);
List<Object> rows = tbl.getContent();

View File

@ -2,7 +2,6 @@ package com.baeldung.eclipsecollections;
import java.util.List;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.set.mutable.UnifiedSet;
public class ConvertContainerToAnother {

View File

@ -7,7 +7,7 @@ import fj.data.IO;
import fj.data.IOFunctions;
public class FunctionalJavaIOMain {
public static IO<Unit> printLetters(final String s) {
return () -> {
for (int i = 0; i < s.length(); i++) {
@ -21,8 +21,7 @@ public class FunctionalJavaIOMain {
F<String, IO<Unit>> printLetters = i -> printLetters(i);
IO<Unit> lowerCase = IOFunctions
.stdoutPrintln("What's your first Name ?");
IO<Unit> lowerCase = IOFunctions.stdoutPrintln("What's your first Name ?");
IO<Unit> input = IOFunctions.stdoutPrint("First Name: ");
@ -32,14 +31,11 @@ public class FunctionalJavaIOMain {
F<String, String> toUpperCase = i -> i.toUpperCase();
F<String, IO<Unit>> transformInput = F1Functions
.<String, IO<Unit>, String> o(printLetters).f(toUpperCase);
F<String, IO<Unit>> transformInput = F1Functions.<String, IO<Unit>, String> o(printLetters).f(toUpperCase);
IO<Unit> readAndPrintResult = IOFunctions.bind(readInput,
transformInput);
IO<Unit> readAndPrintResult = IOFunctions.bind(readInput, transformInput);
IO<Unit> program = IOFunctions.bind(userInput,
nothing -> readAndPrintResult);
IO<Unit> program = IOFunctions.bind(userInput, nothing -> readAndPrintResult);
IOFunctions.toSafe(program).run();

View File

@ -11,16 +11,16 @@ import fj.function.Integers;
public class FunctionalJavaMain {
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
public static void main(String[] args) {
List<Integer> fList = List.list(3, 4, 5, 6);
List<Boolean> evenList = fList.map(isEven);
Show.listShow(Show.booleanShow).println(evenList);
fList = fList.map(i -> i + 1);
Show.listShow(Show.intShow).println(fList);
Array<Integer> a = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
Array<Integer> b = a.filter(Integers.even);
Show.arrayShow(Show.intShow).println(b);
@ -28,11 +28,11 @@ public class FunctionalJavaMain {
Array<String> array = Array.array("Welcome", "To", "baeldung");
Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
System.out.println(isExist);
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
int sum = intArray.foldLeft(Integers.add, 0);
System.out.println(sum);
Option<Integer> n1 = Option.some(1);
Option<Integer> n2 = Option.some(2);

View File

@ -13,8 +13,6 @@ public class LineSplitter implements FlatMapFunction<String, Tuple2<String, Inte
public void flatMap(String value, Collector<Tuple2<String, Integer>> out) {
String[] tokens = value.toLowerCase().split("\\W+");
Stream.of(tokens)
.filter(t -> t.length() > 0)
.forEach(token -> out.collect(new Tuple2<>(token, 1)));
Stream.of(tokens).filter(t -> t.length() > 0).forEach(token -> out.collect(new Tuple2<>(token, 1)));
}
}

View File

@ -12,9 +12,7 @@ public class WordCount {
public static DataSet<Tuple2<String, Integer>> startWordCount(ExecutionEnvironment env, List<String> lines) throws Exception {
DataSet<String> text = env.fromCollection(lines);
return text.flatMap(new LineSplitter())
.groupBy(0)
.aggregate(Aggregations.SUM, 1);
return text.flatMap(new LineSplitter()).groupBy(0).aggregate(Aggregations.SUM, 1);
}
}

View File

@ -20,21 +20,13 @@ import com.google.api.services.sheets.v4.SheetsScopes;
public class GoogleAuthorizeUtil {
public static Credential authorize() throws IOException, GeneralSecurityException {
InputStream in = GoogleAuthorizeUtil.class.getResourceAsStream("/google-sheets-client-secret.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets
.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));
List<String> scopes = Arrays.asList(SheetsScopes.SPREADSHEETS);
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
.Builder(GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
clientSecrets,
scopes)
.setDataStoreFactory(new MemoryDataStoreFactory())
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
.authorize("user");
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), clientSecrets, scopes).setDataStoreFactory(new MemoryDataStoreFactory())
.setAccessType("offline").build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
return credential;
}

View File

@ -14,10 +14,7 @@ public class SheetsServiceUtil {
public static Sheets getSheetsService() throws IOException, GeneralSecurityException {
Credential credential = GoogleAuthorizeUtil.authorize();
return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(), credential)
.setApplicationName(APPLICATION_NAME)
.build();
return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), credential).setApplicationName(APPLICATION_NAME).build();
}
}

View File

@ -4,9 +4,7 @@ import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.apache.ApacheHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
@ -21,30 +19,23 @@ import java.util.concurrent.Future;
public class GitHubExample {
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
//static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport();
// static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory();
//static final JsonFactory JSON_FACTORY = new GsonFactory();
// static final JsonFactory JSON_FACTORY = new GsonFactory();
private static void run() throws Exception {
HttpRequestFactory requestFactory
= HTTP_TRANSPORT.createRequestFactory(
(HttpRequest request) -> {
request.setParser(new JsonObjectParser(JSON_FACTORY));
});
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory((HttpRequest request) -> {
request.setParser(new JsonObjectParser(JSON_FACTORY));
});
GitHubUrl url = new GitHubUrl("https://api.github.com/users");
url.per_page = 10;
url.page = 1;
HttpRequest request = requestFactory.buildGetRequest(url);
ExponentialBackOff backoff = new ExponentialBackOff.Builder()
.setInitialIntervalMillis(500)
.setMaxElapsedTimeMillis(900000)
.setMaxIntervalMillis(6000)
.setMultiplier(1.5)
.setRandomizationFactor(0.5)
.build();
ExponentialBackOff backoff = new ExponentialBackOff.Builder().setInitialIntervalMillis(500).setMaxElapsedTimeMillis(900000).setMaxIntervalMillis(6000).setMultiplier(1.5).setRandomizationFactor(0.5).build();
request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
Type type = new TypeToken<List<User>>() {}.getType();
List<User> users = (List<User>)request.execute().parseAs(type);
Type type = new TypeToken<List<User>>() {
}.getType();
List<User> users = (List<User>) request.execute().parseAs(type);
System.out.println(users);
url.appendRawPath("/eugenp");
request = requestFactory.buildGetRequest(url);

View File

@ -3,16 +3,16 @@ package com.baeldung.googlehttpclientguide;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.util.Key;
public class GitHubUrl extends GenericUrl{
public class GitHubUrl extends GenericUrl {
public GitHubUrl(String encodedUrl) {
super(encodedUrl);
}
}
@Key
public int per_page;
@Key
public int page;
}

View File

@ -16,7 +16,7 @@ public class User extends GenericJson {
private String blog;
@Key
private String email;
@Key("subscriptions_url")
private String subscriptionsUrl;
@ -71,7 +71,6 @@ public class User extends GenericJson {
@Override
public String toString() {
return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}';
}
}
}

View File

@ -1,9 +1,7 @@
package com.baeldung.hikaricp;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
@ -14,15 +12,15 @@ public class DataSource {
private static HikariDataSource ds;
static {
// config = new HikariConfig("datasource.properties");
// Properties props = new Properties();
// props.setProperty("dataSourceClassName", "org.h2.Driver");
// props.setProperty("dataSource.user", "");
// props.setProperty("dataSource.password", "");
// props.put("dataSource.logWriter", new PrintWriter(System.out));
// config = new HikariConfig(props);
// config = new HikariConfig("datasource.properties");
// Properties props = new Properties();
// props.setProperty("dataSourceClassName", "org.h2.Driver");
// props.setProperty("dataSource.user", "");
// props.setProperty("dataSource.password", "");
// props.put("dataSource.logWriter", new PrintWriter(System.out));
// config = new HikariConfig(props);
config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'");
config.setUsername("");
config.setPassword("");
@ -30,13 +28,14 @@ public class DataSource {
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
ds = new HikariDataSource(config);
// ds.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'");
// ds.setUsername("");
// ds.setPassword("");
// ds.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'");
// ds.setUsername("");
// ds.setPassword("");
}
private DataSource() {}
private DataSource() {
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();

View File

@ -12,9 +12,7 @@ public class HikariCPDemo {
public static List<Employee> fetchData() {
final String SQL_QUERY = "select * from emp";
List<Employee> employees = null;
try (Connection con = DataSource.getConnection();
PreparedStatement pst = con.prepareStatement(SQL_QUERY);
ResultSet rs = pst.executeQuery();) {
try (Connection con = DataSource.getConnection(); PreparedStatement pst = con.prepareStatement(SQL_QUERY); ResultSet rs = pst.executeQuery();) {
employees = new ArrayList<Employee>();
Employee employee;
while (rs.next()) {
@ -38,5 +36,5 @@ public class HikariCPDemo {
public static void main(String[] args) {
fetchData();
}
}

View File

@ -43,8 +43,7 @@ public class CacheConfiguration {
return this.buildCache(PASSIVATING_HELLO_WORLD_CACHE, cacheManager, listener, passivatingConfiguration());
}
private <K, V> Cache<K, V> buildCache(String cacheName, DefaultCacheManager cacheManager,
CacheListener listener, Configuration configuration) {
private <K, V> Cache<K, V> buildCache(String cacheName, DefaultCacheManager cacheManager, CacheListener listener, Configuration configuration) {
cacheManager.defineConfiguration(cacheName, configuration);
Cache<K, V> cache = cacheManager.getCache(cacheName);
@ -53,32 +52,19 @@ public class CacheConfiguration {
}
private Configuration expiringConfiguration() {
return new ConfigurationBuilder().expiration().lifespan(1, TimeUnit.SECONDS)
.build();
return new ConfigurationBuilder().expiration().lifespan(1, TimeUnit.SECONDS).build();
}
private Configuration evictingConfiguration() {
return new ConfigurationBuilder()
.memory().evictionType(EvictionType.COUNT).size(1)
.build();
return new ConfigurationBuilder().memory().evictionType(EvictionType.COUNT).size(1).build();
}
private Configuration passivatingConfiguration() {
return new ConfigurationBuilder()
.memory().evictionType(EvictionType.COUNT).size(1)
.persistence()
.passivation(true)
.addSingleFileStore()
.purgeOnStartup(true)
.location(System.getProperty("java.io.tmpdir"))
.build();
return new ConfigurationBuilder().memory().evictionType(EvictionType.COUNT).size(1).persistence().passivation(true).addSingleFileStore().purgeOnStartup(true).location(System.getProperty("java.io.tmpdir")).build();
}
private Configuration transactionalConfiguration() {
return new ConfigurationBuilder()
.transaction().transactionMode(TransactionMode.TRANSACTIONAL)
.lockingMode(LockingMode.PESSIMISTIC)
.build();
return new ConfigurationBuilder().transaction().transactionMode(TransactionMode.TRANSACTIONAL).lockingMode(LockingMode.PESSIMISTIC).build();
}
}

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