Merge remote-tracking branch 'eugenp/master'
This commit is contained in:
commit
be163752ab
2
.gitignore
vendored
2
.gitignore
vendored
@ -34,8 +34,6 @@ spring-security-openid/src/main/resources/application.properties
|
||||
|
||||
spring-all/*.log
|
||||
|
||||
*.jar
|
||||
|
||||
SpringDataInjectionDemo/.mvn/wrapper/maven-wrapper.properties
|
||||
|
||||
spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties
|
||||
|
@ -4,7 +4,7 @@ before_install:
|
||||
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
|
||||
|
||||
install: skip
|
||||
script: travis_wait 60 mvn -q test -fae
|
||||
script: travis_wait 60 mvn -q test
|
||||
|
||||
sudo: required
|
||||
|
||||
|
2
activejdbc/README.md
Normal file
2
activejdbc/README.md
Normal file
@ -0,0 +1,2 @@
|
||||
### Relevant Articles:
|
||||
- [Introduction to ActiveJDBC](http://www.baeldung.com/active-jdbc)
|
@ -1,129 +1,134 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>activejdbc</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>activejdbc</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<activejdbc.version>1.4.13</activejdbc.version>
|
||||
<environments>development.test,development</environments>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<encoding>UTF-8</encoding>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>activejdbc-instrumentation</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>process-classes</phase>
|
||||
<goals>
|
||||
<goal>instrument</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>db-migrator-maven-plugin</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<configuration>
|
||||
<configFile>${project.basedir}/src/main/resources/database.properties</configFile>
|
||||
<environments>${environments}</environments>
|
||||
</configuration>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>activejdbc</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>activejdbc</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<activejdbc.version>1.4.13</activejdbc.version>
|
||||
<environments>development.test,development</environments>
|
||||
</properties>
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<encoding>UTF-8</encoding>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>activejdbc-instrumentation</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>process-classes</phase>
|
||||
<goals>
|
||||
<goal>instrument</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>db-migrator-maven-plugin</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<configuration>
|
||||
<configFile>${project.basedir}/src/main/resources/database.properties</configFile>
|
||||
<environments>${environments}</environments>
|
||||
</configuration>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>5.1.34</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.18.1</version>
|
||||
<configuration>
|
||||
<reportFormat>brief</reportFormat>
|
||||
<trimStackTrace>true</trimStackTrace>
|
||||
<useFile>false</useFile>
|
||||
<includes>
|
||||
<include>**/*Spec*.java</include>
|
||||
<include>**/*Test*.java</include>
|
||||
</includes>
|
||||
<excludes>
|
||||
<exclude>**/helpers/*</exclude>
|
||||
<exclude>**/*$*</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>activejdbc</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>opensymphony</groupId>
|
||||
<artifactId>oscache</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>5.1.34</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.18.1</version>
|
||||
<configuration>
|
||||
<reportFormat>brief</reportFormat>
|
||||
<trimStackTrace>true</trimStackTrace>
|
||||
<useFile>false</useFile>
|
||||
<includes>
|
||||
<include>**/*Spec*.java</include>
|
||||
<include>**/*Test*.java</include>
|
||||
</includes>
|
||||
<excludes>
|
||||
<exclude>**/helpers/*</exclude>
|
||||
<exclude>**/*$*</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>activejdbc</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>opensymphony</groupId>
|
||||
<artifactId>oscache</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>5.1.34</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>1.7.9</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>snapshots1</id>
|
||||
<name>JavaLite Snapshots1</name>
|
||||
<url>http://repo.javalite.io/</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>always</updatePolicy>
|
||||
<checksumPolicy>warn</checksumPolicy>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>snapshots2</id>
|
||||
<name>JavaLite Snapshots2</name>
|
||||
<url>http://repo.javalite.io/</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>always</updatePolicy>
|
||||
<checksumPolicy>warn</checksumPolicy>
|
||||
</snapshots>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>1.7.9</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>snapshots1</id>
|
||||
<name>JavaLite Snapshots1</name>
|
||||
<url>http://repo.javalite.io/</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>always</updatePolicy>
|
||||
<checksumPolicy>warn</checksumPolicy>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>snapshots2</id>
|
||||
<name>JavaLite Snapshots2</name>
|
||||
<url>http://repo.javalite.io/</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>always</updatePolicy>
|
||||
<checksumPolicy>warn</checksumPolicy>
|
||||
</snapshots>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
</project>
|
||||
|
@ -17,3 +17,6 @@
|
||||
- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance)
|
||||
- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element)
|
||||
- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm)
|
||||
- [A Maze Solver in Java](http://www.baeldung.com/java-solve-maze)
|
||||
- [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku)
|
||||
- [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words)
|
||||
|
@ -11,7 +11,11 @@
|
||||
<properties>
|
||||
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
|
@ -19,7 +19,7 @@ import java.util.List;
|
||||
import static junit.framework.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class CayenneAdvancedOperationTests {
|
||||
public class CayenneAdvancedOperationIntegrationTest {
|
||||
private static ObjectContext context = null;
|
||||
|
||||
@BeforeClass
|
@ -16,7 +16,7 @@ import static junit.framework.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
|
||||
public class CayenneOperationTests {
|
||||
public class CayenneOperationIntegrationTest {
|
||||
private static ObjectContext context = null;
|
||||
|
||||
@BeforeClass
|
3
apache-curator/README.md
Normal file
3
apache-curator/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Introduction to Apache Curator](http://www.baeldung.com/apache-curator)
|
32
apache-opennlp/pom.xml
Normal file
32
apache-opennlp/pom.xml
Normal file
@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>apache-opennlp</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.opennlp</groupId>
|
||||
<artifactId>opennlp-tools</artifactId>
|
||||
<version>1.8.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.9.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
100
apache-opennlp/src/main/resources/models/DoccatSample.txt
Normal file
100
apache-opennlp/src/main/resources/models/DoccatSample.txt
Normal file
File diff suppressed because one or more lines are too long
BIN
apache-opennlp/src/main/resources/models/en-chunker.bin
Normal file
BIN
apache-opennlp/src/main/resources/models/en-chunker.bin
Normal file
Binary file not shown.
301403
apache-opennlp/src/main/resources/models/en-lemmatizer.dict
Normal file
301403
apache-opennlp/src/main/resources/models/en-lemmatizer.dict
Normal file
File diff suppressed because it is too large
Load Diff
BIN
apache-opennlp/src/main/resources/models/en-ner-person.bin
Normal file
BIN
apache-opennlp/src/main/resources/models/en-ner-person.bin
Normal file
Binary file not shown.
BIN
apache-opennlp/src/main/resources/models/en-pos-maxent.bin
Normal file
BIN
apache-opennlp/src/main/resources/models/en-pos-maxent.bin
Normal file
Binary file not shown.
BIN
apache-opennlp/src/main/resources/models/en-sent.bin
Normal file
BIN
apache-opennlp/src/main/resources/models/en-sent.bin
Normal file
Binary file not shown.
BIN
apache-opennlp/src/main/resources/models/en-token.bin
Normal file
BIN
apache-opennlp/src/main/resources/models/en-token.bin
Normal file
Binary file not shown.
@ -0,0 +1,32 @@
|
||||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStream;
|
||||
import opennlp.tools.chunker.ChunkerME;
|
||||
import opennlp.tools.chunker.ChunkerModel;
|
||||
import opennlp.tools.postag.POSModel;
|
||||
import opennlp.tools.postag.POSTaggerME;
|
||||
import opennlp.tools.tokenize.SimpleTokenizer;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ChunkerTest {
|
||||
|
||||
@Test
|
||||
public void givenChunkerModel_whenChunk_thenChunksAreDetected() throws Exception {
|
||||
|
||||
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("He reckons the current account deficit will narrow to only 8 billion.");
|
||||
|
||||
InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin");
|
||||
POSModel posModel = new POSModel(inputStreamPOSTagger);
|
||||
POSTaggerME posTagger = new POSTaggerME(posModel);
|
||||
String tags[] = posTagger.tag(tokens);
|
||||
|
||||
InputStream inputStreamChunker = new FileInputStream("src/main/resources/models/en-chunker.bin");
|
||||
ChunkerModel chunkerModel = new ChunkerModel(inputStreamChunker);
|
||||
ChunkerME chunker = new ChunkerME(chunkerModel);
|
||||
String[] chunks = chunker.chunk(tokens, tags);
|
||||
assertThat(chunks).contains("B-NP", "B-VP", "B-NP", "I-NP", "I-NP", "I-NP", "B-VP", "I-VP", "B-PP", "B-NP", "I-NP", "I-NP", "O");
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import opennlp.tools.langdetect.Language;
|
||||
import opennlp.tools.langdetect.LanguageDetector;
|
||||
import opennlp.tools.langdetect.LanguageDetectorFactory;
|
||||
import opennlp.tools.langdetect.LanguageDetectorME;
|
||||
import opennlp.tools.langdetect.LanguageDetectorModel;
|
||||
import opennlp.tools.langdetect.LanguageDetectorSampleStream;
|
||||
import opennlp.tools.util.InputStreamFactory;
|
||||
import opennlp.tools.util.MarkableFileInputStreamFactory;
|
||||
import opennlp.tools.util.ObjectStream;
|
||||
import opennlp.tools.util.PlainTextByLineStream;
|
||||
import opennlp.tools.util.TrainingParameters;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class LanguageDetectorAndTrainingDataTest {
|
||||
|
||||
@Test
|
||||
public void givenLanguageDictionary_whenLanguageDetect_thenLanguageIsDetected() throws FileNotFoundException, IOException {
|
||||
InputStreamFactory dataIn = new MarkableFileInputStreamFactory(new File("src/main/resources/models/DoccatSample.txt"));
|
||||
ObjectStream lineStream = new PlainTextByLineStream(dataIn, "UTF-8");
|
||||
LanguageDetectorSampleStream sampleStream = new LanguageDetectorSampleStream(lineStream);
|
||||
TrainingParameters params = new TrainingParameters();
|
||||
params.put(TrainingParameters.ITERATIONS_PARAM, 100);
|
||||
params.put(TrainingParameters.CUTOFF_PARAM, 5);
|
||||
params.put("DataIndexer", "TwoPass");
|
||||
params.put(TrainingParameters.ALGORITHM_PARAM, "NAIVEBAYES");
|
||||
|
||||
LanguageDetectorModel model = LanguageDetectorME.train(sampleStream, params, new LanguageDetectorFactory());
|
||||
|
||||
LanguageDetector ld = new LanguageDetectorME(model);
|
||||
Language[] languages = ld.predictLanguages("estava em uma marcenaria na Rua Bruno");
|
||||
assertThat(Arrays.asList(languages).toString()).contains("pob (0.9999999950605625)", "ita (4.939427661577956E-9)", "spa (9.665954064665144E-15)",
|
||||
"fra (8.250349924885834E-25)");
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.InputStream;
|
||||
import opennlp.tools.lemmatizer.DictionaryLemmatizer;
|
||||
import opennlp.tools.postag.POSModel;
|
||||
import opennlp.tools.postag.POSTaggerME;
|
||||
import opennlp.tools.tokenize.SimpleTokenizer;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class LemmetizerTest {
|
||||
|
||||
@Test
|
||||
public void givenEnglishDictionary_whenLemmatize_thenLemmasAreDetected() throws Exception {
|
||||
|
||||
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("John has a sister named Penny.");
|
||||
|
||||
InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin");
|
||||
POSModel posModel = new POSModel(inputStreamPOSTagger);
|
||||
POSTaggerME posTagger = new POSTaggerME(posModel);
|
||||
String tags[] = posTagger.tag(tokens);
|
||||
InputStream dictLemmatizer = getClass().getResourceAsStream("/models/en-lemmatizer.dict");
|
||||
DictionaryLemmatizer lemmatizer = new DictionaryLemmatizer(dictLemmatizer);
|
||||
String[] lemmas = lemmatizer.lemmatize(tokens, tags);
|
||||
|
||||
assertThat(lemmas).contains("O", "have", "a", "sister", "name", "O", "O");
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import opennlp.tools.namefind.NameFinderME;
|
||||
import opennlp.tools.namefind.TokenNameFinderModel;
|
||||
import opennlp.tools.tokenize.SimpleTokenizer;
|
||||
import opennlp.tools.util.Span;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NamedEntityRecognitionTest {
|
||||
|
||||
@Test
|
||||
public void givenEnglishPersonModel_whenNER_thenPersonsAreDetected() throws Exception {
|
||||
|
||||
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("John is 26 years old. His best friend's name is Leonard. He has a sister named Penny.");
|
||||
|
||||
InputStream inputStreamNameFinder = getClass().getResourceAsStream("/models/en-ner-person.bin");
|
||||
TokenNameFinderModel model = new TokenNameFinderModel(inputStreamNameFinder);
|
||||
NameFinderME nameFinderME = new NameFinderME(model);
|
||||
List<Span> spans = Arrays.asList(nameFinderME.find(tokens));
|
||||
assertThat(spans.toString()).isEqualTo("[[0..1) person, [13..14) person, [20..21) person]");
|
||||
List<String> names = new ArrayList<String>();
|
||||
int k = 0;
|
||||
for (Span s : spans) {
|
||||
names.add("");
|
||||
for (int index = s.getStart(); index < s.getEnd(); index++) {
|
||||
names.set(k, names.get(k) + tokens[index]);
|
||||
}
|
||||
k++;
|
||||
}
|
||||
assertThat(names).contains("John","Leonard","Penny");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.InputStream;
|
||||
import opennlp.tools.postag.POSModel;
|
||||
import opennlp.tools.postag.POSTaggerME;
|
||||
import opennlp.tools.tokenize.SimpleTokenizer;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class POSTaggerTest {
|
||||
|
||||
@Test
|
||||
public void givenPOSModel_whenPOSTagging_thenPOSAreDetected() throws Exception {
|
||||
|
||||
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("John has a sister named Penny.");
|
||||
|
||||
InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin");
|
||||
POSModel posModel = new POSModel(inputStreamPOSTagger);
|
||||
POSTaggerME posTagger = new POSTaggerME(posModel);
|
||||
String tags[] = posTagger.tag(tokens);
|
||||
assertThat(tags).contains("NNP", "VBZ", "DT", "NN", "VBN", "NNP", ".");
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.InputStream;
|
||||
import opennlp.tools.sentdetect.SentenceDetectorME;
|
||||
import opennlp.tools.sentdetect.SentenceModel;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SentenceDetectionTest {
|
||||
|
||||
@Test
|
||||
public void givenEnglishModel_whenDetect_thenSentencesAreDetected() throws Exception {
|
||||
|
||||
String paragraph = "This is a statement. This is another statement. Now is an abstract word for time, "
|
||||
+ "that is always flying. And my email address is google@gmail.com.";
|
||||
|
||||
InputStream is = getClass().getResourceAsStream("/models/en-sent.bin");
|
||||
SentenceModel model = new SentenceModel(is);
|
||||
|
||||
SentenceDetectorME sdetector = new SentenceDetectorME(model);
|
||||
|
||||
String sentences[] = sdetector.sentDetect(paragraph);
|
||||
assertThat(sentences).contains("This is a statement.",
|
||||
"This is another statement.",
|
||||
"Now is an abstract word for time, that is always flying.",
|
||||
"And my email address is google@gmail.com.");
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.InputStream;
|
||||
import opennlp.tools.tokenize.SimpleTokenizer;
|
||||
import opennlp.tools.tokenize.TokenizerME;
|
||||
import opennlp.tools.tokenize.TokenizerModel;
|
||||
import opennlp.tools.tokenize.WhitespaceTokenizer;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TokenizerTest {
|
||||
|
||||
@Test
|
||||
public void givenEnglishModel_whenTokenize_thenTokensAreDetected() throws Exception {
|
||||
InputStream inputStream = getClass().getResourceAsStream("/models/en-token.bin");
|
||||
TokenizerModel model = new TokenizerModel(inputStream);
|
||||
TokenizerME tokenizer = new TokenizerME(model);
|
||||
String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource.");
|
||||
assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource", ".");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWhitespaceTokenizer_whenTokenize_thenTokensAreDetected() throws Exception {
|
||||
WhitespaceTokenizer tokenizer = WhitespaceTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource.");
|
||||
assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSimpleTokenizer_whenTokenize_thenTokensAreDetected() throws Exception {
|
||||
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource.");
|
||||
assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource", ".");
|
||||
}
|
||||
|
||||
}
|
@ -13,7 +13,11 @@
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core_2.10 -->
|
||||
<dependency>
|
||||
|
3
apache-tika/README.md
Normal file
3
apache-tika/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Content Analysis with Apache Tika](http://www.baeldung.com/apache-tika)
|
3
apache-zookeeper/README.md
Normal file
3
apache-zookeeper/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Getting Started with Java and Zookeeper](http://www.baeldung.com/java-zookeeper)
|
@ -1,36 +1,23 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-zookeeper</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-zookeeper</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.zookeeper</groupId>
|
||||
<artifactId>zookeeper</artifactId>
|
||||
<version>3.3.2</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>com.sun.jmx</groupId>
|
||||
<artifactId>jmxri</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>com.sun.jdmk</groupId>
|
||||
<artifactId>jmxtools</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>javax.jms</groupId>
|
||||
<artifactId>jms</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.zookeeper</groupId>
|
||||
<artifactId>zookeeper</artifactId>
|
||||
<version>3.4.11</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
||||
|
12
asm/pom.xml
12
asm/pom.xml
@ -1,10 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.examples</groupId>
|
||||
<artifactId>asm</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.ow2.asm</groupId>
|
||||
@ -17,12 +23,14 @@
|
||||
<version>5.2</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
<build>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
|
@ -3,4 +3,6 @@
|
||||
- [AWS Lambda Using DynamoDB With Java](http://www.baeldung.com/aws-lambda-dynamodb-java)
|
||||
- [AWS S3 with Java](http://www.baeldung.com/aws-s3-java)
|
||||
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
|
||||
- [Managing EC2 Instances in Java](http://www.baeldung.com/ec2-java)
|
||||
- [http://www.baeldung.com/aws-s3-multipart-upload](https://github.com/eugenp/tutorials/tree/master/aws)
|
||||
|
||||
|
BIN
aws/native-libs/libsqlite4java-linux-amd64-1.0.392.so
Normal file
BIN
aws/native-libs/libsqlite4java-linux-amd64-1.0.392.so
Normal file
Binary file not shown.
BIN
aws/native-libs/libsqlite4java-linux-i386-1.0.392.so
Normal file
BIN
aws/native-libs/libsqlite4java-linux-i386-1.0.392.so
Normal file
Binary file not shown.
BIN
aws/native-libs/libsqlite4java-osx-1.0.392.dylib
Normal file
BIN
aws/native-libs/libsqlite4java-osx-1.0.392.dylib
Normal file
Binary file not shown.
BIN
aws/native-libs/sqlite4java-win32-x64-1.0.392.dll
Normal file
BIN
aws/native-libs/sqlite4java-win32-x64-1.0.392.dll
Normal file
Binary file not shown.
BIN
aws/native-libs/sqlite4java-win32-x86-1.0.392.dll
Normal file
BIN
aws/native-libs/sqlite4java-win32-x86-1.0.392.dll
Normal file
Binary file not shown.
40
aws/pom.xml
40
aws/pom.xml
@ -18,10 +18,12 @@
|
||||
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
|
||||
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
|
||||
<gson.version>2.8.0</gson.version>
|
||||
<aws-java-sdk.version>1.11.154</aws-java-sdk.version>
|
||||
<aws-java-sdk.version>1.11.290</aws-java-sdk.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito-core.version>2.8.9</mockito-core.version>
|
||||
<assertj-core.version>3.8.0</assertj-core.version>
|
||||
<dynamodblocal.version>1.11.86</dynamodblocal.version>
|
||||
<dynamodblocal.repository.url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</dynamodblocal.repository.url>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@ -88,6 +90,13 @@
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>DynamoDBLocal</artifactId>
|
||||
<version>${dynamodblocal.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@ -108,6 +117,35 @@
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>2.10</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>test-compile</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includeScope>test</includeScope>
|
||||
<includeTypes>so,dll,dylib</includeTypes>
|
||||
<outputDirectory>${project.basedir}/native-libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>dynamodb-local</id>
|
||||
<name>DynamoDB Local Release Repository</name>
|
||||
<url>${dynamodblocal.repository.url}</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
</project>
|
@ -0,0 +1,51 @@
|
||||
package com.baeldung.dynamodb.entity;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey;
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
|
||||
|
||||
@DynamoDBTable(tableName = "ProductInfo")
|
||||
public class ProductInfo {
|
||||
|
||||
private String id;
|
||||
private String msrp;
|
||||
private String cost;
|
||||
|
||||
public ProductInfo() {
|
||||
}
|
||||
|
||||
public ProductInfo(String cost, String msrp) {
|
||||
this.msrp = msrp;
|
||||
this.cost = cost;
|
||||
}
|
||||
|
||||
@DynamoDBHashKey
|
||||
@DynamoDBAutoGeneratedKey
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@DynamoDBAttribute
|
||||
public String getMsrp() {
|
||||
return msrp;
|
||||
}
|
||||
|
||||
@DynamoDBAttribute
|
||||
public String getCost() {
|
||||
return cost;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setMsrp(String msrp) {
|
||||
this.msrp = msrp;
|
||||
}
|
||||
|
||||
public void setCost(String cost) {
|
||||
this.cost = cost;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.baeldung.dynamodb.repository;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class AbstractRepository<T, ID extends Serializable> {
|
||||
|
||||
protected DynamoDBMapper mapper;
|
||||
protected Class<T> entityClass;
|
||||
|
||||
protected AbstractRepository() {
|
||||
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
|
||||
|
||||
// This entityClass refers to the actual entity class in the subclass declaration.
|
||||
|
||||
// For instance, ProductInfoDAO extends AbstractDAO<ProductInfo, String>
|
||||
// In this case entityClass = ProductInfo, and ID is String type
|
||||
// which refers to the ProductInfo's partition key string value
|
||||
this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
|
||||
}
|
||||
|
||||
public void save(T t) {
|
||||
mapper.save(t);
|
||||
}
|
||||
|
||||
public T findOne(ID id) {
|
||||
return mapper.load(entityClass, id);
|
||||
}
|
||||
|
||||
/**
|
||||
* <strong>WARNING:</strong> It is not recommended to perform full table scan
|
||||
* targeting the real production environment.
|
||||
*
|
||||
* @return All items
|
||||
*/
|
||||
public List<T> findAll() {
|
||||
DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
|
||||
return mapper.scan(entityClass, scanExpression);
|
||||
}
|
||||
|
||||
public void setMapper(DynamoDBMapper dynamoDBMapper) {
|
||||
this.mapper = dynamoDBMapper;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
package com.baeldung.dynamodb.repository;
|
||||
|
||||
import com.baeldung.dynamodb.entity.ProductInfo;
|
||||
|
||||
public class ProductInfoRepository extends AbstractRepository<ProductInfo, String> {
|
||||
}
|
56
aws/src/main/java/com/baeldung/s3/MultipartUpload.java
Normal file
56
aws/src/main/java/com/baeldung/s3/MultipartUpload.java
Normal file
@ -0,0 +1,56 @@
|
||||
package com.baeldung.s3;
|
||||
|
||||
import com.amazonaws.AmazonClientException;
|
||||
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
|
||||
import com.amazonaws.event.ProgressListener;
|
||||
import com.amazonaws.regions.Regions;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
|
||||
import com.amazonaws.services.s3.model.PutObjectRequest;
|
||||
import com.amazonaws.services.s3.transfer.TransferManager;
|
||||
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
|
||||
import com.amazonaws.services.s3.transfer.Upload;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
public class MultipartUpload {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String existingBucketName = "baeldung-bucket";
|
||||
String keyName = "my-picture.jpg";
|
||||
String filePath = "documents/my-picture.jpg";
|
||||
|
||||
AmazonS3 amazonS3 = AmazonS3ClientBuilder
|
||||
.standard()
|
||||
.withCredentials(new DefaultAWSCredentialsProviderChain())
|
||||
.withRegion(Regions.DEFAULT_REGION)
|
||||
.build();
|
||||
|
||||
int maxUploadThreads = 5;
|
||||
|
||||
TransferManager tm = TransferManagerBuilder
|
||||
.standard()
|
||||
.withS3Client(amazonS3)
|
||||
.withMultipartUploadThreshold((long) (5 * 1024 * 1024))
|
||||
.withExecutorFactory(() -> Executors.newFixedThreadPool(maxUploadThreads))
|
||||
.build();
|
||||
|
||||
ProgressListener progressListener =
|
||||
progressEvent -> System.out.println("Transferred bytes: " + progressEvent.getBytesTransferred());
|
||||
|
||||
PutObjectRequest request = new PutObjectRequest(existingBucketName, keyName, new File(filePath));
|
||||
|
||||
request.setGeneralProgressListener(progressListener);
|
||||
|
||||
Upload upload = tm.upload(request);
|
||||
|
||||
try {
|
||||
upload.waitForCompletion();
|
||||
System.out.println("Upload complete.");
|
||||
} catch (AmazonClientException e) {
|
||||
System.out.println("Error occurred while uploading file");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,120 @@
|
||||
package com.baeldung.dynamodb;
|
||||
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
|
||||
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
|
||||
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
|
||||
import com.amazonaws.services.dynamodbv2.model.ResourceInUseException;
|
||||
import com.baeldung.dynamodb.entity.ProductInfo;
|
||||
import com.baeldung.dynamodb.repository.ProductInfoRepository;
|
||||
import com.baeldung.dynamodb.rule.LocalDbCreationRule;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.ClassRule;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
import static org.hamcrest.core.IsEqual.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class ProductInfoRepositoryIntegrationTest {
|
||||
|
||||
@ClassRule
|
||||
public static LocalDbCreationRule dynamoDB = new LocalDbCreationRule();
|
||||
|
||||
private static DynamoDBMapper dynamoDBMapper;
|
||||
private static AmazonDynamoDB amazonDynamoDB;
|
||||
|
||||
private ProductInfoRepository repository;
|
||||
|
||||
private static final String DYNAMODB_ENDPOINT = "amazon.dynamodb.endpoint";
|
||||
private static final String AWS_ACCESSKEY = "amazon.aws.accesskey";
|
||||
private static final String AWS_SECRETKEY = "amazon.aws.secretkey";
|
||||
|
||||
private static final String EXPECTED_COST = "20";
|
||||
private static final String EXPECTED_PRICE = "50";
|
||||
|
||||
@BeforeClass
|
||||
public static void setupClass() {
|
||||
Properties testProperties = loadFromFileInClasspath("test.properties")
|
||||
.filter(properties -> !isEmpty(properties.getProperty(AWS_ACCESSKEY)))
|
||||
.filter(properties -> !isEmpty(properties.getProperty(AWS_SECRETKEY)))
|
||||
.filter(properties -> !isEmpty(properties.getProperty(DYNAMODB_ENDPOINT)))
|
||||
.orElseThrow(() -> new RuntimeException("Unable to get all of the required test property values"));
|
||||
|
||||
String amazonAWSAccessKey = testProperties.getProperty(AWS_ACCESSKEY);
|
||||
String amazonAWSSecretKey = testProperties.getProperty(AWS_SECRETKEY);
|
||||
String amazonDynamoDBEndpoint = testProperties.getProperty(DYNAMODB_ENDPOINT);
|
||||
|
||||
amazonDynamoDB = new AmazonDynamoDBClient(new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey));
|
||||
amazonDynamoDB.setEndpoint(amazonDynamoDBEndpoint);
|
||||
dynamoDBMapper = new DynamoDBMapper(amazonDynamoDB);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
try {
|
||||
repository = new ProductInfoRepository();
|
||||
repository.setMapper(dynamoDBMapper);
|
||||
|
||||
CreateTableRequest tableRequest = dynamoDBMapper.generateCreateTableRequest(ProductInfo.class);
|
||||
|
||||
tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
|
||||
|
||||
amazonDynamoDB.createTable(tableRequest);
|
||||
} catch (ResourceInUseException e) {
|
||||
// Do nothing, table already created
|
||||
}
|
||||
|
||||
// TODO How to handle different environments. i.e. AVOID deleting all entries in ProductInfo on table
|
||||
dynamoDBMapper.batchDelete((List<ProductInfo>) repository.findAll());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenItemWithExpectedCost_whenRunFindAll_thenItemIsFound() {
|
||||
|
||||
ProductInfo productInfo = new ProductInfo(EXPECTED_COST, EXPECTED_PRICE);
|
||||
repository.save(productInfo);
|
||||
|
||||
List<ProductInfo> result = (List<ProductInfo>) repository.findAll();
|
||||
assertThat(result.size(), is(greaterThan(0)));
|
||||
assertThat(result.get(0).getCost(), is(equalTo(EXPECTED_COST)));
|
||||
}
|
||||
|
||||
private static boolean isEmpty(String inputString) {
|
||||
return inputString == null || "".equals(inputString);
|
||||
}
|
||||
|
||||
private static Optional<Properties> loadFromFileInClasspath(String fileName) {
|
||||
InputStream stream = null;
|
||||
try {
|
||||
Properties config = new Properties();
|
||||
Path configLocation = Paths.get(ClassLoader.getSystemResource(fileName).toURI());
|
||||
stream = Files.newInputStream(configLocation);
|
||||
config.load(stream);
|
||||
return Optional.of(config);
|
||||
} catch (Exception e) {
|
||||
return Optional.empty();
|
||||
} finally {
|
||||
if (stream != null) {
|
||||
try {
|
||||
stream.close();
|
||||
} catch (IOException e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.dynamodb.rule;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.local.main.ServerRunner;
|
||||
import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer;
|
||||
import org.junit.rules.ExternalResource;
|
||||
|
||||
public class LocalDbCreationRule extends ExternalResource {
|
||||
|
||||
protected DynamoDBProxyServer server;
|
||||
|
||||
public LocalDbCreationRule() {
|
||||
System.setProperty("sqlite4java.library.path", "native-libs");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void before() throws Exception {
|
||||
String port = "8000";
|
||||
this.server = ServerRunner.createServerFromCommandLineArgs(new String[]{"-inMemory", "-port", port});
|
||||
server.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void after() {
|
||||
this.stopUnchecked(server);
|
||||
}
|
||||
|
||||
protected void stopUnchecked(DynamoDBProxyServer dynamoDbServer) {
|
||||
try {
|
||||
dynamoDbServer.stop();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,61 @@
|
||||
package com.baeldung.s3;
|
||||
|
||||
import com.amazonaws.event.ProgressListener;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.model.PutObjectRequest;
|
||||
import com.amazonaws.services.s3.model.PutObjectResult;
|
||||
import com.amazonaws.services.s3.transfer.TransferManager;
|
||||
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
|
||||
import com.amazonaws.services.s3.transfer.Upload;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class MultipartUploadLiveTest {
|
||||
|
||||
private static final String BUCKET_NAME = "bucket_name";
|
||||
private static final String KEY_NAME = "picture.jpg";
|
||||
|
||||
private AmazonS3 amazonS3;
|
||||
private TransferManager tm;
|
||||
private ProgressListener progressListener;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
amazonS3 = mock(AmazonS3.class);
|
||||
tm = TransferManagerBuilder
|
||||
.standard()
|
||||
.withS3Client(amazonS3)
|
||||
.withMultipartUploadThreshold((long) (5 * 1024 * 1025))
|
||||
.withExecutorFactory(() -> Executors.newFixedThreadPool(5))
|
||||
.build();
|
||||
progressListener =
|
||||
progressEvent -> System.out.println("Transferred bytes: " + progressEvent.getBytesTransferred());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUploadingFileWithTransferManager_thenVerifyUploadRequested() {
|
||||
File file = mock(File.class);
|
||||
PutObjectResult s3Result = mock(PutObjectResult.class);
|
||||
|
||||
when(amazonS3.putObject(anyString(), anyString(), (File) any())).thenReturn(s3Result);
|
||||
when(file.getName()).thenReturn(KEY_NAME);
|
||||
|
||||
PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, KEY_NAME, file);
|
||||
request.setGeneralProgressListener(progressListener);
|
||||
|
||||
Upload upload = tm.upload(request);
|
||||
|
||||
assertThat(upload).isNotNull();
|
||||
verify(amazonS3).putObject(request);
|
||||
}
|
||||
}
|
3
aws/src/test/resources/test.properties
Normal file
3
aws/src/test/resources/test.properties
Normal file
@ -0,0 +1,3 @@
|
||||
amazon.dynamodb.endpoint=http://localhost:8000/
|
||||
amazon.aws.accesskey=key
|
||||
amazon.aws.secretkey=key2
|
10
baeldung-pmd-rules.xml
Normal file
10
baeldung-pmd-rules.xml
Normal file
@ -0,0 +1,10 @@
|
||||
<?xml version="1.0"?>
|
||||
<ruleset name="Baeldung custom pmd rules" xmlns="http://pmd.sf.net/ruleset/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
|
||||
xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd">
|
||||
<description>Baeldung custom PMD rules</description>
|
||||
<rule name="UnitTestMustFollowNamingConventionRule" message="Test class name doesn't follow the naming convention" class="org.baeldung.pmd.UnitTestNamingConventionRule">
|
||||
<description>Test does not follow Baeldung naming convention</description>
|
||||
<priority>3</priority>
|
||||
</rule>
|
||||
</ruleset>
|
@ -13,10 +13,10 @@
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<groupId>io.bootique.parent</groupId>
|
||||
<artifactId>bootique-parent</artifactId>
|
||||
<version>0.12</version>
|
||||
</parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
|
@ -1,80 +1,79 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>spring-boot-camel</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>Spring-Boot - Camel API</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-servlet-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-jackson-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-swagger-java-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-spring-boot-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<version>${spring-boot-starter.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>spring-boot-camel</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<build>
|
||||
<defaultGoal>spring-boot:run</defaultGoal>
|
||||
|
||||
<name>Spring-Boot - Camel API</name>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot-starter.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<camel.version>2.19.1</camel.version>
|
||||
<spring-boot-starter.version>1.5.4.RELEASE</spring-boot-starter.version>
|
||||
</properties>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<camel.version>2.19.1</camel.version>
|
||||
<spring-boot-starter.version>1.5.4.RELEASE</spring-boot-starter.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-servlet-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-jackson-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-swagger-java-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-spring-boot-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<version>${spring-boot-starter.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<defaultGoal>spring-boot:run</defaultGoal>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot-starter.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
|
@ -7,7 +7,12 @@
|
||||
<artifactId>cas-server</artifactId>
|
||||
<packaging>war</packaging>
|
||||
<version>1.0</version>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.0.M7</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
3
checker-plugin/README.md
Normal file
3
checker-plugin/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
### Relevant articles
|
||||
|
||||
- [The Checker Framework – Pluggable Type Systems for Java](http://www.baeldung.com/checker-framework)
|
@ -7,6 +7,11 @@
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>checker-plugin</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<!-- https://checkerframework.org/manual/#maven -->
|
||||
|
||||
|
@ -2,3 +2,5 @@
|
||||
|
||||
## Relevant articles:
|
||||
|
||||
- [JDBC with Groovy](http://www.baeldung.com/jdbc-groovy)
|
||||
- [Working with JSON in Groovy](http://www.baeldung.com/groovy-json)
|
||||
|
@ -24,7 +24,7 @@ class JsonParserTest extends Specification {
|
||||
account.value == 15.6
|
||||
}
|
||||
|
||||
def 'Should parse to Account given Json String with date property' () {
|
||||
/*def 'Should parse to Account given Json String with date property' () {
|
||||
given:
|
||||
def json = '{"id":"1234","value":15.6,"createdAt":"2018-01-01T00:00:00+0000"}'
|
||||
when:
|
||||
@ -36,9 +36,9 @@ class JsonParserTest extends Specification {
|
||||
account.value == 15.6
|
||||
println account.createdAt
|
||||
account.createdAt == Date.parse('yyyy-MM-dd', '2018-01-01')
|
||||
}
|
||||
}*/
|
||||
|
||||
def 'Should parse to Json given an Account object' () {
|
||||
/*def 'Should parse to Json given an Account object' () {
|
||||
given:
|
||||
Account account = new Account(
|
||||
id: '123',
|
||||
@ -50,7 +50,7 @@ class JsonParserTest extends Specification {
|
||||
then:
|
||||
json
|
||||
json == '{"value":15.6,"createdAt":"2018-01-01T00:00:00+0000","id":"123"}'
|
||||
}
|
||||
}*/
|
||||
|
||||
def 'Should prettify given a json string' () {
|
||||
given:
|
||||
|
@ -43,3 +43,4 @@
|
||||
- [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)
|
||||
- [Java 8 Math New Methods](http://www.baeldung.com/java-8-math)
|
||||
|
@ -8,7 +8,6 @@
|
||||
|
||||
<name>core-java-8</name>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
|
@ -0,0 +1,71 @@
|
||||
package com.baeldung.findanelement;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
import org.apache.commons.collections4.IterableUtils;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.collect.Iterables;
|
||||
|
||||
public class FindElementInAList<T> {
|
||||
|
||||
public T findUsingIndexOf(T element, List<T> list) {
|
||||
int index = list.indexOf(element);
|
||||
if (index >= 0) {
|
||||
return element;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean findUsingListIterator(T element, List<T> list) {
|
||||
ListIterator<T> listIterator = list.listIterator();
|
||||
while (listIterator.hasNext()) {
|
||||
T elementFromList = listIterator.next();
|
||||
if (elementFromList.equals(element)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean findUsingEnhancedForLoop(T element, List<T> list) {
|
||||
for (T elementFromList : list) {
|
||||
if (element.equals(elementFromList)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public T findUsingStream(T element, List<T> list) {
|
||||
return list.stream()
|
||||
.filter(integer -> integer.equals(element))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public T findUsingParallelStream(T element, List<T> list) {
|
||||
return list.parallelStream()
|
||||
.filter(integer -> integer.equals(element))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public T findUsingGuava(T element, List<T> list) {
|
||||
T foundElement = Iterables.tryFind(list, new Predicate<T>() {
|
||||
public boolean apply(T input) {
|
||||
return element.equals(input);
|
||||
}
|
||||
}).orNull();
|
||||
return foundElement;
|
||||
}
|
||||
|
||||
public T findUsingApacheCommon(T element, List<T> list) {
|
||||
T foundElement = IterableUtils.find(list, new org.apache.commons.collections4.Predicate<T>() {
|
||||
public boolean evaluate(T input) {
|
||||
return element.equals(input);
|
||||
}
|
||||
});
|
||||
return foundElement;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class Car {
|
||||
|
||||
private String model;
|
||||
private int topSpeed;
|
||||
|
||||
public Car(String model, int topSpeed) {
|
||||
super();
|
||||
this.model = model;
|
||||
this.topSpeed = topSpeed;
|
||||
}
|
||||
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public void setModel(String model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public int getTopSpeed() {
|
||||
return topSpeed;
|
||||
}
|
||||
|
||||
public void setTopSpeed(int topSpeed) {
|
||||
this.topSpeed = topSpeed;
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,116 @@
|
||||
package com.baeldung.findanelement;
|
||||
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FindAnElementTest {
|
||||
|
||||
private static List<Integer> scores = new ArrayList<>();
|
||||
static {
|
||||
scores.add(0);
|
||||
scores.add(1);
|
||||
scores.add(2);
|
||||
}
|
||||
|
||||
private static FindElementInAList<Integer> findElementInAList = new FindElementInAList<>();
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingIndexOf_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
Integer score = findElementInAList.findUsingIndexOf(scoreToFind, scores);
|
||||
assertTrue(score.equals(scoreToFind));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingListIterator_thenReturnNull() {
|
||||
boolean found = findElementInAList.findUsingListIterator(5, scores);
|
||||
assertTrue(!found);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundListIterator_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
boolean found = findElementInAList.findUsingListIterator(scoreToFind, scores);
|
||||
assertTrue(found);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingIndexOf_thenReturnNull() {
|
||||
Integer score = findElementInAList.findUsingIndexOf(5, scores);
|
||||
assertNull(score);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingEnhancedForLoop_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
boolean found = findElementInAList.findUsingEnhancedForLoop(scoreToFind, scores);
|
||||
assertTrue(found);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingEnhancedForLoop_thenReturnNull() {
|
||||
Integer scoreToFind = 5;
|
||||
boolean found = findElementInAList.findUsingEnhancedForLoop(scoreToFind, scores);
|
||||
assertTrue(!found);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingStream_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
Integer score = findElementInAList.findUsingStream(scoreToFind, scores);
|
||||
assertTrue(score.equals(scoreToFind));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingStream_thenReturnNull() {
|
||||
Integer scoreToFind = 5;
|
||||
Integer score = findElementInAList.findUsingStream(scoreToFind, scores);
|
||||
assertNull(score);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingParallelStream_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
Integer score = findElementInAList.findUsingParallelStream(scoreToFind, scores);
|
||||
assertTrue(score.equals(scoreToFind));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingParallelStream_thenReturnNull() {
|
||||
Integer scoreToFind = 5;
|
||||
Integer score = findElementInAList.findUsingParallelStream(scoreToFind, scores);
|
||||
assertNull(score);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingGuava_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
Integer score = findElementInAList.findUsingGuava(scoreToFind, scores);
|
||||
assertTrue(score.equals(scoreToFind));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingGuava_thenReturnNull() {
|
||||
Integer scoreToFind = 5;
|
||||
Integer score = findElementInAList.findUsingGuava(scoreToFind, scores);
|
||||
assertNull(score);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingApacheCommons_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
Integer score = findElementInAList.findUsingApacheCommon(scoreToFind, scores);
|
||||
assertTrue(score.equals(scoreToFind));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingApacheCommons_thenReturnNull() {
|
||||
Integer scoreToFind = 5;
|
||||
Integer score = findElementInAList.findUsingApacheCommon(scoreToFind, scores);
|
||||
assertNull(score);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,110 @@
|
||||
package com.baeldung.internationalization;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.DateFormatSymbols;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class DateFormatUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenLocaleSpecificDateInstance_givenLanguageSpecificMonths() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
Date date = gregorianCalendar.getTime();
|
||||
|
||||
DateFormat itInstance = DateFormat.getDateInstance(DateFormat.FULL, Locale.ITALY);
|
||||
DateFormat usInstance = DateFormat.getDateInstance(DateFormat.FULL, Locale.US);
|
||||
|
||||
Assert.assertEquals("giovedì 1 febbraio 2018", itInstance.format(date));
|
||||
Assert.assertEquals("Thursday, February 1, 2018", usInstance.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenDateInstanceWithDifferentFormats_givenSpecificDateFormatting() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
Date date = gregorianCalendar.getTime();
|
||||
|
||||
DateFormat fullInstance = DateFormat.getDateInstance(DateFormat.FULL, Locale.ITALY);
|
||||
DateFormat mediumInstance = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ITALY);
|
||||
|
||||
Assert.assertEquals("giovedì 1 febbraio 2018", fullInstance.format(date));
|
||||
Assert.assertEquals("1-feb-2018", mediumInstance.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenTimeInstanceWithDifferentFormats_givenSpecificTimeFormatting() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
gregorianCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
|
||||
Date date = gregorianCalendar.getTime();
|
||||
|
||||
DateFormat fullInstance = DateFormat.getTimeInstance(DateFormat.FULL, Locale.ITALY);
|
||||
DateFormat mediumInstance = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.ITALY);
|
||||
|
||||
Assert.assertEquals("10.15.20 CET", fullInstance.format(date));
|
||||
Assert.assertEquals("10.15.20" , mediumInstance.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenDateTimeInstanceWithDifferentFormats_givenSpecificDateTimeFormatting() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
gregorianCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
|
||||
Date date = gregorianCalendar.getTime();
|
||||
|
||||
DateFormat ffInstance = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.ITALY);
|
||||
DateFormat smInstance = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.ITALY);
|
||||
|
||||
Assert.assertEquals("giovedì 1 febbraio 2018 10.15.20 CET", ffInstance.format(date));
|
||||
Assert.assertEquals("01/02/18 10.15.20", smInstance.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenLocaleSpecificDateTimeInstance_givenLocaleSpecificFormatting() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
gregorianCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
|
||||
Date date = gregorianCalendar.getTime();
|
||||
|
||||
DateFormat itInstance = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.ITALY);
|
||||
DateFormat jpInstance = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.JAPAN);
|
||||
|
||||
Assert.assertEquals("giovedì 1 febbraio 2018 10.15.20 CET", itInstance.format(date));
|
||||
Assert.assertEquals("2018年2月1日 10時15分20秒 CET", jpInstance.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenCustomizedSimpleDateFormat_thenSpecificMonthRepresentations() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
Date date = gregorianCalendar.getTime();
|
||||
Locale.setDefault(new Locale("pl", "PL"));
|
||||
|
||||
SimpleDateFormat fullMonthDateFormat = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss:SSS");
|
||||
SimpleDateFormat shortMonthsimpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:SSS");
|
||||
|
||||
Assert.assertEquals("01-lutego-2018 10:15:20:000", fullMonthDateFormat.format(date));
|
||||
Assert.assertEquals("01-02-2018 10:15:20:000" , shortMonthsimpleDateFormat.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenCustomizedDateFormatSymbols_thenChangedDayNames() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
Date date = gregorianCalendar.getTime();
|
||||
Locale.setDefault(new Locale("pl", "PL"));
|
||||
|
||||
DateFormatSymbols dateFormatSymbols = new DateFormatSymbols();
|
||||
dateFormatSymbols.setWeekdays(new String[]{"A", "B", "C", "D", "E", "F", "G", "H"});
|
||||
SimpleDateFormat standardDateFormat = new SimpleDateFormat("EEEE-MMMM-yyyy HH:mm:ss:SSS");
|
||||
SimpleDateFormat newDaysDateFormat = new SimpleDateFormat("EEEE-MMMM-yyyy HH:mm:ss:SSS", dateFormatSymbols);
|
||||
|
||||
Assert.assertEquals("czwartek-lutego-2018 10:15:20:000", standardDateFormat.format(date));
|
||||
Assert.assertEquals("F-lutego-2018 10:15:20:000", newDaysDateFormat.format(date));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
package com.baeldung.internationalization;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.FormatStyle;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class DateTimeFormatterUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDefaultUsLocaleAndDateTimeAndPattern_whenFormatWithDifferentLocales_thenGettingLocalizedDateTimes() {
|
||||
Locale.setDefault(Locale.US);
|
||||
LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500);
|
||||
String pattern = "dd-MMMM-yyyy HH:mm:ss.SSS";
|
||||
|
||||
DateTimeFormatter defaultTimeFormatter = DateTimeFormatter.ofPattern(pattern);
|
||||
DateTimeFormatter plTimeFormatter = DateTimeFormatter.ofPattern(pattern, new Locale("pl", "PL"));
|
||||
DateTimeFormatter deTimeFormatter = DateTimeFormatter.ofPattern(pattern).withLocale(Locale.GERMANY);
|
||||
|
||||
Assert.assertEquals("01-January-2018 10:15:50.000", defaultTimeFormatter.format(localDateTime));
|
||||
Assert.assertEquals("01-stycznia-2018 10:15:50.000", plTimeFormatter.format(localDateTime));
|
||||
Assert.assertEquals("01-Januar-2018 10:15:50.000", deTimeFormatter.format(localDateTime));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateTimeAndTimeZone_whenFormatWithDifferentLocales_thenGettingLocalizedZonedDateTimes() {
|
||||
Locale.setDefault(Locale.US);
|
||||
LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500);
|
||||
ZoneId losAngelesTimeZone = TimeZone.getTimeZone("America/Los_Angeles").toZoneId();
|
||||
|
||||
DateTimeFormatter localizedFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
|
||||
DateTimeFormatter frLocalizedFormatter =
|
||||
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.FRANCE);
|
||||
String formattedDateTime = localizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
|
||||
String frFormattedDateTime = frLocalizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
|
||||
|
||||
Assert.assertEquals("Monday, January 1, 2018 10:15:50 AM PST", formattedDateTime);
|
||||
Assert.assertEquals("lundi 1 janvier 2018 10 h 15 PST", frFormattedDateTime);
|
||||
}
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
package com.baeldung.internationalization;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.DecimalFormatSymbols;
|
||||
import java.text.NumberFormat;
|
||||
import java.util.Currency;
|
||||
import java.util.Locale;
|
||||
|
||||
public class NumbersCurrenciesFormattingUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDifferentLocalesAndDoubleNumber_whenNumberInstance_thenDifferentOutput() {
|
||||
Locale usLocale = Locale.US;
|
||||
Locale plLocale = new Locale("pl", "PL");
|
||||
Locale deLocale = Locale.GERMANY;
|
||||
double number = 102_300.456d;
|
||||
|
||||
NumberFormat usNumberFormat = NumberFormat.getInstance(usLocale);
|
||||
NumberFormat plNumberFormat = NumberFormat.getInstance(plLocale);
|
||||
NumberFormat deNumberFormat = NumberFormat.getInstance(deLocale);
|
||||
|
||||
Assert.assertEquals(usNumberFormat.format(number), "102,300.456");
|
||||
Assert.assertEquals(plNumberFormat.format(number), "102 300,456");
|
||||
Assert.assertEquals(deNumberFormat.format(number), "102.300,456");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDifferentLocalesAndDoubleAmount_whenCurrencyInstance_thenDifferentOutput() {
|
||||
Locale usLocale = Locale.US;
|
||||
Locale plLocale = new Locale("pl", "PL");
|
||||
Locale deLocale = Locale.GERMANY;
|
||||
BigDecimal number = new BigDecimal(102_300.456d);
|
||||
|
||||
NumberFormat usNumberFormat = NumberFormat.getCurrencyInstance(usLocale);
|
||||
NumberFormat plNumberFormat = NumberFormat.getCurrencyInstance(plLocale);
|
||||
NumberFormat deNumberFormat = NumberFormat.getCurrencyInstance(deLocale);
|
||||
|
||||
Assert.assertEquals(usNumberFormat.format(number), "$102,300.46");
|
||||
Assert.assertEquals(plNumberFormat.format(number), "102 300,46 zł");
|
||||
Assert.assertEquals(deNumberFormat.format(number), "102.300,46 €");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocaleAndNumber_whenSpecificDecimalFormat_thenSpecificOutput() {
|
||||
Locale.setDefault(Locale.FRANCE);
|
||||
BigDecimal number = new BigDecimal(102_300.456d);
|
||||
|
||||
DecimalFormat zeroDecimalFormat = new DecimalFormat("000000000.0000");
|
||||
DecimalFormat hashDecimalFormat = new DecimalFormat("###,###.#");
|
||||
DecimalFormat dollarDecimalFormat = new DecimalFormat("$###,###.##");
|
||||
|
||||
Assert.assertEquals(zeroDecimalFormat.format(number), "000102300,4560");
|
||||
Assert.assertEquals(hashDecimalFormat.format(number), "102 300,5");
|
||||
Assert.assertEquals(dollarDecimalFormat.format(number), "$102 300,46");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocaleAndNumber_whenSpecificDecimalFormatSymbols_thenSpecificOutput() {
|
||||
Locale.setDefault(Locale.FRANCE);
|
||||
BigDecimal number = new BigDecimal(102_300.456d);
|
||||
|
||||
DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance();
|
||||
decimalFormatSymbols.setGroupingSeparator('^');
|
||||
decimalFormatSymbols.setDecimalSeparator('@');
|
||||
DecimalFormat separatorsDecimalFormat = new DecimalFormat("$###,###.##");
|
||||
separatorsDecimalFormat.setGroupingSize(4);
|
||||
separatorsDecimalFormat.setCurrency(Currency.getInstance(Locale.JAPAN));
|
||||
separatorsDecimalFormat.setDecimalFormatSymbols(decimalFormatSymbols);
|
||||
|
||||
Assert.assertEquals(separatorsDecimalFormat.format(number), "$10^2300@46");
|
||||
}
|
||||
}
|
@ -1,6 +1,8 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.Car;
|
||||
import com.baeldung.java_8_features.Person;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
@ -44,4 +46,29 @@ public class Java8MaxMinUnitTest {
|
||||
assertEquals("Should be Alex", alex, minByAge);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenArrayIsOfIntegerThenMinUsesIntegerComparator() {
|
||||
int[] integers = new int[] { 20, 98, 12, 7, 35 };
|
||||
|
||||
int min = Arrays.stream(integers)
|
||||
.min()
|
||||
.getAsInt();
|
||||
|
||||
assertEquals(7, min);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenArrayIsOfCustomTypeThenMaxUsesCustomComparator() {
|
||||
final Car porsche = new Car("Porsche 959", 319);
|
||||
final Car ferrari = new Car("Ferrari 288 GTO", 303);
|
||||
final Car bugatti = new Car("Bugatti Veyron 16.4 Super Sport", 415);
|
||||
final Car mcLaren = new Car("McLaren F1", 355);
|
||||
final Car[] fastCars = { porsche, ferrari, bugatti, mcLaren };
|
||||
|
||||
final Car maxBySpeed = Arrays.stream(fastCars)
|
||||
.max(Comparator.comparing(Car::getTopSpeed))
|
||||
.orElseThrow(NoSuchElementException::new);
|
||||
|
||||
assertEquals(bugatti, maxBySpeed);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,89 @@
|
||||
package com.baeldung.math;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class MathNewMethodsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenAddExactToInteger_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(150, Math.addExact(100, 50)); // Returns 150
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSubstractExactFromInteger_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(50, Math.subtractExact(100, 50)); // Returns 50
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDecrementExactInteger_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(99, Math.decrementExact(100)); // Returns 99
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIncrementExactToInteger_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(101, Math.incrementExact(100)); // Returns 101
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMultiplyExactTwoIntegers_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(500, Math.multiplyExact(100, 5)); // Returns 500
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNegateExactInteger_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(-100, Math.negateExact(100)); // Returns -100
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenAddToMaxInteger_thenThrowsArithmeticException() {
|
||||
Math.addExact(Integer.MAX_VALUE, 1); // Throws ArithmeticException
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenDecrementMinInteger_thenThrowsArithmeticException() {
|
||||
Math.decrementExact(Integer.MIN_VALUE); // Throws ArithmeticException
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenIncrementMaxLong_thenThrowsArithmeticException() {
|
||||
Math.incrementExact(Long.MAX_VALUE); // Throws ArithmeticException
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenMultiplyMaxLong_thenThrowsArithmeticException() {
|
||||
Math.multiplyExact(Long.MAX_VALUE, 2); // Throws ArithmeticException
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenNegateMinInteger_thenThrowsArithmeticException() {
|
||||
Math.negateExact(Integer.MIN_VALUE); // MinInt value: −2.147.483.648, but MaxInt Value: 2.147.483.647 => Throws ArithmeticException
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenSubstractFromMinInteger_thenThrowsArithmeticException() {
|
||||
Math.subtractExact(Integer.MIN_VALUE, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFloorDivTwoIntegers_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(3, Math.floorDiv(7, 2)); // Exact quotient is 3.5 so floor(3.5) == 3
|
||||
assertEquals(-4, Math.floorDiv(-7, 2)); // Exact quotient is -3.5 so floor(-3.5) == -4
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModDivTwoIntegers_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(2, Math.floorMod(5, 3)); // Returns 2: floorMod for positive numbers returns the same as % operator
|
||||
assertEquals(1, Math.floorMod(-5, 3)); // Returns 1 and not 2 because floorDiv(-5, 3) is -2 and not -1 and (-2*3) + (1) = -5
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNextDownOfDouble_thenExpectCorrectNumber() {
|
||||
double number = 3.0;
|
||||
double expected = 2.999999999999;
|
||||
double delta = 0.00000001;
|
||||
assertEquals(expected, Math.nextDown(number), delta); // The delta defines the accepted error range
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
package com.baeldung.time;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ElapsedTimeUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenRunningTask_whenMeasuringTimeWithCurrentTimeMillis_thenGetElapsedTime() throws InterruptedException {
|
||||
long start = System.currentTimeMillis();
|
||||
|
||||
simulateRunningTask();
|
||||
|
||||
long finish = System.currentTimeMillis();
|
||||
|
||||
long timeElapsed = finish - start;
|
||||
|
||||
assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveRunningTask_whenMeasuringTimeWithNanoTime_thenGetElapsedTime() throws InterruptedException {
|
||||
long start = System.nanoTime();
|
||||
|
||||
simulateRunningTask();
|
||||
|
||||
long finish = System.nanoTime();
|
||||
|
||||
long timeElapsed = finish - start;
|
||||
|
||||
assertEquals(true, (2000000000L <= timeElapsed) && (timeElapsed <= 3000000000L));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRunningTask_whenMeasuringTimeWithStopWatch_thenGetElapsedTime() throws InterruptedException {
|
||||
StopWatch watch = new StopWatch();
|
||||
watch.start();
|
||||
|
||||
simulateRunningTask();
|
||||
|
||||
watch.stop();
|
||||
|
||||
long timeElapsed = watch.getTime();
|
||||
|
||||
assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRunningTask_whenMeasuringTimeWithInstantClass_thenGetElapsedTime() throws InterruptedException {
|
||||
Instant start = Instant.now();
|
||||
|
||||
simulateRunningTask();
|
||||
|
||||
Instant finish = Instant.now();
|
||||
|
||||
long timeElapsed = Duration.between(start, finish).toMillis();
|
||||
|
||||
assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L));
|
||||
}
|
||||
|
||||
/**
|
||||
* Simulate task running for 2.5 seconds.
|
||||
*
|
||||
* @throws InterruptedException
|
||||
*/
|
||||
private static void simulateRunningTask() throws InterruptedException {
|
||||
TimeUnit.MILLISECONDS.sleep(2500); // 2.5 seconds
|
||||
|
||||
}
|
||||
}
|
@ -20,3 +20,5 @@
|
||||
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
|
||||
- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
|
||||
- [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles)
|
||||
- [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client)
|
||||
- [Method Handles in Java](http://www.baeldung.com/java-method-handles)
|
||||
|
0
core-java-9/compile-modules.sh
Normal file → Executable file
0
core-java-9/compile-modules.sh
Normal file → Executable file
2
core-java-9/compile-simple-modules.sh
Executable file
2
core-java-9/compile-simple-modules.sh
Executable file
@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env bash
|
||||
javac -d outDir --module-source-path src/simple-modules $(find src/simple-modules -name "*.java")
|
@ -6,7 +6,11 @@
|
||||
<version>0.2-SNAPSHOT</version>
|
||||
|
||||
<name>core-java-9</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>apache.snapshots</id>
|
||||
|
2
core-java-9/run-simple-module-app.sh
Executable file
2
core-java-9/run-simple-module-app.sh
Executable file
@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env bash
|
||||
java --module-path outDir -m main.app/com.baeldung.modules.main.MainApp
|
0
core-java-9/run-student-client.sh
Normal file → Executable file
0
core-java-9/run-student-client.sh
Normal file → Executable file
@ -0,0 +1,5 @@
|
||||
package com.baeldung.modules.hello;
|
||||
|
||||
public interface HelloInterface {
|
||||
public void sayHello();
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.modules.hello;
|
||||
|
||||
public class HelloModules implements HelloInterface {
|
||||
public static void doSomething() {
|
||||
System.out.println("Hello, Modules!");
|
||||
}
|
||||
|
||||
public void sayHello() {
|
||||
System.out.println("Hello!");
|
||||
}
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
module hello.modules {
|
||||
exports com.baeldung.modules.hello;
|
||||
provides com.baeldung.modules.hello.HelloInterface with com.baeldung.modules.hello.HelloModules;
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.modules.main;
|
||||
|
||||
import com.baeldung.modules.hello.HelloModules;
|
||||
|
||||
public class MainApp {
|
||||
public static void main(String[] args) {
|
||||
HelloModules.doSomething();
|
||||
|
||||
HelloModules module = new HelloModules();
|
||||
module.sayHello();
|
||||
}
|
||||
}
|
4
core-java-9/src/simple-modules/main.app/module-info.java
Normal file
4
core-java-9/src/simple-modules/main.app/module-info.java
Normal file
@ -0,0 +1,4 @@
|
||||
module main.app {
|
||||
requires hello.modules;
|
||||
uses com.baeldung.modules.hello.HelloInterface;
|
||||
}
|
@ -34,3 +34,7 @@
|
||||
- [Implementing a Runnable vs Extending a Thread](http://www.baeldung.com/java-runnable-vs-extending-thread)
|
||||
- [How to Kill a Java Thread](http://www.baeldung.com/java-thread-stop)
|
||||
- [ExecutorService - Waiting for Threads to Finish](http://www.baeldung.com/java-executor-wait-for-threads)
|
||||
- [wait and notify() Methods in Java](http://www.baeldung.com/java-wait-notify)
|
||||
- [Priority-based Job Scheduling in Java](http://www.baeldung.com/java-priority-job-schedule)
|
||||
- [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer)
|
||||
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
|
||||
|
@ -6,7 +6,11 @@
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>core-java-io</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
|
||||
<!-- utils -->
|
||||
|
@ -6,7 +6,11 @@
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>core-java-sun</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
|
||||
<!-- utils -->
|
||||
|
@ -136,4 +136,19 @@
|
||||
- [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)
|
||||
- [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy)
|
||||
- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome)
|
||||
- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
|
||||
- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance)
|
||||
- [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
|
||||
- [The Observer Pattern in Java](https://github.com/eugenp/tutorials/tree/master/core-java)
|
||||
- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight)
|
||||
- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting)
|
||||
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat)
|
||||
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
|
||||
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
|
||||
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
|
||||
- [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced)
|
||||
- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings)
|
||||
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
|
||||
|
||||
|
@ -7,7 +7,11 @@
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>core-java</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
|
||||
<!-- utils -->
|
||||
|
@ -6,8 +6,8 @@ public class SumAndAverageInArray {
|
||||
|
||||
public static int findSumWithoutUsingStream(int[] array) {
|
||||
int sum = 0;
|
||||
for (int index = 0; index < array.length; index++) {
|
||||
sum += array[index];
|
||||
for (int value : array) {
|
||||
sum += value;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
@ -16,12 +16,16 @@ public class SumAndAverageInArray {
|
||||
return Arrays.stream(array).sum();
|
||||
}
|
||||
|
||||
public static int findSumUsingStream(Integer[] array) {
|
||||
return Arrays.stream(array).mapToInt(Integer::intValue).sum();
|
||||
}
|
||||
|
||||
public static double findAverageWithoutUsingStream(int[] array) {
|
||||
int sum = findSumWithoutUsingStream(array);
|
||||
return (double) sum / array.length;
|
||||
}
|
||||
|
||||
public static double findAverageUsingStream(int[] array) {
|
||||
return Arrays.stream(array).average().getAsDouble();
|
||||
return Arrays.stream(array).average().orElse(Double.NaN);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.externalizable;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
public class Community implements Serializable {
|
||||
|
||||
private int id;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Community{" +
|
||||
"id=" + id +
|
||||
'}';
|
||||
}
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
package com.baeldung.externalizable;
|
||||
|
||||
import java.io.Externalizable;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInput;
|
||||
import java.io.ObjectOutput;
|
||||
|
||||
public class Country implements Externalizable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private String name;
|
||||
private String capital;
|
||||
private int code;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getCapital() {
|
||||
return capital;
|
||||
}
|
||||
|
||||
public void setCapital(String capital) {
|
||||
this.capital = capital;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeExternal(ObjectOutput out) throws IOException {
|
||||
out.writeUTF(name);
|
||||
out.writeUTF(capital);
|
||||
out.writeInt(code);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
|
||||
this.name = in.readUTF();
|
||||
this.capital = in.readUTF();
|
||||
this.code = in.readInt();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Country{" +
|
||||
"name='" + name + '\'' +
|
||||
", capital='" + capital + '\'' +
|
||||
", code=" + code +
|
||||
'}';
|
||||
}
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
package com.baeldung.externalizable;
|
||||
|
||||
import java.io.Externalizable;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInput;
|
||||
import java.io.ObjectOutput;
|
||||
|
||||
public class Region extends Country implements Externalizable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private String climate;
|
||||
private Double population;
|
||||
private Community community;
|
||||
|
||||
public String getClimate() {
|
||||
return climate;
|
||||
}
|
||||
|
||||
public void setClimate(String climate) {
|
||||
this.climate = climate;
|
||||
}
|
||||
|
||||
public Double getPopulation() {
|
||||
return population;
|
||||
}
|
||||
|
||||
public void setPopulation(Double population) {
|
||||
this.population = population;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeExternal(ObjectOutput out) throws IOException {
|
||||
super.writeExternal(out);
|
||||
out.writeUTF(climate);
|
||||
community = new Community();
|
||||
community.setId(5);
|
||||
out.writeObject(community);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
|
||||
super.readExternal(in);
|
||||
this.climate = in.readUTF();
|
||||
community = (Community) in.readObject();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Region = {" +
|
||||
"country='" + super.toString() + '\'' +
|
||||
"community='" + community.toString() + '\'' +
|
||||
"climate='" + climate + '\'' +
|
||||
", population=" + population +
|
||||
'}';
|
||||
}
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public class BlackCat {
|
||||
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public class BlackDog extends Dog {
|
||||
// public void sound() {
|
||||
// }
|
||||
}
|
18
core-java/src/main/java/com/baeldung/finalkeyword/Cat.java
Normal file
18
core-java/src/main/java/com/baeldung/finalkeyword/Cat.java
Normal file
@ -0,0 +1,18 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public final class Cat {
|
||||
|
||||
private int weight;
|
||||
|
||||
public int getWeight() {
|
||||
return weight;
|
||||
}
|
||||
|
||||
public void setWeight(int weight) {
|
||||
this.weight = weight;
|
||||
}
|
||||
|
||||
public void methodWithFinalArguments(final int x) {
|
||||
// x=1;
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public class Dog {
|
||||
|
||||
public final void sound() {
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.inheritancecomposition.application;
|
||||
|
||||
import com.baeldung.inheritancecomposition.model.Actress;
|
||||
import com.baeldung.inheritancecomposition.model.Computer;
|
||||
import com.baeldung.inheritancecomposition.model.StandardMemory;
|
||||
import com.baeldung.inheritancecomposition.model.Person;
|
||||
import com.baeldung.inheritancecomposition.model.StandardProcessor;
|
||||
import com.baeldung.inheritancecomposition.model.StandardSoundCard;
|
||||
import com.baeldung.inheritancecomposition.model.Waitress;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Person person = new Person("John", "john@domain.com", 35);
|
||||
Waitress waitress = new Waitress("Mary", "mary@domain.com", 22);
|
||||
System.out.println(waitress.serveStarter("mixed salad"));
|
||||
System.out.println(waitress.serveMainCourse("steak"));
|
||||
System.out.println(waitress.serveDessert("cup of cofee"));
|
||||
Actress actress = new Actress("Susan", "susan@domain.com", 30);
|
||||
System.out.println(actress.readScript("Psycho"));
|
||||
System.out.println(actress.performRole());
|
||||
Computer computer = new Computer(new StandardProcessor("Intel I3"), new StandardMemory("Kingston", "1TB"));
|
||||
computer.setSoundCard(new StandardSoundCard("Generic Sound Card"));
|
||||
System.out.println(computer);
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public class Actress extends Person {
|
||||
|
||||
public Actress(String name, String email, int age) {
|
||||
super(name, email, age);
|
||||
}
|
||||
|
||||
public String readScript(String movie) {
|
||||
return "Reading the script of " + movie;
|
||||
}
|
||||
|
||||
public String performRole() {
|
||||
return "Performing a role";
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class Computer {
|
||||
|
||||
private Processor processor;
|
||||
private Memory memory;
|
||||
private SoundCard soundCard;
|
||||
|
||||
public Computer(Processor processor, Memory memory) {
|
||||
this.processor = processor;
|
||||
this.memory = memory;
|
||||
}
|
||||
|
||||
public void setSoundCard(SoundCard soundCard) {
|
||||
this.soundCard = soundCard;
|
||||
}
|
||||
|
||||
public Processor getProcessor() {
|
||||
return processor;
|
||||
}
|
||||
|
||||
public Memory getMemory() {
|
||||
return memory;
|
||||
}
|
||||
|
||||
public Optional<SoundCard> getSoundCard() {
|
||||
return Optional.ofNullable(soundCard);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Computer{" + "processor=" + processor + ", memory=" + memory + ", soundcard=" + soundCard +"}";
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public interface Memory {
|
||||
|
||||
String getBrand();
|
||||
|
||||
String getSize();
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public class Person {
|
||||
|
||||
private final String name;
|
||||
private final String email;
|
||||
private final int age;
|
||||
|
||||
public Person(String name, String email, int age) {
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Person{" + "name=" + name + ", email=" + email + ", age=" + age + "}";
|
||||
}
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public interface Processor {
|
||||
|
||||
String getModel();
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public interface SoundCard {
|
||||
|
||||
String getBrand();
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public class StandardMemory implements Memory {
|
||||
|
||||
private String brand;
|
||||
private String size;
|
||||
|
||||
public StandardMemory(String brand, String size) {
|
||||
this.brand = brand;
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
public String getBrand() {
|
||||
return brand;
|
||||
}
|
||||
|
||||
public String getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Memory{" + "brand=" + brand + ", size=" + size + "}";
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public class StandardProcessor implements Processor {
|
||||
|
||||
private String model;
|
||||
|
||||
public StandardProcessor(String model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Processor{" + "model=" + model + "}";
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public class StandardSoundCard implements SoundCard {
|
||||
|
||||
private String brand;
|
||||
|
||||
public StandardSoundCard(String brand) {
|
||||
this.brand = brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBrand() {
|
||||
return brand;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SoundCard{" + "brand=" + brand + "}";
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public class Waitress extends Person {
|
||||
|
||||
public Waitress(String name, String email, int age) {
|
||||
super(name, email, age);
|
||||
}
|
||||
|
||||
public String serveStarter(String starter) {
|
||||
return "Serving a " + starter;
|
||||
}
|
||||
|
||||
public String serveMainCourse(String mainCourse) {
|
||||
return "Serving a " + mainCourse;
|
||||
}
|
||||
|
||||
public String serveDessert(String dessert) {
|
||||
return "Serving a " + dessert;
|
||||
}
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
package com.baeldung.ssl;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
import javax.net.ssl.SSLSocket;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
|
||||
public class SecureConnection {
|
||||
|
||||
public static void main(String[] args) {
|
||||
if (args.length != 2) {
|
||||
System.out.println("Use: SecureConnection host port");
|
||||
System.exit(1);
|
||||
}
|
||||
try {
|
||||
String host = getHost(args);
|
||||
Integer port = getPort(args);
|
||||
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
|
||||
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(host, port);
|
||||
InputStream in = sslsocket.getInputStream();
|
||||
OutputStream out = sslsocket.getOutputStream();
|
||||
|
||||
out.write(1);
|
||||
|
||||
while (in.available() > 0) {
|
||||
System.out.print(in.read());
|
||||
}
|
||||
|
||||
System.out.println("Secured connection performed successfully");
|
||||
|
||||
} catch (Exception exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the host from arguments
|
||||
* @param args the arguments
|
||||
* @return the host
|
||||
*/
|
||||
private static String getHost(String[] args) {
|
||||
return args[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the port from arguments
|
||||
* @param args the arguments
|
||||
* @return the port
|
||||
*/
|
||||
private static Integer getPort(String[] args) {
|
||||
return Integer.parseInt(args[1]);
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user