Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2018-03-05 16:54:37 +02:00
commit a3a24b7c7c
340 changed files with 2846 additions and 3459 deletions

View File

@ -0,0 +1,139 @@
package com.baeldung.ec2;
import java.util.Arrays;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
import com.amazonaws.services.ec2.model.CreateKeyPairResult;
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.DescribeKeyPairsRequest;
import com.amazonaws.services.ec2.model.DescribeKeyPairsResult;
import com.amazonaws.services.ec2.model.IpPermission;
import com.amazonaws.services.ec2.model.IpRange;
import com.amazonaws.services.ec2.model.MonitorInstancesRequest;
import com.amazonaws.services.ec2.model.RebootInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.StartInstancesRequest;
import com.amazonaws.services.ec2.model.StopInstancesRequest;
import com.amazonaws.services.ec2.model.UnmonitorInstancesRequest;
public class EC2Application {
private static final AWSCredentials credentials;
static {
// put your accesskey and secretkey here
credentials = new BasicAWSCredentials(
"<AWS accesskey>",
"<AWS secretkey>"
);
}
public static void main(String[] args) {
String yourInstanceId = "<you-instance>";
// 0) - Set up the client
AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(Regions.US_EAST_1)
.build();
// 1) - Create a security group
CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup")
.withDescription("Baeldung Security Group");
ec2Client.createSecurityGroup(createSecurityGroupRequest);
// 2) - Allow HTTP and SSH traffic
IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0");
IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
.withIpProtocol("tcp")
.withFromPort(80)
.withToPort(80);
IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
.withIpProtocol("tcp")
.withFromPort(22)
.withToPort(22);
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
.withGroupName("BaeldungSecurityGroup")
.withIpPermissions(ipPermission1, ipPermission2);
ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
// 3) - Create KeyPair
CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
.withKeyName("baeldung-key-pair");
CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest);
String privateKey = createKeyPairResult
.getKeyPair()
.getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key
// 4) - See what key-pairs you've got
DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest);
// 5) - Launch an Amazon Instance
RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html
.withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
.withMinCount(1)
.withMaxCount(1)
.withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance
.withSecurityGroups("BaeldungSecurityGroup");
ec2Client.runInstances(runInstancesRequest);
// 6) Monitor Instances
MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest()
.withInstanceIds(yourInstanceId);
ec2Client.monitorInstances(monitorInstancesRequest);
UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest()
.withInstanceIds(yourInstanceId);
ec2Client.unmonitorInstances(unmonitorInstancesRequest);
// 7) - Reboot an Instance
RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest()
.withInstanceIds(yourInstanceId);
ec2Client.rebootInstances(rebootInstancesRequest);
// 8) - Stop an Instance
StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
.withInstanceIds(yourInstanceId);
ec2Client.stopInstances(stopInstancesRequest)
.getStoppingInstances()
.get(0)
.getPreviousState()
.getName();
// 9) - Start an Instance
StartInstancesRequest startInstancesRequest = new StartInstancesRequest()
.withInstanceIds("instance-id");
ec2Client.startInstances(startInstancesRequest);
// 10) - Describe an Instance
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest);
System.out.println(response.getReservations()
.get(0)
.getInstances()
.get(0)
.getKernelId());
}
}

View File

