Merge branch 'master' into BAEL-1423-jctools
This commit is contained in:
commit
45a4e47ddc
2
.gitignore
vendored
2
.gitignore
vendored
@ -34,8 +34,6 @@ spring-security-openid/src/main/resources/application.properties
|
||||
|
||||
spring-all/*.log
|
||||
|
||||
*.jar
|
||||
|
||||
SpringDataInjectionDemo/.mvn/wrapper/maven-wrapper.properties
|
||||
|
||||
spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties
|
||||
|
2
activejdbc/README.md
Normal file
2
activejdbc/README.md
Normal file
@ -0,0 +1,2 @@
|
||||
### Relevant Articles:
|
||||
- [Introduction to ActiveJDBC](http://www.baeldung.com/active-jdbc)
|
@ -1,129 +1,134 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>activejdbc</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>activejdbc</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<activejdbc.version>1.4.13</activejdbc.version>
|
||||
<environments>development.test,development</environments>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<encoding>UTF-8</encoding>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>activejdbc-instrumentation</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>process-classes</phase>
|
||||
<goals>
|
||||
<goal>instrument</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>db-migrator-maven-plugin</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<configuration>
|
||||
<configFile>${project.basedir}/src/main/resources/database.properties</configFile>
|
||||
<environments>${environments}</environments>
|
||||
</configuration>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>activejdbc</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>activejdbc</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<activejdbc.version>1.4.13</activejdbc.version>
|
||||
<environments>development.test,development</environments>
|
||||
</properties>
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.6.0</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<encoding>UTF-8</encoding>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>activejdbc-instrumentation</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>process-classes</phase>
|
||||
<goals>
|
||||
<goal>instrument</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>db-migrator-maven-plugin</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<configuration>
|
||||
<configFile>${project.basedir}/src/main/resources/database.properties</configFile>
|
||||
<environments>${environments}</environments>
|
||||
</configuration>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>5.1.34</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.18.1</version>
|
||||
<configuration>
|
||||
<reportFormat>brief</reportFormat>
|
||||
<trimStackTrace>true</trimStackTrace>
|
||||
<useFile>false</useFile>
|
||||
<includes>
|
||||
<include>**/*Spec*.java</include>
|
||||
<include>**/*Test*.java</include>
|
||||
</includes>
|
||||
<excludes>
|
||||
<exclude>**/helpers/*</exclude>
|
||||
<exclude>**/*$*</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>activejdbc</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>opensymphony</groupId>
|
||||
<artifactId>oscache</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>5.1.34</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.18.1</version>
|
||||
<configuration>
|
||||
<reportFormat>brief</reportFormat>
|
||||
<trimStackTrace>true</trimStackTrace>
|
||||
<useFile>false</useFile>
|
||||
<includes>
|
||||
<include>**/*Spec*.java</include>
|
||||
<include>**/*Test*.java</include>
|
||||
</includes>
|
||||
<excludes>
|
||||
<exclude>**/helpers/*</exclude>
|
||||
<exclude>**/*$*</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.javalite</groupId>
|
||||
<artifactId>activejdbc</artifactId>
|
||||
<version>${activejdbc.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>opensymphony</groupId>
|
||||
<artifactId>oscache</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>5.1.34</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>1.7.9</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>snapshots1</id>
|
||||
<name>JavaLite Snapshots1</name>
|
||||
<url>http://repo.javalite.io/</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>always</updatePolicy>
|
||||
<checksumPolicy>warn</checksumPolicy>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>snapshots2</id>
|
||||
<name>JavaLite Snapshots2</name>
|
||||
<url>http://repo.javalite.io/</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>always</updatePolicy>
|
||||
<checksumPolicy>warn</checksumPolicy>
|
||||
</snapshots>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>1.7.9</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>snapshots1</id>
|
||||
<name>JavaLite Snapshots1</name>
|
||||
<url>http://repo.javalite.io/</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>always</updatePolicy>
|
||||
<checksumPolicy>warn</checksumPolicy>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>snapshots2</id>
|
||||
<name>JavaLite Snapshots2</name>
|
||||
<url>http://repo.javalite.io/</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>always</updatePolicy>
|
||||
<checksumPolicy>warn</checksumPolicy>
|
||||
</snapshots>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
</project>
|
||||
|
@ -17,3 +17,6 @@
|
||||
- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance)
|
||||
- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element)
|
||||
- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm)
|
||||
- [A Maze Solver in Java](http://www.baeldung.com/java-solve-maze)
|
||||
- [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku)
|
||||
- [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words)
|
||||
|
@ -11,7 +11,11 @@
|
||||
<properties>
|
||||
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
|
@ -19,7 +19,7 @@ import java.util.List;
|
||||
import static junit.framework.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class CayenneAdvancedOperationTests {
|
||||
public class CayenneAdvancedOperationIntegrationTest {
|
||||
private static ObjectContext context = null;
|
||||
|
||||
@BeforeClass
|
@ -16,7 +16,7 @@ import static junit.framework.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
|
||||
public class CayenneOperationTests {
|
||||
public class CayenneOperationIntegrationTest {
|
||||
private static ObjectContext context = null;
|
||||
|
||||
@BeforeClass
|
3
apache-curator/README.md
Normal file
3
apache-curator/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Introduction to Apache Curator](http://www.baeldung.com/apache-curator)
|
32
apache-opennlp/pom.xml
Normal file
32
apache-opennlp/pom.xml
Normal file
@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>apache-opennlp</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.opennlp</groupId>
|
||||
<artifactId>opennlp-tools</artifactId>
|
||||
<version>1.8.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.9.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
100
apache-opennlp/src/main/resources/models/DoccatSample.txt
Normal file
100
apache-opennlp/src/main/resources/models/DoccatSample.txt
Normal file
File diff suppressed because one or more lines are too long
BIN
apache-opennlp/src/main/resources/models/en-chunker.bin
Normal file
BIN
apache-opennlp/src/main/resources/models/en-chunker.bin
Normal file
Binary file not shown.
301403
apache-opennlp/src/main/resources/models/en-lemmatizer.dict
Normal file
301403
apache-opennlp/src/main/resources/models/en-lemmatizer.dict
Normal file
File diff suppressed because it is too large
Load Diff
BIN
apache-opennlp/src/main/resources/models/en-ner-person.bin
Normal file
BIN
apache-opennlp/src/main/resources/models/en-ner-person.bin
Normal file
Binary file not shown.
BIN
apache-opennlp/src/main/resources/models/en-pos-maxent.bin
Normal file
BIN
apache-opennlp/src/main/resources/models/en-pos-maxent.bin
Normal file
Binary file not shown.
BIN
apache-opennlp/src/main/resources/models/en-sent.bin
Normal file
BIN
apache-opennlp/src/main/resources/models/en-sent.bin
Normal file
Binary file not shown.
BIN
apache-opennlp/src/main/resources/models/en-token.bin
Normal file
BIN
apache-opennlp/src/main/resources/models/en-token.bin
Normal file
Binary file not shown.
@ -0,0 +1,32 @@
|
||||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStream;
|
||||
import opennlp.tools.chunker.ChunkerME;
|
||||
import opennlp.tools.chunker.ChunkerModel;
|
||||
import opennlp.tools.postag.POSModel;
|
||||
import opennlp.tools.postag.POSTaggerME;
|
||||
import opennlp.tools.tokenize.SimpleTokenizer;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ChunkerTest {
|
||||
|
||||
@Test
|
||||
public void givenChunkerModel_whenChunk_thenChunksAreDetected() throws Exception {
|
||||
|
||||
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("He reckons the current account deficit will narrow to only 8 billion.");
|
||||
|
||||
InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin");
|
||||
POSModel posModel = new POSModel(inputStreamPOSTagger);
|
||||
POSTaggerME posTagger = new POSTaggerME(posModel);
|
||||
String tags[] = posTagger.tag(tokens);
|
||||
|
||||
InputStream inputStreamChunker = new FileInputStream("src/main/resources/models/en-chunker.bin");
|
||||
ChunkerModel chunkerModel = new ChunkerModel(inputStreamChunker);
|
||||
ChunkerME chunker = new ChunkerME(chunkerModel);
|
||||
String[] chunks = chunker.chunk(tokens, tags);
|
||||
assertThat(chunks).contains("B-NP", "B-VP", "B-NP", "I-NP", "I-NP", "I-NP", "B-VP", "I-VP", "B-PP", "B-NP", "I-NP", "I-NP", "O");
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
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 static org.assertj.core.api.Assertions.tuple;
|
||||
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)).extracting("lang", "confidence").contains(tuple("pob", 0.9999999950605625),
|
||||
tuple("ita", 4.939427661577956E-9), tuple("spa", 9.665954064665144E-15),
|
||||
tuple("fra", 8.250349924885834E-25));
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.InputStream;
|
||||
import opennlp.tools.lemmatizer.DictionaryLemmatizer;
|
||||
import opennlp.tools.postag.POSModel;
|
||||
import opennlp.tools.postag.POSTaggerME;
|
||||
import opennlp.tools.tokenize.SimpleTokenizer;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class LemmetizerTest {
|
||||
|
||||
@Test
|
||||
public void givenEnglishDictionary_whenLemmatize_thenLemmasAreDetected() throws Exception {
|
||||
|
||||
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("John has a sister named Penny.");
|
||||
|
||||
InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin");
|
||||
POSModel posModel = new POSModel(inputStreamPOSTagger);
|
||||
POSTaggerME posTagger = new POSTaggerME(posModel);
|
||||
String tags[] = posTagger.tag(tokens);
|
||||
InputStream dictLemmatizer = getClass().getResourceAsStream("/models/en-lemmatizer.dict");
|
||||
DictionaryLemmatizer lemmatizer = new DictionaryLemmatizer(dictLemmatizer);
|
||||
String[] lemmas = lemmatizer.lemmatize(tokens, tags);
|
||||
|
||||
assertThat(lemmas).contains("O", "have", "a", "sister", "name", "O", "O");
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import opennlp.tools.namefind.NameFinderME;
|
||||
import opennlp.tools.namefind.TokenNameFinderModel;
|
||||
import opennlp.tools.tokenize.SimpleTokenizer;
|
||||
import opennlp.tools.util.Span;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NamedEntityRecognitionTest {
|
||||
|
||||
@Test
|
||||
public void givenEnglishPersonModel_whenNER_thenPersonsAreDetected() throws Exception {
|
||||
|
||||
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("John is 26 years old. His best friend's name is Leonard. He has a sister named Penny.");
|
||||
|
||||
InputStream inputStreamNameFinder = getClass().getResourceAsStream("/models/en-ner-person.bin");
|
||||
TokenNameFinderModel model = new TokenNameFinderModel(inputStreamNameFinder);
|
||||
NameFinderME nameFinderME = new NameFinderME(model);
|
||||
List<Span> spans = Arrays.asList(nameFinderME.find(tokens));
|
||||
assertThat(spans.toString()).isEqualTo("[[0..1) person, [13..14) person, [20..21) person]");
|
||||
List<String> names = new ArrayList<String>();
|
||||
int k = 0;
|
||||
for (Span s : spans) {
|
||||
names.add("");
|
||||
for (int index = s.getStart(); index < s.getEnd(); index++) {
|
||||
names.set(k, names.get(k) + tokens[index]);
|
||||
}
|
||||
k++;
|
||||
}
|
||||
assertThat(names).contains("John","Leonard","Penny");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.InputStream;
|
||||
import opennlp.tools.postag.POSModel;
|
||||
import opennlp.tools.postag.POSTaggerME;
|
||||
import opennlp.tools.tokenize.SimpleTokenizer;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class POSTaggerTest {
|
||||
|
||||
@Test
|
||||
public void givenPOSModel_whenPOSTagging_thenPOSAreDetected() throws Exception {
|
||||
|
||||
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("John has a sister named Penny.");
|
||||
|
||||
InputStream inputStreamPOSTagger = getClass().getResourceAsStream("/models/en-pos-maxent.bin");
|
||||
POSModel posModel = new POSModel(inputStreamPOSTagger);
|
||||
POSTaggerME posTagger = new POSTaggerME(posModel);
|
||||
String tags[] = posTagger.tag(tokens);
|
||||
assertThat(tags).contains("NNP", "VBZ", "DT", "NN", "VBN", "NNP", ".");
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.InputStream;
|
||||
import opennlp.tools.sentdetect.SentenceDetectorME;
|
||||
import opennlp.tools.sentdetect.SentenceModel;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SentenceDetectionTest {
|
||||
|
||||
@Test
|
||||
public void givenEnglishModel_whenDetect_thenSentencesAreDetected() throws Exception {
|
||||
|
||||
String paragraph = "This is a statement. This is another statement. Now is an abstract word for time, "
|
||||
+ "that is always flying. And my email address is google@gmail.com.";
|
||||
|
||||
InputStream is = getClass().getResourceAsStream("/models/en-sent.bin");
|
||||
SentenceModel model = new SentenceModel(is);
|
||||
|
||||
SentenceDetectorME sdetector = new SentenceDetectorME(model);
|
||||
|
||||
String sentences[] = sdetector.sentDetect(paragraph);
|
||||
assertThat(sentences).contains("This is a statement.",
|
||||
"This is another statement.",
|
||||
"Now is an abstract word for time, that is always flying.",
|
||||
"And my email address is google@gmail.com.");
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.apache.opennlp;
|
||||
|
||||
import java.io.InputStream;
|
||||
import opennlp.tools.tokenize.SimpleTokenizer;
|
||||
import opennlp.tools.tokenize.TokenizerME;
|
||||
import opennlp.tools.tokenize.TokenizerModel;
|
||||
import opennlp.tools.tokenize.WhitespaceTokenizer;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TokenizerTest {
|
||||
|
||||
@Test
|
||||
public void givenEnglishModel_whenTokenize_thenTokensAreDetected() throws Exception {
|
||||
InputStream inputStream = getClass().getResourceAsStream("/models/en-token.bin");
|
||||
TokenizerModel model = new TokenizerModel(inputStream);
|
||||
TokenizerME tokenizer = new TokenizerME(model);
|
||||
String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource.");
|
||||
assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource", ".");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWhitespaceTokenizer_whenTokenize_thenTokensAreDetected() throws Exception {
|
||||
WhitespaceTokenizer tokenizer = WhitespaceTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource.");
|
||||
assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSimpleTokenizer_whenTokenize_thenTokensAreDetected() throws Exception {
|
||||
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
|
||||
String[] tokens = tokenizer.tokenize("Baeldung is a Spring Resource.");
|
||||
assertThat(tokens).contains("Baeldung", "is", "a", "Spring", "Resource", ".");
|
||||
}
|
||||
|
||||
}
|
@ -13,7 +13,11 @@
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core_2.10 -->
|
||||
<dependency>
|
||||
|
3
apache-tika/README.md
Normal file
3
apache-tika/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Content Analysis with Apache Tika](http://www.baeldung.com/apache-tika)
|
3
apache-zookeeper/README.md
Normal file
3
apache-zookeeper/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Getting Started with Java and Zookeeper](http://www.baeldung.com/java-zookeeper)
|
12
asm/pom.xml
12
asm/pom.xml
@ -1,10 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.examples</groupId>
|
||||
<artifactId>asm</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.ow2.asm</groupId>
|
||||
@ -17,12 +23,14 @@
|
||||
<version>5.2</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
<build>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
|
@ -3,5 +3,6 @@
|
||||
- [AWS Lambda Using DynamoDB With Java](http://www.baeldung.com/aws-lambda-dynamodb-java)
|
||||
- [AWS S3 with Java](http://www.baeldung.com/aws-s3-java)
|
||||
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
|
||||
- [Managing EC2 Instances in Java] (http://www.baeldung.com/ec2-java)
|
||||
- [Managing EC2 Instances in Java](http://www.baeldung.com/ec2-java)
|
||||
- [http://www.baeldung.com/aws-s3-multipart-upload](https://github.com/eugenp/tutorials/tree/master/aws)
|
||||
|
||||
|
BIN
aws/native-libs/libsqlite4java-linux-amd64-1.0.392.so
Normal file
BIN
aws/native-libs/libsqlite4java-linux-amd64-1.0.392.so
Normal file
Binary file not shown.
BIN
aws/native-libs/libsqlite4java-linux-i386-1.0.392.so
Normal file
BIN
aws/native-libs/libsqlite4java-linux-i386-1.0.392.so
Normal file
Binary file not shown.
BIN
aws/native-libs/libsqlite4java-osx-1.0.392.dylib
Normal file
BIN
aws/native-libs/libsqlite4java-osx-1.0.392.dylib
Normal file
Binary file not shown.
BIN
aws/native-libs/sqlite4java-win32-x64-1.0.392.dll
Normal file
BIN
aws/native-libs/sqlite4java-win32-x64-1.0.392.dll
Normal file
Binary file not shown.
BIN
aws/native-libs/sqlite4java-win32-x86-1.0.392.dll
Normal file
BIN
aws/native-libs/sqlite4java-win32-x86-1.0.392.dll
Normal file
Binary file not shown.
15
aws/pom.xml
15
aws/pom.xml
@ -24,6 +24,8 @@
|
||||
<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>
|
||||
<commons-codec-version>1.10.L001</commons-codec-version>
|
||||
<jets3t-version>0.9.4.0006L</jets3t-version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@ -97,6 +99,19 @@
|
||||
<version>${dynamodblocal.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- JetS3t -->
|
||||
<dependency>
|
||||
<groupId>org.lucee</groupId>
|
||||
<artifactId>jets3t</artifactId>
|
||||
<version>${jets3t-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.lucee</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec-version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -17,7 +17,6 @@ import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
351
aws/src/test/java/com/baeldung/jets3t/JetS3tLiveTest.java
Normal file
351
aws/src/test/java/com/baeldung/jets3t/JetS3tLiveTest.java
Normal file
@ -0,0 +1,351 @@
|
||||
package com.baeldung.jets3t;
|
||||
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.jets3t.service.S3Service;
|
||||
import org.jets3t.service.ServiceException;
|
||||
import org.jets3t.service.impl.rest.httpclient.RestS3Service;
|
||||
import org.jets3t.service.model.S3Bucket;
|
||||
import org.jets3t.service.model.S3Object;
|
||||
import org.jets3t.service.model.StorageObject;
|
||||
import org.jets3t.service.security.AWSCredentials;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class JetS3tLiveTest {
|
||||
|
||||
private Log log = LogFactory.getLog(JetS3tLiveTest.class);
|
||||
|
||||
private static final String BucketName = "baeldung-barfoo";
|
||||
private static final String TestString = "test string";
|
||||
private static final String TestStringName = "string object";
|
||||
private static final String TgtBucket = "baeldung-tgtbucket";
|
||||
|
||||
private static S3Service s3Service;
|
||||
|
||||
@BeforeClass
|
||||
public static void connectS3() throws Exception {
|
||||
|
||||
// Replace with your keys
|
||||
String awsAccessKey = "your access key";
|
||||
String awsSecretKey = "your secret key";
|
||||
|
||||
// Create credentials
|
||||
AWSCredentials awsCredentials = new AWSCredentials(awsAccessKey, awsSecretKey);
|
||||
|
||||
// Create service
|
||||
s3Service = new RestS3Service(awsCredentials);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCreate_AndDeleteBucket_CountGoesUpThenDown() throws Exception {
|
||||
|
||||
// List buckets, get a count
|
||||
S3Bucket[] myBuckets = s3Service.listAllBuckets();
|
||||
int count = Arrays.stream(myBuckets).map(S3Bucket::getName).collect(Collectors.toList()).size();
|
||||
|
||||
// Create a bucket
|
||||
S3Bucket bucket = createBucket();
|
||||
assertNotNull(bucket);
|
||||
|
||||
// List again
|
||||
myBuckets = s3Service.listAllBuckets();
|
||||
int newCount = Arrays.stream(myBuckets).map(S3Bucket::getName).collect(Collectors.toList()).size();
|
||||
|
||||
// We should have one more
|
||||
assertEquals((count + 1), newCount);
|
||||
|
||||
// Delete so next test doesn't fail
|
||||
deleteBucket();
|
||||
|
||||
// Check the count again, just for laughs
|
||||
myBuckets = s3Service.listAllBuckets();
|
||||
newCount = Arrays.stream(myBuckets).map(S3Bucket::getName).collect(Collectors.toList()).size();
|
||||
assertEquals(count, newCount);
|
||||
|
||||
}
|
||||
|
||||
private S3Bucket createBucket() throws Exception {
|
||||
S3Bucket bucket = s3Service.createBucket(BucketName);
|
||||
log.info(bucket);
|
||||
return bucket;
|
||||
}
|
||||
|
||||
|
||||
private void deleteBucket() throws ServiceException {
|
||||
s3Service.deleteBucket(BucketName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_Uploaded_StringInfoIsAvailable() throws Exception {
|
||||
|
||||
// Create a bucket
|
||||
S3Bucket bucket = createBucket();
|
||||
assertNotNull(bucket);
|
||||
|
||||
// Upload a string
|
||||
uploadStringData();
|
||||
|
||||
// Get the details
|
||||
StorageObject objectDetailsOnly = s3Service.getObjectDetails(BucketName, TestStringName);
|
||||
log.info("Content type: " + objectDetailsOnly.getContentType() + " length: " + objectDetailsOnly.getContentLength());
|
||||
|
||||
// Delete it
|
||||
deleteObject(TestStringName);
|
||||
|
||||
// For next test
|
||||
deleteBucket();
|
||||
}
|
||||
|
||||
private void uploadStringData() throws Exception {
|
||||
S3Object stringObject = new S3Object(TestStringName, TestString);
|
||||
s3Service.putObject(BucketName, stringObject);
|
||||
log.info("Content type:" + stringObject.getContentType());
|
||||
}
|
||||
|
||||
private void deleteObject(String objectName) throws ServiceException {
|
||||
s3Service.deleteObject(BucketName, objectName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringUploaded_StringIsDownloaded() throws Exception {
|
||||
|
||||
// Get a bucket
|
||||
S3Bucket bucket = createBucket();
|
||||
assertNotNull(bucket);
|
||||
|
||||
uploadStringData();
|
||||
|
||||
// Download
|
||||
S3Object stringObject = s3Service.getObject(BucketName, TestStringName);
|
||||
|
||||
// Process stream into a string
|
||||
String downloadedString = new BufferedReader(new InputStreamReader(stringObject.getDataInputStream())).lines().collect(Collectors.joining("\n"));
|
||||
|
||||
// Verify
|
||||
assertTrue(TestString.equals(downloadedString));
|
||||
|
||||
|
||||
// Clean up for next test
|
||||
deleteObject(TestStringName);
|
||||
deleteBucket();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBinaryFileUploaded_FileIsDownloaded() throws Exception {
|
||||
|
||||
// get a bucket
|
||||
S3Bucket bucket = createBucket();
|
||||
assertNotNull(bucket);
|
||||
|
||||
// Put a binary file
|
||||
S3Object fileObject = new S3Object(new File("src/test/resources/test.jpg"));
|
||||
s3Service.putObject(BucketName, fileObject);
|
||||
|
||||
// Print info about type and name
|
||||
log.info("Content type:" + fileObject.getContentType());
|
||||
log.info("File object name is " + fileObject.getName());
|
||||
|
||||
// Download
|
||||
S3Object newFileObject = s3Service.getObject(BucketName, "test.jpg");
|
||||
|
||||
// Save to a different name
|
||||
File newFile = new File("src/test/resources/newtest.jpg");
|
||||
Files.copy(newFileObject.getDataInputStream(), newFile.toPath(), REPLACE_EXISTING);
|
||||
|
||||
|
||||
// Get hashes and compare
|
||||
String origMD5 = getFileMD5("src/test/resources/test.jpg");
|
||||
String newMD5 = getFileMD5("src/test/resources/newtest.jpg");
|
||||
assertTrue(origMD5.equals(newMD5));
|
||||
|
||||
// Clean up
|
||||
deleteObject("test.jpg");
|
||||
deleteBucket();
|
||||
}
|
||||
|
||||
// Get MD5 hash for a file
|
||||
private String getFileMD5(String filename) throws IOException {
|
||||
try (FileInputStream fis = new FileInputStream(new File(filename))) {
|
||||
return DigestUtils.md5Hex(fis);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void givenStreamDataUploaded_StreamDataIsDownloaded() throws Exception {
|
||||
|
||||
// get a bucket
|
||||
S3Bucket bucket = createBucket();
|
||||
assertNotNull(bucket);
|
||||
|
||||
ArrayList<Integer> numbers = new ArrayList<>();
|
||||
numbers.add(2);
|
||||
numbers.add(3);
|
||||
numbers.add(5);
|
||||
numbers.add(7);
|
||||
|
||||
// Serialize ArrayList
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
ObjectOutputStream objectOutputStream = new ObjectOutputStream(bytes);
|
||||
objectOutputStream.writeObject(numbers);
|
||||
|
||||
// Wrap bytes
|
||||
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes.toByteArray());
|
||||
|
||||
// Create and populate object
|
||||
S3Object streamObject = new S3Object("stream");
|
||||
streamObject.setDataInputStream(byteArrayInputStream);
|
||||
streamObject.setContentLength(byteArrayInputStream.available());
|
||||
streamObject.setContentType("binary/octet-stream");
|
||||
|
||||
// Put it
|
||||
s3Service.putObject(BucketName, streamObject);
|
||||
|
||||
// Get it
|
||||
S3Object newStreamObject = s3Service.getObject(BucketName, "stream");
|
||||
|
||||
// Convert back to ArrayList
|
||||
ObjectInputStream objectInputStream = new ObjectInputStream(newStreamObject.getDataInputStream());
|
||||
ArrayList<Integer> newNumbers = (ArrayList<Integer>)objectInputStream.readObject();
|
||||
|
||||
assertEquals(2, (int)newNumbers.get(0));
|
||||
assertEquals(3, (int)newNumbers.get(1));
|
||||
assertEquals(5, (int)newNumbers.get(2));
|
||||
assertEquals(7, (int)newNumbers.get(3));
|
||||
|
||||
// Clean up
|
||||
deleteObject("stream");
|
||||
deleteBucket();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFileCopied_CopyIsSame() throws Exception {
|
||||
|
||||
// get a bucket
|
||||
S3Bucket bucket = createBucket();
|
||||
assertNotNull(bucket);
|
||||
|
||||
// Put a binary file
|
||||
S3Object fileObject = new S3Object(new File("src/test/resources/test.jpg"));
|
||||
s3Service.putObject(BucketName, fileObject);
|
||||
|
||||
|
||||
// Copy it
|
||||
S3Object targetObject = new S3Object("testcopy.jpg");
|
||||
s3Service.copyObject(BucketName, "test.jpg", BucketName, targetObject, false);
|
||||
|
||||
|
||||
// Download
|
||||
S3Object newFileObject = s3Service.getObject(BucketName, "testcopy.jpg");
|
||||
|
||||
// Save to a different name
|
||||
File newFile = new File("src/test/resources/testcopy.jpg");
|
||||
Files.copy(newFileObject.getDataInputStream(), newFile.toPath(), REPLACE_EXISTING);
|
||||
|
||||
|
||||
// Get hashes and compare
|
||||
String origMD5 = getFileMD5("src/test/resources/test.jpg");
|
||||
String newMD5 = getFileMD5("src/test/resources/testcopy.jpg");
|
||||
assertTrue(origMD5.equals(newMD5));
|
||||
|
||||
// Clean up
|
||||
deleteObject("test.jpg");
|
||||
deleteObject("testcopy.jpg");
|
||||
deleteBucket();
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenFileRenamed_NewNameIsSame() throws Exception {
|
||||
|
||||
// get a bucket
|
||||
S3Bucket bucket = createBucket();
|
||||
assertNotNull(bucket);
|
||||
|
||||
// Put a binary file
|
||||
S3Object fileObject = new S3Object(new File("src/test/resources/test.jpg"));
|
||||
s3Service.putObject(BucketName, fileObject);
|
||||
|
||||
|
||||
// Copy it
|
||||
s3Service.renameObject(BucketName, "test.jpg", new S3Object("spidey.jpg"));
|
||||
|
||||
|
||||
// Download
|
||||
S3Object newFileObject = s3Service.getObject(BucketName, "spidey.jpg");
|
||||
|
||||
// Save to a different name
|
||||
File newFile = new File("src/test/resources/spidey.jpg");
|
||||
Files.copy(newFileObject.getDataInputStream(), newFile.toPath(), REPLACE_EXISTING);
|
||||
|
||||
|
||||
// Get hashes and compare
|
||||
String origMD5 = getFileMD5("src/test/resources/test.jpg");
|
||||
String newMD5 = getFileMD5("src/test/resources/spidey.jpg");
|
||||
assertTrue(origMD5.equals(newMD5));
|
||||
|
||||
// Clean up
|
||||
deleteObject("test.jpg");
|
||||
deleteObject("spidey.jpg");
|
||||
deleteBucket();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFileMoved_NewInstanceIsSame() throws Exception {
|
||||
|
||||
// get a bucket
|
||||
S3Bucket bucket = createBucket();
|
||||
assertNotNull(bucket);
|
||||
|
||||
// create another bucket
|
||||
S3Bucket tgtBucket = s3Service.createBucket(TgtBucket);
|
||||
|
||||
|
||||
// Put a binary file
|
||||
S3Object fileObject = new S3Object(new File("src/test/resources/test.jpg"));
|
||||
s3Service.putObject(BucketName, fileObject);
|
||||
|
||||
|
||||
// Copy it
|
||||
s3Service.moveObject(BucketName, "test.jpg", TgtBucket,
|
||||
new S3Object("spidey.jpg"), false);
|
||||
|
||||
|
||||
// Download
|
||||
S3Object newFileObject = s3Service.getObject(TgtBucket, "spidey.jpg");
|
||||
|
||||
// Save to a different name
|
||||
File newFile = new File("src/test/resources/spidey.jpg");
|
||||
Files.copy(newFileObject.getDataInputStream(), newFile.toPath(), REPLACE_EXISTING);
|
||||
|
||||
|
||||
// Get hashes and compare
|
||||
String origMD5 = getFileMD5("src/test/resources/test.jpg");
|
||||
String newMD5 = getFileMD5("src/test/resources/spidey.jpg");
|
||||
assertTrue(origMD5.equals(newMD5));
|
||||
|
||||
// Clean up
|
||||
deleteBucket();
|
||||
|
||||
s3Service.deleteObject(TgtBucket, "spidey.jpg");
|
||||
s3Service.deleteBucket(TgtBucket);
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -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";
|
10
baeldung-pmd-rules.xml
Normal file
10
baeldung-pmd-rules.xml
Normal file
@ -0,0 +1,10 @@
|
||||
<?xml version="1.0"?>
|
||||
<ruleset name="Baeldung custom pmd rules" xmlns="http://pmd.sf.net/ruleset/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
|
||||
xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd">
|
||||
<description>Baeldung custom PMD rules</description>
|
||||
<rule name="UnitTestMustFollowNamingConventionRule" message="Test class name doesn't follow the naming convention" class="org.baeldung.pmd.UnitTestNamingConventionRule">
|
||||
<description>Test does not follow Baeldung naming convention</description>
|
||||
<priority>3</priority>
|
||||
</rule>
|
||||
</ruleset>
|
@ -13,10 +13,10 @@
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<groupId>io.bootique.parent</groupId>
|
||||
<artifactId>bootique-parent</artifactId>
|
||||
<version>0.12</version>
|
||||
</parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
|
@ -1,80 +1,79 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>spring-boot-camel</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>Spring-Boot - Camel API</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-servlet-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-jackson-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-swagger-java-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-spring-boot-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<version>${spring-boot-starter.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>spring-boot-camel</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<build>
|
||||
<defaultGoal>spring-boot:run</defaultGoal>
|
||||
|
||||
<name>Spring-Boot - Camel API</name>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot-starter.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<camel.version>2.19.1</camel.version>
|
||||
<spring-boot-starter.version>1.5.4.RELEASE</spring-boot-starter.version>
|
||||
</properties>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<camel.version>2.19.1</camel.version>
|
||||
<spring-boot-starter.version>1.5.4.RELEASE</spring-boot-starter.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-servlet-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-jackson-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-swagger-java-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.camel</groupId>
|
||||
<artifactId>camel-spring-boot-starter</artifactId>
|
||||
<version>${camel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<version>${spring-boot-starter.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<defaultGoal>spring-boot:run</defaultGoal>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot-starter.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
|
@ -7,7 +7,12 @@
|
||||
<artifactId>cas-server</artifactId>
|
||||
<packaging>war</packaging>
|
||||
<version>1.0</version>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.0.M7</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
3
checker-plugin/README.md
Normal file
3
checker-plugin/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
### Relevant articles
|
||||
|
||||
- [The Checker Framework – Pluggable Type Systems for Java](http://www.baeldung.com/checker-framework)
|
@ -7,6 +7,11 @@
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>checker-plugin</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<!-- https://checkerframework.org/manual/#maven -->
|
||||
|
||||
|
@ -2,3 +2,5 @@
|
||||
|
||||
## Relevant articles:
|
||||
|
||||
- [JDBC with Groovy](http://www.baeldung.com/jdbc-groovy)
|
||||
- [Working with JSON in Groovy](http://www.baeldung.com/groovy-json)
|
||||
|
@ -24,7 +24,7 @@ class JsonParserTest extends Specification {
|
||||
account.value == 15.6
|
||||
}
|
||||
|
||||
def 'Should parse to Account given Json String with date property' () {
|
||||
/*def 'Should parse to Account given Json String with date property' () {
|
||||
given:
|
||||
def json = '{"id":"1234","value":15.6,"createdAt":"2018-01-01T00:00:00+0000"}'
|
||||
when:
|
||||
@ -36,9 +36,9 @@ class JsonParserTest extends Specification {
|
||||
account.value == 15.6
|
||||
println account.createdAt
|
||||
account.createdAt == Date.parse('yyyy-MM-dd', '2018-01-01')
|
||||
}
|
||||
}*/
|
||||
|
||||
def 'Should parse to Json given an Account object' () {
|
||||
/*def 'Should parse to Json given an Account object' () {
|
||||
given:
|
||||
Account account = new Account(
|
||||
id: '123',
|
||||
@ -50,7 +50,7 @@ class JsonParserTest extends Specification {
|
||||
then:
|
||||
json
|
||||
json == '{"value":15.6,"createdAt":"2018-01-01T00:00:00+0000","id":"123"}'
|
||||
}
|
||||
}*/
|
||||
|
||||
def 'Should prettify given a json string' () {
|
||||
given:
|
||||
|
@ -43,3 +43,4 @@
|
||||
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
|
||||
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
|
||||
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
|
||||
- [Java 8 Math New Methods](http://www.baeldung.com/java-8-math)
|
||||
|
@ -8,7 +8,6 @@
|
||||
|
||||
<name>core-java-8</name>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class Car {
|
||||
|
||||
private String model;
|
||||
private int topSpeed;
|
||||
|
||||
public Car(String model, int topSpeed) {
|
||||
super();
|
||||
this.model = model;
|
||||
this.topSpeed = topSpeed;
|
||||
}
|
||||
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public void setModel(String model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public int getTopSpeed() {
|
||||
return topSpeed;
|
||||
}
|
||||
|
||||
public void setTopSpeed(int topSpeed) {
|
||||
this.topSpeed = topSpeed;
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -1,6 +1,8 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.Car;
|
||||
import com.baeldung.java_8_features.Person;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
@ -44,4 +46,29 @@ public class Java8MaxMinUnitTest {
|
||||
assertEquals("Should be Alex", alex, minByAge);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenArrayIsOfIntegerThenMinUsesIntegerComparator() {
|
||||
int[] integers = new int[] { 20, 98, 12, 7, 35 };
|
||||
|
||||
int min = Arrays.stream(integers)
|
||||
.min()
|
||||
.getAsInt();
|
||||
|
||||
assertEquals(7, min);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenArrayIsOfCustomTypeThenMaxUsesCustomComparator() {
|
||||
final Car porsche = new Car("Porsche 959", 319);
|
||||
final Car ferrari = new Car("Ferrari 288 GTO", 303);
|
||||
final Car bugatti = new Car("Bugatti Veyron 16.4 Super Sport", 415);
|
||||
final Car mcLaren = new Car("McLaren F1", 355);
|
||||
final Car[] fastCars = { porsche, ferrari, bugatti, mcLaren };
|
||||
|
||||
final Car maxBySpeed = Arrays.stream(fastCars)
|
||||
.max(Comparator.comparing(Car::getTopSpeed))
|
||||
.orElseThrow(NoSuchElementException::new);
|
||||
|
||||
assertEquals(bugatti, maxBySpeed);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,76 @@
|
||||
package com.baeldung.time;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.commons.lang3.time.StopWatch;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ElapsedTimeUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenRunningTask_whenMeasuringTimeWithCurrentTimeMillis_thenGetElapsedTime() throws InterruptedException {
|
||||
long start = System.currentTimeMillis();
|
||||
|
||||
simulateRunningTask();
|
||||
|
||||
long finish = System.currentTimeMillis();
|
||||
|
||||
long timeElapsed = finish - start;
|
||||
|
||||
assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveRunningTask_whenMeasuringTimeWithNanoTime_thenGetElapsedTime() throws InterruptedException {
|
||||
long start = System.nanoTime();
|
||||
|
||||
simulateRunningTask();
|
||||
|
||||
long finish = System.nanoTime();
|
||||
|
||||
long timeElapsed = finish - start;
|
||||
|
||||
assertEquals(true, (2000000000L <= timeElapsed) && (timeElapsed <= 3000000000L));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRunningTask_whenMeasuringTimeWithStopWatch_thenGetElapsedTime() throws InterruptedException {
|
||||
StopWatch watch = new StopWatch();
|
||||
watch.start();
|
||||
|
||||
simulateRunningTask();
|
||||
|
||||
watch.stop();
|
||||
|
||||
long timeElapsed = watch.getTime();
|
||||
|
||||
assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRunningTask_whenMeasuringTimeWithInstantClass_thenGetElapsedTime() throws InterruptedException {
|
||||
Instant start = Instant.now();
|
||||
|
||||
simulateRunningTask();
|
||||
|
||||
Instant finish = Instant.now();
|
||||
|
||||
long timeElapsed = Duration.between(start, finish).toMillis();
|
||||
|
||||
assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L));
|
||||
}
|
||||
|
||||
/**
|
||||
* Simulate task running for 2.5 seconds.
|
||||
*
|
||||
* @throws InterruptedException
|
||||
*/
|
||||
private static void simulateRunningTask() throws InterruptedException {
|
||||
TimeUnit.MILLISECONDS.sleep(2500); // 2.5 seconds
|
||||
|
||||
}
|
||||
}
|
@ -20,3 +20,5 @@
|
||||
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
|
||||
- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
|
||||
- [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles)
|
||||
- [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client)
|
||||
- [Method Handles in Java](http://www.baeldung.com/java-method-handles)
|
||||
|
0
core-java-9/compile-modules.sh
Normal file → Executable file
0
core-java-9/compile-modules.sh
Normal file → Executable file
2
core-java-9/compile-simple-modules.sh
Executable file
2
core-java-9/compile-simple-modules.sh
Executable file
@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env bash
|
||||
javac -d outDir --module-source-path src/simple-modules $(find src/simple-modules -name "*.java")
|
@ -6,7 +6,11 @@
|
||||
<version>0.2-SNAPSHOT</version>
|
||||
|
||||
<name>core-java-9</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>apache.snapshots</id>
|
||||
|
2
core-java-9/run-simple-module-app.sh
Executable file
2
core-java-9/run-simple-module-app.sh
Executable file
@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env bash
|
||||
java --module-path outDir -m main.app/com.baeldung.modules.main.MainApp
|
0
core-java-9/run-student-client.sh
Normal file → Executable file
0
core-java-9/run-student-client.sh
Normal file → Executable file
@ -0,0 +1,5 @@
|
||||
package com.baeldung.modules.hello;
|
||||
|
||||
public interface HelloInterface {
|
||||
public void sayHello();
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.modules.hello;
|
||||
|
||||
public class HelloModules implements HelloInterface {
|
||||
public static void doSomething() {
|
||||
System.out.println("Hello, Modules!");
|
||||
}
|
||||
|
||||
public void sayHello() {
|
||||
System.out.println("Hello!");
|
||||
}
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
module hello.modules {
|
||||
exports com.baeldung.modules.hello;
|
||||
provides com.baeldung.modules.hello.HelloInterface with com.baeldung.modules.hello.HelloModules;
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.baeldung.modules.main;
|
||||
|
||||
import com.baeldung.modules.hello.HelloModules;
|
||||
|
||||
public class MainApp {
|
||||
public static void main(String[] args) {
|
||||
HelloModules.doSomething();
|
||||
|
||||
HelloModules module = new HelloModules();
|
||||
module.sayHello();
|
||||
}
|
||||
}
|
4
core-java-9/src/simple-modules/main.app/module-info.java
Normal file
4
core-java-9/src/simple-modules/main.app/module-info.java
Normal file
@ -0,0 +1,4 @@
|
||||
module main.app {
|
||||
requires hello.modules;
|
||||
uses com.baeldung.modules.hello.HelloInterface;
|
||||
}
|
@ -34,3 +34,7 @@
|
||||
- [Implementing a Runnable vs Extending a Thread](http://www.baeldung.com/java-runnable-vs-extending-thread)
|
||||
- [How to Kill a Java Thread](http://www.baeldung.com/java-thread-stop)
|
||||
- [ExecutorService - Waiting for Threads to Finish](http://www.baeldung.com/java-executor-wait-for-threads)
|
||||
- [wait and notify() Methods in Java](http://www.baeldung.com/java-wait-notify)
|
||||
- [Priority-based Job Scheduling in Java](http://www.baeldung.com/java-priority-job-schedule)
|
||||
- [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer)
|
||||
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
|
||||
|
@ -1,55 +1,36 @@
|
||||
package com.baeldung.concurrent.volatilekeyword;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.Assert.assertEquals;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class SharedObjectManualTest {
|
||||
|
||||
private SharedObject sharedObject;
|
||||
private int valueReadByThread2;
|
||||
private int valueReadByThread3;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
sharedObject = new SharedObject();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOneThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException {
|
||||
SharedObject sharedObject = new SharedObject();
|
||||
|
||||
Thread writer = new Thread(() -> sharedObject.increamentCount());
|
||||
writer.start();
|
||||
|
||||
Thread.sleep(100);
|
||||
|
||||
Thread readerOne = new Thread(() -> {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
valueReadByThread2 = sharedObject.getCount();
|
||||
int valueReadByThread2 = sharedObject.getCount();
|
||||
assertEquals(1, valueReadByThread2);
|
||||
});
|
||||
readerOne.start();
|
||||
|
||||
Thread readerTwo = new Thread(() -> {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
valueReadByThread3 = sharedObject.getCount();
|
||||
int valueReadByThread3 = sharedObject.getCount();
|
||||
assertEquals(1, valueReadByThread3);
|
||||
});
|
||||
readerTwo.start();
|
||||
|
||||
assertEquals(1, valueReadByThread2);
|
||||
assertEquals(1, valueReadByThread3);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTwoThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException {
|
||||
SharedObject sharedObject = new SharedObject();
|
||||
Thread writerOne = new Thread(() -> sharedObject.increamentCount());
|
||||
writerOne.start();
|
||||
Thread.sleep(100);
|
||||
@ -58,14 +39,17 @@ public class SharedObjectManualTest {
|
||||
writerTwo.start();
|
||||
Thread.sleep(100);
|
||||
|
||||
Thread readerOne = new Thread(() -> valueReadByThread2 = sharedObject.getCount());
|
||||
Thread readerOne = new Thread(() -> {
|
||||
int valueReadByThread2 = sharedObject.getCount();
|
||||
assertEquals(2, valueReadByThread2);
|
||||
});
|
||||
readerOne.start();
|
||||
|
||||
Thread readerTwo = new Thread(() -> valueReadByThread3 = sharedObject.getCount());
|
||||
Thread readerTwo = new Thread(() -> {
|
||||
int valueReadByThread3 = sharedObject.getCount();
|
||||
assertEquals(2, valueReadByThread3);
|
||||
});
|
||||
readerTwo.start();
|
||||
|
||||
assertEquals(2, valueReadByThread2);
|
||||
assertEquals(2, valueReadByThread3);
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -6,7 +6,11 @@
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>core-java-io</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
|
||||
<!-- utils -->
|
||||
|
@ -6,7 +6,11 @@
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>core-java-sun</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
|
||||
<!-- utils -->
|
||||
|
1
core-java/.gitignore
vendored
1
core-java/.gitignore
vendored
@ -16,7 +16,6 @@
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
*.txt
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
@ -141,5 +141,14 @@
|
||||
- [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)
|
||||
- [The Observer Pattern in Java](https://github.com/eugenp/tutorials/tree/master/core-java)
|
||||
- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight)
|
||||
- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting)
|
||||
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat)
|
||||
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
|
||||
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
|
||||
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
|
||||
- [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced)
|
||||
- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings)
|
||||
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
|
||||
|
||||
|
@ -7,7 +7,11 @@
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>core-java</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
|
||||
<!-- utils -->
|
||||
@ -227,10 +231,9 @@
|
||||
<version>1.5.8.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>2.4.0</version>
|
||||
<scope>runtime</scope>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>1.4.197</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -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;
|
||||
}
|
||||
}
|
@ -13,8 +13,8 @@ public class BatchProcessing {
|
||||
|
||||
public void getConnection(){
|
||||
try {
|
||||
Class.forName("org.hsqldb.jdbcDriver");
|
||||
connection = DriverManager.getConnection("jdbc:hsqldb:file:C:\\EMPLOYEEDB", "SA", "");
|
||||
Class.forName("org.h2.Driver");
|
||||
connection = DriverManager.getConnection("jdbc:h2:mem:db", "SA", "");
|
||||
connection.setAutoCommit(false);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace(System.out);
|
||||
|
@ -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]);
|
||||
}
|
||||
}
|
17
core-java/src/main/java/com/baeldung/system/ChatWindow.java
Normal file
17
core-java/src/main/java/com/baeldung/system/ChatWindow.java
Normal file
@ -0,0 +1,17 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
import java.awt.event.WindowEvent;
|
||||
|
||||
/**
|
||||
* Note: This class is not meant for unit-testing since it uses system
|
||||
* features at low level and that it uses 'System' gc() which suggests
|
||||
* JVM for garbage collection. But the usage below demonstrates how the
|
||||
* method can be used.
|
||||
*/
|
||||
public class ChatWindow {
|
||||
public void windowStateChanged(WindowEvent event) {
|
||||
if (event.getNewState() == WindowEvent.WINDOW_DEACTIVATED ) {
|
||||
System.gc(); // if it ends up running, great!
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class DateTimeService {
|
||||
|
||||
// One hour from now
|
||||
public long nowPlusOneHour() {
|
||||
return System.currentTimeMillis() + 3600 * 1000L;
|
||||
}
|
||||
|
||||
// Human-readable format
|
||||
public String nowPrettyPrinted() {
|
||||
return new Date(System.currentTimeMillis()).toString();
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
public class EnvironmentVariables {
|
||||
public String getPath() {
|
||||
return System.getenv("PATH");
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
/**
|
||||
* Note: This class is not meant for unit-testing since it uses system
|
||||
* features at low level and that it uses 'System' standard error stream
|
||||
* methods to show output on screen. Also unit-tests in CI environments
|
||||
* don't have console output for user to see messages. But the usage below
|
||||
* demonstrates how the methods can be used.
|
||||
*/
|
||||
public class SystemErrDemo {
|
||||
public static void main(String[] args) {
|
||||
// Print without 'hitting' return
|
||||
System.err.print("some inline error message");
|
||||
|
||||
// Print and then 'hit' return
|
||||
System.err.println("an error message having new line at the end");
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
/**
|
||||
* Note: This class is not meant for unit-testing since it uses system
|
||||
* features at low level and that it uses 'System' exit() which will
|
||||
* exit the JVM. Also unit-tests in CI environments are not meant to
|
||||
* exit unit tests like that. But the usage below demonstrates how the
|
||||
* method can be used.
|
||||
*/
|
||||
public class SystemExitDemo {
|
||||
public static void main(String[] args) {
|
||||
boolean error = false;
|
||||
|
||||
// do something and set error value
|
||||
|
||||
if (error) {
|
||||
System.exit(1); // error case exit
|
||||
} else {
|
||||
System.exit(0); // normal case exit
|
||||
}
|
||||
|
||||
// Will not do anything after exit()
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.PrintStream;
|
||||
|
||||
/**
|
||||
* Note: This class is not meant for unit-testing since it uses system
|
||||
* features at low level and that it uses 'System' standard output stream
|
||||
* methods to show output on screen. Also unit-tests in CI environments
|
||||
* don't have console output for user to see messages. But the usage below
|
||||
* demonstrates how the methods can be used.
|
||||
*/
|
||||
public class SystemOutDemo {
|
||||
|
||||
public static void main(String[] args) throws FileNotFoundException {
|
||||
// Print without 'hitting' return
|
||||
System.out.print("some inline message");
|
||||
|
||||
// Print and then 'hit' return
|
||||
System.out.println("a message having new line at the end");
|
||||
|
||||
// Changes output stream to send messages to file.
|
||||
System.setOut(new PrintStream("file.txt"));
|
||||
}
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.Console;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
/**
|
||||
* Note: This class is not meant for unit-testing since it uses system
|
||||
* features at low level and that it uses 'System' standard input stream
|
||||
* methods to read text from user. Also unit-tests in CI environments
|
||||
* don't have console input for user to type in text. But the usage below
|
||||
* demonstrates how the methods can be used.
|
||||
*/
|
||||
public class UserCredentials {
|
||||
|
||||
public String readUsername(int length) throws IOException {
|
||||
byte[] name = new byte[length];
|
||||
System.in.read(name, 0, length); // by default, from the console
|
||||
return new String(name);
|
||||
}
|
||||
|
||||
public String readUsername() throws IOException {
|
||||
BufferedReader reader =
|
||||
new BufferedReader(new InputStreamReader(System.in));
|
||||
return reader.readLine();
|
||||
}
|
||||
|
||||
public String readUsernameWithPrompt() {
|
||||
Console console = System.console();
|
||||
|
||||
return console == null ? null : // Console not available
|
||||
console.readLine("%s", "Enter your name: ");
|
||||
}
|
||||
}
|
1
core-java/src/main/resources/file.txt
Normal file
1
core-java/src/main/resources/file.txt
Normal file
@ -0,0 +1 @@
|
||||
baeldung.com
|
@ -0,0 +1,116 @@
|
||||
package com.baeldung.array.converter;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ArrayConvertToListTest {
|
||||
|
||||
@Test
|
||||
public void givenAnStringArray_whenConvertArrayToList_thenListCreated() {
|
||||
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
|
||||
List<String> flowerList = Arrays.asList(flowers);
|
||||
|
||||
assertNotNull(flowerList);
|
||||
assertEquals(flowerList.size(), 4);
|
||||
assertEquals(flowerList.get(0), "Ageratum");
|
||||
assertEquals(flowerList.get(1), "Allium");
|
||||
assertEquals(flowerList.get(2), "Poppy");
|
||||
assertEquals(flowerList.get(3), "Catmint");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIntArray_whenConvertArrayToList_thenListWithOneElementCreated() {
|
||||
int[] primitives = { 1, 2, 3, 4 };
|
||||
List numbers = Arrays.asList(primitives);
|
||||
|
||||
assertNotNull(numbers);
|
||||
assertEquals(numbers.size(), 1);
|
||||
assertEquals(numbers.get(0), primitives);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void givenAnStringArray_whenConvertArrayToListAndAddAnElement_thenThrowUnsupportedOperationException() {
|
||||
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
|
||||
List<String> flowerList = Arrays.asList(flowers);
|
||||
|
||||
assertNotNull(flowerList);
|
||||
assertEquals(flowerList.size(), 4);
|
||||
assertEquals(flowerList.get(0), "Ageratum");
|
||||
assertEquals(flowerList.get(1), "Allium");
|
||||
assertEquals(flowerList.get(2), "Poppy");
|
||||
assertEquals(flowerList.get(3), "Catmint");
|
||||
|
||||
flowerList.add("Celosia");
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void givenAnStringArray_whenConvertArrayToListAndRemoveAnElement_thenThrowUnsupportedOperationException() {
|
||||
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
|
||||
List<String> flowerList = Arrays.asList(flowers);
|
||||
|
||||
assertNotNull(flowerList);
|
||||
assertEquals(flowerList.size(), 4);
|
||||
assertEquals(flowerList.get(0), "Ageratum");
|
||||
assertEquals(flowerList.get(1), "Allium");
|
||||
assertEquals(flowerList.get(2), "Poppy");
|
||||
assertEquals(flowerList.get(3), "Catmint");
|
||||
|
||||
flowerList.remove("Poppy");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnStringArray_whenCreateListFromArrayAndAddAnElement_thenListOk() {
|
||||
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
|
||||
List<String> flowerList = Arrays.asList(flowers);
|
||||
|
||||
assertNotNull(flowerList);
|
||||
assertEquals(flowerList.size(), 4);
|
||||
|
||||
assertEquals(flowerList.get(0), "Ageratum");
|
||||
assertEquals(flowerList.get(1), "Allium");
|
||||
assertEquals(flowerList.get(2), "Poppy");
|
||||
assertEquals(flowerList.get(3), "Catmint");
|
||||
|
||||
List<String> newflowerList = new ArrayList<>(flowerList);
|
||||
|
||||
assertNotNull(newflowerList);
|
||||
assertEquals(newflowerList.size(), 4);
|
||||
assertEquals(newflowerList.get(0), "Ageratum");
|
||||
assertEquals(newflowerList.get(1), "Allium");
|
||||
assertEquals(newflowerList.get(2), "Poppy");
|
||||
assertEquals(newflowerList.get(3), "Catmint");
|
||||
|
||||
newflowerList.add("Celosia");
|
||||
|
||||
assertEquals(newflowerList.size(), 5);
|
||||
assertEquals(newflowerList.get(4), "Celosia");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnStringArray_whenIterateArrayAndAddTheElementsToNewListAndAddAnElement_thenListOk() {
|
||||
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
|
||||
|
||||
List<String> flowerList = new ArrayList<>();
|
||||
for(String flower: flowers) {
|
||||
flowerList.add(flower);
|
||||
}
|
||||
|
||||
assertNotNull(flowerList);
|
||||
assertEquals(flowerList.size(), 4);
|
||||
|
||||
assertEquals(flowerList.get(0), "Ageratum");
|
||||
assertEquals(flowerList.get(1), "Allium");
|
||||
assertEquals(flowerList.get(2), "Poppy");
|
||||
assertEquals(flowerList.get(3), "Catmint");
|
||||
|
||||
flowerList.add("Celosia");
|
||||
|
||||
assertEquals(flowerList.size(), 5);
|
||||
assertEquals(flowerList.get(4), "Celosia");
|
||||
}
|
||||
}
|
@ -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,15 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DateTimeServiceTest {
|
||||
|
||||
@Test
|
||||
public void givenClass_whenCalledMethods_thenNotNullInResult() {
|
||||
DateTimeService dateTimeService = new DateTimeService();
|
||||
|
||||
Assert.assertNotNull(dateTimeService.nowPlusOneHour());
|
||||
Assert.assertNotNull(dateTimeService.nowPrettyPrinted());
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class EnvironmentVariablesTest {
|
||||
|
||||
@Test
|
||||
public void givenEnvVars_whenReadPath_thenGetValueinResult() {
|
||||
EnvironmentVariables environmentVariables = new EnvironmentVariables();
|
||||
|
||||
Assert.assertNotNull(environmentVariables.getPath());
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SystemArrayCopyTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoArraysAB_whenUseArrayCopy_thenArrayCopiedFromAToBInResult() {
|
||||
int[] a = {34, 22, 44, 2, 55, 3};
|
||||
int[] b = new int[a.length];
|
||||
|
||||
// copy all elements from a to b
|
||||
System.arraycopy(a, 0, b, 0, a.length);
|
||||
Assert.assertArrayEquals(a, b);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoArraysAB_whenUseArrayCopyPosition_thenArrayCopiedFromAToBInResult() {
|
||||
int[] a = {34, 22, 44, 2, 55, 3};
|
||||
int[] b = new int[a.length];
|
||||
|
||||
// copy 2 elements from a, starting at a[1] to b, starting at b[3]
|
||||
System.arraycopy(a, 1, b, 3, 2);
|
||||
Assert.assertArrayEquals(new int[] {0, 0, 0, 22, 44, 0}, b);
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SystemNanoTest {
|
||||
|
||||
@Test
|
||||
public void givenSystem_whenCalledNanoTime_thenGivesTimeinResult() {
|
||||
long startTime = System.nanoTime();
|
||||
// do something that takes time
|
||||
long endTime = System.nanoTime();
|
||||
|
||||
Assert.assertTrue(endTime - startTime < 10000);
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
public class SystemPropertiesTest {
|
||||
|
||||
@Test
|
||||
public void givenSystem_whenCalledGetProperty_thenReturnPropertyinResult() {
|
||||
Assert.assertNotNull(System.getProperty("java.vm.vendor"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSystem_whenCalledSetProperty_thenSetPropertyasResult() {
|
||||
|
||||
// set a particular property
|
||||
System.setProperty("abckey", "abcvaluefoo");
|
||||
Assert.assertEquals("abcvaluefoo", System.getProperty("abckey"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSystem_whenCalledClearProperty_thenDeletePropertyasResult() {
|
||||
|
||||
// Delete a property
|
||||
System.clearProperty("abckey");
|
||||
Assert.assertNull(System.getProperty("abckey"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSystem_whenCalledGetPropertyDefaultValue_thenReturnPropertyinResult() {
|
||||
|
||||
System.clearProperty("dbHost");
|
||||
String myKey = System.getProperty("dbHost", "db.host.com");
|
||||
Assert.assertEquals("db.host.com", myKey);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSystem_whenCalledGetProperties_thenReturnPropertiesinResult() {
|
||||
Properties properties = System.getProperties();
|
||||
|
||||
Assert.assertNotNull(properties);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void givenSystem_whenCalledClearProperties_thenDeleteAllPropertiesasResult() {
|
||||
|
||||
// Clears all system properties. Use with care!
|
||||
System.getProperties().clear();
|
||||
|
||||
Assert.assertTrue(System.getProperties().isEmpty());
|
||||
}
|
||||
}
|
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