Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
2b7fe591fd
@ -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
|
||||
|
||||
|
@ -1,129 +1,129 @@
|
||||
<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>
|
||||
<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>
|
||||
|
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", ".");
|
||||
}
|
||||
|
||||
}
|
@ -1,10 +1,12 @@
|
||||
<?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>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.ow2.asm</groupId>
|
||||
@ -17,11 +19,13 @@
|
||||
<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>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -3,4 +3,5 @@
|
||||
- [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)
|
||||
|
||||
|
38
aws/pom.xml
38
aws/pom.xml
@ -22,6 +22,8 @@
|
||||
<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> {
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -20,7 +20,7 @@ import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class MultipartUploadTest {
|
||||
public class MultipartUploadLiveTest {
|
||||
|
||||
private static final String BUCKET_NAME = "bucket_name";
|
||||
private static final String KEY_NAME = "picture.jpg";
|
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
|
@ -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>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>spring-boot-camel</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<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>
|
||||
|
||||
<name>Spring-Boot - Camel API</name>
|
||||
<build>
|
||||
<defaultGoal>spring-boot:run</defaultGoal>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
|
||||
<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>
|
||||
|
@ -8,7 +8,6 @@
|
||||
|
||||
<name>core-java-8</name>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
|
@ -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");
|
||||
}
|
||||
}
|
@ -136,4 +136,10 @@
|
||||
- [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 “final” Keyword in Java](http://www.baeldung.com/java-final)
|
||||
|
||||
|
@ -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,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;
|
||||
}
|
||||
}
|
29
core-java/src/main/java/com/baeldung/javafx/Main.java
Normal file
29
core-java/src/main/java/com/baeldung/javafx/Main.java
Normal file
@ -0,0 +1,29 @@
|
||||
package com.baeldung.javafx;
|
||||
|
||||
import javafx.application.Application;
|
||||
import javafx.fxml.FXMLLoader;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.layout.AnchorPane;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
public class Main extends Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
launch(args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start(Stage primaryStage) throws Exception {
|
||||
|
||||
FXMLLoader loader = new FXMLLoader(Main.class.getResource("/SearchController.fxml"));
|
||||
AnchorPane page = (AnchorPane) loader.load();
|
||||
Scene scene = new Scene(page);
|
||||
|
||||
scene.getStylesheets().add("/search.css");
|
||||
|
||||
primaryStage.setTitle("Title goes here");
|
||||
primaryStage.setScene(scene);
|
||||
primaryStage.show();
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,61 @@
|
||||
package com.baeldung.javafx.model;
|
||||
|
||||
import javafx.beans.property.*;
|
||||
|
||||
public class Person {
|
||||
|
||||
private SimpleIntegerProperty id;
|
||||
private SimpleStringProperty name;
|
||||
private SimpleBooleanProperty isEmployed;
|
||||
|
||||
public Person(Integer id, String name, boolean isEmployed) {
|
||||
this.id = new SimpleIntegerProperty(id);
|
||||
this.name = new SimpleStringProperty(name);
|
||||
this.isEmployed = new SimpleBooleanProperty(isEmployed);
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id.get();
|
||||
}
|
||||
|
||||
public IntegerProperty idProperty() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id.set(id);
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name.get();
|
||||
}
|
||||
|
||||
public StringProperty nameProperty() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name.set(name);
|
||||
}
|
||||
|
||||
public boolean getIsEmployed() {
|
||||
return isEmployed.get();
|
||||
}
|
||||
|
||||
public BooleanProperty isEmployedProperty() {
|
||||
return isEmployed;
|
||||
}
|
||||
|
||||
public void setIsEmployed(boolean isEmployed) {
|
||||
this.isEmployed.set(isEmployed);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Person{" +
|
||||
"id=" + id +
|
||||
", name='" + name + '\'' +
|
||||
", isEmployed=" + isEmployed +
|
||||
'}';
|
||||
}
|
||||
}
|
@ -0,0 +1,100 @@
|
||||
package com.baeldung.javafx.view;
|
||||
|
||||
|
||||
import com.baeldung.javafx.model.Person;
|
||||
import javafx.collections.FXCollections;
|
||||
import javafx.collections.ObservableList;
|
||||
import javafx.concurrent.Task;
|
||||
import javafx.fxml.FXML;
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.input.KeyCode;
|
||||
import javafx.scene.layout.VBox;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class SearchController {
|
||||
|
||||
public static final int PAGE_ITEMS_COUNT = 10;
|
||||
|
||||
@FXML
|
||||
private TextField searchField;
|
||||
@FXML
|
||||
private Button searchButton;
|
||||
@FXML
|
||||
private Pagination pagination;
|
||||
@FXML
|
||||
private Label searchLabel;
|
||||
|
||||
private ObservableList<Person> masterData = FXCollections.observableArrayList();
|
||||
|
||||
public SearchController() {
|
||||
masterData.add(new Person(5, "John", true));
|
||||
masterData.add(new Person(7, "Albert", true));
|
||||
masterData.add(new Person(11, "Monica", false));
|
||||
}
|
||||
|
||||
@FXML
|
||||
private void initialize() {
|
||||
|
||||
// search panel
|
||||
searchButton.setText("Search");
|
||||
searchButton.setOnAction(event -> loadData());
|
||||
searchButton.setStyle("-fx-background-color: #457ecd; -fx-text-fill: #ffffff;");
|
||||
|
||||
searchField.setOnKeyPressed(event -> {
|
||||
if (event.getCode().equals(KeyCode.ENTER)) {
|
||||
loadData();
|
||||
}
|
||||
});
|
||||
|
||||
searchField.textProperty().addListener((observable, oldValue, newValue) -> {
|
||||
searchLabel.setText(newValue);
|
||||
});
|
||||
|
||||
pagination.setPageFactory(SearchController.this::createPage);
|
||||
}
|
||||
|
||||
private Node createPage(Integer pageIndex) {
|
||||
|
||||
VBox dataContainer = new VBox();
|
||||
|
||||
TableView<Person> tableView = new TableView<>(masterData);
|
||||
TableColumn id = new TableColumn("ID");
|
||||
TableColumn name = new TableColumn("NAME");
|
||||
TableColumn employed = new TableColumn("EMPLOYED");
|
||||
|
||||
tableView.getColumns().addAll(id, name, employed);
|
||||
dataContainer.getChildren().add(tableView);
|
||||
|
||||
return dataContainer;
|
||||
}
|
||||
|
||||
private void loadData() {
|
||||
|
||||
String searchText = searchField.getText();
|
||||
|
||||
Task<ObservableList<Person>> task = new Task<ObservableList<Person>>() {
|
||||
@Override
|
||||
protected ObservableList<Person> call() throws Exception {
|
||||
updateMessage("Loading data");
|
||||
return FXCollections.observableArrayList(masterData
|
||||
.stream()
|
||||
.filter(value -> value.getName().toLowerCase().contains(searchText))
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
};
|
||||
|
||||
task.setOnSucceeded(event -> {
|
||||
masterData = task.getValue();
|
||||
pagination.setVisible(true);
|
||||
pagination.setPageCount(masterData.size() / PAGE_ITEMS_COUNT);
|
||||
});
|
||||
|
||||
Thread th = new Thread(task);
|
||||
th.setDaemon(true);
|
||||
th.start();
|
||||
}
|
||||
|
||||
}
|
@ -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]);
|
||||
}
|
||||
}
|
33
core-java/src/main/resources/SearchController.fxml
Normal file
33
core-java/src/main/resources/SearchController.fxml
Normal file
@ -0,0 +1,33 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<?import javafx.scene.control.Button?>
|
||||
<?import javafx.scene.control.Label?>
|
||||
<?import javafx.scene.control.Pagination?>
|
||||
<?import javafx.scene.control.TextField?>
|
||||
<?import javafx.scene.layout.*?>
|
||||
<AnchorPane xmlns:fx="http://javafx.com/fxml"
|
||||
xmlns="http://javafx.com/javafx"
|
||||
fx:controller="com.baeldung.javafx.view.SearchController"
|
||||
prefHeight="400.0" prefWidth="600.0">
|
||||
<children>
|
||||
|
||||
<HBox id="HBox" alignment="CENTER" spacing="5.0" AnchorPane.leftAnchor="10.0"
|
||||
AnchorPane.rightAnchor="10.0" AnchorPane.topAnchor="10.0">
|
||||
<children>
|
||||
<Label text="Search Text:"/>
|
||||
<TextField fx:id="searchField" prefWidth="-1.0" HBox.hgrow="ALWAYS"/>
|
||||
<Button fx:id="searchButton" prefWidth="-1.0" HBox.hgrow="ALWAYS"/>
|
||||
<Label fx:id="searchLabel"/>
|
||||
</children>
|
||||
</HBox>
|
||||
|
||||
<Pagination fx:id="pagination"
|
||||
AnchorPane.leftAnchor="10.0"
|
||||
AnchorPane.rightAnchor="10.0"
|
||||
AnchorPane.topAnchor="50.0"
|
||||
visible="false">
|
||||
|
||||
</Pagination>
|
||||
|
||||
</children>
|
||||
</AnchorPane>
|
4
core-java/src/main/resources/search.css
Normal file
4
core-java/src/main/resources/search.css
Normal file
@ -0,0 +1,4 @@
|
||||
.button {
|
||||
-fx-background-color: red;
|
||||
-fx-text-fill: white;
|
||||
}
|
@ -21,6 +21,15 @@ public class SumAndAverageInArrayTest {
|
||||
Assert.assertEquals(expectedSumOfArray, actualSumOfArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnBoxedIntegerArray_whenUsingStream_thenFindSum() {
|
||||
Integer[] array = new Integer[]{1, 3, 4, 8, 19, 20};
|
||||
int expectedSumOfArray = 55;
|
||||
int actualSumOfArray = SumAndAverageInArray.findSumUsingStream(array);
|
||||
|
||||
Assert.assertEquals(expectedSumOfArray, actualSumOfArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIntArray_whenNotUsingStream_thenFindAverage() {
|
||||
int[] array = { 1, 3, 4, 8, 19, 20 };
|
||||
@ -38,4 +47,13 @@ public class SumAndAverageInArrayTest {
|
||||
|
||||
Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnEmptyIntArray_whenUsingStream_thenFindAverage() {
|
||||
int[] array = {};
|
||||
double expectedAvgOfArray = Double.NaN;
|
||||
double actualAvgOfArray = SumAndAverageInArray.findAverageUsingStream(array);
|
||||
|
||||
Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.00);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,69 @@
|
||||
package com.baeldung.dst;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DaylightSavingTimeExamplesTest {
|
||||
|
||||
@Test
|
||||
public void givenItalianTimeZone_WhenDSTHappens_ThenCorrectlyShiftTimeZone() throws ParseException {
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("Europe/Rome"));
|
||||
|
||||
TimeZone tz = TimeZone.getTimeZone("Europe/Rome");
|
||||
Calendar cal = Calendar.getInstance(tz, Locale.ITALIAN);
|
||||
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ITALIAN);
|
||||
Date dateBeforeDST = df.parse("2018-03-25 01:55");
|
||||
prettyPrint(cal.getTimeZone());
|
||||
|
||||
cal.setTime(dateBeforeDST);
|
||||
System.out.println("Before DST (00:55 UTC - 01:55 GMT+1) = " + dateBeforeDST);
|
||||
|
||||
System.out.println("With this Calendar " + (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (60 * 1000) + " minutes must be added to UTC (GMT TimeZone) to get a correct date for this TimeZone\n");
|
||||
assertThat(cal.get(Calendar.ZONE_OFFSET)).isEqualTo(3600000);
|
||||
assertThat(cal.get(Calendar.DST_OFFSET)).isEqualTo(0);
|
||||
|
||||
cal.add(Calendar.MINUTE, 10);
|
||||
|
||||
Date dateAfterDST = cal.getTime();
|
||||
|
||||
System.out.println(" After DST (01:05 UTC - 03:05 GMT+2) = " + dateAfterDST);
|
||||
System.out.println("With this Calendar " + (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (60 * 1000) + " minutes must be added to UTC (GMT TimeZone) to get a correct date for this TimeZone\n");
|
||||
assertThat(cal.get(Calendar.DST_OFFSET)).isEqualTo(3600000);
|
||||
assertThat(dateAfterDST).isEqualTo(df.parse("2018-03-25 03:05"));
|
||||
|
||||
Long deltaBetweenDatesInMillis = dateAfterDST.getTime() - dateBeforeDST.getTime();
|
||||
Long tenMinutesInMillis = (1000L * 60 * 10);
|
||||
assertThat(deltaBetweenDatesInMillis).isEqualTo(tenMinutesInMillis);
|
||||
}
|
||||
|
||||
private void prettyPrint(TimeZone tz) {
|
||||
|
||||
//@formatter:off
|
||||
System.out.println(String.format(
|
||||
" Zone ID = %s (%s)\n"
|
||||
+ " RawOffset = %s minutes\n"
|
||||
+ " DST = %s minutes\n"
|
||||
+ " -----------------------------------------",
|
||||
tz.getID(), tz.getDisplayName(), tz.getRawOffset()/60000, tz.getDSTSavings()/60000));
|
||||
//@formatter:on
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void whenIterating_ThenPrintAllTimeZones() {
|
||||
for (String id : TimeZone.getAvailableIDs()) {
|
||||
TimeZone tz = TimeZone.getTimeZone(id);
|
||||
prettyPrint(tz);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
package com.baeldung.dst;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class DaylightSavingTimeJavaTimeExamplesTest {
|
||||
|
||||
@Test
|
||||
public void givenItalianTimeZone_WhenDSTHappens_ThenCorrectlyShiftTimeZone() throws ParseException {
|
||||
ZoneId italianZoneId = ZoneId.of("Europe/Rome");
|
||||
|
||||
LocalDateTime localDateTimeBeforeDST = LocalDateTime.of(2018, 3, 25, 1, 55);
|
||||
System.out.println(localDateTimeBeforeDST);
|
||||
assertThat(localDateTimeBeforeDST.toString()).isEqualTo("2018-03-25T01:55");
|
||||
|
||||
ZonedDateTime zonedDateTimeBeforeDST = localDateTimeBeforeDST.atZone(italianZoneId);
|
||||
prettyPrint(zonedDateTimeBeforeDST);
|
||||
assertThat(zonedDateTimeBeforeDST.toString()).isEqualTo("2018-03-25T01:55+01:00[Europe/Rome]");
|
||||
|
||||
ZonedDateTime zonedDateTimeAfterDST = zonedDateTimeBeforeDST.plus(10, ChronoUnit.MINUTES);
|
||||
prettyPrint(zonedDateTimeAfterDST);
|
||||
assertThat(zonedDateTimeAfterDST.toString()).isEqualTo("2018-03-25T03:05+02:00[Europe/Rome]");
|
||||
|
||||
Long deltaBetweenDatesInMinutes = ChronoUnit.MINUTES.between(zonedDateTimeBeforeDST, zonedDateTimeAfterDST);
|
||||
assertThat(deltaBetweenDatesInMinutes).isEqualTo(10);
|
||||
|
||||
}
|
||||
|
||||
private void prettyPrint(ZonedDateTime zdt) {
|
||||
//@formatter:off
|
||||
System.out.println(String.format(
|
||||
" ZonedDateTime = %s\n"
|
||||
+ " Zone ID = %s (%s)\n"
|
||||
+ " RawOffset = %s minutes\n"
|
||||
+ " -----------------------------------------",
|
||||
zdt, zdt.getZone(), zdt.getZone().getId(), zdt.getOffset().getTotalSeconds()/60));
|
||||
//@formatter:on
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCounting_ThenPrintDifferencesBetweenAPIs() {
|
||||
System.out.println("Total java.time.ZoneId count : " + ZoneId.getAvailableZoneIds()
|
||||
.size());
|
||||
System.out.println("Total java.util.TimeZone Id count : " + TimeZone.getAvailableIDs().length);
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class FinalUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenChangedFinalClassProperties_thenChanged() {
|
||||
Cat cat = new Cat();
|
||||
cat.setWeight(1);
|
||||
|
||||
assertEquals(1, cat.getWeight());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFinalVariableAssign_thenOnlyOnce() {
|
||||
final int i;
|
||||
i = 1;
|
||||
// i=2;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenChangedFinalReference_thenChanged() {
|
||||
|
||||
final Cat cat = new Cat();
|
||||
// cat=new Cat();
|
||||
cat.setWeight(5);
|
||||
|
||||
assertEquals(5, cat.getWeight());
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.baeldung.inheritancecomposition.test;
|
||||
|
||||
import com.baeldung.inheritancecomposition.model.Actress;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class ActressUnitTest {
|
||||
|
||||
private static Actress actress;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpActressInstance() {
|
||||
actress = new Actress("Susan", "susan@domain.com", 30);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenActressInstance_whenCalledgetName_thenEqual() {
|
||||
assertThat(actress.getName()).isEqualTo("Susan");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenActressInstance_whenCalledgetEmail_thenEqual() {
|
||||
assertThat(actress.getEmail()).isEqualTo("susan@domain.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenActressInstance_whenCalledgetAge_thenEqual() {
|
||||
assertThat(actress.getAge()).isEqualTo(30);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenActressInstance_whenCalledreadScript_thenEqual() {
|
||||
assertThat(actress.readScript("Psycho")).isEqualTo("Reading the script of Psycho");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenActressInstance_whenCalledperfomRole_thenEqual() {
|
||||
assertThat(actress.performRole()).isEqualTo("Performing a role");
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.inheritancecomposition.test;
|
||||
|
||||
import com.baeldung.inheritancecomposition.model.Computer;
|
||||
import com.baeldung.inheritancecomposition.model.Memory;
|
||||
import com.baeldung.inheritancecomposition.model.Processor;
|
||||
import com.baeldung.inheritancecomposition.model.StandardMemory;
|
||||
import com.baeldung.inheritancecomposition.model.StandardProcessor;
|
||||
import com.baeldung.inheritancecomposition.model.StandardSoundCard;
|
||||
import java.util.Optional;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CompositionUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void givenComputerInstance_whenExtractedEachField_thenThreeAssertions() {
|
||||
Computer computer = new Computer(new StandardProcessor("Intel I3"), new StandardMemory("Kingston", "1TB"));
|
||||
computer.setSoundCard(new StandardSoundCard("Generic Sound Card"));
|
||||
assertThat(computer.getProcessor()).isInstanceOf(Processor.class);
|
||||
assertThat(computer.getMemory()).isInstanceOf(Memory.class);
|
||||
assertThat(computer.getSoundCard()).isInstanceOf(Optional.class);
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.inheritancecomposition.test;
|
||||
|
||||
import com.baeldung.inheritancecomposition.model.Actress;
|
||||
import com.baeldung.inheritancecomposition.model.Person;
|
||||
import com.baeldung.inheritancecomposition.model.Waitress;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class InheritanceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenWaitressInstance_whenCheckedType_thenIsInstanceOfPerson() {
|
||||
assertThat(new Waitress("Mary", "mary@domain.com", 22)).isInstanceOf(Person.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenActressInstance_whenCheckedType_thenIsInstanceOfPerson() {
|
||||
assertThat(new Actress("Susan", "susan@domain.com", 30)).isInstanceOf(Person.class);
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.inheritancecomposition.test;
|
||||
|
||||
import com.baeldung.inheritancecomposition.model.Person;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class PersonUnitTest {
|
||||
|
||||
private static Person person;
|
||||
|
||||
@BeforeClass
|
||||
public static void setPersonInstance() {
|
||||
person = new Person("John", "john@domain.com", 35);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPersonInstance_whenCalledgetName_thenEqual() {
|
||||
assertThat(person.getName()).isEqualTo("John");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPersonInstance_whenCalledgetEmail_thenEqual() {
|
||||
assertThat(person.getEmail()).isEqualTo("john@domain.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPersonInstance_whenCalledgetAge_thenEqual() {
|
||||
assertThat(person.getAge()).isEqualTo(35);
|
||||
}
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
package com.baeldung.inheritancecomposition.test;
|
||||
|
||||
import com.baeldung.inheritancecomposition.model.Waitress;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class WaitressUnitTest {
|
||||
|
||||
private static Waitress waitress;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpWaitressInstance() {
|
||||
waitress = new Waitress("Mary", "mary@domain.com", 22);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWaitressInstance_whenCalledgetName_thenOneAssertion() {
|
||||
assertThat(waitress.getName()).isEqualTo("Mary");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWaitressInstance_whenCalledgetEmail_thenOneAssertion() {
|
||||
assertThat(waitress.getEmail()).isEqualTo("mary@domain.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWaitressInstance_whenCalledgetAge_thenOneAssertion() {
|
||||
assertThat(waitress.getAge()).isEqualTo(22);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWaitressInstance_whenCalledserveStarter_thenOneAssertion() {
|
||||
assertThat(waitress.serveStarter("mixed salad")).isEqualTo("Serving a mixed salad");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWaitressInstance_whenCalledserveMainCourse_thenOneAssertion() {
|
||||
assertThat(waitress.serveMainCourse("steak")).isEqualTo("Serving a steak");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWaitressInstance_whenCalledserveDessert_thenOneAssertion() {
|
||||
assertThat(waitress.serveDessert("cup of coffee")).isEqualTo("Serving a cup of coffee");
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package com.baeldung.filesystem
|
||||
|
||||
import java.io.BufferedReader
|
||||
import java.io.File
|
||||
import java.io.InputStream
|
||||
|
||||
class FileReader {
|
||||
|
||||
fun readFileLineByLineUsingForEachLine(fileName: String): List<String> {
|
||||
val lineList = mutableListOf<String>()
|
||||
File(fileName).forEachLine { line -> lineList.add(line) }
|
||||
return lineList
|
||||
}
|
||||
|
||||
fun readFileAsLinesUsingUseLines(fileName: String): List<String> {
|
||||
val lineList = mutableListOf<String>()
|
||||
File(fileName).useLines { lines -> lineList.addAll(lines) }
|
||||
return lineList
|
||||
}
|
||||
|
||||
fun readFileAsLinesUsingBufferedReader(fileName: String): List<String> {
|
||||
val bufferedReader: BufferedReader = File(fileName).bufferedReader()
|
||||
return bufferedReader.readLines()
|
||||
}
|
||||
|
||||
fun readFileAsLinesUsingReadLines(fileName: String): List<String> {
|
||||
return File(fileName).readLines()
|
||||
}
|
||||
|
||||
fun readFileAsTextUsingInputStream(fileName: String): String {
|
||||
val inputStream: InputStream = File(fileName).inputStream()
|
||||
return inputStream.readBytes().toString(Charsets.UTF_8)
|
||||
}
|
||||
|
||||
fun readFileDirectlyAsText(fileName: String): String {
|
||||
return File(fileName).readText(Charsets.UTF_8)
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.baeldung.filesystem
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
internal class FileReaderTest {
|
||||
|
||||
private val fileName = "src/test/resources/Kotlin.in"
|
||||
|
||||
private val fileReader = FileReader()
|
||||
|
||||
@Test
|
||||
fun whenReadFileLineByLineUsingForEachLine_thenCorrect() {
|
||||
val lines = fileReader.readFileLineByLineUsingForEachLine(fileName)
|
||||
|
||||
assertTrue { lines.contains("Hello to Kotlin. Its:") }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenReadFileAsLinesUsingUseLines_thenCorrect() {
|
||||
val lines = fileReader.readFileAsLinesUsingUseLines(fileName)
|
||||
|
||||
assertTrue { lines.contains("1. Concise") }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenReadFileAsLinesUsingBufferedReader_thenCorrect() {
|
||||
val lines = fileReader.readFileAsLinesUsingBufferedReader(fileName)
|
||||
|
||||
assertTrue { lines.contains("2. Safe") }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenReadFileAsLinesUsingReadLines_thenCorrect() {
|
||||
val lines = fileReader.readFileAsLinesUsingReadLines(fileName)
|
||||
|
||||
assertTrue { lines.contains("3. Interoperable") }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenReadFileAsTextUsingInputStream_thenCorrect() {
|
||||
val text = fileReader.readFileAsTextUsingInputStream(fileName)
|
||||
|
||||
assertTrue { text.contains("4. Tool-friendly") }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenReadDirectlyAsText_thenCorrect() {
|
||||
val text = fileReader.readFileDirectlyAsText(fileName)
|
||||
|
||||
assertTrue { text.contains("Hello to Kotlin") }
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
object Counter {
|
||||
private var count: Int = 0
|
||||
|
||||
fun currentCount() = count
|
||||
|
||||
fun increment() {
|
||||
++count
|
||||
}
|
||||
|
||||
fun decrement() {
|
||||
--count
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class ObjectsTest {
|
||||
@Test
|
||||
fun singleton() {
|
||||
|
||||
Assert.assertEquals(42, SimpleSingleton.answer)
|
||||
Assert.assertEquals("Hello, world!", SimpleSingleton.greet("world"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun counter() {
|
||||
Assert.assertEquals(0, Counter.currentCount())
|
||||
Counter.increment()
|
||||
Assert.assertEquals(1, Counter.currentCount())
|
||||
Counter.decrement()
|
||||
Assert.assertEquals(0, Counter.currentCount())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun comparator() {
|
||||
val strings = listOf("Hello", "World")
|
||||
val sortedStrings = strings.sortedWith(ReverseStringComparator)
|
||||
|
||||
Assert.assertEquals(listOf("World", "Hello"), sortedStrings)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun companion() {
|
||||
Assert.assertEquals("You can see me", OuterClass.public)
|
||||
// Assert.assertEquals("You can't see me", OuterClass.secret) // Cannot access 'secret'
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
class OuterClass {
|
||||
companion object {
|
||||
private val secret = "You can't see me"
|
||||
val public = "You can see me"
|
||||
}
|
||||
|
||||
fun getSecretValue() = secret
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
object ReverseStringComparator : Comparator<String> {
|
||||
override fun compare(o1: String, o2: String) = o1.reversed().compareTo(o2.reversed())
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
object SimpleSingleton {
|
||||
val answer = 42;
|
||||
|
||||
fun greet(name: String) = "Hello, $name!"
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.kotlin.objects
|
||||
|
||||
class StaticClass {
|
||||
companion object {
|
||||
@JvmStatic
|
||||
val staticField = 42
|
||||
}
|
||||
}
|
5
core-kotlin/src/test/resources/Kotlin.in
Normal file
5
core-kotlin/src/test/resources/Kotlin.in
Normal file
@ -0,0 +1,5 @@
|
||||
Hello to Kotlin. Its:
|
||||
1. Concise
|
||||
2. Safe
|
||||
3. Interoperable
|
||||
4. Tool-friendly
|
1
data-structures/.gitignore
vendored
Normal file
1
data-structures/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
/target/
|
4
data-structures/README.md
Normal file
4
data-structures/README.md
Normal file
@ -0,0 +1,4 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [The Trie Data Structure in Java](http://www.baeldung.com/trie-java)
|
||||
- [Implementing a Binary Tree in Java](http://www.baeldung.com/java-binary-tree)
|
24
data-structures/pom.xml
Normal file
24
data-structures/pom.xml
Normal file
@ -0,0 +1,24 @@
|
||||
<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>data-structures</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>
|
@ -48,6 +48,13 @@
|
||||
<version>1.5.0-RELEASE</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Web3j -->
|
||||
<dependency>
|
||||
<groupId>org.web3j</groupId>
|
||||
<artifactId>core</artifactId>
|
||||
<version>3.3.1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- JSTL/JSP -->
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
|
41
ethereumj/src/main/java/com/baeldung/web3j/Template.java
Normal file
41
ethereumj/src/main/java/com/baeldung/web3j/Template.java
Normal file
@ -0,0 +1,41 @@
|
||||
package com.baeldung.web3j;
|
||||
|
||||
import com.baeldung.web3j.contracts.Greeting;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.web3j.crypto.Credentials;
|
||||
import org.web3j.crypto.WalletUtils;
|
||||
import org.web3j.protocol.Web3j;
|
||||
import org.web3j.protocol.core.methods.response.TransactionReceipt;
|
||||
import org.web3j.protocol.http.HttpService;
|
||||
import org.web3j.tx.Contract;
|
||||
import org.web3j.tx.ManagedTransaction;
|
||||
|
||||
public class Template {
|
||||
|
||||
private Logger l = LoggerFactory.getLogger(Template.class);
|
||||
|
||||
private void deployContract() throws Exception{
|
||||
|
||||
Web3j web3j = Web3j.build(new HttpService("https://rinkeby.infura.io/<your_token>"));
|
||||
|
||||
Credentials credentials =
|
||||
WalletUtils.loadCredentials(
|
||||
"<password>",
|
||||
"/path/to/<walletfile>");
|
||||
|
||||
Greeting contract = Greeting.deploy(
|
||||
web3j, credentials,
|
||||
ManagedTransaction.GAS_PRICE, Contract.GAS_LIMIT,
|
||||
"Hello blockchain world!").send();
|
||||
|
||||
String contractAddress = contract.getContractAddress();
|
||||
l.debug("Smart contract deployed to address "+ contractAddress);
|
||||
|
||||
l.debug("Value stored in remote smart contract: "+ contract.greet().send());
|
||||
|
||||
TransactionReceipt transactionReceipt = contract.setGreeting("Well hello again").send();
|
||||
|
||||
l.debug("New value stored in remote smart contract: "+ contract.greet().send());
|
||||
}
|
||||
}
|
@ -0,0 +1,71 @@
|
||||
package com.baeldung.web3j.contracts;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import org.web3j.abi.FunctionEncoder;
|
||||
import org.web3j.abi.TypeReference;
|
||||
import org.web3j.abi.datatypes.Function;
|
||||
import org.web3j.abi.datatypes.Type;
|
||||
import org.web3j.abi.datatypes.Utf8String;
|
||||
import org.web3j.crypto.Credentials;
|
||||
import org.web3j.protocol.Web3j;
|
||||
import org.web3j.protocol.core.RemoteCall;
|
||||
import org.web3j.protocol.core.methods.response.TransactionReceipt;
|
||||
import org.web3j.tx.Contract;
|
||||
import org.web3j.tx.TransactionManager;
|
||||
|
||||
/**
|
||||
* <p>Auto generated code.
|
||||
* <p><strong>Do not modify!</strong>
|
||||
* <p>Please use the <a href="https://docs.web3j.io/command_line.html">web3j command line tools</a>,
|
||||
* or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the
|
||||
* <a href="https://github.com/web3j/web3j/tree/master/codegen">codegen module</a> to update.
|
||||
*
|
||||
* <p>Generated with web3j version 3.3.1.
|
||||
*/
|
||||
public class Greeting extends Contract {
|
||||
private static final String BINARY = "6060604052341561000f57600080fd5b6040516103cc3803806103cc833981016040528080519091019050600181805161003d92916020019061005f565b505060008054600160a060020a03191633600160a060020a03161790556100fa565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100a057805160ff19168380011785556100cd565b828001600101855582156100cd579182015b828111156100cd5782518255916020019190600101906100b2565b506100d99291506100dd565b5090565b6100f791905b808211156100d957600081556001016100e3565b90565b6102c3806101096000396000f30060606040526004361061004b5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663a41368628114610050578063cfae3217146100a3575b600080fd5b341561005b57600080fd5b6100a160046024813581810190830135806020601f8201819004810201604051908101604052818152929190602084018383808284375094965061012d95505050505050565b005b34156100ae57600080fd5b6100b6610144565b60405160208082528190810183818151815260200191508051906020019080838360005b838110156100f25780820151838201526020016100da565b50505050905090810190601f16801561011f5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60018180516101409291602001906101ed565b5050565b61014c61026b565b60018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156101e25780601f106101b7576101008083540402835291602001916101e2565b820191906000526020600020905b8154815290600101906020018083116101c557829003601f168201915b505050505090505b90565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061022e57805160ff191683800117855561025b565b8280016001018555821561025b579182015b8281111561025b578251825591602001919060010190610240565b5061026792915061027d565b5090565b60206040519081016040526000815290565b6101ea91905b8082111561026757600081556001016102835600a165627a7a723058206cfb726ed213c2fe842a4c886c8089e918b6de9c6cdfb372fa459eca4840c5740029";
|
||||
|
||||
protected Greeting(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
|
||||
super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);
|
||||
}
|
||||
|
||||
protected Greeting(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
|
||||
super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit);
|
||||
}
|
||||
|
||||
public RemoteCall<TransactionReceipt> setGreeting(String _message) {
|
||||
final Function function = new Function(
|
||||
"setGreeting",
|
||||
Arrays.<Type>asList(new org.web3j.abi.datatypes.Utf8String(_message)),
|
||||
Collections.<TypeReference<?>>emptyList());
|
||||
return executeRemoteCallTransaction(function);
|
||||
}
|
||||
|
||||
public RemoteCall<String> greet() {
|
||||
final Function function = new Function("greet",
|
||||
Arrays.<Type>asList(),
|
||||
Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {}));
|
||||
return executeRemoteCallSingleValueReturn(function, String.class);
|
||||
}
|
||||
|
||||
public static RemoteCall<Greeting> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit, String _message) {
|
||||
String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.<Type>asList(new org.web3j.abi.datatypes.Utf8String(_message)));
|
||||
return deployRemoteCall(Greeting.class, web3j, credentials, gasPrice, gasLimit, BINARY, encodedConstructor);
|
||||
}
|
||||
|
||||
public static RemoteCall<Greeting> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit, String _message) {
|
||||
String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.<Type>asList(new org.web3j.abi.datatypes.Utf8String(_message)));
|
||||
return deployRemoteCall(Greeting.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, encodedConstructor);
|
||||
}
|
||||
|
||||
public static Greeting load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
|
||||
return new Greeting(contractAddress, web3j, credentials, gasPrice, gasLimit);
|
||||
}
|
||||
|
||||
public static Greeting load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
|
||||
return new Greeting(contractAddress, web3j, transactionManager, gasPrice, gasLimit);
|
||||
}
|
||||
}
|
||||
|
19
ethereumj/src/main/resources/solidity/Greeting.sol
Normal file
19
ethereumj/src/main/resources/solidity/Greeting.sol
Normal file
@ -0,0 +1,19 @@
|
||||
pragma solidity ^0.4.0;
|
||||
|
||||
contract Greeting {
|
||||
address creator;
|
||||
string message;
|
||||
|
||||
function Greeting(string _message) {
|
||||
message = _message;
|
||||
creator = msg.sender;
|
||||
}
|
||||
|
||||
function greet() constant returns (string) {
|
||||
return message;
|
||||
}
|
||||
|
||||
function setGreeting(string _message) {
|
||||
message = _message;
|
||||
}
|
||||
}
|
1
ethereumj/src/main/resources/solidity/build/Greeting.abi
Normal file
1
ethereumj/src/main/resources/solidity/build/Greeting.abi
Normal file
@ -0,0 +1 @@
|
||||
[{"constant":false,"inputs":[{"name":"_message","type":"string"}],"name":"setGreeting","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"greet","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"_message","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]
|
1
ethereumj/src/main/resources/solidity/build/Greeting.bin
Normal file
1
ethereumj/src/main/resources/solidity/build/Greeting.bin
Normal file
@ -0,0 +1 @@
|
||||
6060604052341561000f57600080fd5b6040516103cc3803806103cc833981016040528080519091019050600181805161003d92916020019061005f565b505060008054600160a060020a03191633600160a060020a03161790556100fa565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100a057805160ff19168380011785556100cd565b828001600101855582156100cd579182015b828111156100cd5782518255916020019190600101906100b2565b506100d99291506100dd565b5090565b6100f791905b808211156100d957600081556001016100e3565b90565b6102c3806101096000396000f30060606040526004361061004b5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663a41368628114610050578063cfae3217146100a3575b600080fd5b341561005b57600080fd5b6100a160046024813581810190830135806020601f8201819004810201604051908101604052818152929190602084018383808284375094965061012d95505050505050565b005b34156100ae57600080fd5b6100b6610144565b60405160208082528190810183818151815260200191508051906020019080838360005b838110156100f25780820151838201526020016100da565b50505050905090810190601f16801561011f5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60018180516101409291602001906101ed565b5050565b61014c61026b565b60018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156101e25780601f106101b7576101008083540402835291602001916101e2565b820191906000526020600020905b8154815290600101906020018083116101c557829003601f168201915b505050505090505b90565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061022e57805160ff191683800117855561025b565b8280016001018555821561025b579182015b8281111561025b578251825591602001919060010190610240565b5061026792915061027d565b5090565b60206040519081016040526000815290565b6101ea91905b8082111561026757600081556001016102835600a165627a7a723058206cfb726ed213c2fe842a4c886c8089e918b6de9c6cdfb372fa459eca4840c5740029
|
2
flips/README.md
Normal file
2
flips/README.md
Normal file
@ -0,0 +1,2 @@
|
||||
### Relevant Articles:
|
||||
- [Guide to Flips For Spring](http://www.baeldung.com/guide-to-flips-for-spring/)
|
65
flips/pom.xml
Normal file
65
flips/pom.xml
Normal file
@ -0,0 +1,65 @@
|
||||
<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>flips</groupId>
|
||||
<artifactId>flips</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>flips</name>
|
||||
|
||||
<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>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<version>1.5.10.RELEASE</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<version>1.5.9.RELEASE</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.feature-flip</groupId>
|
||||
<artifactId>flips-web</artifactId>
|
||||
<version>1.0.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<!-- Check for the most recent available version: https://projectlombok.org/changelog.html -->
|
||||
<version>1.16.18</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.flips;
|
||||
|
||||
import org.flips.describe.config.FlipWebContextConfiguration;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
@SpringBootApplication
|
||||
@Import(FlipWebContextConfiguration.class)
|
||||
public class ApplicationConfig {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ApplicationConfig.class, args);
|
||||
}
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
package com.baeldung.flips.controller;
|
||||
|
||||
import com.baeldung.flips.model.Foo;
|
||||
import com.baeldung.flips.service.FlipService;
|
||||
import org.flips.annotation.FlipOnDateTime;
|
||||
import org.flips.annotation.FlipOnDaysOfWeek;
|
||||
import org.flips.annotation.FlipOnEnvironmentProperty;
|
||||
import org.flips.annotation.FlipOnProfiles;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
public class FlipController {
|
||||
|
||||
private FlipService flipService;
|
||||
|
||||
@Autowired
|
||||
public FlipController(FlipService flipService) {
|
||||
this.flipService = flipService;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/foos", method = RequestMethod.GET)
|
||||
@FlipOnProfiles(activeProfiles = "dev")
|
||||
public List<Foo> getAllFoos() {
|
||||
return flipService.getAllFoos();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/foo/{id}", method = RequestMethod.GET)
|
||||
@FlipOnDaysOfWeek(daysOfWeek = {
|
||||
DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY,
|
||||
DayOfWeek.FRIDAY, DayOfWeek.SATURDAY, DayOfWeek.SUNDAY
|
||||
})
|
||||
public Foo getFooByNewId(@PathVariable int id) {
|
||||
return flipService.getFooById(id).orElse(new Foo("Not Found", -1));
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/foo/last", method = RequestMethod.GET)
|
||||
@FlipOnDateTime(cutoffDateTimeProperty = "last.active.after")
|
||||
public Foo getLastFoo() {
|
||||
return flipService.getLastFoo();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/foo/first", method = RequestMethod.GET)
|
||||
@FlipOnDateTime(cutoffDateTimeProperty = "first.active.after")
|
||||
public Foo getFirstFoo() {
|
||||
return flipService.getLastFoo();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/foos/{id}", method = RequestMethod.GET)
|
||||
@FlipOnEnvironmentProperty(property = "feature.foo.by.id", expectedValue = "Y")
|
||||
public Foo getFooById(@PathVariable int id) {
|
||||
return flipService.getFooById(id).orElse(new Foo("Not Found", -1));
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/foo/new", method = RequestMethod.GET)
|
||||
public Foo getNewThing() {
|
||||
return flipService.getNewFoo();
|
||||
}
|
||||
}
|
11
flips/src/main/java/com/baeldung/flips/model/Foo.java
Normal file
11
flips/src/main/java/com/baeldung/flips/model/Foo.java
Normal file
@ -0,0 +1,11 @@
|
||||
package com.baeldung.flips.model;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@Data
|
||||
@RequiredArgsConstructor
|
||||
public class Foo {
|
||||
private final String name;
|
||||
private final int id;
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package com.baeldung.flips.service;
|
||||
|
||||
import com.baeldung.flips.model.Foo;
|
||||
import org.flips.annotation.FlipBean;
|
||||
import org.flips.annotation.FlipOnSpringExpression;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class FlipService {
|
||||
|
||||
private final List<Foo> foos;
|
||||
|
||||
public FlipService() {
|
||||
foos = new ArrayList<>();
|
||||
foos.add(new Foo("Foo1", 1));
|
||||
foos.add(new Foo("Foo2", 2));
|
||||
foos.add(new Foo("Foo3", 3));
|
||||
foos.add(new Foo("Foo4", 4));
|
||||
foos.add(new Foo("Foo5", 5));
|
||||
foos.add(new Foo("Foo6", 6));
|
||||
|
||||
}
|
||||
|
||||
public List<Foo> getAllFoos() {
|
||||
return foos;
|
||||
}
|
||||
|
||||
public Optional<Foo> getFooById(int id) {
|
||||
return foos.stream().filter(foo -> (foo.getId() == id)).findFirst();
|
||||
}
|
||||
|
||||
@FlipBean(with = NewFlipService.class)
|
||||
@FlipOnSpringExpression(expression = "(2 + 2) == 4")
|
||||
public Foo getNewFoo() {
|
||||
return new Foo("New Foo!", 99);
|
||||
}
|
||||
|
||||
public Foo getLastFoo() {
|
||||
return foos.get(foos.size() - 1);
|
||||
}
|
||||
|
||||
public Foo getFirstFoo() {
|
||||
return foos.get(0);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.flips.service;
|
||||
|
||||
import com.baeldung.flips.model.Foo;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class NewFlipService {
|
||||
|
||||
public Foo getNewFoo() {
|
||||
return new Foo("Shiny New Foo!", 100);
|
||||
}
|
||||
|
||||
}
|
5
flips/src/main/resources/application.properties
Normal file
5
flips/src/main/resources/application.properties
Normal file
@ -0,0 +1,5 @@
|
||||
feature.foo.by.id=Y
|
||||
feature.new.foo=Y
|
||||
last.active.after=2018-03-14T00:00:00Z
|
||||
first.active.after=2999-03-15T00:00:00Z
|
||||
logging.level.org.flips=info
|
@ -0,0 +1,74 @@
|
||||
package com.baeldung.flips.controller;
|
||||
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(properties = {
|
||||
"feature.foo.by.id=Y",
|
||||
"feature.new.foo=Y",
|
||||
"last.active.after=2018-03-14T00:00:00Z",
|
||||
"first.active.after=2999-03-15T00:00:00Z",
|
||||
"logging.level.org.flips=info"
|
||||
|
||||
})
|
||||
@AutoConfigureMockMvc
|
||||
@ActiveProfiles("dev")
|
||||
public class FlipControllerTest {
|
||||
|
||||
@Autowired private MockMvc mvc;
|
||||
|
||||
@Test
|
||||
public void givenValidDayOfWeek_APIAvailable() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/foo/1"))
|
||||
.andExpect(MockMvcResultMatchers.status().is(200))
|
||||
.andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1")))
|
||||
.andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidDate_APIAvailable() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/foo/last"))
|
||||
.andExpect(MockMvcResultMatchers.status().is(200))
|
||||
.andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo6")))
|
||||
.andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(6)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidDate_APINotAvailable() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/foo/first"))
|
||||
.andExpect(MockMvcResultMatchers.status().is(501));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCorrectProfile_APIAvailable() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/foos"))
|
||||
.andExpect(MockMvcResultMatchers.status().isOk())
|
||||
.andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(6)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPropertySet_APIAvailable() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/foos/1"))
|
||||
.andExpect(MockMvcResultMatchers.status().isOk())
|
||||
.andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1")))
|
||||
.andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getValidExpression_FlipBean() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/foo/new"))
|
||||
.andExpect(MockMvcResultMatchers.status().is(200))
|
||||
.andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Shiny New Foo!")))
|
||||
.andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(100)));
|
||||
}
|
||||
}
|
12
grails/.gitignore
vendored
Normal file
12
grails/.gitignore
vendored
Normal file
@ -0,0 +1,12 @@
|
||||
Thumbs.db
|
||||
.DS_Store
|
||||
.gradle
|
||||
build/
|
||||
out/
|
||||
.idea
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.project
|
||||
.settings
|
||||
.classpath
|
3
grails/README.md
Normal file
3
grails/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
### Relevant articles
|
||||
|
||||
- [Build an MVC Web Application with Grails](http://www.baeldung.com/grails-mvc-application)
|
80
grails/build.gradle
Normal file
80
grails/build.gradle
Normal file
@ -0,0 +1,80 @@
|
||||
buildscript {
|
||||
repositories {
|
||||
mavenLocal()
|
||||
maven { url "https://repo.grails.org/grails/core" }
|
||||
}
|
||||
dependencies {
|
||||
classpath "org.grails:grails-gradle-plugin:$grailsVersion"
|
||||
classpath "org.grails.plugins:hibernate5:${gormVersion-".RELEASE"}"
|
||||
classpath "com.bertramlabs.plugins:asset-pipeline-gradle:2.14.8"
|
||||
}
|
||||
}
|
||||
|
||||
version "0.1"
|
||||
group "grails"
|
||||
|
||||
apply plugin:"eclipse"
|
||||
apply plugin:"idea"
|
||||
apply plugin:"war"
|
||||
apply plugin:"org.grails.grails-web"
|
||||
apply plugin:"asset-pipeline"
|
||||
apply plugin:"org.grails.grails-gsp"
|
||||
|
||||
repositories {
|
||||
mavenLocal()
|
||||
maven { url "https://repo.grails.org/grails/core" }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile "org.springframework.boot:spring-boot-starter-logging"
|
||||
compile "org.springframework.boot:spring-boot-autoconfigure"
|
||||
compile "org.grails:grails-core"
|
||||
compile "org.springframework.boot:spring-boot-starter-actuator"
|
||||
compile "org.springframework.boot:spring-boot-starter-tomcat"
|
||||
compile "org.grails:grails-web-boot"
|
||||
compile "org.grails:grails-logging"
|
||||
compile "org.grails:grails-plugin-rest"
|
||||
compile "org.grails:grails-plugin-databinding"
|
||||
compile "org.grails:grails-plugin-i18n"
|
||||
compile "org.grails:grails-plugin-services"
|
||||
compile "org.grails:grails-plugin-url-mappings"
|
||||
compile "org.grails:grails-plugin-interceptors"
|
||||
compile "org.grails.plugins:cache"
|
||||
compile "org.grails.plugins:async"
|
||||
compile "org.grails.plugins:scaffolding"
|
||||
compile "org.grails.plugins:events"
|
||||
compile "org.grails.plugins:hibernate5"
|
||||
compile "org.hibernate:hibernate-core:5.1.5.Final"
|
||||
compile "org.grails.plugins:gsp"
|
||||
console "org.grails:grails-console"
|
||||
profile "org.grails.profiles:web"
|
||||
runtime "org.glassfish.web:el-impl:2.1.2-b03"
|
||||
runtime "com.h2database:h2"
|
||||
runtime "org.apache.tomcat:tomcat-jdbc"
|
||||
runtime "com.bertramlabs.plugins:asset-pipeline-grails:2.14.8"
|
||||
testCompile "org.grails:grails-gorm-testing-support"
|
||||
testCompile "org.grails:grails-web-testing-support"
|
||||
testCompile "org.grails.plugins:geb:1.1.2"
|
||||
testRuntime "org.seleniumhq.selenium:selenium-chrome-driver:2.47.1"
|
||||
testRuntime "org.seleniumhq.selenium:selenium-htmlunit-driver:2.47.1"
|
||||
testRuntime "net.sourceforge.htmlunit:htmlunit:2.18"
|
||||
}
|
||||
|
||||
bootRun {
|
||||
jvmArgs('-Dspring.output.ansi.enabled=always')
|
||||
addResources = true
|
||||
String springProfilesActive = 'spring.profiles.active'
|
||||
systemProperty springProfilesActive, System.getProperty(springProfilesActive)
|
||||
}
|
||||
|
||||
tasks.withType(Test) {
|
||||
systemProperty "geb.env", System.getProperty('geb.env')
|
||||
systemProperty "geb.build.reportsDir", reporting.file("geb/integrationTest")
|
||||
systemProperty "webdriver.chrome.driver", System.getProperty('webdriver.chrome.driver')
|
||||
systemProperty "webdriver.gecko.driver", System.getProperty('webdriver.gecko.driver')
|
||||
}
|
||||
|
||||
assets {
|
||||
minifyJs = true
|
||||
minifyCss = true
|
||||
}
|
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