@ -41,3 +41,5 @@
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams) - [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) - [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) - [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.* 0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests # Files generated by integration tests
*.txt # *.txt
backup-pom.xml /temp
/bin/
/temp
#IntelliJ specific
.idea/
*.iml

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" <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">
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> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>core-java-io</artifactId> <artifactId>core-java-io</artifactId>
@ -211,16 +210,6 @@
<artifactId>jmh-generator-annprocess</artifactId> <artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version> <version>1.19</version>
</dependency> </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> <dependency>
<groupId>org.hsqldb</groupId> <groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId> <artifactId>hsqldb</artifactId>
@ -264,99 +253,6 @@
</configuration> </configuration>
</plugin> </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> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
@ -384,19 +280,19 @@
<argument>-Xmx300m</argument> <argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument> <argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument> <argument>-classpath</argument>
<classpath/> <classpath />
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument> <argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments> </arguments>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>3.0.0-M1</version> <version>3.0.0-M1</version>
<configuration> <configuration>
<source>1.8</source> <source>1.8</source>
<target>1.8</target> <target>1.8</target>
</configuration> </configuration>
</plugin> </plugin>
@ -442,7 +338,7 @@
<executions> <executions>
<execution> <execution>
<id>run-benchmarks</id> <id>run-benchmarks</id>
<!-- <phase>integration-test</phase>--> <!-- <phase>integration-test</phase> -->
<phase>none</phase> <phase>none</phase>
<goals> <goals>
<goal>exec</goal> <goal>exec</goal>
@ -452,7 +348,7 @@
<executable>java</executable> <executable>java</executable>
<arguments> <arguments>
<argument>-classpath</argument> <argument>-classpath</argument>
<classpath/> <classpath />
<argument>org.openjdk.jmh.Main</argument> <argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument> <argument>.*</argument>
</arguments> </arguments>
@ -490,7 +386,7 @@
<protonpack.version>1.13</protonpack.version> <protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version> <streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version> <vavr.version>0.9.0</vavr.version>
<!-- testing --> <!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version> <org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>

View File

@ -10,7 +10,7 @@ import java.nio.file.WatchKey;
import java.nio.file.WatchService; import java.nio.file.WatchService;
public class DirectoryWatcherExample { public class DirectoryWatcherExample {
public static void main(String[] args) throws IOException, InterruptedException { public static void main(String[] args) throws IOException, InterruptedException {
WatchService watchService = FileSystems.getDefault().newWatchService(); WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get(System.getProperty("user.home")); Path path = Paths.get(System.getProperty("user.home"));
@ -25,5 +25,5 @@ public class DirectoryWatcherExample {
watchService.close(); 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.*; import static org.assertj.core.api.Assertions.*;
public class FileCopierTest { public class FileCopierTest {
File original = new File("src/test/resources/original.txt"); File original = new File("src/test/resources/original.txt");
@Before @Before
public void init() throws IOException { public void init() throws IOException {
if (!original.exists()) if (!original.exists())
Files.createFile(original.toPath()); Files.createFile(original.toPath());
} }
@Test @Test
public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException { public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithIo.txt"); File copied = new File("src/test/resources/copiedWithIo.txt");
try (InputStream in = new BufferedInputStream(new FileInputStream(original)); try (InputStream in = new BufferedInputStream(new FileInputStream(original)); OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) {
OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) { byte[] buffer = new byte[1024];
byte[] buffer = new byte[1024]; int lengthRead;
int lengthRead; while ((lengthRead = in.read(buffer)) > 0) {
while ((lengthRead = in.read(buffer)) > 0) { out.write(buffer, 0, lengthRead);
out.write(buffer, 0, lengthRead); out.flush();
out.flush(); }
} }
} assertThat(copied).exists();
assertThat(copied).exists(); assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); }
}
@Test @Test
public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException { public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithApacheCommons.txt"); File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
FileUtils.copyFile(original, copied); FileUtils.copyFile(original, copied);
assertThat(copied).exists(); assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
} }
@Test @Test
public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException { public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException {
Path copied = Paths.get("src/test/resources/copiedWithNio.txt"); Path copied = Paths.get("src/test/resources/copiedWithNio.txt");
Path originalPath = original.toPath(); Path originalPath = original.toPath();
Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING); Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING);
assertThat(copied).exists(); assertThat(copied).exists();
assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied))); assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied)));
} }
@Test @Test
public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException { public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException {
File copied = new File("src/test/resources/copiedWithApacheCommons.txt"); File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
com.google.common.io.Files.copy(original, copied); com.google.common.io.Files.copy(original, copied);
assertThat(copied).exists(); assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); 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.apache.commons.io.FileUtils;
import org.hamcrest.CoreMatchers; import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import java.io.BufferedReader; 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); CharSink chs = com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);
chs.write("Spain\r\n"); chs.write("Spain\r\n");
assertThat(StreamUtils.getStringFromInputStream( assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
new FileInputStream(fileName)))
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
} }
@Test @Test
public void whenAppendToFileUsingFiles_thenCorrect() throws IOException { public void whenAppendToFileUsingFiles_thenCorrect() throws IOException {
Files.write(Paths.get(fileName), "Spain\r\n".getBytes(), StandardOpenOption.APPEND); Files.write(Paths.get(fileName), "Spain\r\n".getBytes(), StandardOpenOption.APPEND);
assertThat(StreamUtils.getStringFromInputStream( assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
new FileInputStream(fileName)))
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
} }
@Test @Test
@ -62,9 +57,7 @@ public class FilesTest {
File file = new File(fileName); File file = new File(fileName);
FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true); FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true);
assertThat(StreamUtils.getStringFromInputStream( assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
new FileInputStream(fileName)))
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
} }
@Test @Test
@ -73,9 +66,7 @@ public class FilesTest {
fos.write("Spain\r\n".getBytes()); fos.write("Spain\r\n".getBytes());
fos.close(); fos.close();
assertThat(StreamUtils.getStringFromInputStream( assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
new FileInputStream(fileName)))
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
} }
@Test @Test
@ -86,9 +77,6 @@ public class FilesTest {
bw.newLine(); bw.newLine();
bw.close(); bw.close();
assertThat( assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n");
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 @Test
public void givenInitialContext_whenLokupFileExists_thenSuccess() { public void givenInitialContext_whenLokupFileExists_thenSuccess() {
File file = fsjndi.getFile(FILENAME); File file = fsjndi.getFile(FILENAME);
assertNotNull("File exists", file); assertNotNull("File exists", file);
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -18,14 +18,13 @@ import static org.junit.Assert.assertNotNull;
public class MappedByteBufferUnitTest { public class MappedByteBufferUnitTest {
@Test @Test
public void givenFileChannel_whenReadToTheMappedByteBuffer_thenShouldSuccess() throws Exception { public void givenFileChannel_whenReadToTheMappedByteBuffer_thenShouldSuccess() throws Exception {
//given // given
CharBuffer charBuffer = null; CharBuffer charBuffer = null;
Path pathToRead = getFileURIFromResources("fileToRead.txt"); Path pathToRead = getFileURIFromResources("fileToRead.txt");
//when // when
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToRead, EnumSet.of(StandardOpenOption.READ))) { try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToRead, EnumSet.of(StandardOpenOption.READ))) {
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size()); MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
@ -34,20 +33,19 @@ public class MappedByteBufferUnitTest {
} }
} }
//then // then
assertNotNull(charBuffer); assertNotNull(charBuffer);
assertEquals(charBuffer.toString(), "This is a content of the file"); assertEquals(charBuffer.toString(), "This is a content of the file");
} }
@Test @Test
public void givenPath_whenWriteToItUsingMappedByteBuffer_thenShouldSuccessfullyWrite() throws Exception { public void givenPath_whenWriteToItUsingMappedByteBuffer_thenShouldSuccessfullyWrite() throws Exception {
//given // given
CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file"); final CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file");
Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt"); final Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt");
//when // when
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite, try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite, EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length()); MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length());
if (mappedByteBuffer != null) { if (mappedByteBuffer != null) {
@ -55,14 +53,16 @@ public class MappedByteBufferUnitTest {
} }
} }
//then // then
List<String> fileContent = Files.readAllLines(pathToWrite); final List<String> fileContent = Files.readAllLines(pathToWrite);
assertEquals(fileContent.get(0), "This will be written to the file"); 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()); 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 @Test
public final void whenConvertingToFile_thenCorrect() throws IOException { 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()]; final byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer); 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); final OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer); outStream.write(buffer);
@ -166,8 +166,8 @@ public class JavaInputStreamToXUnitTest {
@Test @Test
public final void whenConvertingInProgressToFile_thenCorrect() throws IOException { public final void whenConvertingInProgressToFile_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 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); final OutputStream outStream = new FileOutputStream(targetFile);
final byte[] buffer = new byte[8 * 1024]; final byte[] buffer = new byte[8 * 1024];
@ -182,8 +182,8 @@ public class JavaInputStreamToXUnitTest {
@Test @Test
public final void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() throws IOException { public final void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() 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 File targetFile = new File("src/main/resources/targetFile.tmp"); final File targetFile = new File("src/test/resources/targetFile.tmp");
java.nio.file.Files.copy(initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); java.nio.file.Files.copy(initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
@ -192,11 +192,11 @@ public class JavaInputStreamToXUnitTest {
@Test @Test
public final void whenConvertingInputStreamToFile_thenCorrect3() throws IOException { 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()]; final byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer); 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); Files.write(buffer, targetFile);
IOUtils.closeQuietly(initialStream); IOUtils.closeQuietly(initialStream);
@ -204,13 +204,13 @@ public class JavaInputStreamToXUnitTest {
@Test @Test
public final void whenConvertingInputStreamToFile_thenCorrect4() throws IOException { 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); FileUtils.copyInputStreamToFile(initialStream, targetFile);
} }
@Test @Test
public final void givenUsingPlainJava_whenConvertingAnInputStreamToString_thenCorrect() throws IOException { public final void givenUsingPlainJava_whenConvertingAnInputStreamToString_thenCorrect() throws IOException {
String originalString = randomAlphabetic(8); String originalString = randomAlphabetic(8);
@ -225,7 +225,7 @@ public class JavaInputStreamToXUnitTest {
buffer.flush(); buffer.flush();
byte[] byteArray = buffer.toByteArray(); byte[] byteArray = buffer.toByteArray();
String text = new String(byteArray, StandardCharsets.UTF_8); String text = new String(byteArray, StandardCharsets.UTF_8);
assertThat(text, equalTo(originalString)); assertThat(text, equalTo(originalString));
} }

View File

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

View File

@ -68,7 +68,7 @@ public class JavaXToInputStreamUnitTest {
@Test @Test
public final void givenUsingPlainJava_whenConvertingFileToInputStream_thenCorrect() throws IOException { 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); final InputStream targetStream = new FileInputStream(initialFile);
IOUtils.closeQuietly(targetStream); IOUtils.closeQuietly(targetStream);
@ -76,7 +76,7 @@ public class JavaXToInputStreamUnitTest {
@Test @Test
public final void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect() throws IOException { 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(); final InputStream targetStream = Files.asByteSource(initialFile).openStream();
IOUtils.closeQuietly(targetStream); IOUtils.closeQuietly(targetStream);
@ -84,7 +84,7 @@ public class JavaXToInputStreamUnitTest {
@Test @Test
public final void givenUsingCommonsIO_whenConvertingFileToInputStream_thenCorrect() throws IOException { 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); final InputStream targetStream = FileUtils.openInputStream(initialFile);
IOUtils.closeQuietly(targetStream); 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) - [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) - [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) - [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() { public void whenPrimitiveConverted_thenValueChanged() {
double myDouble = 1.1; double myDouble = 1.1;
int myInt = (int) myDouble; int myInt = (int) myDouble;
assertNotEquals(myDouble, myInt); assertNotEquals(myDouble, myInt);
} }
@ -55,4 +56,25 @@ public class CastingTest {
animals.add(new Dog()); animals.add(new Dog());
new AnimalFeeder().uncheckedFeed(animals); 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) - [JUnit 5 for Kotlin Developers](http://www.baeldung.com/junit-5-kotlin)
- [Extension Methods in Kotlin](http://www.baeldung.com/kotlin-extension-methods) - [Extension Methods in Kotlin](http://www.baeldung.com/kotlin-extension-methods)
- [Infix Functions in Kotlin](http://www.baeldung.com/kotlin-infix-functions) - [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 static org.junit.Assert.assertNotNull;
import org.geotools.feature.DefaultFeatureCollection; import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.junit.Test; import org.junit.Test;
import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.simple.SimpleFeatureType;
@ -19,4 +18,5 @@ public class GeoToolsUnitTest {
assertNotNull(collection); assertNotNull(collection);
} }
} }

View File

@ -1,2 +1,3 @@
### Relevant Articles: ### 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) - [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) - [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) - [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"?> <?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" <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">
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> <parent>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
</parent> </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> <dependencies>
<!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client --> <!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client -->
<dependency> <dependency>
<groupId>org.asynchttpclient</groupId> <groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId> <artifactId>async-http-client</artifactId>
@ -200,11 +95,11 @@
<artifactId>jetty-servlet</artifactId> <artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version> <version>${jetty.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.eclipse.jetty</groupId> <groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId> <artifactId>jetty-webapp</artifactId>
<version>${jetty.version}</version> <version>${jetty.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>rome</groupId> <groupId>rome</groupId>
<artifactId>rome</artifactId> <artifactId>rome</artifactId>
@ -640,14 +535,14 @@
<version>${googleclient.version}</version> <version>${googleclient.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.http-client</groupId> <groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson2</artifactId> <artifactId>google-http-client-jackson2</artifactId>
<version>${googleclient.version}</version> <version>${googleclient.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.http-client</groupId> <groupId>com.google.http-client</groupId>
<artifactId>google-http-client-gson</artifactId> <artifactId>google-http-client-gson</artifactId>
<version>${googleclient.version}</version> <version>${googleclient.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.infinispan</groupId> <groupId>org.infinispan</groupId>
@ -655,7 +550,7 @@
<version>${infinispan.version}</version> <version>${infinispan.version}</version>
</dependency> </dependency>
<!--Java Docker API Client--> <!--Java Docker API Client -->
<dependency> <dependency>
<groupId>com.github.docker-java</groupId> <groupId>com.github.docker-java</groupId>
<artifactId>docker-java</artifactId> <artifactId>docker-java</artifactId>
@ -680,23 +575,23 @@
<artifactId>jersey-client</artifactId> <artifactId>jersey-client</artifactId>
<version>1.19.4</version> <version>1.19.4</version>
</dependency> </dependency>
<!--Java Docker API Client--> <!--Java Docker API Client -->
<!-- google api --> <!-- google api -->
<dependency> <dependency>
<groupId>com.google.api-client</groupId> <groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId> <artifactId>google-api-client</artifactId>
<version>${google-api.version}</version> <version>${google-api.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.oauth-client</groupId> <groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId> <artifactId>google-oauth-client-jetty</artifactId>
<version>${google-api.version}</version> <version>${google-api.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.apis</groupId> <groupId>com.google.apis</groupId>
<artifactId>google-api-services-sheets</artifactId> <artifactId>google-api-services-sheets</artifactId>
<version>${google-sheets.version}</version> <version>${google-sheets.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.kafka</groupId> <groupId>org.apache.kafka</groupId>
@ -753,6 +648,108 @@
<url>https://repository.apache.org/content/groups/staging</url> <url>https://repository.apache.org/content/groups/staging</url>
</repository> </repository>
</repositories> </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> <properties>
<googleclient.version>1.23.0</googleclient.version> <googleclient.version>1.23.0</googleclient.version>
<crdt.version>0.1.0</crdt.version> <crdt.version>0.1.0</crdt.version>
@ -818,4 +815,5 @@
<async.http.client.version>2.2.0</async.http.client.version> <async.http.client.version>2.2.0</async.http.client.version>
<infinispan.version>9.1.5.Final</infinispan.version> <infinispan.version>9.1.5.Final</infinispan.version>
</properties> </properties>
</project> </project>

View File

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

View File

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

View File

@ -2,6 +2,8 @@ package com.baeldung.bytebuddy;
public class Foo { 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 @Override
public String toString() { public String toString() {
return "DataObject{" + return "DataObject{" + "data='" + data + '\'' + '}';
"data='" + data + '\'' +
'}';
} }
public static DataObject get(String data) { public static DataObject get(String data) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -11,16 +11,16 @@ import fj.function.Integers;
public class FunctionalJavaMain { public class FunctionalJavaMain {
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0; public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
public static void main(String[] args) { public static void main(String[] args) {
List<Integer> fList = List.list(3, 4, 5, 6); List<Integer> fList = List.list(3, 4, 5, 6);
List<Boolean> evenList = fList.map(isEven); List<Boolean> evenList = fList.map(isEven);
Show.listShow(Show.booleanShow).println(evenList); Show.listShow(Show.booleanShow).println(evenList);
fList = fList.map(i -> i + 1); fList = fList.map(i -> i + 1);
Show.listShow(Show.intShow).println(fList); Show.listShow(Show.intShow).println(fList);
Array<Integer> a = Array.array(17, 44, 67, 2, 22, 80, 1, 27); Array<Integer> a = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
Array<Integer> b = a.filter(Integers.even); Array<Integer> b = a.filter(Integers.even);
Show.arrayShow(Show.intShow).println(b); Show.arrayShow(Show.intShow).println(b);
@ -28,11 +28,11 @@ public class FunctionalJavaMain {
Array<String> array = Array.array("Welcome", "To", "baeldung"); Array<String> array = Array.array("Welcome", "To", "baeldung");
Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
System.out.println(isExist); System.out.println(isExist);
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27); Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
int sum = intArray.foldLeft(Integers.add, 0); int sum = intArray.foldLeft(Integers.add, 0);
System.out.println(sum); System.out.println(sum);
Option<Integer> n1 = Option.some(1); Option<Integer> n1 = Option.some(1);
Option<Integer> n2 = Option.some(2); 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) { public void flatMap(String value, Collector<Tuple2<String, Integer>> out) {
String[] tokens = value.toLowerCase().split("\\W+"); String[] tokens = value.toLowerCase().split("\\W+");
Stream.of(tokens) Stream.of(tokens).filter(t -> t.length() > 0).forEach(token -> out.collect(new Tuple2<>(token, 1)));
.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 { public static DataSet<Tuple2<String, Integer>> startWordCount(ExecutionEnvironment env, List<String> lines) throws Exception {
DataSet<String> text = env.fromCollection(lines); DataSet<String> text = env.fromCollection(lines);
return text.flatMap(new LineSplitter()) return text.flatMap(new LineSplitter()).groupBy(0).aggregate(Aggregations.SUM, 1);
.groupBy(0)
.aggregate(Aggregations.SUM, 1);
} }
} }

View File

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

View File

@ -14,10 +14,7 @@ public class SheetsServiceUtil {
public static Sheets getSheetsService() throws IOException, GeneralSecurityException { public static Sheets getSheetsService() throws IOException, GeneralSecurityException {
Credential credential = GoogleAuthorizeUtil.authorize(); Credential credential = GoogleAuthorizeUtil.authorize();
return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), credential).setApplicationName(APPLICATION_NAME).build();
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.HttpRequest;
import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse; 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.HttpTransport;
import com.google.api.client.http.apache.ApacheHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser; import com.google.api.client.json.JsonObjectParser;
@ -21,30 +19,23 @@ import java.util.concurrent.Future;
public class GitHubExample { public class GitHubExample {
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); 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 JacksonFactory();
//static final JsonFactory JSON_FACTORY = new GsonFactory(); // static final JsonFactory JSON_FACTORY = new GsonFactory();
private static void run() throws Exception { private static void run() throws Exception {
HttpRequestFactory requestFactory HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory((HttpRequest request) -> {
= HTTP_TRANSPORT.createRequestFactory( request.setParser(new JsonObjectParser(JSON_FACTORY));
(HttpRequest request) -> { });
request.setParser(new JsonObjectParser(JSON_FACTORY));
});
GitHubUrl url = new GitHubUrl("https://api.github.com/users"); GitHubUrl url = new GitHubUrl("https://api.github.com/users");
url.per_page = 10; url.per_page = 10;
url.page = 1; url.page = 1;
HttpRequest request = requestFactory.buildGetRequest(url); HttpRequest request = requestFactory.buildGetRequest(url);
ExponentialBackOff backoff = new ExponentialBackOff.Builder() ExponentialBackOff backoff = new ExponentialBackOff.Builder().setInitialIntervalMillis(500).setMaxElapsedTimeMillis(900000).setMaxIntervalMillis(6000).setMultiplier(1.5).setRandomizationFactor(0.5).build();
.setInitialIntervalMillis(500)
.setMaxElapsedTimeMillis(900000)
.setMaxIntervalMillis(6000)
.setMultiplier(1.5)
.setRandomizationFactor(0.5)
.build();
request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff)); request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
Type type = new TypeToken<List<User>>() {}.getType(); Type type = new TypeToken<List<User>>() {
List<User> users = (List<User>)request.execute().parseAs(type); }.getType();
List<User> users = (List<User>) request.execute().parseAs(type);
System.out.println(users); System.out.println(users);
url.appendRawPath("/eugenp"); url.appendRawPath("/eugenp");
request = requestFactory.buildGetRequest(url); 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.http.GenericUrl;
import com.google.api.client.util.Key; import com.google.api.client.util.Key;
public class GitHubUrl extends GenericUrl{ public class GitHubUrl extends GenericUrl {
public GitHubUrl(String encodedUrl) { public GitHubUrl(String encodedUrl) {
super(encodedUrl); super(encodedUrl);
} }
@Key @Key
public int per_page; public int per_page;
@Key @Key
public int page; public int page;
} }

View File

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

View File

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

View File

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

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